s3: Send a dropped_ip message if we lose an IP
[obnox/samba-ctdb.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 #include "lib/addrchange.h"
28
29 #undef DBGC_CLASS
30 #define DBGC_CLASS DBGC_WINBIND
31
32 static bool opt_nocache = False;
33 static bool interactive = False;
34
35 extern bool override_logfile;
36
37 struct event_context *winbind_event_context(void)
38 {
39         static struct event_context *ctx;
40
41         if (!ctx && !(ctx = event_context_init(NULL))) {
42                 smb_panic("Could not init winbind event context");
43         }
44         return ctx;
45 }
46
47 struct messaging_context *winbind_messaging_context(void)
48 {
49         static struct messaging_context *ctx;
50
51         if (ctx == NULL) {
52                 ctx = messaging_init(NULL, server_id_self(),
53                                      winbind_event_context());
54         }
55         if (ctx == NULL) {
56                 DEBUG(0, ("Could not init winbind messaging context.\n"));
57         }
58         return ctx;
59 }
60
61 /* Reload configuration */
62
63 static bool reload_services_file(const char *lfile)
64 {
65         bool ret;
66
67         if (lp_loaded()) {
68                 const char *fname = lp_configfile();
69
70                 if (file_exist(fname) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
71                         set_dyn_CONFIGFILE(fname);
72                 }
73         }
74
75         /* if this is a child, restore the logfile to the special
76            name - <domain>, idmap, etc. */
77         if (lfile && *lfile) {
78                 lp_set_logfile(lfile);
79         }
80
81         reopen_logs();
82         ret = lp_load(get_dyn_CONFIGFILE(),False,False,True,True);
83
84         reopen_logs();
85         load_interfaces();
86
87         return(ret);
88 }
89
90
91 /**************************************************************************** **
92  Handle a fault..
93  **************************************************************************** */
94
95 static void fault_quit(void)
96 {
97         dump_core();
98 }
99
100 static void winbindd_status(void)
101 {
102         struct winbindd_cli_state *tmp;
103
104         DEBUG(0, ("winbindd status:\n"));
105
106         /* Print client state information */
107
108         DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
109
110         if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
111                 DEBUG(2, ("\tclient list:\n"));
112                 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
113                         DEBUGADD(2, ("\t\tpid %lu, sock %d\n",
114                                   (unsigned long)tmp->pid, tmp->sock));
115                 }
116         }
117 }
118
119 /* Print winbindd status to log file */
120
121 static void print_winbindd_status(void)
122 {
123         winbindd_status();
124 }
125
126 /* Flush client cache */
127
128 static void flush_caches(void)
129 {
130         /* We need to invalidate cached user list entries on a SIGHUP 
131            otherwise cached access denied errors due to restrict anonymous
132            hang around until the sequence number changes. */
133
134         if (!wcache_invalidate_cache()) {
135                 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
136                 if (!winbindd_cache_validate_and_initialize()) {
137                         exit(1);
138                 }
139         }
140 }
141
142 /* Handle the signal by unlinking socket and exiting */
143
144 static void terminate(bool is_parent)
145 {
146         if (is_parent) {
147                 /* When parent goes away we should
148                  * remove the socket file. Not so
149                  * when children terminate.
150                  */ 
151                 char *path = NULL;
152
153                 if (asprintf(&path, "%s/%s",
154                         get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME) > 0) {
155                         unlink(path);
156                         SAFE_FREE(path);
157                 }
158         }
159
160         idmap_close();
161
162         trustdom_cache_shutdown();
163
164         gencache_stabilize();
165
166 #if 0
167         if (interactive) {
168                 TALLOC_CTX *mem_ctx = talloc_init("end_description");
169                 char *description = talloc_describe_all(mem_ctx);
170
171                 DEBUG(3, ("tallocs left:\n%s\n", description));
172                 talloc_destroy(mem_ctx);
173         }
174 #endif
175
176         if (is_parent) {
177                 pidfile_unlink();
178         }
179
180         exit(0);
181 }
182
183 static void winbindd_sig_term_handler(struct tevent_context *ev,
184                                       struct tevent_signal *se,
185                                       int signum,
186                                       int count,
187                                       void *siginfo,
188                                       void *private_data)
189 {
190         bool *is_parent = talloc_get_type_abort(private_data, bool);
191
192         DEBUG(0,("Got sig[%d] terminate (is_parent=%d)\n",
193                  signum, (int)*is_parent));
194
195         /* if the parent killed us due to a timeout log where we were */
196         if (signum == SIGXCPU) {
197                 log_stack_trace_with_level(1);
198         }
199
200         terminate(*is_parent);
201 }
202
203 bool winbindd_setup_sig_term_handler(bool parent)
204 {
205         struct tevent_signal *se;
206         bool *is_parent;
207
208         is_parent = talloc(winbind_event_context(), bool);
209         if (!is_parent) {
210                 return false;
211         }
212
213         *is_parent = parent;
214
215         se = tevent_add_signal(winbind_event_context(),
216                                is_parent,
217                                SIGTERM, 0,
218                                winbindd_sig_term_handler,
219                                is_parent);
220         if (!se) {
221                 DEBUG(0,("failed to setup SIGTERM handler"));
222                 talloc_free(is_parent);
223                 return false;
224         }
225
226         se = tevent_add_signal(winbind_event_context(),
227                                is_parent,
228                                SIGINT, 0,
229                                winbindd_sig_term_handler,
230                                is_parent);
231         if (!se) {
232                 DEBUG(0,("failed to setup SIGINT handler"));
233                 talloc_free(is_parent);
234                 return false;
235         }
236
237         se = tevent_add_signal(winbind_event_context(),
238                                is_parent,
239                                SIGQUIT, 0,
240                                winbindd_sig_term_handler,
241                                is_parent);
242         if (!se) {
243                 DEBUG(0,("failed to setup SIGINT handler"));
244                 talloc_free(is_parent);
245                 return false;
246         }
247
248         se = tevent_add_signal(winbind_event_context(),
249                                is_parent,
250                                SIGXCPU, 0,
251                                winbindd_sig_term_handler,
252                                is_parent);
253         if (!se) {
254                 DEBUG(0,("failed to setup SIGXCPU handler"));
255                 talloc_free(is_parent);
256                 return false;
257         }
258         return true;
259 }
260
261 static void winbindd_sig_hup_handler(struct tevent_context *ev,
262                                      struct tevent_signal *se,
263                                      int signum,
264                                      int count,
265                                      void *siginfo,
266                                      void *private_data)
267 {
268         const char *file = (const char *)private_data;
269
270         DEBUG(1,("Reloading services after SIGHUP\n"));
271         flush_caches();
272         reload_services_file(file);
273 }
274
275 bool winbindd_setup_sig_hup_handler(const char *lfile)
276 {
277         struct tevent_signal *se;
278         char *file = NULL;
279
280         if (lfile) {
281                 file = talloc_strdup(winbind_event_context(),
282                                      lfile);
283                 if (!file) {
284                         return false;
285                 }
286         }
287
288         se = tevent_add_signal(winbind_event_context(),
289                                winbind_event_context(),
290                                SIGHUP, 0,
291                                winbindd_sig_hup_handler,
292                                file);
293         if (!se) {
294                 return false;
295         }
296
297         return true;
298 }
299
300 static void winbindd_sig_chld_handler(struct tevent_context *ev,
301                                       struct tevent_signal *se,
302                                       int signum,
303                                       int count,
304                                       void *siginfo,
305                                       void *private_data)
306 {
307         pid_t pid;
308
309         while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
310                 winbind_child_died(pid);
311         }
312 }
313
314 static bool winbindd_setup_sig_chld_handler(void)
315 {
316         struct tevent_signal *se;
317
318         se = tevent_add_signal(winbind_event_context(),
319                                winbind_event_context(),
320                                SIGCHLD, 0,
321                                winbindd_sig_chld_handler,
322                                NULL);
323         if (!se) {
324                 return false;
325         }
326
327         return true;
328 }
329
330 static void winbindd_sig_usr2_handler(struct tevent_context *ev,
331                                       struct tevent_signal *se,
332                                       int signum,
333                                       int count,
334                                       void *siginfo,
335                                       void *private_data)
336 {
337         print_winbindd_status();
338 }
339
340 static bool winbindd_setup_sig_usr2_handler(void)
341 {
342         struct tevent_signal *se;
343
344         se = tevent_add_signal(winbind_event_context(),
345                                winbind_event_context(),
346                                SIGUSR2, 0,
347                                winbindd_sig_usr2_handler,
348                                NULL);
349         if (!se) {
350                 return false;
351         }
352
353         return true;
354 }
355
356 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
357 static void msg_reload_services(struct messaging_context *msg,
358                                 void *private_data,
359                                 uint32_t msg_type,
360                                 struct server_id server_id,
361                                 DATA_BLOB *data)
362 {
363         /* Flush various caches */
364         flush_caches();
365         reload_services_file((const char *) private_data);
366 }
367
368 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
369 static void msg_shutdown(struct messaging_context *msg,
370                          void *private_data,
371                          uint32_t msg_type,
372                          struct server_id server_id,
373                          DATA_BLOB *data)
374 {
375         /* only the parent waits for this message */
376         DEBUG(0,("Got shutdown message\n"));
377         terminate(true);
378 }
379
380
381 static void winbind_msg_validate_cache(struct messaging_context *msg_ctx,
382                                        void *private_data,
383                                        uint32_t msg_type,
384                                        struct server_id server_id,
385                                        DATA_BLOB *data)
386 {
387         uint8 ret;
388         pid_t child_pid;
389
390         DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
391                    "message.\n"));
392
393         /*
394          * call the validation code from a child:
395          * so we don't block the main winbindd and the validation
396          * code can safely use fork/waitpid...
397          */
398         child_pid = sys_fork();
399
400         if (child_pid == -1) {
401                 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
402                           strerror(errno)));
403                 return;
404         }
405
406         if (child_pid != 0) {
407                 /* parent */
408                 DEBUG(5, ("winbind_msg_validate_cache: child created with "
409                           "pid %d.\n", (int)child_pid));
410                 return;
411         }
412
413         /* child */
414
415         if (!winbindd_reinit_after_fork(NULL)) {
416                 _exit(0);
417         }
418
419         /* install default SIGCHLD handler: validation code uses fork/waitpid */
420         CatchSignal(SIGCHLD, SIG_DFL);
421
422         ret = (uint8)winbindd_validate_cache_nobackup();
423         DEBUG(10, ("winbindd_msg_validata_cache: got return value %d\n", ret));
424         messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_VALIDATE_CACHE, &ret,
425                            (size_t)1);
426         _exit(0);
427 }
428
429 static struct winbindd_dispatch_table {
430         enum winbindd_cmd cmd;
431         void (*fn)(struct winbindd_cli_state *state);
432         const char *winbindd_cmd_name;
433 } dispatch_table[] = {
434
435         /* User functions */
436
437         { WINBINDD_GETPWNAM, winbindd_getpwnam, "GETPWNAM" },
438         { WINBINDD_GETPWUID, winbindd_getpwuid, "GETPWUID" },
439         { WINBINDD_GETPWSID, winbindd_getpwsid, "GETPWSID" },
440
441         { WINBINDD_SETPWENT, winbindd_setpwent, "SETPWENT" },
442         { WINBINDD_ENDPWENT, winbindd_endpwent, "ENDPWENT" },
443         { WINBINDD_GETPWENT, winbindd_getpwent, "GETPWENT" },
444
445         { WINBINDD_GETGROUPS, winbindd_getgroups, "GETGROUPS" },
446         { WINBINDD_GETUSERSIDS, winbindd_getusersids, "GETUSERSIDS" },
447         { WINBINDD_GETUSERDOMGROUPS, winbindd_getuserdomgroups,
448           "GETUSERDOMGROUPS" },
449         { WINBINDD_GETSIDALIASES, winbindd_getsidaliases,
450            "LOOKUPUSERALIASES" },
451
452         /* Group functions */
453
454         { WINBINDD_GETGRNAM, winbindd_getgrnam, "GETGRNAM" },
455         { WINBINDD_GETGRGID, winbindd_getgrgid, "GETGRGID" },
456         { WINBINDD_SETGRENT, winbindd_setgrent, "SETGRENT" },
457         { WINBINDD_ENDGRENT, winbindd_endgrent, "ENDGRENT" },
458         { WINBINDD_GETGRENT, winbindd_getgrent, "GETGRENT" },
459         { WINBINDD_GETGRLST, winbindd_getgrent, "GETGRLST" },
460
461         /* PAM auth functions */
462
463         { WINBINDD_PAM_AUTH, winbindd_pam_auth, "PAM_AUTH" },
464         { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap, "AUTH_CRAP" },
465         { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok, "CHAUTHTOK" },
466         { WINBINDD_PAM_LOGOFF, winbindd_pam_logoff, "PAM_LOGOFF" },
467         { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, winbindd_pam_chng_pswd_auth_crap, "CHNG_PSWD_AUTH_CRAP" },
468
469         /* Enumeration functions */
470
471         { WINBINDD_LIST_USERS, winbindd_list_users, "LIST_USERS" },
472         { WINBINDD_LIST_GROUPS, winbindd_list_groups, "LIST_GROUPS" },
473         { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
474           "LIST_TRUSTDOM" },
475         { WINBINDD_SHOW_SEQUENCE, winbindd_show_sequence, "SHOW_SEQUENCE" },
476
477         /* SID related functions */
478
479         { WINBINDD_LOOKUPSID, winbindd_lookupsid, "LOOKUPSID" },
480         { WINBINDD_LOOKUPNAME, winbindd_lookupname, "LOOKUPNAME" },
481         { WINBINDD_LOOKUPRIDS, winbindd_lookuprids, "LOOKUPRIDS" },
482
483         /* Lookup related functions */
484
485         { WINBINDD_SID_TO_UID, winbindd_sid_to_uid, "SID_TO_UID" },
486         { WINBINDD_SID_TO_GID, winbindd_sid_to_gid, "SID_TO_GID" },
487         { WINBINDD_UID_TO_SID, winbindd_uid_to_sid, "UID_TO_SID" },
488         { WINBINDD_GID_TO_SID, winbindd_gid_to_sid, "GID_TO_SID" },
489         { WINBINDD_ALLOCATE_UID, winbindd_allocate_uid, "ALLOCATE_UID" },
490         { WINBINDD_ALLOCATE_GID, winbindd_allocate_gid, "ALLOCATE_GID" },
491
492         /* Miscellaneous */
493
494         { WINBINDD_CHECK_MACHACC, winbindd_check_machine_acct, "CHECK_MACHACC" },
495         { WINBINDD_PING_DC, winbindd_ping_dc, "PING_DC" },
496         { WINBINDD_PING, winbindd_ping, "PING" },
497         { WINBINDD_INFO, winbindd_info, "INFO" },
498         { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
499           "INTERFACE_VERSION" },
500         { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
501         { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
502         { WINBINDD_DC_INFO, winbindd_dc_info, "DC_INFO" },
503         { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
504         { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
505           "WINBINDD_PRIV_PIPE_DIR" },
506         { WINBINDD_GETDCNAME, winbindd_getdcname, "GETDCNAME" },
507         { WINBINDD_DSGETDCNAME, winbindd_dsgetdcname, "DSGETDCNAME" },
508
509         /* Credential cache access */
510         { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
511
512         /* WINS functions */
513
514         { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
515         { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
516
517         /* End of list */
518
519         { WINBINDD_NUM_CMDS, NULL, "NONE" }
520 };
521
522 static void process_request(struct winbindd_cli_state *state)
523 {
524         struct winbindd_dispatch_table *table = dispatch_table;
525
526         /* Free response data - we may be interrupted and receive another
527            command before being able to send this data off. */
528
529         SAFE_FREE(state->response.extra_data.data);  
530
531         ZERO_STRUCT(state->response);
532
533         state->response.result = WINBINDD_PENDING;
534         state->response.length = sizeof(struct winbindd_response);
535
536         state->mem_ctx = talloc_init("winbind request");
537         if (state->mem_ctx == NULL)
538                 return;
539
540         /* Remember who asked us. */
541         state->pid = state->request.pid;
542
543         /* Process command */
544
545         for (table = dispatch_table; table->fn; table++) {
546                 if (state->request.cmd == table->cmd) {
547                         DEBUG(10,("process_request: request fn %s\n",
548                                   table->winbindd_cmd_name ));
549                         table->fn(state);
550                         break;
551                 }
552         }
553
554         if (!table->fn) {
555                 DEBUG(10,("process_request: unknown request fn number %d\n",
556                           (int)state->request.cmd ));
557                 request_error(state);
558         }
559 }
560
561 /*
562  * A list of file descriptors being monitored by select in the main processing
563  * loop. winbindd_fd_event->handler is called whenever the socket is readable/writable.
564  */
565
566 static struct winbindd_fd_event *fd_events = NULL;
567
568 void add_fd_event(struct winbindd_fd_event *ev)
569 {
570         struct winbindd_fd_event *match;
571
572         /* only add unique winbindd_fd_event structs */
573
574         for (match=fd_events; match; match=match->next ) {
575 #ifdef DEVELOPER
576                 SMB_ASSERT( match != ev );
577 #else
578                 if ( match == ev )
579                         return;
580 #endif
581         }
582
583         DLIST_ADD(fd_events, ev);
584 }
585
586 void remove_fd_event(struct winbindd_fd_event *ev)
587 {
588         DLIST_REMOVE(fd_events, ev);
589 }
590
591 /*
592  * Handler for winbindd_fd_events to complete a read/write request, set up by
593  * setup_async_read/setup_async_write.
594  */
595
596 static void rw_callback(struct winbindd_fd_event *event, int flags)
597 {
598         size_t todo;
599         ssize_t done = 0;
600
601         todo = event->length - event->done;
602
603         if (event->flags & EVENT_FD_WRITE) {
604                 SMB_ASSERT(flags == EVENT_FD_WRITE);
605                 done = sys_write(event->fd,
606                                  &((char *)event->data)[event->done],
607                                  todo);
608
609                 if (done <= 0) {
610                         event->flags = 0;
611                         event->finished(event->private_data, False);
612                         return;
613                 }
614         }
615
616         if (event->flags & EVENT_FD_READ) {
617                 SMB_ASSERT(flags == EVENT_FD_READ);
618                 done = sys_read(event->fd, &((char *)event->data)[event->done],
619                                 todo);
620
621                 if (done <= 0) {
622                         event->flags = 0;
623                         event->finished(event->private_data, False);
624                         return;
625                 }
626         }
627
628         event->done += done;
629
630         if (event->done == event->length) {
631                 event->flags = 0;
632                 event->finished(event->private_data, True);
633         }
634 }
635
636 /*
637  * Request an async read/write on a winbindd_fd_event structure. (*finished) is called
638  * when the request is completed or an error had occurred.
639  */
640
641 void setup_async_read(struct winbindd_fd_event *event, void *data, size_t length,
642                       void (*finished)(void *private_data, bool success),
643                       void *private_data)
644 {
645         SMB_ASSERT(event->flags == 0);
646         event->data = data;
647         event->length = length;
648         event->done = 0;
649         event->handler = rw_callback;
650         event->finished = finished;
651         event->private_data = private_data;
652         event->flags = EVENT_FD_READ;
653 }
654
655 void setup_async_write(struct winbindd_fd_event *event, void *data, size_t length,
656                        void (*finished)(void *private_data, bool success),
657                        void *private_data)
658 {
659         SMB_ASSERT(event->flags == 0);
660         event->data = data;
661         event->length = length;
662         event->done = 0;
663         event->handler = rw_callback;
664         event->finished = finished;
665         event->private_data = private_data;
666         event->flags = EVENT_FD_WRITE;
667 }
668
669 /*
670  * This is the main event loop of winbind requests. It goes through a
671  * state-machine of 3 read/write requests, 4 if you have extra data to send.
672  *
673  * An idle winbind client has a read request of 4 bytes outstanding,
674  * finalizing function is request_len_recv, checking the length. request_recv
675  * then processes the packet. The processing function then at some point has
676  * to call request_finished which schedules sending the response.
677  */
678
679 static void request_len_recv(void *private_data, bool success);
680 static void request_recv(void *private_data, bool success);
681 static void request_main_recv(void *private_data, bool success);
682 static void request_finished(struct winbindd_cli_state *state);
683 static void response_main_sent(void *private_data, bool success);
684 static void response_extra_sent(void *private_data, bool success);
685
686 static void response_extra_sent(void *private_data, bool success)
687 {
688         struct winbindd_cli_state *state =
689                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
690
691         TALLOC_FREE(state->mem_ctx);
692
693         if (!success) {
694                 state->finished = True;
695                 return;
696         }
697
698         SAFE_FREE(state->response.extra_data.data);
699
700         setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
701                          request_len_recv, state);
702 }
703
704 static void response_main_sent(void *private_data, bool success)
705 {
706         struct winbindd_cli_state *state =
707                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
708
709         if (!success) {
710                 state->finished = True;
711                 return;
712         }
713
714         if (state->response.length == sizeof(state->response)) {
715                 TALLOC_FREE(state->mem_ctx);
716
717                 setup_async_read(&state->fd_event, &state->request,
718                                  sizeof(uint32), request_len_recv, state);
719                 return;
720         }
721
722         setup_async_write(&state->fd_event, state->response.extra_data.data,
723                           state->response.length - sizeof(state->response),
724                           response_extra_sent, state);
725 }
726
727 static void request_finished(struct winbindd_cli_state *state)
728 {
729         /* Make sure request.extra_data is freed when finish processing a request */
730         SAFE_FREE(state->request.extra_data.data);
731         setup_async_write(&state->fd_event, &state->response,
732                           sizeof(state->response), response_main_sent, state);
733 }
734
735 void request_error(struct winbindd_cli_state *state)
736 {
737         SMB_ASSERT(state->response.result == WINBINDD_PENDING);
738         state->response.result = WINBINDD_ERROR;
739         request_finished(state);
740 }
741
742 void request_ok(struct winbindd_cli_state *state)
743 {
744         SMB_ASSERT(state->response.result == WINBINDD_PENDING);
745         state->response.result = WINBINDD_OK;
746         request_finished(state);
747 }
748
749 static void request_len_recv(void *private_data, bool success)
750 {
751         struct winbindd_cli_state *state =
752                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
753
754         if (!success) {
755                 state->finished = True;
756                 return;
757         }
758
759         if (*(uint32 *)(&state->request) != sizeof(state->request)) {
760                 DEBUG(0,("request_len_recv: Invalid request size received: %d (expected %u)\n",
761                          *(uint32_t *)(&state->request), (uint32_t)sizeof(state->request)));
762                 state->finished = True;
763                 return;
764         }
765
766         setup_async_read(&state->fd_event, (uint32 *)(&state->request)+1,
767                          sizeof(state->request) - sizeof(uint32),
768                          request_main_recv, state);
769 }
770
771 static void request_main_recv(void *private_data, bool success)
772 {
773         struct winbindd_cli_state *state =
774                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
775
776         if (!success) {
777                 state->finished = True;
778                 return;
779         }
780
781         if (state->request.extra_len == 0) {
782                 state->request.extra_data.data = NULL;
783                 request_recv(state, True);
784                 return;
785         }
786
787         if ((!state->privileged) &&
788             (state->request.extra_len > WINBINDD_MAX_EXTRA_DATA)) {
789                 DEBUG(3, ("Got request with %d bytes extra data on "
790                           "unprivileged socket\n", (int)state->request.extra_len));
791                 state->request.extra_data.data = NULL;
792                 state->finished = True;
793                 return;
794         }
795
796         state->request.extra_data.data =
797                 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
798
799         if (state->request.extra_data.data == NULL) {
800                 DEBUG(0, ("malloc failed\n"));
801                 state->finished = True;
802                 return;
803         }
804
805         /* Ensure null termination */
806         state->request.extra_data.data[state->request.extra_len] = '\0';
807
808         setup_async_read(&state->fd_event, state->request.extra_data.data,
809                          state->request.extra_len, request_recv, state);
810 }
811
812 static void request_recv(void *private_data, bool success)
813 {
814         struct winbindd_cli_state *state =
815                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
816
817         if (!success) {
818                 state->finished = True;
819                 return;
820         }
821
822         process_request(state);
823 }
824
825 /* Process a new connection by adding it to the client connection list */
826
827 static void new_connection(int listen_sock, bool privileged)
828 {
829         struct sockaddr_un sunaddr;
830         struct winbindd_cli_state *state;
831         socklen_t len;
832         int sock;
833
834         /* Accept connection */
835
836         len = sizeof(sunaddr);
837
838         do {
839                 sock = accept(listen_sock, (struct sockaddr *)&sunaddr, &len);
840         } while (sock == -1 && errno == EINTR);
841
842         if (sock == -1)
843                 return;
844
845         DEBUG(6,("accepted socket %d\n", sock));
846
847         /* Create new connection structure */
848
849         if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
850                 close(sock);
851                 return;
852         }
853
854         state->sock = sock;
855
856         state->last_access = time(NULL);        
857
858         state->privileged = privileged;
859
860         state->fd_event.fd = state->sock;
861         state->fd_event.flags = 0;
862         add_fd_event(&state->fd_event);
863
864         setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
865                          request_len_recv, state);
866
867         /* Add to connection list */
868
869         winbindd_add_client(state);
870 }
871
872 /* Remove a client connection from client connection list */
873
874 static void remove_client(struct winbindd_cli_state *state)
875 {
876         char c = 0;
877         int nwritten;
878
879         /* It's a dead client - hold a funeral */
880
881         if (state == NULL) {
882                 return;
883         }
884
885         if (!state->finished) {
886                 /* tell client, we are closing ... */
887                 nwritten = write(state->sock, &c, sizeof(c));
888                 if (nwritten == -1) {
889                         DEBUG(2, ("final write to client failed: %s\n",
890                                   strerror(errno)));
891                 }
892         }
893
894         /* Close socket */
895
896         close(state->sock);
897
898         /* Free any getent state */
899
900         free_getent_state(state->getpwent_state);
901         free_getent_state(state->getgrent_state);
902
903         /* We may have some extra data that was not freed if the client was
904            killed unexpectedly */
905
906         SAFE_FREE(state->response.extra_data.data);
907
908         TALLOC_FREE(state->mem_ctx);
909
910         remove_fd_event(&state->fd_event);
911
912         /* Remove from list and free */
913
914         winbindd_remove_client(state);
915         TALLOC_FREE(state);
916 }
917
918 /* Shutdown client connection which has been idle for the longest time */
919
920 static bool remove_idle_client(void)
921 {
922         struct winbindd_cli_state *state, *remove_state = NULL;
923         time_t last_access = 0;
924         int nidle = 0;
925
926         for (state = winbindd_client_list(); state; state = state->next) {
927                 if (state->response.result != WINBINDD_PENDING &&
928                     state->fd_event.flags == EVENT_FD_READ &&
929                     !state->getpwent_state && !state->getgrent_state) {
930                         nidle++;
931                         if (!last_access || state->last_access < last_access) {
932                                 last_access = state->last_access;
933                                 remove_state = state;
934                         }
935                 }
936         }
937
938         if (remove_state) {
939                 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
940                         nidle, remove_state->sock, (unsigned int)remove_state->pid));
941                 remove_client(remove_state);
942                 return True;
943         }
944
945         return False;
946 }
947
948 struct winbindd_listen_state {
949         bool privileged;
950         int fd;
951         struct tevent_fd *fde;
952 };
953
954 static void winbindd_listen_fde_handler(struct tevent_context *ev,
955                                         struct tevent_fd *fde,
956                                         uint16_t flags,
957                                         void *private_data)
958 {
959         struct winbindd_listen_state *s = talloc_get_type_abort(private_data,
960                                           struct winbindd_listen_state);
961
962         while (winbindd_num_clients() >
963                WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
964                 DEBUG(5,("winbindd: Exceeding %d client "
965                          "connections, removing idle "
966                          "connection.\n",
967                          WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
968                 if (!remove_idle_client()) {
969                         DEBUG(0,("winbindd: Exceeding %d "
970                                  "client connections, no idle "
971                                  "connection found\n",
972                                  WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
973                         break;
974                 }
975         }
976
977         /* new, non-privileged connection */
978         new_connection(s->fd, s->privileged);
979 }
980
981 static bool winbindd_setup_listeners(void)
982 {
983         struct winbindd_listen_state *pub_state = NULL;
984         struct winbindd_listen_state *priv_state = NULL;
985
986         pub_state = talloc(winbind_event_context(),
987                            struct winbindd_listen_state);
988         if (!pub_state) {
989                 goto failed;
990         }
991
992         pub_state->privileged = false;
993         pub_state->fd = open_winbindd_socket();
994         if (pub_state->fd == -1) {
995                 goto failed;
996         }
997
998         pub_state->fde = tevent_add_fd(winbind_event_context(),
999                                        pub_state, pub_state->fd,
1000                                        TEVENT_FD_READ,
1001                                        winbindd_listen_fde_handler,
1002                                        pub_state);
1003         if (!pub_state->fde) {
1004                 close(pub_state->fd);
1005                 goto failed;
1006         }
1007         tevent_fd_set_auto_close(pub_state->fde);
1008
1009         priv_state = talloc(winbind_event_context(),
1010                             struct winbindd_listen_state);
1011         if (!priv_state) {
1012                 goto failed;
1013         }
1014
1015         priv_state->privileged = true;
1016         priv_state->fd = open_winbindd_priv_socket();
1017         if (priv_state->fd == -1) {
1018                 goto failed;
1019         }
1020
1021         priv_state->fde = tevent_add_fd(winbind_event_context(),
1022                                         priv_state, priv_state->fd,
1023                                         TEVENT_FD_READ,
1024                                         winbindd_listen_fde_handler,
1025                                         priv_state);
1026         if (!priv_state->fde) {
1027                 close(priv_state->fd);
1028                 goto failed;
1029         }
1030         tevent_fd_set_auto_close(priv_state->fde);
1031
1032         return true;
1033 failed:
1034         TALLOC_FREE(pub_state);
1035         TALLOC_FREE(priv_state);
1036         return false;
1037 }
1038
1039 /* Process incoming clients on listen_sock.  We use a tricky non-blocking,
1040    non-forking, non-threaded model which allows us to handle many
1041    simultaneous connections while remaining impervious to many denial of
1042    service attacks. */
1043
1044 static void process_loop(void)
1045 {
1046         struct winbindd_fd_event *ev;
1047         fd_set r_fds, w_fds;
1048         int maxfd = 0, selret;
1049         struct timeval timeout, ev_timeout;
1050
1051         if (run_events(winbind_event_context(), 0, NULL, NULL)) {
1052                 return;
1053         }
1054
1055         /* Initialise fd lists for select() */
1056
1057         FD_ZERO(&r_fds);
1058         FD_ZERO(&w_fds);
1059
1060         timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
1061         timeout.tv_usec = 0;
1062
1063         /* Check for any event timeouts. */
1064         {
1065                 struct timeval now;
1066                 GetTimeOfDay(&now);
1067
1068                 event_add_to_select_args(winbind_event_context(), &now,
1069                                          &r_fds, &w_fds, &ev_timeout, &maxfd);
1070         }
1071         if (get_timed_events_timeout(winbind_event_context(), &ev_timeout)) {
1072                 timeout = timeval_min(&timeout, &ev_timeout);
1073         }
1074
1075         for (ev = fd_events; ev; ev = ev->next) {
1076                 if (ev->flags & EVENT_FD_READ) {
1077                         FD_SET(ev->fd, &r_fds);
1078                         maxfd = MAX(ev->fd, maxfd);
1079                 }
1080                 if (ev->flags & EVENT_FD_WRITE) {
1081                         FD_SET(ev->fd, &w_fds);
1082                         maxfd = MAX(ev->fd, maxfd);
1083                 }
1084         }
1085
1086         /* Call select */
1087
1088         selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
1089
1090         if (selret == 0) {
1091                 goto no_fds_ready;
1092         }
1093
1094         if (selret == -1) {
1095                 if (errno == EINTR) {
1096                         goto no_fds_ready;
1097                 }
1098
1099                 /* Select error, something is badly wrong */
1100
1101                 perror("select");
1102                 exit(1);
1103         }
1104
1105         /* selret > 0 */
1106
1107         if (run_events(winbind_event_context(), selret, &r_fds, &w_fds)) {
1108                 return;
1109         }
1110
1111         ev = fd_events;
1112         while (ev != NULL) {
1113                 struct winbindd_fd_event *next = ev->next;
1114                 int flags = 0;
1115                 if (FD_ISSET(ev->fd, &r_fds))
1116                         flags |= EVENT_FD_READ;
1117                 if (FD_ISSET(ev->fd, &w_fds))
1118                         flags |= EVENT_FD_WRITE;
1119                 if (flags) {
1120                         ev->handler(ev, flags);
1121                         return;
1122                 }
1123                 ev = next;
1124         }
1125
1126         return;
1127
1128  no_fds_ready:
1129
1130         run_events(winbind_event_context(), selret, &r_fds, &w_fds);
1131
1132 #if 0
1133         winbindd_check_cache_size(time(NULL));
1134 #endif
1135 }
1136
1137 bool winbindd_use_idmap_cache(void)
1138 {
1139         return !opt_nocache;
1140 }
1141
1142 bool winbindd_use_cache(void)
1143 {
1144         return !opt_nocache;
1145 }
1146
1147 struct winbindd_addrchanged_state {
1148         struct addrchange_context *ctx;
1149         struct tevent_context *ev;
1150         struct messaging_context *msg_ctx;
1151 };
1152
1153 static void winbindd_addr_changed(struct tevent_req *req);
1154
1155 static void winbindd_init_addrchange(TALLOC_CTX *mem_ctx,
1156                                      struct tevent_context *ev,
1157                                      struct messaging_context *msg_ctx)
1158 {
1159         struct winbindd_addrchanged_state *state;
1160         struct tevent_req *req;
1161         NTSTATUS status;
1162
1163         state = talloc(mem_ctx, struct winbindd_addrchanged_state);
1164         if (state == NULL) {
1165                 DEBUG(10, ("talloc failed\n"));
1166                 return;
1167         }
1168         state->ev = ev;
1169         state->msg_ctx = msg_ctx;
1170
1171         status = addrchange_context_create(state, &state->ctx);
1172         if (!NT_STATUS_IS_OK(status)) {
1173                 DEBUG(10, ("addrchange_context_create failed: %s\n",
1174                            nt_errstr(status)));
1175                 TALLOC_FREE(state);
1176                 return;
1177         }
1178         req = addrchange_send(state, ev, state->ctx);
1179         if (req == NULL) {
1180                 DEBUG(10, ("addrchange_send failed\n"));
1181                 TALLOC_FREE(state);
1182         }
1183         tevent_req_set_callback(req, winbindd_addr_changed, state);
1184 }
1185
1186 static void winbindd_addr_changed(struct tevent_req *req)
1187 {
1188         struct winbindd_addrchanged_state *state = tevent_req_callback_data(
1189                 req, struct winbindd_addrchanged_state);
1190         enum addrchange_type type;
1191         struct sockaddr_storage addr;
1192         NTSTATUS status;
1193
1194         status = addrchange_recv(req, &type, &addr);
1195         TALLOC_FREE(req);
1196         if (!NT_STATUS_IS_OK(status)) {
1197                 DEBUG(10, ("addrchange_recv failed: %s, stop listening\n",
1198                            nt_errstr(status)));
1199                 TALLOC_FREE(state);
1200         }
1201         if (type == ADDRCHANGE_DEL) {
1202                 char addrstr[INET6_ADDRSTRLEN];
1203                 DATA_BLOB blob;
1204
1205                 print_sockaddr(addrstr, sizeof(addrstr), &addr);
1206
1207                 DEBUG(3, ("winbindd: kernel (AF_NETLINK) dropped ip %s\n",
1208                           addrstr));
1209
1210                 blob = data_blob_const(addrstr, strlen(addrstr)+1);
1211
1212                 status = messaging_send(state->msg_ctx, procid_self(),
1213                                         MSG_WINBIND_IP_DROPPED, &blob);
1214                 if (!NT_STATUS_IS_OK(status)) {
1215                         DEBUG(10, ("messaging_send failed: %s\n",
1216                                    nt_errstr(status)));
1217                 }
1218         }
1219         req = addrchange_send(state, state->ev, state->ctx);
1220         if (req == NULL) {
1221                 DEBUG(10, ("addrchange_send failed\n"));
1222                 TALLOC_FREE(state);
1223         }
1224         tevent_req_set_callback(req, winbindd_addr_changed, state);
1225 }
1226
1227 /* Main function */
1228
1229 int main(int argc, char **argv, char **envp)
1230 {
1231         static bool is_daemon = False;
1232         static bool Fork = True;
1233         static bool log_stdout = False;
1234         static bool no_process_group = False;
1235         enum {
1236                 OPT_DAEMON = 1000,
1237                 OPT_FORK,
1238                 OPT_NO_PROCESS_GROUP,
1239                 OPT_LOG_STDOUT
1240         };
1241         struct poptOption long_options[] = {
1242                 POPT_AUTOHELP
1243                 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1244                 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1245                 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1246                 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1247                 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1248                 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1249                 POPT_COMMON_SAMBA
1250                 POPT_TABLEEND
1251         };
1252         poptContext pc;
1253         int opt;
1254         TALLOC_CTX *frame = talloc_stackframe();
1255
1256         /* glibc (?) likes to print "User defined signal 1" and exit if a
1257            SIGUSR[12] is received before a handler is installed */
1258
1259         CatchSignal(SIGUSR1, SIG_IGN);
1260         CatchSignal(SIGUSR2, SIG_IGN);
1261
1262         fault_setup((void (*)(void *))fault_quit );
1263         dump_core_setup("winbindd");
1264
1265         load_case_tables();
1266
1267         /* Initialise for running in non-root mode */
1268
1269         sec_init();
1270
1271         set_remote_machine_name("winbindd", False);
1272
1273         /* Set environment variable so we don't recursively call ourselves.
1274            This may also be useful interactively. */
1275
1276         if ( !winbind_off() ) {
1277                 DEBUG(0,("Failed to disable recusive winbindd calls.  Exiting.\n"));
1278                 exit(1);
1279         }
1280
1281         /* Initialise samba/rpc client stuff */
1282
1283         pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1284
1285         while ((opt = poptGetNextOpt(pc)) != -1) {
1286                 switch (opt) {
1287                         /* Don't become a daemon */
1288                 case OPT_DAEMON:
1289                         is_daemon = True;
1290                         break;
1291                 case 'i':
1292                         interactive = True;
1293                         log_stdout = True;
1294                         Fork = False;
1295                         break;
1296                 case OPT_FORK:
1297                         Fork = false;
1298                         break;
1299                 case OPT_NO_PROCESS_GROUP:
1300                         no_process_group = true;
1301                         break;
1302                 case OPT_LOG_STDOUT:
1303                         log_stdout = true;
1304                         break;
1305                 case 'n':
1306                         opt_nocache = true;
1307                         break;
1308                 default:
1309                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1310                                   poptBadOption(pc, 0), poptStrerror(opt));
1311                         poptPrintUsage(pc, stderr, 0);
1312                         exit(1);
1313                 }
1314         }
1315
1316         if (is_daemon && interactive) {
1317                 d_fprintf(stderr,"\nERROR: "
1318                           "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1319                 poptPrintUsage(pc, stderr, 0);
1320                 exit(1);
1321         }
1322
1323         if (log_stdout && Fork) {
1324                 d_fprintf(stderr, "\nERROR: "
1325                           "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1326                 poptPrintUsage(pc, stderr, 0);
1327                 exit(1);
1328         }
1329
1330         poptFreeContext(pc);
1331
1332         if (!override_logfile) {
1333                 char *lfile = NULL;
1334                 if (asprintf(&lfile,"%s/log.winbindd",
1335                                 get_dyn_LOGFILEBASE()) > 0) {
1336                         lp_set_logfile(lfile);
1337                         SAFE_FREE(lfile);
1338                 }
1339         }
1340         setup_logging("winbindd", log_stdout);
1341         reopen_logs();
1342
1343         DEBUG(0,("winbindd version %s started.\n", samba_version_string()));
1344         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1345
1346         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1347                 DEBUG(0, ("error opening config file\n"));
1348                 exit(1);
1349         }
1350
1351         /* Initialise messaging system */
1352
1353         if (winbind_messaging_context() == NULL) {
1354                 exit(1);
1355         }
1356
1357         if (!reload_services_file(NULL)) {
1358                 DEBUG(0, ("error opening config file\n"));
1359                 exit(1);
1360         }
1361
1362         if (!directory_exist(lp_lockdir())) {
1363                 mkdir(lp_lockdir(), 0755);
1364         }
1365
1366         /* Setup names. */
1367
1368         if (!init_names())
1369                 exit(1);
1370
1371         load_interfaces();
1372
1373         if (!secrets_init()) {
1374
1375                 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1376                 return False;
1377         }
1378
1379         /* Enable netbios namecache */
1380
1381         namecache_enable();
1382
1383         /* Unblock all signals we are interested in as they may have been
1384            blocked by the parent process. */
1385
1386         BlockSignals(False, SIGINT);
1387         BlockSignals(False, SIGQUIT);
1388         BlockSignals(False, SIGTERM);
1389         BlockSignals(False, SIGUSR1);
1390         BlockSignals(False, SIGUSR2);
1391         BlockSignals(False, SIGHUP);
1392         BlockSignals(False, SIGCHLD);
1393         BlockSignals(False, SIGXCPU);
1394
1395         if (!interactive)
1396                 become_daemon(Fork, no_process_group);
1397
1398         pidfile_create("winbindd");
1399
1400 #if HAVE_SETPGID
1401         /*
1402          * If we're interactive we want to set our own process group for
1403          * signal management.
1404          */
1405         if (interactive && !no_process_group)
1406                 setpgid( (pid_t)0, (pid_t)0);
1407 #endif
1408
1409         TimeInit();
1410
1411         /* Don't use winbindd_reinit_after_fork here as
1412          * we're just starting up and haven't created any
1413          * winbindd-specific resources we must free yet. JRA.
1414          */
1415
1416         if (!NT_STATUS_IS_OK(reinit_after_fork(winbind_messaging_context(),
1417                                                winbind_event_context(),
1418                                                false))) {
1419                 DEBUG(0,("reinit_after_fork() failed\n"));
1420                 exit(1);
1421         }
1422
1423         /* Setup signal handlers */
1424
1425         if (!winbindd_setup_sig_term_handler(true))
1426                 exit(1);
1427         if (!winbindd_setup_sig_hup_handler(NULL))
1428                 exit(1);
1429         if (!winbindd_setup_sig_chld_handler())
1430                 exit(1);
1431         if (!winbindd_setup_sig_usr2_handler())
1432                 exit(1);
1433
1434         CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
1435
1436         /*
1437          * Ensure all cache and idmap caches are consistent
1438          * and initialized before we startup.
1439          */
1440         if (!winbindd_cache_validate_and_initialize()) {
1441                 exit(1);
1442         }
1443
1444         /* get broadcast messages */
1445
1446         if (!serverid_register(procid_self(),
1447                                FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP)) {
1448                 DEBUG(1, ("Could not register myself in serverid.tdb\n"));
1449                 exit(1);
1450         }
1451
1452         /* React on 'smbcontrol winbindd reload-config' in the same way
1453            as to SIGHUP signal */
1454         messaging_register(winbind_messaging_context(), NULL,
1455                            MSG_SMB_CONF_UPDATED, msg_reload_services);
1456         messaging_register(winbind_messaging_context(), NULL,
1457                            MSG_SHUTDOWN, msg_shutdown);
1458
1459         /* Handle online/offline messages. */
1460         messaging_register(winbind_messaging_context(), NULL,
1461                            MSG_WINBIND_OFFLINE, winbind_msg_offline);
1462         messaging_register(winbind_messaging_context(), NULL,
1463                            MSG_WINBIND_ONLINE, winbind_msg_online);
1464         messaging_register(winbind_messaging_context(), NULL,
1465                            MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1466
1467         messaging_register(winbind_messaging_context(), NULL,
1468                            MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1469
1470         messaging_register(winbind_messaging_context(), NULL,
1471                            MSG_WINBIND_VALIDATE_CACHE,
1472                            winbind_msg_validate_cache);
1473
1474         messaging_register(winbind_messaging_context(), NULL,
1475                            MSG_WINBIND_DUMP_DOMAIN_LIST,
1476                            winbind_msg_dump_domain_list);
1477
1478         messaging_register(winbind_messaging_context(), NULL,
1479                            MSG_WINBIND_IP_DROPPED,
1480                            winbind_msg_ip_dropped_parent);
1481
1482         /* Register handler for MSG_DEBUG. */
1483         messaging_register(winbind_messaging_context(), NULL,
1484                            MSG_DEBUG,
1485                            winbind_msg_debug);
1486
1487         netsamlogon_cache_init(); /* Non-critical */
1488
1489         /* clear the cached list of trusted domains */
1490
1491         wcache_tdc_clear();     
1492
1493         if (!init_domain_list()) {
1494                 DEBUG(0,("unable to initialize domain list\n"));
1495                 exit(1);
1496         }
1497
1498         init_idmap_child();
1499         init_locator_child();
1500
1501         smb_nscd_flush_user_cache();
1502         smb_nscd_flush_group_cache();
1503
1504         winbindd_init_addrchange(NULL, winbind_event_context(),
1505                                  winbind_messaging_context());
1506
1507         /* setup listen sockets */
1508
1509         if (!winbindd_setup_listeners()) {
1510                 DEBUG(0,("winbindd_setup_listeners() failed\n"));
1511                 exit(1);
1512         }
1513
1514         TALLOC_FREE(frame);
1515         /* Loop waiting for requests */
1516         while (1) {
1517                 struct winbindd_cli_state *state;
1518
1519                 frame = talloc_stackframe();
1520
1521                 /* refresh the trusted domain cache */
1522
1523                 rescan_trusted_domains();
1524
1525                 /* Dispose of client connection if it is marked as
1526                    finished */
1527                 state = winbindd_client_list();
1528                 while (state) {
1529                         struct winbindd_cli_state *next = state->next;
1530
1531                         if (state->finished) {
1532                                 remove_client(state);
1533                         }
1534
1535                         state = next;
1536                 }
1537
1538                 process_loop();
1539
1540                 TALLOC_FREE(frame);
1541         }
1542
1543         return 0;
1544 }