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