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