winbindd: don't panic if messaging_init() fails - return NULL instead.
[samba.git] / source3 / winbindd / winbindd.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind daemon for ntdom nss module
5
6    Copyright (C) by Tim Potter 2000-2002
7    Copyright (C) Andrew Tridgell 2002
8    Copyright (C) Jelmer Vernooij 2003
9    Copyright (C) Volker Lendecke 2004
10    
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15    
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20    
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26 #include "winbindd.h"
27
28 #undef DBGC_CLASS
29 #define DBGC_CLASS DBGC_WINBIND
30
31 bool opt_nocache = False;
32 static bool interactive = False;
33
34 extern bool override_logfile;
35
36 struct event_context *winbind_event_context(void)
37 {
38         static struct event_context *ctx;
39
40         if (!ctx && !(ctx = event_context_init(NULL))) {
41                 smb_panic("Could not init winbind event context");
42         }
43         return ctx;
44 }
45
46 struct messaging_context *winbind_messaging_context(void)
47 {
48         static struct messaging_context *ctx;
49
50         if (!ctx && !(ctx = messaging_init(NULL, server_id_self(),
51                                            winbind_event_context()))) {
52                 DEBUG(0, ("Could not init winbind messaging context.\n"));
53         }
54         return ctx;
55 }
56
57 /* Reload configuration */
58
59 static bool reload_services_file(void)
60 {
61         bool ret;
62
63         if (lp_loaded()) {
64                 const char *fname = lp_configfile();
65
66                 if (file_exist(fname,NULL) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
67                         set_dyn_CONFIGFILE(fname);
68                 }
69         }
70
71         reopen_logs();
72         ret = lp_load(get_dyn_CONFIGFILE(),False,False,True,True);
73
74         reopen_logs();
75         load_interfaces();
76
77         return(ret);
78 }
79
80
81 /**************************************************************************** **
82  Handle a fault..
83  **************************************************************************** */
84
85 static void fault_quit(void)
86 {
87         dump_core();
88 }
89
90 static void winbindd_status(void)
91 {
92         struct winbindd_cli_state *tmp;
93
94         DEBUG(0, ("winbindd status:\n"));
95
96         /* Print client state information */
97         
98         DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
99         
100         if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
101                 DEBUG(2, ("\tclient list:\n"));
102                 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
103                         DEBUGADD(2, ("\t\tpid %lu, sock %d\n",
104                                   (unsigned long)tmp->pid, tmp->sock));
105                 }
106         }
107 }
108
109 /* Print winbindd status to log file */
110
111 static void print_winbindd_status(void)
112 {
113         winbindd_status();
114 }
115
116 /* Flush client cache */
117
118 static void flush_caches(void)
119 {
120         /* We need to invalidate cached user list entries on a SIGHUP 
121            otherwise cached access denied errors due to restrict anonymous
122            hang around until the sequence number changes. */
123
124         if (!wcache_invalidate_cache()) {
125                 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
126                 if (!winbindd_cache_validate_and_initialize()) {
127                         exit(1);
128                 }
129         }
130 }
131
132 /* Handle the signal by unlinking socket and exiting */
133
134 static void terminate(bool is_parent)
135 {
136         if (is_parent) {
137                 /* When parent goes away we should
138                  * remove the socket file. Not so
139                  * when children terminate.
140                  */ 
141                 char *path = NULL;
142
143                 if (asprintf(&path, "%s/%s",
144                         get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME) > 0) {
145                         unlink(path);
146                         SAFE_FREE(path);
147                 }
148         }
149
150         idmap_close();
151         
152         trustdom_cache_shutdown();
153
154 #if 0
155         if (interactive) {
156                 TALLOC_CTX *mem_ctx = talloc_init("end_description");
157                 char *description = talloc_describe_all(mem_ctx);
158
159                 DEBUG(3, ("tallocs left:\n%s\n", description));
160                 talloc_destroy(mem_ctx);
161         }
162 #endif
163
164         exit(0);
165 }
166
167 static bool do_sigterm;
168
169 static void termination_handler(int signum)
170 {
171         do_sigterm = True;
172         sys_select_signal(signum);
173 }
174
175 static bool do_sigusr2;
176
177 static void sigusr2_handler(int signum)
178 {
179         do_sigusr2 = True;
180         sys_select_signal(SIGUSR2);
181 }
182
183 static bool do_sighup;
184
185 static void sighup_handler(int signum)
186 {
187         do_sighup = True;
188         sys_select_signal(SIGHUP);
189 }
190
191 static bool do_sigchld;
192
193 static void sigchld_handler(int signum)
194 {
195         do_sigchld = True;
196         sys_select_signal(SIGCHLD);
197 }
198
199 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
200 static void msg_reload_services(struct messaging_context *msg,
201                                 void *private_data,
202                                 uint32_t msg_type,
203                                 struct server_id server_id,
204                                 DATA_BLOB *data)
205 {
206         /* Flush various caches */
207         flush_caches();
208         reload_services_file();
209 }
210
211 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
212 static void msg_shutdown(struct messaging_context *msg,
213                          void *private_data,
214                          uint32_t msg_type,
215                          struct server_id server_id,
216                          DATA_BLOB *data)
217 {
218         do_sigterm = True;
219 }
220
221
222 static void winbind_msg_validate_cache(struct messaging_context *msg_ctx,
223                                        void *private_data,
224                                        uint32_t msg_type,
225                                        struct server_id server_id,
226                                        DATA_BLOB *data)
227 {
228         uint8 ret;
229         pid_t child_pid;
230         struct sigaction act;
231         struct sigaction oldact;
232
233         DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
234                    "message.\n"));
235
236         /*
237          * call the validation code from a child:
238          * so we don't block the main winbindd and the validation
239          * code can safely use fork/waitpid...
240          */
241         CatchChild();
242         child_pid = sys_fork();
243
244         if (child_pid == -1) {
245                 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
246                           strerror(errno)));
247                 return;
248         }
249
250         if (child_pid != 0) {
251                 /* parent */
252                 DEBUG(5, ("winbind_msg_validate_cache: child created with "
253                           "pid %d.\n", child_pid));
254                 return;
255         }
256
257         /* child */
258
259         /* install default SIGCHLD handler: validation code uses fork/waitpid */
260         ZERO_STRUCT(act);
261         act.sa_handler = SIG_DFL;
262 #ifdef SA_RESTART
263         /* We *want* SIGALRM to interrupt a system call. */
264         act.sa_flags = SA_RESTART;
265 #endif
266         sigemptyset(&act.sa_mask);
267         sigaddset(&act.sa_mask,SIGCHLD);
268         sigaction(SIGCHLD,&act,&oldact);
269
270         ret = (uint8)winbindd_validate_cache_nobackup();
271         DEBUG(10, ("winbindd_msg_validata_cache: got return value %d\n", ret));
272         messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_VALIDATE_CACHE, &ret,
273                            (size_t)1);
274         _exit(0);
275 }
276
277 static struct winbindd_dispatch_table {
278         enum winbindd_cmd cmd;
279         void (*fn)(struct winbindd_cli_state *state);
280         const char *winbindd_cmd_name;
281 } dispatch_table[] = {
282         
283         /* User functions */
284
285         { WINBINDD_GETPWNAM, winbindd_getpwnam, "GETPWNAM" },
286         { WINBINDD_GETPWUID, winbindd_getpwuid, "GETPWUID" },
287
288         { WINBINDD_SETPWENT, winbindd_setpwent, "SETPWENT" },
289         { WINBINDD_ENDPWENT, winbindd_endpwent, "ENDPWENT" },
290         { WINBINDD_GETPWENT, winbindd_getpwent, "GETPWENT" },
291
292         { WINBINDD_GETGROUPS, winbindd_getgroups, "GETGROUPS" },
293         { WINBINDD_GETUSERSIDS, winbindd_getusersids, "GETUSERSIDS" },
294         { WINBINDD_GETUSERDOMGROUPS, winbindd_getuserdomgroups,
295           "GETUSERDOMGROUPS" },
296
297         /* Group functions */
298
299         { WINBINDD_GETGRNAM, winbindd_getgrnam, "GETGRNAM" },
300         { WINBINDD_GETGRGID, winbindd_getgrgid, "GETGRGID" },
301         { WINBINDD_SETGRENT, winbindd_setgrent, "SETGRENT" },
302         { WINBINDD_ENDGRENT, winbindd_endgrent, "ENDGRENT" },
303         { WINBINDD_GETGRENT, winbindd_getgrent, "GETGRENT" },
304         { WINBINDD_GETGRLST, winbindd_getgrent, "GETGRLST" },
305
306         /* PAM auth functions */
307
308         { WINBINDD_PAM_AUTH, winbindd_pam_auth, "PAM_AUTH" },
309         { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap, "AUTH_CRAP" },
310         { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok, "CHAUTHTOK" },
311         { WINBINDD_PAM_LOGOFF, winbindd_pam_logoff, "PAM_LOGOFF" },
312         { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, winbindd_pam_chng_pswd_auth_crap, "CHNG_PSWD_AUTH_CRAP" },
313
314         /* Enumeration functions */
315
316         { WINBINDD_LIST_USERS, winbindd_list_users, "LIST_USERS" },
317         { WINBINDD_LIST_GROUPS, winbindd_list_groups, "LIST_GROUPS" },
318         { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
319           "LIST_TRUSTDOM" },
320         { WINBINDD_SHOW_SEQUENCE, winbindd_show_sequence, "SHOW_SEQUENCE" },
321
322         /* SID related functions */
323
324         { WINBINDD_LOOKUPSID, winbindd_lookupsid, "LOOKUPSID" },
325         { WINBINDD_LOOKUPNAME, winbindd_lookupname, "LOOKUPNAME" },
326         { WINBINDD_LOOKUPRIDS, winbindd_lookuprids, "LOOKUPRIDS" },
327
328         /* Lookup related functions */
329
330         { WINBINDD_SID_TO_UID, winbindd_sid_to_uid, "SID_TO_UID" },
331         { WINBINDD_SID_TO_GID, winbindd_sid_to_gid, "SID_TO_GID" },
332         { WINBINDD_UID_TO_SID, winbindd_uid_to_sid, "UID_TO_SID" },
333         { WINBINDD_GID_TO_SID, winbindd_gid_to_sid, "GID_TO_SID" },
334 #if 0   /* DISABLED until we fix the interface in Samba 3.0.26 --jerry */
335         { WINBINDD_SIDS_TO_XIDS, winbindd_sids_to_unixids, "SIDS_TO_XIDS" },
336 #endif  /* end DISABLED */
337         { WINBINDD_ALLOCATE_UID, winbindd_allocate_uid, "ALLOCATE_UID" },
338         { WINBINDD_ALLOCATE_GID, winbindd_allocate_gid, "ALLOCATE_GID" },
339         { WINBINDD_SET_MAPPING, winbindd_set_mapping, "SET_MAPPING" },
340         { WINBINDD_SET_HWM, winbindd_set_hwm, "SET_HWMS" },
341
342         /* Miscellaneous */
343
344         { WINBINDD_CHECK_MACHACC, winbindd_check_machine_acct, "CHECK_MACHACC" },
345         { WINBINDD_PING, winbindd_ping, "PING" },
346         { WINBINDD_INFO, winbindd_info, "INFO" },
347         { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
348           "INTERFACE_VERSION" },
349         { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
350         { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
351         { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
352         { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
353           "WINBINDD_PRIV_PIPE_DIR" },
354         { WINBINDD_GETDCNAME, winbindd_getdcname, "GETDCNAME" },
355         { WINBINDD_DSGETDCNAME, winbindd_dsgetdcname, "DSGETDCNAME" },
356
357         /* Credential cache access */
358         { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
359
360         /* WINS functions */
361
362         { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
363         { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
364         
365         /* End of list */
366
367         { WINBINDD_NUM_CMDS, NULL, "NONE" }
368 };
369
370 static void process_request(struct winbindd_cli_state *state)
371 {
372         struct winbindd_dispatch_table *table = dispatch_table;
373
374         /* Free response data - we may be interrupted and receive another
375            command before being able to send this data off. */
376
377         SAFE_FREE(state->response.extra_data.data);  
378
379         ZERO_STRUCT(state->response);
380
381         state->response.result = WINBINDD_PENDING;
382         state->response.length = sizeof(struct winbindd_response);
383
384         state->mem_ctx = talloc_init("winbind request");
385         if (state->mem_ctx == NULL)
386                 return;
387
388         /* Remember who asked us. */
389         state->pid = state->request.pid;
390
391         /* Process command */
392
393         for (table = dispatch_table; table->fn; table++) {
394                 if (state->request.cmd == table->cmd) {
395                         DEBUG(10,("process_request: request fn %s\n",
396                                   table->winbindd_cmd_name ));
397                         table->fn(state);
398                         break;
399                 }
400         }
401
402         if (!table->fn) {
403                 DEBUG(10,("process_request: unknown request fn number %d\n",
404                           (int)state->request.cmd ));
405                 request_error(state);
406         }
407 }
408
409 /*
410  * A list of file descriptors being monitored by select in the main processing
411  * loop. fd_event->handler is called whenever the socket is readable/writable.
412  */
413
414 static struct fd_event *fd_events = NULL;
415
416 void add_fd_event(struct fd_event *ev)
417 {
418         struct fd_event *match;
419
420         /* only add unique fd_event structs */
421
422         for (match=fd_events; match; match=match->next ) {
423 #ifdef DEVELOPER
424                 SMB_ASSERT( match != ev );
425 #else
426                 if ( match == ev )
427                         return;
428 #endif
429         }
430
431         DLIST_ADD(fd_events, ev);
432 }
433
434 void remove_fd_event(struct fd_event *ev)
435 {
436         DLIST_REMOVE(fd_events, ev);
437 }
438
439 /*
440  * Handler for fd_events to complete a read/write request, set up by
441  * setup_async_read/setup_async_write.
442  */
443
444 static void rw_callback(struct fd_event *event, int flags)
445 {
446         size_t todo;
447         ssize_t done = 0;
448
449         todo = event->length - event->done;
450
451         if (event->flags & EVENT_FD_WRITE) {
452                 SMB_ASSERT(flags == EVENT_FD_WRITE);
453                 done = sys_write(event->fd,
454                                  &((char *)event->data)[event->done],
455                                  todo);
456
457                 if (done <= 0) {
458                         event->flags = 0;
459                         event->finished(event->private_data, False);
460                         return;
461                 }
462         }
463
464         if (event->flags & EVENT_FD_READ) {
465                 SMB_ASSERT(flags == EVENT_FD_READ);
466                 done = sys_read(event->fd, &((char *)event->data)[event->done],
467                                 todo);
468
469                 if (done <= 0) {
470                         event->flags = 0;
471                         event->finished(event->private_data, False);
472                         return;
473                 }
474         }
475
476         event->done += done;
477
478         if (event->done == event->length) {
479                 event->flags = 0;
480                 event->finished(event->private_data, True);
481         }
482 }
483
484 /*
485  * Request an async read/write on a fd_event structure. (*finished) is called
486  * when the request is completed or an error had occurred.
487  */
488
489 void setup_async_read(struct fd_event *event, void *data, size_t length,
490                       void (*finished)(void *private_data, bool success),
491                       void *private_data)
492 {
493         SMB_ASSERT(event->flags == 0);
494         event->data = data;
495         event->length = length;
496         event->done = 0;
497         event->handler = rw_callback;
498         event->finished = finished;
499         event->private_data = private_data;
500         event->flags = EVENT_FD_READ;
501 }
502
503 void setup_async_write(struct fd_event *event, void *data, size_t length,
504                        void (*finished)(void *private_data, bool success),
505                        void *private_data)
506 {
507         SMB_ASSERT(event->flags == 0);
508         event->data = data;
509         event->length = length;
510         event->done = 0;
511         event->handler = rw_callback;
512         event->finished = finished;
513         event->private_data = private_data;
514         event->flags = EVENT_FD_WRITE;
515 }
516
517 /*
518  * This is the main event loop of winbind requests. It goes through a
519  * state-machine of 3 read/write requests, 4 if you have extra data to send.
520  *
521  * An idle winbind client has a read request of 4 bytes outstanding,
522  * finalizing function is request_len_recv, checking the length. request_recv
523  * then processes the packet. The processing function then at some point has
524  * to call request_finished which schedules sending the response.
525  */
526
527 static void request_len_recv(void *private_data, bool success);
528 static void request_recv(void *private_data, bool success);
529 static void request_main_recv(void *private_data, bool success);
530 static void request_finished(struct winbindd_cli_state *state);
531 void request_finished_cont(void *private_data, bool success);
532 static void response_main_sent(void *private_data, bool success);
533 static void response_extra_sent(void *private_data, bool success);
534
535 static void response_extra_sent(void *private_data, bool success)
536 {
537         struct winbindd_cli_state *state =
538                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
539
540         if (state->mem_ctx != NULL) {
541                 talloc_destroy(state->mem_ctx);
542                 state->mem_ctx = NULL;
543         }
544
545         if (!success) {
546                 state->finished = True;
547                 return;
548         }
549
550         SAFE_FREE(state->request.extra_data.data);
551         SAFE_FREE(state->response.extra_data.data);
552
553         setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
554                          request_len_recv, state);
555 }
556
557 static void response_main_sent(void *private_data, bool success)
558 {
559         struct winbindd_cli_state *state =
560                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
561
562         if (!success) {
563                 state->finished = True;
564                 return;
565         }
566
567         if (state->response.length == sizeof(state->response)) {
568                 if (state->mem_ctx != NULL) {
569                         talloc_destroy(state->mem_ctx);
570                         state->mem_ctx = NULL;
571                 }
572
573                 setup_async_read(&state->fd_event, &state->request,
574                                  sizeof(uint32), request_len_recv, state);
575                 return;
576         }
577
578         setup_async_write(&state->fd_event, state->response.extra_data.data,
579                           state->response.length - sizeof(state->response),
580                           response_extra_sent, state);
581 }
582
583 static void request_finished(struct winbindd_cli_state *state)
584 {
585         setup_async_write(&state->fd_event, &state->response,
586                           sizeof(state->response), response_main_sent, state);
587 }
588
589 void request_error(struct winbindd_cli_state *state)
590 {
591         SMB_ASSERT(state->response.result == WINBINDD_PENDING);
592         state->response.result = WINBINDD_ERROR;
593         request_finished(state);
594 }
595
596 void request_ok(struct winbindd_cli_state *state)
597 {
598         SMB_ASSERT(state->response.result == WINBINDD_PENDING);
599         state->response.result = WINBINDD_OK;
600         request_finished(state);
601 }
602
603 void request_finished_cont(void *private_data, bool success)
604 {
605         struct winbindd_cli_state *state =
606                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
607
608         if (success)
609                 request_ok(state);
610         else
611                 request_error(state);
612 }
613
614 static void request_len_recv(void *private_data, bool success)
615 {
616         struct winbindd_cli_state *state =
617                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
618
619         if (!success) {
620                 state->finished = True;
621                 return;
622         }
623
624         if (*(uint32 *)(&state->request) != sizeof(state->request)) {
625                 DEBUG(0,("request_len_recv: Invalid request size received: %d (expected %u)\n",
626                          *(uint32_t *)(&state->request), (uint32_t)sizeof(state->request)));
627                 state->finished = True;
628                 return;
629         }
630
631         setup_async_read(&state->fd_event, (uint32 *)(&state->request)+1,
632                          sizeof(state->request) - sizeof(uint32),
633                          request_main_recv, state);
634 }
635
636 static void request_main_recv(void *private_data, bool success)
637 {
638         struct winbindd_cli_state *state =
639                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
640
641         if (!success) {
642                 state->finished = True;
643                 return;
644         }
645
646         if (state->request.extra_len == 0) {
647                 state->request.extra_data.data = NULL;
648                 request_recv(state, True);
649                 return;
650         }
651
652         if ((!state->privileged) &&
653             (state->request.extra_len > WINBINDD_MAX_EXTRA_DATA)) {
654                 DEBUG(3, ("Got request with %d bytes extra data on "
655                           "unprivileged socket\n", (int)state->request.extra_len));
656                 state->request.extra_data.data = NULL;
657                 state->finished = True;
658                 return;
659         }
660
661         state->request.extra_data.data =
662                 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
663
664         if (state->request.extra_data.data == NULL) {
665                 DEBUG(0, ("malloc failed\n"));
666                 state->finished = True;
667                 return;
668         }
669
670         /* Ensure null termination */
671         state->request.extra_data.data[state->request.extra_len] = '\0';
672
673         setup_async_read(&state->fd_event, state->request.extra_data.data,
674                          state->request.extra_len, request_recv, state);
675 }
676
677 static void request_recv(void *private_data, bool success)
678 {
679         struct winbindd_cli_state *state =
680                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
681
682         if (!success) {
683                 state->finished = True;
684                 return;
685         }
686
687         process_request(state);
688 }
689
690 /* Process a new connection by adding it to the client connection list */
691
692 static void new_connection(int listen_sock, bool privileged)
693 {
694         struct sockaddr_un sunaddr;
695         struct winbindd_cli_state *state;
696         socklen_t len;
697         int sock;
698         
699         /* Accept connection */
700         
701         len = sizeof(sunaddr);
702
703         do {
704                 sock = accept(listen_sock, (struct sockaddr *)&sunaddr, &len);
705         } while (sock == -1 && errno == EINTR);
706
707         if (sock == -1)
708                 return;
709         
710         DEBUG(6,("accepted socket %d\n", sock));
711         
712         /* Create new connection structure */
713         
714         if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
715                 close(sock);
716                 return;
717         }
718         
719         state->sock = sock;
720
721         state->last_access = time(NULL);        
722
723         state->privileged = privileged;
724
725         state->fd_event.fd = state->sock;
726         state->fd_event.flags = 0;
727         add_fd_event(&state->fd_event);
728
729         setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
730                          request_len_recv, state);
731
732         /* Add to connection list */
733         
734         winbindd_add_client(state);
735 }
736
737 /* Remove a client connection from client connection list */
738
739 static void remove_client(struct winbindd_cli_state *state)
740 {
741         /* It's a dead client - hold a funeral */
742         
743         if (state == NULL) {
744                 return;
745         }
746                 
747         /* Close socket */
748                 
749         close(state->sock);
750                 
751         /* Free any getent state */
752                 
753         free_getent_state(state->getpwent_state);
754         free_getent_state(state->getgrent_state);
755                 
756         /* We may have some extra data that was not freed if the client was
757            killed unexpectedly */
758
759         SAFE_FREE(state->response.extra_data.data);
760
761         if (state->mem_ctx != NULL) {
762                 talloc_destroy(state->mem_ctx);
763                 state->mem_ctx = NULL;
764         }
765
766         remove_fd_event(&state->fd_event);
767                 
768         /* Remove from list and free */
769                 
770         winbindd_remove_client(state);
771         TALLOC_FREE(state);
772 }
773
774 /* Shutdown client connection which has been idle for the longest time */
775
776 static bool remove_idle_client(void)
777 {
778         struct winbindd_cli_state *state, *remove_state = NULL;
779         time_t last_access = 0;
780         int nidle = 0;
781
782         for (state = winbindd_client_list(); state; state = state->next) {
783                 if (state->response.result != WINBINDD_PENDING &&
784                     !state->getpwent_state && !state->getgrent_state) {
785                         nidle++;
786                         if (!last_access || state->last_access < last_access) {
787                                 last_access = state->last_access;
788                                 remove_state = state;
789                         }
790                 }
791         }
792
793         if (remove_state) {
794                 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
795                         nidle, remove_state->sock, (unsigned int)remove_state->pid));
796                 remove_client(remove_state);
797                 return True;
798         }
799
800         return False;
801 }
802
803 /* check if HUP has been received and reload files */
804 void winbind_check_sighup(void)
805 {
806         if (do_sighup) {
807
808                 DEBUG(3, ("got SIGHUP\n"));
809
810                 flush_caches();
811                 reload_services_file();
812
813                 do_sighup = False;
814         }
815 }
816
817 /* check if TERM has been received */
818 void winbind_check_sigterm(bool is_parent)
819 {
820         if (do_sigterm)
821                 terminate(is_parent);
822 }
823
824 /* Process incoming clients on listen_sock.  We use a tricky non-blocking,
825    non-forking, non-threaded model which allows us to handle many
826    simultaneous connections while remaining impervious to many denial of
827    service attacks. */
828
829 static void process_loop(void)
830 {
831         struct winbindd_cli_state *state;
832         struct fd_event *ev;
833         fd_set r_fds, w_fds;
834         int maxfd, listen_sock, listen_priv_sock, selret;
835         struct timeval timeout, ev_timeout;
836
837         /* Open Sockets here to get stuff going ASAP */
838         listen_sock = open_winbindd_socket();
839         listen_priv_sock = open_winbindd_priv_socket();
840
841         if (listen_sock == -1 || listen_priv_sock == -1) {
842                 perror("open_winbind_socket");
843                 exit(1);
844         }
845
846         /* We'll be doing this a lot */
847
848         /* Handle messages */
849
850         message_dispatch(winbind_messaging_context());
851
852         run_events(winbind_event_context(), 0, NULL, NULL);
853
854         /* refresh the trusted domain cache */
855
856         rescan_trusted_domains();
857
858         /* Initialise fd lists for select() */
859
860         maxfd = MAX(listen_sock, listen_priv_sock);
861
862         FD_ZERO(&r_fds);
863         FD_ZERO(&w_fds);
864         FD_SET(listen_sock, &r_fds);
865         FD_SET(listen_priv_sock, &r_fds);
866
867         timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
868         timeout.tv_usec = 0;
869
870         /* Check for any event timeouts. */
871         if (get_timed_events_timeout(winbind_event_context(), &ev_timeout)) {
872                 timeout = timeval_min(&timeout, &ev_timeout);
873         }
874
875         /* Set up client readers and writers */
876
877         state = winbindd_client_list();
878
879         while (state) {
880
881                 struct winbindd_cli_state *next = state->next;
882
883                 /* Dispose of client connection if it is marked as 
884                    finished */ 
885
886                 if (state->finished)
887                         remove_client(state);
888
889                 state = next;
890         }
891
892         for (ev = fd_events; ev; ev = ev->next) {
893                 if (ev->flags & EVENT_FD_READ) {
894                         FD_SET(ev->fd, &r_fds);
895                         maxfd = MAX(ev->fd, maxfd);
896                 }
897                 if (ev->flags & EVENT_FD_WRITE) {
898                         FD_SET(ev->fd, &w_fds);
899                         maxfd = MAX(ev->fd, maxfd);
900                 }
901         }
902
903         /* Call select */
904         
905         selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
906
907         if (selret == 0) {
908                 goto no_fds_ready;
909         }
910
911         if (selret == -1) {
912                 if (errno == EINTR) {
913                         goto no_fds_ready;
914                 }
915
916                 /* Select error, something is badly wrong */
917
918                 perror("select");
919                 exit(1);
920         }
921
922         /* selret > 0 */
923
924         ev = fd_events;
925         while (ev != NULL) {
926                 struct fd_event *next = ev->next;
927                 int flags = 0;
928                 if (FD_ISSET(ev->fd, &r_fds))
929                         flags |= EVENT_FD_READ;
930                 if (FD_ISSET(ev->fd, &w_fds))
931                         flags |= EVENT_FD_WRITE;
932                 if (flags)
933                         ev->handler(ev, flags);
934                 ev = next;
935         }
936
937         if (FD_ISSET(listen_sock, &r_fds)) {
938                 while (winbindd_num_clients() >
939                        WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
940                         DEBUG(5,("winbindd: Exceeding %d client "
941                                  "connections, removing idle "
942                                  "connection.\n",
943                                  WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
944                         if (!remove_idle_client()) {
945                                 DEBUG(0,("winbindd: Exceeding %d "
946                                          "client connections, no idle "
947                                          "connection found\n",
948                                          WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
949                                 break;
950                         }
951                 }
952                 /* new, non-privileged connection */
953                 new_connection(listen_sock, False);
954         }
955             
956         if (FD_ISSET(listen_priv_sock, &r_fds)) {
957                 while (winbindd_num_clients() >
958                        WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
959                         DEBUG(5,("winbindd: Exceeding %d client "
960                                  "connections, removing idle "
961                                  "connection.\n",
962                                  WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
963                         if (!remove_idle_client()) {
964                                 DEBUG(0,("winbindd: Exceeding %d "
965                                          "client connections, no idle "
966                                          "connection found\n",
967                                          WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
968                                 break;
969                         }
970                 }
971                 /* new, privileged connection */
972                 new_connection(listen_priv_sock, True);
973         }
974
975  no_fds_ready:
976
977 #if 0
978         winbindd_check_cache_size(time(NULL));
979 #endif
980
981         /* Check signal handling things */
982
983         winbind_check_sigterm(true);
984         winbind_check_sighup();
985
986         if (do_sigusr2) {
987                 print_winbindd_status();
988                 do_sigusr2 = False;
989         }
990
991         if (do_sigchld) {
992                 pid_t pid;
993
994                 do_sigchld = False;
995
996                 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
997                         winbind_child_died(pid);
998                 }
999         }
1000 }
1001
1002 /* Main function */
1003
1004 int main(int argc, char **argv, char **envp)
1005 {
1006         static bool is_daemon = False;
1007         static bool Fork = True;
1008         static bool log_stdout = False;
1009         static bool no_process_group = False;
1010         enum {
1011                 OPT_DAEMON = 1000,
1012                 OPT_FORK,
1013                 OPT_NO_PROCESS_GROUP,
1014                 OPT_LOG_STDOUT
1015         };
1016         struct poptOption long_options[] = {
1017                 POPT_AUTOHELP
1018                 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1019                 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1020                 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1021                 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1022                 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1023                 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1024                 POPT_COMMON_SAMBA
1025                 POPT_TABLEEND
1026         };
1027         poptContext pc;
1028         int opt;
1029         TALLOC_CTX *frame = talloc_stackframe();
1030
1031         /* glibc (?) likes to print "User defined signal 1" and exit if a
1032            SIGUSR[12] is received before a handler is installed */
1033
1034         CatchSignal(SIGUSR1, SIG_IGN);
1035         CatchSignal(SIGUSR2, SIG_IGN);
1036
1037         fault_setup((void (*)(void *))fault_quit );
1038         dump_core_setup("winbindd");
1039
1040         load_case_tables();
1041
1042         db_tdb2_setup_messaging(NULL, false);
1043
1044         /* Initialise for running in non-root mode */
1045
1046         sec_init();
1047
1048         set_remote_machine_name("winbindd", False);
1049
1050         /* Set environment variable so we don't recursively call ourselves.
1051            This may also be useful interactively. */
1052
1053         if ( !winbind_off() ) {
1054                 DEBUG(0,("Failed to disable recusive winbindd calls.  Exiting.\n"));
1055                 exit(1);
1056         }
1057
1058         /* Initialise samba/rpc client stuff */
1059
1060         pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1061
1062         while ((opt = poptGetNextOpt(pc)) != -1) {
1063                 switch (opt) {
1064                         /* Don't become a daemon */
1065                 case OPT_DAEMON:
1066                         is_daemon = True;
1067                         break;
1068                 case 'i':
1069                         interactive = True;
1070                         log_stdout = True;
1071                         Fork = False;
1072                         break;
1073                 case OPT_FORK:
1074                         Fork = false;
1075                         break;
1076                 case OPT_NO_PROCESS_GROUP:
1077                         no_process_group = true;
1078                         break;
1079                 case OPT_LOG_STDOUT:
1080                         log_stdout = true;
1081                         break;
1082                 case 'n':
1083                         opt_nocache = true;
1084                         break;
1085                 default:
1086                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1087                                   poptBadOption(pc, 0), poptStrerror(opt));
1088                         poptPrintUsage(pc, stderr, 0);
1089                         exit(1);
1090                 }
1091         }
1092
1093         if (is_daemon && interactive) {
1094                 d_fprintf(stderr,"\nERROR: "
1095                           "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1096                 poptPrintUsage(pc, stderr, 0);
1097                 exit(1);
1098         }
1099
1100         if (log_stdout && Fork) {
1101                 d_fprintf(stderr, "\nERROR: "
1102                           "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1103                 poptPrintUsage(pc, stderr, 0);
1104                 exit(1);
1105         }
1106
1107         poptFreeContext(pc);
1108
1109         if (!override_logfile) {
1110                 char *logfile = NULL;
1111                 if (asprintf(&logfile,"%s/log.winbindd",
1112                                 get_dyn_LOGFILEBASE()) > 0) {
1113                         lp_set_logfile(logfile);
1114                         SAFE_FREE(logfile);
1115                 }
1116         }
1117         setup_logging("winbindd", log_stdout);
1118         reopen_logs();
1119
1120         DEBUG(0,("winbindd version %s started.\n", SAMBA_VERSION_STRING));
1121         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1122
1123         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1124                 DEBUG(0, ("error opening config file\n"));
1125                 exit(1);
1126         }
1127
1128         /* Initialise messaging system */
1129
1130         if (winbind_messaging_context() == NULL) {
1131                 DEBUG(0, ("unable to initialize messaging system\n"));
1132                 exit(1);
1133         }
1134
1135         db_tdb2_setup_messaging(winbind_messaging_context(), true);
1136
1137         if (!reload_services_file()) {
1138                 DEBUG(0, ("error opening config file\n"));
1139                 exit(1);
1140         }
1141
1142         if (!directory_exist(lp_lockdir(), NULL)) {
1143                 mkdir(lp_lockdir(), 0755);
1144         }
1145
1146         /* Setup names. */
1147
1148         if (!init_names())
1149                 exit(1);
1150
1151         load_interfaces();
1152
1153         if (!secrets_init()) {
1154
1155                 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1156                 return False;
1157         }
1158
1159         /* Enable netbios namecache */
1160
1161         namecache_enable();
1162
1163         /* Winbind daemon initialisation */
1164
1165         if ( ! NT_STATUS_IS_OK(idmap_init_cache()) ) {
1166                 DEBUG(1, ("Could not init idmap cache!\n"));            
1167         }
1168
1169         /* Unblock all signals we are interested in as they may have been
1170            blocked by the parent process. */
1171
1172         BlockSignals(False, SIGINT);
1173         BlockSignals(False, SIGQUIT);
1174         BlockSignals(False, SIGTERM);
1175         BlockSignals(False, SIGUSR1);
1176         BlockSignals(False, SIGUSR2);
1177         BlockSignals(False, SIGHUP);
1178         BlockSignals(False, SIGCHLD);
1179
1180         /* Setup signal handlers */
1181         
1182         CatchSignal(SIGINT, termination_handler);      /* Exit on these sigs */
1183         CatchSignal(SIGQUIT, termination_handler);
1184         CatchSignal(SIGTERM, termination_handler);
1185         CatchSignal(SIGCHLD, sigchld_handler);
1186
1187         CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
1188
1189         CatchSignal(SIGUSR2, sigusr2_handler);         /* Debugging sigs */
1190         CatchSignal(SIGHUP, sighup_handler);
1191
1192         if (!interactive)
1193                 become_daemon(Fork, no_process_group);
1194
1195         pidfile_create("winbindd");
1196
1197 #if HAVE_SETPGID
1198         /*
1199          * If we're interactive we want to set our own process group for
1200          * signal management.
1201          */
1202         if (interactive && !no_process_group)
1203                 setpgid( (pid_t)0, (pid_t)0);
1204 #endif
1205
1206         TimeInit();
1207
1208         if (!reinit_after_fork(winbind_messaging_context(), false)) {
1209                 DEBUG(0,("reinit_after_fork() failed\n"));
1210                 exit(1);
1211         }
1212
1213         /*
1214          * Ensure all cache and idmap caches are consistent
1215          * and initialized before we startup.
1216          */
1217         if (!winbindd_cache_validate_and_initialize()) {
1218                 exit(1);
1219         }
1220
1221         /* get broadcast messages */
1222         claim_connection(NULL,"",FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP);
1223
1224         /* React on 'smbcontrol winbindd reload-config' in the same way
1225            as to SIGHUP signal */
1226         messaging_register(winbind_messaging_context(), NULL,
1227                            MSG_SMB_CONF_UPDATED, msg_reload_services);
1228         messaging_register(winbind_messaging_context(), NULL,
1229                            MSG_SHUTDOWN, msg_shutdown);
1230
1231         /* Handle online/offline messages. */
1232         messaging_register(winbind_messaging_context(), NULL,
1233                            MSG_WINBIND_OFFLINE, winbind_msg_offline);
1234         messaging_register(winbind_messaging_context(), NULL,
1235                            MSG_WINBIND_ONLINE, winbind_msg_online);
1236         messaging_register(winbind_messaging_context(), NULL,
1237                            MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1238
1239         messaging_register(winbind_messaging_context(), NULL,
1240                            MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1241
1242         messaging_register(winbind_messaging_context(), NULL,
1243                            MSG_WINBIND_VALIDATE_CACHE,
1244                            winbind_msg_validate_cache);
1245
1246         messaging_register(winbind_messaging_context(), NULL,
1247                            MSG_WINBIND_DUMP_DOMAIN_LIST,
1248                            winbind_msg_dump_domain_list);
1249
1250         netsamlogon_cache_init(); /* Non-critical */
1251         
1252         /* clear the cached list of trusted domains */
1253
1254         wcache_tdc_clear();     
1255         
1256         if (!init_domain_list()) {
1257                 DEBUG(0,("unable to initialize domain list\n"));
1258                 exit(1);
1259         }
1260
1261         init_idmap_child();
1262         init_locator_child();
1263
1264         smb_nscd_flush_user_cache();
1265         smb_nscd_flush_group_cache();
1266
1267         /* Loop waiting for requests */
1268
1269         TALLOC_FREE(frame);
1270         while (1) {
1271                 frame = talloc_stackframe();
1272                 process_loop();
1273                 TALLOC_FREE(frame);
1274         }
1275
1276         return 0;
1277 }