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