s3compat-only s3:winbindd Move more parts of winbindd.c into winbindd_event.c
[abartlet/samba.git/.git] / source3 / winbindd / winbindd.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind daemon for ntdom nss module
5
6    Copyright (C) by Tim Potter 2000-2002
7    Copyright (C) Andrew Tridgell 2002
8    Copyright (C) Jelmer Vernooij 2003
9    Copyright (C) Volker Lendecke 2004
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26 #include "popt_common.h"
27 #include "winbindd.h"
28 #include "nsswitch/winbind_client.h"
29 #include "../../nsswitch/libwbclient/wbc_async.h"
30 #include "librpc/gen_ndr/messaging.h"
31 #include "../librpc/gen_ndr/srv_lsa.h"
32 #include "../librpc/gen_ndr/srv_samr.h"
33 #include "secrets.h"
34 #include "idmap.h"
35
36 #undef DBGC_CLASS
37 #define DBGC_CLASS DBGC_WINBIND
38
39 static bool opt_nocache = False;
40 static bool interactive = False;
41
42 extern bool override_logfile;
43
44 /* Reload configuration */
45
46 static bool reload_services_file(const char *lfile)
47 {
48         bool ret;
49
50         if (lp_loaded()) {
51                 const char *fname = lp_configfile();
52
53                 if (file_exist(fname) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
54                         set_dyn_CONFIGFILE(fname);
55                 }
56         }
57
58         /* if this is a child, restore the logfile to the special
59            name - <domain>, idmap, etc. */
60         if (lfile && *lfile) {
61                 lp_set_logfile(lfile);
62         }
63
64         reopen_logs();
65         ret = lp_load(get_dyn_CONFIGFILE(),False,False,True,True);
66
67         reopen_logs();
68         load_interfaces();
69
70         return(ret);
71 }
72
73
74 /**************************************************************************** **
75  Handle a fault..
76  **************************************************************************** */
77
78 static void fault_quit(void)
79 {
80         dump_core();
81 }
82
83 static void winbindd_status(void)
84 {
85         struct winbindd_cli_state *tmp;
86
87         DEBUG(0, ("winbindd status:\n"));
88
89         /* Print client state information */
90
91         DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
92
93         if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
94                 DEBUG(2, ("\tclient list:\n"));
95                 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
96                         DEBUGADD(2, ("\t\tpid %lu, sock %d (%s)\n",
97                                      (unsigned long)tmp->pid, tmp->sock,
98                                      client_is_idle(tmp) ? "idle" : "active"));
99                 }
100         }
101 }
102
103 /* Flush client cache */
104
105 static void flush_caches(void)
106 {
107         /* We need to invalidate cached user list entries on a SIGHUP 
108            otherwise cached access denied errors due to restrict anonymous
109            hang around until the sequence number changes. */
110
111         if (!wcache_invalidate_cache()) {
112                 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
113                 if (!winbindd_cache_validate_and_initialize()) {
114                         exit(1);
115                 }
116         }
117 }
118
119 static void flush_caches_noinit(void)
120 {
121         /*
122          * We need to invalidate cached user list entries on a SIGHUP
123          * otherwise cached access denied errors due to restrict anonymous
124          * hang around until the sequence number changes.
125          * NB
126          * Skip uninitialized domains when flush cache.
127          * If domain is not initialized, it means it is never
128          * used or never become online. look, wcache_invalidate_cache()
129          * -> get_cache() -> init_dc_connection(). It causes a lot of traffic
130          * for unused domains and large traffic for primay domain's DC if there
131          * are many domains..
132          */
133
134         if (!wcache_invalidate_cache_noinit()) {
135                 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
136                 if (!winbindd_cache_validate_and_initialize()) {
137                         exit(1);
138                 }
139         }
140 }
141
142 /* Handle the signal by unlinking socket and exiting */
143
144 static void terminate(bool is_parent)
145 {
146         if (is_parent) {
147                 /* When parent goes away we should
148                  * remove the socket file. Not so
149                  * when children terminate.
150                  */ 
151                 char *path = NULL;
152
153                 if (asprintf(&path, "%s/%s",
154                         get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME) > 0) {
155                         unlink(path);
156                         SAFE_FREE(path);
157                 }
158         }
159
160         idmap_close();
161
162         trustdom_cache_shutdown();
163
164         gencache_stabilize();
165
166 #if 0
167         if (interactive) {
168                 TALLOC_CTX *mem_ctx = talloc_init("end_description");
169                 char *description = talloc_describe_all(mem_ctx);
170
171                 DEBUG(3, ("tallocs left:\n%s\n", description));
172                 talloc_destroy(mem_ctx);
173         }
174 #endif
175
176         if (is_parent) {
177                 serverid_deregister(procid_self());
178                 pidfile_unlink();
179         }
180
181         exit(0);
182 }
183
184 static void winbindd_sig_term_handler(struct tevent_context *ev,
185                                       struct tevent_signal *se,
186                                       int signum,
187                                       int count,
188                                       void *siginfo,
189                                       void *private_data)
190 {
191         bool *is_parent = talloc_get_type_abort(private_data, bool);
192
193         DEBUG(0,("Got sig[%d] terminate (is_parent=%d)\n",
194                  signum, (int)*is_parent));
195         terminate(*is_parent);
196 }
197
198 bool winbindd_setup_sig_term_handler(bool parent)
199 {
200         struct tevent_signal *se;
201         bool *is_parent;
202
203         is_parent = talloc(winbind_event_context(), bool);
204         if (!is_parent) {
205                 return false;
206         }
207
208         *is_parent = parent;
209
210         se = tevent_add_signal(winbind_event_context(),
211                                is_parent,
212                                SIGTERM, 0,
213                                winbindd_sig_term_handler,
214                                is_parent);
215         if (!se) {
216                 DEBUG(0,("failed to setup SIGTERM handler"));
217                 talloc_free(is_parent);
218                 return false;
219         }
220
221         se = tevent_add_signal(winbind_event_context(),
222                                is_parent,
223                                SIGINT, 0,
224                                winbindd_sig_term_handler,
225                                is_parent);
226         if (!se) {
227                 DEBUG(0,("failed to setup SIGINT handler"));
228                 talloc_free(is_parent);
229                 return false;
230         }
231
232         se = tevent_add_signal(winbind_event_context(),
233                                is_parent,
234                                SIGQUIT, 0,
235                                winbindd_sig_term_handler,
236                                is_parent);
237         if (!se) {
238                 DEBUG(0,("failed to setup SIGINT handler"));
239                 talloc_free(is_parent);
240                 return false;
241         }
242
243         return true;
244 }
245
246 static void winbindd_sig_hup_handler(struct tevent_context *ev,
247                                      struct tevent_signal *se,
248                                      int signum,
249                                      int count,
250                                      void *siginfo,
251                                      void *private_data)
252 {
253         const char *file = (const char *)private_data;
254
255         DEBUG(1,("Reloading services after SIGHUP\n"));
256         flush_caches_noinit();
257         reload_services_file(file);
258 }
259
260 bool winbindd_setup_sig_hup_handler(const char *lfile)
261 {
262         struct tevent_signal *se;
263         char *file = NULL;
264
265         if (lfile) {
266                 file = talloc_strdup(winbind_event_context(),
267                                      lfile);
268                 if (!file) {
269                         return false;
270                 }
271         }
272
273         se = tevent_add_signal(winbind_event_context(),
274                                winbind_event_context(),
275                                SIGHUP, 0,
276                                winbindd_sig_hup_handler,
277                                file);
278         if (!se) {
279                 return false;
280         }
281
282         return true;
283 }
284
285 static void winbindd_sig_chld_handler(struct tevent_context *ev,
286                                       struct tevent_signal *se,
287                                       int signum,
288                                       int count,
289                                       void *siginfo,
290                                       void *private_data)
291 {
292         pid_t pid;
293
294         while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
295                 winbind_child_died(pid);
296         }
297 }
298
299 static bool winbindd_setup_sig_chld_handler(void)
300 {
301         struct tevent_signal *se;
302
303         se = tevent_add_signal(winbind_event_context(),
304                                winbind_event_context(),
305                                SIGCHLD, 0,
306                                winbindd_sig_chld_handler,
307                                NULL);
308         if (!se) {
309                 return false;
310         }
311
312         return true;
313 }
314
315 static void winbindd_sig_usr2_handler(struct tevent_context *ev,
316                                       struct tevent_signal *se,
317                                       int signum,
318                                       int count,
319                                       void *siginfo,
320                                       void *private_data)
321 {
322         winbindd_status();
323 }
324
325 static bool winbindd_setup_sig_usr2_handler(void)
326 {
327         struct tevent_signal *se;
328
329         se = tevent_add_signal(winbind_event_context(),
330                                winbind_event_context(),
331                                SIGUSR2, 0,
332                                winbindd_sig_usr2_handler,
333                                NULL);
334         if (!se) {
335                 return false;
336         }
337
338         return true;
339 }
340
341 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
342 static void msg_reload_services(struct messaging_context *msg,
343                                 void *private_data,
344                                 uint32_t msg_type,
345                                 struct server_id server_id,
346                                 DATA_BLOB *data)
347 {
348         /* Flush various caches */
349         flush_caches();
350         reload_services_file((const char *) private_data);
351 }
352
353 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
354 static void msg_shutdown(struct messaging_context *msg,
355                          void *private_data,
356                          uint32_t msg_type,
357                          struct server_id server_id,
358                          DATA_BLOB *data)
359 {
360         /* only the parent waits for this message */
361         DEBUG(0,("Got shutdown message\n"));
362         terminate(true);
363 }
364
365
366 static void winbind_msg_validate_cache(struct messaging_context *msg_ctx,
367                                        void *private_data,
368                                        uint32_t msg_type,
369                                        struct server_id server_id,
370                                        DATA_BLOB *data)
371 {
372         uint8 ret;
373         pid_t child_pid;
374
375         DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
376                    "message.\n"));
377
378         /*
379          * call the validation code from a child:
380          * so we don't block the main winbindd and the validation
381          * code can safely use fork/waitpid...
382          */
383         child_pid = sys_fork();
384
385         if (child_pid == -1) {
386                 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
387                           strerror(errno)));
388                 return;
389         }
390
391         if (child_pid != 0) {
392                 /* parent */
393                 DEBUG(5, ("winbind_msg_validate_cache: child created with "
394                           "pid %d.\n", (int)child_pid));
395                 return;
396         }
397
398         /* child */
399
400         if (!winbindd_reinit_after_fork(NULL)) {
401                 _exit(0);
402         }
403
404         /* install default SIGCHLD handler: validation code uses fork/waitpid */
405         CatchSignal(SIGCHLD, SIG_DFL);
406
407         ret = (uint8)winbindd_validate_cache_nobackup();
408         DEBUG(10, ("winbindd_msg_validata_cache: got return value %d\n", ret));
409         messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_VALIDATE_CACHE, &ret,
410                            (size_t)1);
411         _exit(0);
412 }
413
414 static struct winbindd_dispatch_table {
415         enum winbindd_cmd cmd;
416         void (*fn)(struct winbindd_cli_state *state);
417         const char *winbindd_cmd_name;
418 } dispatch_table[] = {
419
420         /* Enumeration functions */
421
422         { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
423           "LIST_TRUSTDOM" },
424
425         /* Miscellaneous */
426
427         { WINBINDD_INFO, winbindd_info, "INFO" },
428         { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
429           "INTERFACE_VERSION" },
430         { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
431         { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
432         { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
433         { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
434           "WINBINDD_PRIV_PIPE_DIR" },
435
436         /* Credential cache access */
437         { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
438         { WINBINDD_CCACHE_SAVE, winbindd_ccache_save, "CCACHE_SAVE" },
439
440         /* WINS functions */
441
442         { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
443         { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
444
445         /* End of list */
446
447         { WINBINDD_NUM_CMDS, NULL, "NONE" }
448 };
449
450 struct winbindd_async_dispatch_table {
451         enum winbindd_cmd cmd;
452         const char *cmd_name;
453         struct tevent_req *(*send_req)(TALLOC_CTX *mem_ctx,
454                                        struct tevent_context *ev,
455                                        struct winbindd_cli_state *cli,
456                                        struct winbindd_request *request);
457         NTSTATUS (*recv_req)(struct tevent_req *req,
458                              struct winbindd_response *presp);
459 };
460
461 static struct winbindd_async_dispatch_table async_nonpriv_table[] = {
462         { WINBINDD_PING, "PING",
463           wb_ping_send, wb_ping_recv },
464         { WINBINDD_LOOKUPSID, "LOOKUPSID",
465           winbindd_lookupsid_send, winbindd_lookupsid_recv },
466         { WINBINDD_LOOKUPNAME, "LOOKUPNAME",
467           winbindd_lookupname_send, winbindd_lookupname_recv },
468         { WINBINDD_SID_TO_UID, "SID_TO_UID",
469           winbindd_sid_to_uid_send, winbindd_sid_to_uid_recv },
470         { WINBINDD_SID_TO_GID, "SID_TO_GID",
471           winbindd_sid_to_gid_send, winbindd_sid_to_gid_recv },
472         { WINBINDD_UID_TO_SID, "UID_TO_SID",
473           winbindd_uid_to_sid_send, winbindd_uid_to_sid_recv },
474         { WINBINDD_GID_TO_SID, "GID_TO_SID",
475           winbindd_gid_to_sid_send, winbindd_gid_to_sid_recv },
476         { WINBINDD_GETPWSID, "GETPWSID",
477           winbindd_getpwsid_send, winbindd_getpwsid_recv },
478         { WINBINDD_GETPWNAM, "GETPWNAM",
479           winbindd_getpwnam_send, winbindd_getpwnam_recv },
480         { WINBINDD_GETPWUID, "GETPWUID",
481           winbindd_getpwuid_send, winbindd_getpwuid_recv },
482         { WINBINDD_GETSIDALIASES, "GETSIDALIASES",
483           winbindd_getsidaliases_send, winbindd_getsidaliases_recv },
484         { WINBINDD_GETUSERDOMGROUPS, "GETUSERDOMGROUPS",
485           winbindd_getuserdomgroups_send, winbindd_getuserdomgroups_recv },
486         { WINBINDD_GETGROUPS, "GETGROUPS",
487           winbindd_getgroups_send, winbindd_getgroups_recv },
488         { WINBINDD_SHOW_SEQUENCE, "SHOW_SEQUENCE",
489           winbindd_show_sequence_send, winbindd_show_sequence_recv },
490         { WINBINDD_GETGRGID, "GETGRGID",
491           winbindd_getgrgid_send, winbindd_getgrgid_recv },
492         { WINBINDD_GETGRNAM, "GETGRNAM",
493           winbindd_getgrnam_send, winbindd_getgrnam_recv },
494         { WINBINDD_GETUSERSIDS, "GETUSERSIDS",
495           winbindd_getusersids_send, winbindd_getusersids_recv },
496         { WINBINDD_LOOKUPRIDS, "LOOKUPRIDS",
497           winbindd_lookuprids_send, winbindd_lookuprids_recv },
498         { WINBINDD_SETPWENT, "SETPWENT",
499           winbindd_setpwent_send, winbindd_setpwent_recv },
500         { WINBINDD_GETPWENT, "GETPWENT",
501           winbindd_getpwent_send, winbindd_getpwent_recv },
502         { WINBINDD_ENDPWENT, "ENDPWENT",
503           winbindd_endpwent_send, winbindd_endpwent_recv },
504         { WINBINDD_DSGETDCNAME, "DSGETDCNAME",
505           winbindd_dsgetdcname_send, winbindd_dsgetdcname_recv },
506         { WINBINDD_GETDCNAME, "GETDCNAME",
507           winbindd_getdcname_send, winbindd_getdcname_recv },
508         { WINBINDD_SETGRENT, "SETGRENT",
509           winbindd_setgrent_send, winbindd_setgrent_recv },
510         { WINBINDD_GETGRENT, "GETGRENT",
511           winbindd_getgrent_send, winbindd_getgrent_recv },
512         { WINBINDD_ENDGRENT, "ENDGRENT",
513           winbindd_endgrent_send, winbindd_endgrent_recv },
514         { WINBINDD_LIST_USERS, "LIST_USERS",
515           winbindd_list_users_send, winbindd_list_users_recv },
516         { WINBINDD_LIST_GROUPS, "LIST_GROUPS",
517           winbindd_list_groups_send, winbindd_list_groups_recv },
518         { WINBINDD_CHECK_MACHACC, "CHECK_MACHACC",
519           winbindd_check_machine_acct_send, winbindd_check_machine_acct_recv },
520         { WINBINDD_PING_DC, "PING_DC",
521           winbindd_ping_dc_send, winbindd_ping_dc_recv },
522         { WINBINDD_PAM_AUTH, "PAM_AUTH",
523           winbindd_pam_auth_send, winbindd_pam_auth_recv },
524         { WINBINDD_PAM_LOGOFF, "PAM_LOGOFF",
525           winbindd_pam_logoff_send, winbindd_pam_logoff_recv },
526         { WINBINDD_PAM_CHAUTHTOK, "PAM_CHAUTHTOK",
527           winbindd_pam_chauthtok_send, winbindd_pam_chauthtok_recv },
528         { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, "PAM_CHNG_PSWD_AUTH_CRAP",
529           winbindd_pam_chng_pswd_auth_crap_send,
530           winbindd_pam_chng_pswd_auth_crap_recv },
531
532         { 0, NULL, NULL, NULL }
533 };
534
535 static struct winbindd_async_dispatch_table async_priv_table[] = {
536         { WINBINDD_ALLOCATE_UID, "ALLOCATE_UID",
537           winbindd_allocate_uid_send, winbindd_allocate_uid_recv },
538         { WINBINDD_ALLOCATE_GID, "ALLOCATE_GID",
539           winbindd_allocate_gid_send, winbindd_allocate_gid_recv },
540         { WINBINDD_CHANGE_MACHACC, "CHANGE_MACHACC",
541           winbindd_change_machine_acct_send, winbindd_change_machine_acct_recv },
542         { WINBINDD_PAM_AUTH_CRAP, "PAM_AUTH_CRAP",
543           winbindd_pam_auth_crap_send, winbindd_pam_auth_crap_recv },
544
545         { 0, NULL, NULL, NULL }
546 };
547
548 static void wb_request_done(struct tevent_req *req);
549
550 void wb_process_request(struct winbindd_cli_state *state)
551 {
552         struct winbindd_dispatch_table *table = dispatch_table;
553         struct winbindd_async_dispatch_table *atable;
554
555         state->mem_ctx = talloc_named(state, 0, "winbind request");
556         if (state->mem_ctx == NULL)
557                 return;
558
559         /* Remember who asked us. */
560         state->pid = state->request->pid;
561
562         state->cmd_name = "unknown request";
563         state->recv_fn = NULL;
564
565         /* Process command */
566
567         for (atable = async_nonpriv_table; atable->send_req; atable += 1) {
568                 if (state->request->cmd == atable->cmd) {
569                         break;
570                 }
571         }
572
573         if ((atable->send_req == NULL) && state->privileged) {
574                 for (atable = async_priv_table; atable->send_req;
575                      atable += 1) {
576                         if (state->request->cmd == atable->cmd) {
577                                 break;
578                         }
579                 }
580         }
581
582         if (atable->send_req != NULL) {
583                 struct tevent_req *req;
584
585                 state->cmd_name = atable->cmd_name;
586                 state->recv_fn = atable->recv_req;
587
588                 DEBUG(10, ("wb_process_request: Handling async request %d:%s\n",
589                            (int)state->pid, state->cmd_name));
590
591                 req = atable->send_req(state->mem_ctx, winbind_event_context(),
592                                        state, state->request);
593                 if (req == NULL) {
594                         DEBUG(0, ("wb_process_request: atable->send failed for "
595                                   "%s\n", atable->cmd_name));
596                         request_error(state);
597                         return;
598                 }
599                 tevent_req_set_callback(req, wb_request_done, state);
600                 return;
601         }
602
603         state->response = talloc_zero(state->mem_ctx,
604                                       struct winbindd_response);
605         if (state->response == NULL) {
606                 DEBUG(10, ("talloc failed\n"));
607                 winbindd_remove_client(state);
608                 return;
609         }
610         state->response->result = WINBINDD_PENDING;
611         state->response->length = sizeof(struct winbindd_response);
612
613         for (table = dispatch_table; table->fn; table++) {
614                 if (state->request->cmd == table->cmd) {
615                         DEBUG(10,("wb_process_request: request fn %s\n",
616                                   table->winbindd_cmd_name ));
617                         state->cmd_name = table->winbindd_cmd_name;
618                         table->fn(state);
619                         break;
620                 }
621         }
622
623         if (!table->fn) {
624                 DEBUG(10,("wb_process_request: unknown request fn number %d\n",
625                           (int)state->request->cmd ));
626                 request_error(state);
627         }
628 }
629
630 static void wb_request_done(struct tevent_req *req)
631 {
632         struct winbindd_cli_state *state = tevent_req_callback_data(
633                 req, struct winbindd_cli_state);
634         NTSTATUS status;
635
636         state->response = talloc_zero(state->mem_ctx,
637                                       struct winbindd_response);
638         if (state->response == NULL) {
639                 DEBUG(0, ("wb_request_done[%d:%s]: talloc_zero failed - removing client\n",
640                           (int)state->pid, state->cmd_name));
641                 winbindd_remove_client(state);
642                 return;
643         }
644         state->response->result = WINBINDD_PENDING;
645         state->response->length = sizeof(struct winbindd_response);
646
647         status = state->recv_fn(req, state->response);
648         TALLOC_FREE(req);
649
650         DEBUG(10,("wb_request_done[%d:%s]: %s\n",
651                   (int)state->pid, state->cmd_name, nt_errstr(status)));
652
653         if (!NT_STATUS_IS_OK(status)) {
654                 request_error(state);
655                 return;
656         }
657         request_ok(state);
658 }
659
660 void request_error(struct winbindd_cli_state *state)
661 {
662         SMB_ASSERT(state->response->result == WINBINDD_PENDING);
663         state->response->result = WINBINDD_ERROR;
664         request_finished(state);
665 }
666
667 void request_ok(struct winbindd_cli_state *state)
668 {
669         SMB_ASSERT(state->response->result == WINBINDD_PENDING);
670         state->response->result = WINBINDD_OK;
671         request_finished(state);
672 }
673
674 bool winbindd_use_idmap_cache(void)
675 {
676         return !opt_nocache;
677 }
678
679 bool winbindd_use_cache(void)
680 {
681         return !opt_nocache;
682 }
683
684 void winbindd_register_handlers(void)
685 {
686         struct tevent_timer *te;
687         /* Setup signal handlers */
688
689         if (!winbindd_setup_sig_term_handler(true))
690                 exit(1);
691         if (!winbindd_setup_sig_hup_handler(NULL))
692                 exit(1);
693         if (!winbindd_setup_sig_chld_handler())
694                 exit(1);
695         if (!winbindd_setup_sig_usr2_handler())
696                 exit(1);
697
698         CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
699
700         /*
701          * Ensure all cache and idmap caches are consistent
702          * and initialized before we startup.
703          */
704         if (!winbindd_cache_validate_and_initialize()) {
705                 exit(1);
706         }
707
708         /* get broadcast messages */
709
710         if (!serverid_register(procid_self(),
711                                FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP)) {
712                 DEBUG(1, ("Could not register myself in serverid.tdb\n"));
713                 exit(1);
714         }
715
716         /* React on 'smbcontrol winbindd reload-config' in the same way
717            as to SIGHUP signal */
718         messaging_register(winbind_messaging_context(), NULL,
719                            MSG_SMB_CONF_UPDATED, msg_reload_services);
720         messaging_register(winbind_messaging_context(), NULL,
721                            MSG_SHUTDOWN, msg_shutdown);
722
723         /* Handle online/offline messages. */
724         messaging_register(winbind_messaging_context(), NULL,
725                            MSG_WINBIND_OFFLINE, winbind_msg_offline);
726         messaging_register(winbind_messaging_context(), NULL,
727                            MSG_WINBIND_ONLINE, winbind_msg_online);
728         messaging_register(winbind_messaging_context(), NULL,
729                            MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
730
731         messaging_register(winbind_messaging_context(), NULL,
732                            MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
733
734         messaging_register(winbind_messaging_context(), NULL,
735                            MSG_WINBIND_VALIDATE_CACHE,
736                            winbind_msg_validate_cache);
737
738         messaging_register(winbind_messaging_context(), NULL,
739                            MSG_WINBIND_DUMP_DOMAIN_LIST,
740                            winbind_msg_dump_domain_list);
741
742         /* Register handler for MSG_DEBUG. */
743         messaging_register(winbind_messaging_context(), NULL,
744                            MSG_DEBUG,
745                            winbind_msg_debug);
746
747         netsamlogon_cache_init(); /* Non-critical */
748
749         /* clear the cached list of trusted domains */
750
751         wcache_tdc_clear();
752
753         if (!init_domain_list()) {
754                 DEBUG(0,("unable to initialize domain list\n"));
755                 exit(1);
756         }
757
758         init_idmap_child();
759         init_locator_child();
760
761         smb_nscd_flush_user_cache();
762         smb_nscd_flush_group_cache();
763
764         te = tevent_add_timer(winbind_event_context(), NULL, timeval_zero(),
765                               rescan_trusted_domains, NULL);
766         if (te == NULL) {
767                 DEBUG(0, ("Could not trigger rescan_trusted_domains()\n"));
768                 exit(1);
769         }
770
771 }
772
773 /* Main function */
774
775 int main(int argc, char **argv, char **envp)
776 {
777         static bool is_daemon = False;
778         static bool Fork = True;
779         static bool log_stdout = False;
780         static bool no_process_group = False;
781         enum {
782                 OPT_DAEMON = 1000,
783                 OPT_FORK,
784                 OPT_NO_PROCESS_GROUP,
785                 OPT_LOG_STDOUT
786         };
787         struct poptOption long_options[] = {
788                 POPT_AUTOHELP
789                 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
790                 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
791                 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
792                 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
793                 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
794                 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
795                 POPT_COMMON_SAMBA
796                 POPT_TABLEEND
797         };
798         poptContext pc;
799         int opt;
800         TALLOC_CTX *frame = talloc_stackframe();
801         NTSTATUS status;
802
803         /* glibc (?) likes to print "User defined signal 1" and exit if a
804            SIGUSR[12] is received before a handler is installed */
805
806         CatchSignal(SIGUSR1, SIG_IGN);
807         CatchSignal(SIGUSR2, SIG_IGN);
808
809         fault_setup((void (*)(void *))fault_quit );
810         dump_core_setup("winbindd");
811
812         load_case_tables();
813
814         /* Initialise for running in non-root mode */
815
816         sec_init();
817
818         set_remote_machine_name("winbindd", False);
819
820         /* Set environment variable so we don't recursively call ourselves.
821            This may also be useful interactively. */
822
823         if ( !winbind_off() ) {
824                 DEBUG(0,("Failed to disable recusive winbindd calls.  Exiting.\n"));
825                 exit(1);
826         }
827
828         /* Initialise samba/rpc client stuff */
829
830         pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
831
832         while ((opt = poptGetNextOpt(pc)) != -1) {
833                 switch (opt) {
834                         /* Don't become a daemon */
835                 case OPT_DAEMON:
836                         is_daemon = True;
837                         break;
838                 case 'i':
839                         interactive = True;
840                         log_stdout = True;
841                         Fork = False;
842                         break;
843                 case OPT_FORK:
844                         Fork = false;
845                         break;
846                 case OPT_NO_PROCESS_GROUP:
847                         no_process_group = true;
848                         break;
849                 case OPT_LOG_STDOUT:
850                         log_stdout = true;
851                         break;
852                 case 'n':
853                         opt_nocache = true;
854                         break;
855                 default:
856                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
857                                   poptBadOption(pc, 0), poptStrerror(opt));
858                         poptPrintUsage(pc, stderr, 0);
859                         exit(1);
860                 }
861         }
862
863         if (is_daemon && interactive) {
864                 d_fprintf(stderr,"\nERROR: "
865                           "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
866                 poptPrintUsage(pc, stderr, 0);
867                 exit(1);
868         }
869
870         if (log_stdout && Fork) {
871                 d_fprintf(stderr, "\nERROR: "
872                           "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
873                 poptPrintUsage(pc, stderr, 0);
874                 exit(1);
875         }
876
877         poptFreeContext(pc);
878
879         if (!override_logfile) {
880                 char *lfile = NULL;
881                 if (asprintf(&lfile,"%s/log.winbindd",
882                                 get_dyn_LOGFILEBASE()) > 0) {
883                         lp_set_logfile(lfile);
884                         SAFE_FREE(lfile);
885                 }
886         }
887         setup_logging("winbindd", log_stdout);
888         reopen_logs();
889
890         DEBUG(0,("winbindd version %s started.\n", samba_version_string()));
891         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
892
893         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
894                 DEBUG(0, ("error opening config file\n"));
895                 exit(1);
896         }
897
898         /* Initialise messaging system */
899
900         if (winbind_messaging_context() == NULL) {
901                 exit(1);
902         }
903
904         if (!reload_services_file(NULL)) {
905                 DEBUG(0, ("error opening config file\n"));
906                 exit(1);
907         }
908
909         if (!directory_exist(lp_lockdir())) {
910                 mkdir(lp_lockdir(), 0755);
911         }
912
913         /* Setup names. */
914
915         if (!init_names())
916                 exit(1);
917
918         load_interfaces();
919
920         if (!secrets_init()) {
921
922                 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
923                 return False;
924         }
925
926         /* Unblock all signals we are interested in as they may have been
927            blocked by the parent process. */
928
929         BlockSignals(False, SIGINT);
930         BlockSignals(False, SIGQUIT);
931         BlockSignals(False, SIGTERM);
932         BlockSignals(False, SIGUSR1);
933         BlockSignals(False, SIGUSR2);
934         BlockSignals(False, SIGHUP);
935         BlockSignals(False, SIGCHLD);
936
937         if (!interactive)
938                 become_daemon(Fork, no_process_group, log_stdout);
939
940         pidfile_create("winbindd");
941
942 #if HAVE_SETPGID
943         /*
944          * If we're interactive we want to set our own process group for
945          * signal management.
946          */
947         if (interactive && !no_process_group)
948                 setpgid( (pid_t)0, (pid_t)0);
949 #endif
950
951         TimeInit();
952
953         /* Don't use winbindd_reinit_after_fork here as
954          * we're just starting up and haven't created any
955          * winbindd-specific resources we must free yet. JRA.
956          */
957
958         status = reinit_after_fork(winbind_messaging_context(),
959                                    winbind_event_context(),
960                                    procid_self(), false);
961         if (!NT_STATUS_IS_OK(status)) {
962                 DEBUG(0,("reinit_after_fork() failed\n"));
963                 exit(1);
964         }
965
966         winbindd_register_handlers();
967
968         rpc_lsarpc_init(NULL);
969         rpc_samr_init(NULL);
970
971         if (!init_system_info()) {
972                 DEBUG(0,("ERROR: failed to setup system user info.\n"));
973                 exit(1);
974         }
975
976         /* setup listen sockets */
977
978         if (!winbindd_setup_listeners()) {
979                 DEBUG(0,("winbindd_setup_listeners() failed\n"));
980                 exit(1);
981         }
982
983         TALLOC_FREE(frame);
984         /* Loop waiting for requests */
985         while (1) {
986                 frame = talloc_stackframe();
987
988                 if (tevent_loop_once(winbind_event_context()) == -1) {
989                         DEBUG(1, ("tevent_loop_once() failed: %s\n",
990                                   strerror(errno)));
991                         return 1;
992                 }
993
994                 TALLOC_FREE(frame);
995         }
996
997         return 0;
998 }