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