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