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