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