s3:winbindd: fix problems with SIGCHLD handling (bug #7317)
[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         struct sigaction act;
400         struct sigaction oldact;
401
402         DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
403                    "message.\n"));
404
405         /*
406          * call the validation code from a child:
407          * so we don't block the main winbindd and the validation
408          * code can safely use fork/waitpid...
409          */
410         child_pid = sys_fork();
411
412         if (child_pid == -1) {
413                 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
414                           strerror(errno)));
415                 return;
416         }
417
418         if (child_pid != 0) {
419                 /* parent */
420                 DEBUG(5, ("winbind_msg_validate_cache: child created with "
421                           "pid %d.\n", (int)child_pid));
422                 return;
423         }
424
425         /* child */
426
427         if (!winbindd_reinit_after_fork(NULL)) {
428                 _exit(0);
429         }
430
431         ret = (uint8)winbindd_validate_cache_nobackup();
432         DEBUG(10, ("winbindd_msg_validata_cache: got return value %d\n", ret));
433         messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_VALIDATE_CACHE, &ret,
434                            (size_t)1);
435         _exit(0);
436 }
437
438 static struct winbindd_dispatch_table {
439         enum winbindd_cmd cmd;
440         void (*fn)(struct winbindd_cli_state *state);
441         const char *winbindd_cmd_name;
442 } dispatch_table[] = {
443
444         /* PAM auth functions */
445
446         { WINBINDD_PAM_AUTH, winbindd_pam_auth, "PAM_AUTH" },
447         { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap, "AUTH_CRAP" },
448         { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok, "CHAUTHTOK" },
449         { WINBINDD_PAM_LOGOFF, winbindd_pam_logoff, "PAM_LOGOFF" },
450         { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, winbindd_pam_chng_pswd_auth_crap, "CHNG_PSWD_AUTH_CRAP" },
451
452         /* Enumeration functions */
453
454         { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
455           "LIST_TRUSTDOM" },
456
457         /* Miscellaneous */
458
459         { WINBINDD_INFO, winbindd_info, "INFO" },
460         { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
461           "INTERFACE_VERSION" },
462         { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
463         { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
464         { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
465         { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
466           "WINBINDD_PRIV_PIPE_DIR" },
467
468         /* Credential cache access */
469         { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
470         { WINBINDD_CCACHE_SAVE, winbindd_ccache_save, "CCACHE_SAVE" },
471
472         /* WINS functions */
473
474         { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
475         { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
476
477         /* End of list */
478
479         { WINBINDD_NUM_CMDS, NULL, "NONE" }
480 };
481
482 struct winbindd_async_dispatch_table {
483         enum winbindd_cmd cmd;
484         const char *cmd_name;
485         struct tevent_req *(*send_req)(TALLOC_CTX *mem_ctx,
486                                        struct tevent_context *ev,
487                                        struct winbindd_cli_state *cli,
488                                        struct winbindd_request *request);
489         NTSTATUS (*recv_req)(struct tevent_req *req,
490                              struct winbindd_response *presp);
491 };
492
493 static struct winbindd_async_dispatch_table async_nonpriv_table[] = {
494         { WINBINDD_PING, "PING",
495           wb_ping_send, wb_ping_recv },
496         { WINBINDD_LOOKUPSID, "LOOKUPSID",
497           winbindd_lookupsid_send, winbindd_lookupsid_recv },
498         { WINBINDD_LOOKUPNAME, "LOOKUPNAME",
499           winbindd_lookupname_send, winbindd_lookupname_recv },
500         { WINBINDD_SID_TO_UID, "SID_TO_UID",
501           winbindd_sid_to_uid_send, winbindd_sid_to_uid_recv },
502         { WINBINDD_SID_TO_GID, "SID_TO_GID",
503           winbindd_sid_to_gid_send, winbindd_sid_to_gid_recv },
504         { WINBINDD_UID_TO_SID, "UID_TO_SID",
505           winbindd_uid_to_sid_send, winbindd_uid_to_sid_recv },
506         { WINBINDD_GID_TO_SID, "GID_TO_SID",
507           winbindd_gid_to_sid_send, winbindd_gid_to_sid_recv },
508         { WINBINDD_GETPWSID, "GETPWSID",
509           winbindd_getpwsid_send, winbindd_getpwsid_recv },
510         { WINBINDD_GETPWNAM, "GETPWNAM",
511           winbindd_getpwnam_send, winbindd_getpwnam_recv },
512         { WINBINDD_GETPWUID, "GETPWUID",
513           winbindd_getpwuid_send, winbindd_getpwuid_recv },
514         { WINBINDD_GETSIDALIASES, "GETSIDALIASES",
515           winbindd_getsidaliases_send, winbindd_getsidaliases_recv },
516         { WINBINDD_GETUSERDOMGROUPS, "GETUSERDOMGROUPS",
517           winbindd_getuserdomgroups_send, winbindd_getuserdomgroups_recv },
518         { WINBINDD_GETGROUPS, "GETGROUPS",
519           winbindd_getgroups_send, winbindd_getgroups_recv },
520         { WINBINDD_SHOW_SEQUENCE, "SHOW_SEQUENCE",
521           winbindd_show_sequence_send, winbindd_show_sequence_recv },
522         { WINBINDD_GETGRGID, "GETGRGID",
523           winbindd_getgrgid_send, winbindd_getgrgid_recv },
524         { WINBINDD_GETGRNAM, "GETGRNAM",
525           winbindd_getgrnam_send, winbindd_getgrnam_recv },
526         { WINBINDD_GETUSERSIDS, "GETUSERSIDS",
527           winbindd_getusersids_send, winbindd_getusersids_recv },
528         { WINBINDD_LOOKUPRIDS, "LOOKUPRIDS",
529           winbindd_lookuprids_send, winbindd_lookuprids_recv },
530         { WINBINDD_SETPWENT, "SETPWENT",
531           winbindd_setpwent_send, winbindd_setpwent_recv },
532         { WINBINDD_GETPWENT, "GETPWENT",
533           winbindd_getpwent_send, winbindd_getpwent_recv },
534         { WINBINDD_ENDPWENT, "ENDPWENT",
535           winbindd_endpwent_send, winbindd_endpwent_recv },
536         { WINBINDD_DSGETDCNAME, "DSGETDCNAME",
537           winbindd_dsgetdcname_send, winbindd_dsgetdcname_recv },
538         { WINBINDD_GETDCNAME, "GETDCNAME",
539           winbindd_getdcname_send, winbindd_getdcname_recv },
540         { WINBINDD_SETGRENT, "SETGRENT",
541           winbindd_setgrent_send, winbindd_setgrent_recv },
542         { WINBINDD_GETGRENT, "GETGRENT",
543           winbindd_getgrent_send, winbindd_getgrent_recv },
544         { WINBINDD_ENDGRENT, "ENDGRENT",
545           winbindd_endgrent_send, winbindd_endgrent_recv },
546         { WINBINDD_LIST_USERS, "LIST_USERS",
547           winbindd_list_users_send, winbindd_list_users_recv },
548         { WINBINDD_LIST_GROUPS, "LIST_GROUPS",
549           winbindd_list_groups_send, winbindd_list_groups_recv },
550         { WINBINDD_CHECK_MACHACC, "CHECK_MACHACC",
551           winbindd_check_machine_acct_send, winbindd_check_machine_acct_recv },
552         { WINBINDD_PING_DC, "PING_DC",
553           winbindd_ping_dc_send, winbindd_ping_dc_recv },
554
555         { 0, NULL, NULL, NULL }
556 };
557
558 static struct winbindd_async_dispatch_table async_priv_table[] = {
559         { WINBINDD_ALLOCATE_UID, "ALLOCATE_UID",
560           winbindd_allocate_uid_send, winbindd_allocate_uid_recv },
561         { WINBINDD_ALLOCATE_GID, "ALLOCATE_GID",
562           winbindd_allocate_gid_send, winbindd_allocate_gid_recv },
563         { WINBINDD_SET_MAPPING, "SET_MAPPING",
564           winbindd_set_mapping_send, winbindd_set_mapping_recv },
565         { WINBINDD_REMOVE_MAPPING, "SET_MAPPING",
566           winbindd_remove_mapping_send, winbindd_remove_mapping_recv },
567         { WINBINDD_SET_HWM, "SET_HWM",
568           winbindd_set_hwm_send, winbindd_set_hwm_recv },
569         { WINBINDD_CHANGE_MACHACC, "CHANGE_MACHACC",
570           winbindd_change_machine_acct_send, winbindd_change_machine_acct_recv },
571
572         { 0, NULL, NULL, NULL }
573 };
574
575 static void wb_request_done(struct tevent_req *req);
576
577 static void process_request(struct winbindd_cli_state *state)
578 {
579         struct winbindd_dispatch_table *table = dispatch_table;
580         struct winbindd_async_dispatch_table *atable;
581
582         state->mem_ctx = talloc_init("winbind request");
583         if (state->mem_ctx == NULL)
584                 return;
585
586         /* Remember who asked us. */
587         state->pid = state->request->pid;
588
589         state->cmd_name = "unknown request";
590         state->recv_fn = NULL;
591
592         /* Process command */
593
594         for (atable = async_nonpriv_table; atable->send_req; atable += 1) {
595                 if (state->request->cmd == atable->cmd) {
596                         break;
597                 }
598         }
599
600         if ((atable->send_req == NULL) && state->privileged) {
601                 for (atable = async_priv_table; atable->send_req;
602                      atable += 1) {
603                         if (state->request->cmd == atable->cmd) {
604                                 break;
605                         }
606                 }
607         }
608
609         if (atable->send_req != NULL) {
610                 struct tevent_req *req;
611
612                 state->cmd_name = atable->cmd_name;
613                 state->recv_fn = atable->recv_req;
614
615                 DEBUG(10, ("process_request: Handling async request %d:%s\n",
616                            (int)state->pid, state->cmd_name));
617
618                 req = atable->send_req(state->mem_ctx, winbind_event_context(),
619                                        state, state->request);
620                 if (req == NULL) {
621                         DEBUG(0, ("process_request: atable->send failed for "
622                                   "%s\n", atable->cmd_name));
623                         request_error(state);
624                         return;
625                 }
626                 tevent_req_set_callback(req, wb_request_done, state);
627                 return;
628         }
629
630         state->response = talloc_zero(state->mem_ctx,
631                                       struct winbindd_response);
632         if (state->response == NULL) {
633                 DEBUG(10, ("talloc failed\n"));
634                 remove_client(state);
635                 return;
636         }
637         state->response->result = WINBINDD_PENDING;
638         state->response->length = sizeof(struct winbindd_response);
639
640         for (table = dispatch_table; table->fn; table++) {
641                 if (state->request->cmd == table->cmd) {
642                         DEBUG(10,("process_request: request fn %s\n",
643                                   table->winbindd_cmd_name ));
644                         state->cmd_name = table->winbindd_cmd_name;
645                         table->fn(state);
646                         break;
647                 }
648         }
649
650         if (!table->fn) {
651                 DEBUG(10,("process_request: unknown request fn number %d\n",
652                           (int)state->request->cmd ));
653                 request_error(state);
654         }
655 }
656
657 static void wb_request_done(struct tevent_req *req)
658 {
659         struct winbindd_cli_state *state = tevent_req_callback_data(
660                 req, struct winbindd_cli_state);
661         NTSTATUS status;
662
663         state->response = talloc_zero(state->mem_ctx,
664                                       struct winbindd_response);
665         if (state->response == NULL) {
666                 DEBUG(0, ("wb_request_done[%d:%s]: talloc_zero failed - removing client\n",
667                           (int)state->pid, state->cmd_name));
668                 remove_client(state);
669                 return;
670         }
671         state->response->result = WINBINDD_PENDING;
672         state->response->length = sizeof(struct winbindd_response);
673
674         status = state->recv_fn(req, state->response);
675         TALLOC_FREE(req);
676
677         DEBUG(10,("wb_request_done[%d:%s]: %s\n",
678                   (int)state->pid, state->cmd_name, nt_errstr(status)));
679
680         if (!NT_STATUS_IS_OK(status)) {
681                 request_error(state);
682                 return;
683         }
684         request_ok(state);
685 }
686
687 /*
688  * This is the main event loop of winbind requests. It goes through a
689  * state-machine of 3 read/write requests, 4 if you have extra data to send.
690  *
691  * An idle winbind client has a read request of 4 bytes outstanding,
692  * finalizing function is request_len_recv, checking the length. request_recv
693  * then processes the packet. The processing function then at some point has
694  * to call request_finished which schedules sending the response.
695  */
696
697 static void request_finished(struct winbindd_cli_state *state);
698
699 static void winbind_client_request_read(struct tevent_req *req);
700 static void winbind_client_response_written(struct tevent_req *req);
701
702 static void request_finished(struct winbindd_cli_state *state)
703 {
704         struct tevent_req *req;
705
706         TALLOC_FREE(state->request);
707
708         req = wb_resp_write_send(state, winbind_event_context(),
709                                  state->out_queue, state->sock,
710                                  state->response);
711         if (req == NULL) {
712                 DEBUG(10,("request_finished[%d:%s]: wb_resp_write_send() failed\n",
713                           (int)state->pid, state->cmd_name));
714                 remove_client(state);
715                 return;
716         }
717         tevent_req_set_callback(req, winbind_client_response_written, state);
718 }
719
720 static void winbind_client_response_written(struct tevent_req *req)
721 {
722         struct winbindd_cli_state *state = tevent_req_callback_data(
723                 req, struct winbindd_cli_state);
724         ssize_t ret;
725         int err;
726
727         ret = wb_resp_write_recv(req, &err);
728         TALLOC_FREE(req);
729         if (ret == -1) {
730                 close(state->sock);
731                 state->sock = -1;
732                 DEBUG(2, ("Could not write response[%d:%s] to client: %s\n",
733                           (int)state->pid, state->cmd_name, strerror(err)));
734                 remove_client(state);
735                 return;
736         }
737
738         DEBUG(10,("winbind_client_response_written[%d:%s]: delivered response "
739                   "to client\n", (int)state->pid, state->cmd_name));
740
741         TALLOC_FREE(state->mem_ctx);
742         state->response = NULL;
743         state->cmd_name = "no request";
744         state->recv_fn = NULL;
745
746         req = wb_req_read_send(state, winbind_event_context(), state->sock,
747                                WINBINDD_MAX_EXTRA_DATA);
748         if (req == NULL) {
749                 remove_client(state);
750                 return;
751         }
752         tevent_req_set_callback(req, winbind_client_request_read, state);
753 }
754
755 void request_error(struct winbindd_cli_state *state)
756 {
757         SMB_ASSERT(state->response->result == WINBINDD_PENDING);
758         state->response->result = WINBINDD_ERROR;
759         request_finished(state);
760 }
761
762 void request_ok(struct winbindd_cli_state *state)
763 {
764         SMB_ASSERT(state->response->result == WINBINDD_PENDING);
765         state->response->result = WINBINDD_OK;
766         request_finished(state);
767 }
768
769 /* Process a new connection by adding it to the client connection list */
770
771 static void new_connection(int listen_sock, bool privileged)
772 {
773         struct sockaddr_un sunaddr;
774         struct winbindd_cli_state *state;
775         struct tevent_req *req;
776         socklen_t len;
777         int sock;
778
779         /* Accept connection */
780
781         len = sizeof(sunaddr);
782
783         do {
784                 sock = accept(listen_sock, (struct sockaddr *)(void *)&sunaddr,
785                               &len);
786         } while (sock == -1 && errno == EINTR);
787
788         if (sock == -1)
789                 return;
790
791         DEBUG(6,("accepted socket %d\n", sock));
792
793         /* Create new connection structure */
794
795         if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
796                 close(sock);
797                 return;
798         }
799
800         state->sock = sock;
801
802         state->out_queue = tevent_queue_create(state, "winbind client reply");
803         if (state->out_queue == NULL) {
804                 close(sock);
805                 TALLOC_FREE(state);
806                 return;
807         }
808
809         state->last_access = time(NULL);        
810
811         state->privileged = privileged;
812
813         req = wb_req_read_send(state, winbind_event_context(), state->sock,
814                                WINBINDD_MAX_EXTRA_DATA);
815         if (req == NULL) {
816                 TALLOC_FREE(state);
817                 close(sock);
818                 return;
819         }
820         tevent_req_set_callback(req, winbind_client_request_read, state);
821
822         /* Add to connection list */
823
824         winbindd_add_client(state);
825 }
826
827 static void winbind_client_request_read(struct tevent_req *req)
828 {
829         struct winbindd_cli_state *state = tevent_req_callback_data(
830                 req, struct winbindd_cli_state);
831         ssize_t ret;
832         int err;
833
834         ret = wb_req_read_recv(req, state, &state->request, &err);
835         TALLOC_FREE(req);
836         if (ret == -1) {
837                 if (err == EPIPE) {
838                         DEBUG(6, ("closing socket %d, client exited\n",
839                                   state->sock));
840                 } else {
841                         DEBUG(2, ("Could not read client request from fd %d: "
842                                   "%s\n", state->sock, strerror(err)));
843                 }
844                 close(state->sock);
845                 state->sock = -1;
846                 remove_client(state);
847                 return;
848         }
849         process_request(state);
850 }
851
852 /* Remove a client connection from client connection list */
853
854 static void remove_client(struct winbindd_cli_state *state)
855 {
856         char c = 0;
857         int nwritten;
858
859         /* It's a dead client - hold a funeral */
860
861         if (state == NULL) {
862                 return;
863         }
864
865         if (state->sock != -1) {
866                 /* tell client, we are closing ... */
867                 nwritten = write(state->sock, &c, sizeof(c));
868                 if (nwritten == -1) {
869                         DEBUG(2, ("final write to client failed: %s\n",
870                                 strerror(errno)));
871                 }
872
873                 /* Close socket */
874
875                 close(state->sock);
876                 state->sock = -1;
877         }
878
879         TALLOC_FREE(state->mem_ctx);
880
881         /* Remove from list and free */
882
883         winbindd_remove_client(state);
884         TALLOC_FREE(state);
885 }
886
887 /* Shutdown client connection which has been idle for the longest time */
888
889 static bool remove_idle_client(void)
890 {
891         struct winbindd_cli_state *state, *remove_state = NULL;
892         time_t last_access = 0;
893         int nidle = 0;
894
895         for (state = winbindd_client_list(); state; state = state->next) {
896                 if (state->response == NULL &&
897                     !state->pwent_state && !state->grent_state) {
898                         nidle++;
899                         if (!last_access || state->last_access < last_access) {
900                                 last_access = state->last_access;
901                                 remove_state = state;
902                         }
903                 }
904         }
905
906         if (remove_state) {
907                 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
908                         nidle, remove_state->sock, (unsigned int)remove_state->pid));
909                 remove_client(remove_state);
910                 return True;
911         }
912
913         return False;
914 }
915
916 struct winbindd_listen_state {
917         bool privileged;
918         int fd;
919 };
920
921 static void winbindd_listen_fde_handler(struct tevent_context *ev,
922                                         struct tevent_fd *fde,
923                                         uint16_t flags,
924                                         void *private_data)
925 {
926         struct winbindd_listen_state *s = talloc_get_type_abort(private_data,
927                                           struct winbindd_listen_state);
928
929         while (winbindd_num_clients() >
930                WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
931                 DEBUG(5,("winbindd: Exceeding %d client "
932                          "connections, removing idle "
933                          "connection.\n",
934                          WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
935                 if (!remove_idle_client()) {
936                         DEBUG(0,("winbindd: Exceeding %d "
937                                  "client connections, no idle "
938                                  "connection found\n",
939                                  WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
940                         break;
941                 }
942         }
943         new_connection(s->fd, s->privileged);
944 }
945
946 static bool winbindd_setup_listeners(void)
947 {
948         struct winbindd_listen_state *pub_state = NULL;
949         struct winbindd_listen_state *priv_state = NULL;
950         struct tevent_fd *fde;
951
952         pub_state = talloc(winbind_event_context(),
953                            struct winbindd_listen_state);
954         if (!pub_state) {
955                 goto failed;
956         }
957
958         pub_state->privileged = false;
959         pub_state->fd = open_winbindd_socket();
960         if (pub_state->fd == -1) {
961                 goto failed;
962         }
963
964         fde = tevent_add_fd(winbind_event_context(), pub_state, pub_state->fd,
965                             TEVENT_FD_READ, winbindd_listen_fde_handler,
966                             pub_state);
967         if (fde == NULL) {
968                 close(pub_state->fd);
969                 goto failed;
970         }
971         tevent_fd_set_auto_close(fde);
972
973         priv_state = talloc(winbind_event_context(),
974                             struct winbindd_listen_state);
975         if (!priv_state) {
976                 goto failed;
977         }
978
979         priv_state->privileged = true;
980         priv_state->fd = open_winbindd_priv_socket();
981         if (priv_state->fd == -1) {
982                 goto failed;
983         }
984
985         fde = tevent_add_fd(winbind_event_context(), priv_state,
986                             priv_state->fd, TEVENT_FD_READ,
987                             winbindd_listen_fde_handler, priv_state);
988         if (fde == NULL) {
989                 close(priv_state->fd);
990                 goto failed;
991         }
992         tevent_fd_set_auto_close(fde);
993
994         return true;
995 failed:
996         TALLOC_FREE(pub_state);
997         TALLOC_FREE(priv_state);
998         return false;
999 }
1000
1001 bool winbindd_use_idmap_cache(void)
1002 {
1003         return !opt_nocache;
1004 }
1005
1006 bool winbindd_use_cache(void)
1007 {
1008         return !opt_nocache;
1009 }
1010
1011 /* Main function */
1012
1013 int main(int argc, char **argv, char **envp)
1014 {
1015         static bool is_daemon = False;
1016         static bool Fork = True;
1017         static bool log_stdout = False;
1018         static bool no_process_group = False;
1019         enum {
1020                 OPT_DAEMON = 1000,
1021                 OPT_FORK,
1022                 OPT_NO_PROCESS_GROUP,
1023                 OPT_LOG_STDOUT
1024         };
1025         struct poptOption long_options[] = {
1026                 POPT_AUTOHELP
1027                 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1028                 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1029                 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1030                 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1031                 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1032                 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1033                 POPT_COMMON_SAMBA
1034                 POPT_TABLEEND
1035         };
1036         poptContext pc;
1037         int opt;
1038         TALLOC_CTX *frame = talloc_stackframe();
1039         struct tevent_timer *te;
1040
1041         /* glibc (?) likes to print "User defined signal 1" and exit if a
1042            SIGUSR[12] is received before a handler is installed */
1043
1044         CatchSignal(SIGUSR1, SIG_IGN);
1045         CatchSignal(SIGUSR2, SIG_IGN);
1046
1047         fault_setup((void (*)(void *))fault_quit );
1048         dump_core_setup("winbindd");
1049
1050         load_case_tables();
1051
1052         /* Initialise for running in non-root mode */
1053
1054         sec_init();
1055
1056         set_remote_machine_name("winbindd", False);
1057
1058         /* Set environment variable so we don't recursively call ourselves.
1059            This may also be useful interactively. */
1060
1061         if ( !winbind_off() ) {
1062                 DEBUG(0,("Failed to disable recusive winbindd calls.  Exiting.\n"));
1063                 exit(1);
1064         }
1065
1066         /* Initialise samba/rpc client stuff */
1067
1068         pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1069
1070         while ((opt = poptGetNextOpt(pc)) != -1) {
1071                 switch (opt) {
1072                         /* Don't become a daemon */
1073                 case OPT_DAEMON:
1074                         is_daemon = True;
1075                         break;
1076                 case 'i':
1077                         interactive = True;
1078                         log_stdout = True;
1079                         Fork = False;
1080                         break;
1081                 case OPT_FORK:
1082                         Fork = false;
1083                         break;
1084                 case OPT_NO_PROCESS_GROUP:
1085                         no_process_group = true;
1086                         break;
1087                 case OPT_LOG_STDOUT:
1088                         log_stdout = true;
1089                         break;
1090                 case 'n':
1091                         opt_nocache = true;
1092                         break;
1093                 default:
1094                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1095                                   poptBadOption(pc, 0), poptStrerror(opt));
1096                         poptPrintUsage(pc, stderr, 0);
1097                         exit(1);
1098                 }
1099         }
1100
1101         if (is_daemon && interactive) {
1102                 d_fprintf(stderr,"\nERROR: "
1103                           "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1104                 poptPrintUsage(pc, stderr, 0);
1105                 exit(1);
1106         }
1107
1108         if (log_stdout && Fork) {
1109                 d_fprintf(stderr, "\nERROR: "
1110                           "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1111                 poptPrintUsage(pc, stderr, 0);
1112                 exit(1);
1113         }
1114
1115         poptFreeContext(pc);
1116
1117         if (!override_logfile) {
1118                 char *lfile = NULL;
1119                 if (asprintf(&lfile,"%s/log.winbindd",
1120                                 get_dyn_LOGFILEBASE()) > 0) {
1121                         lp_set_logfile(lfile);
1122                         SAFE_FREE(lfile);
1123                 }
1124         }
1125         setup_logging("winbindd", log_stdout);
1126         reopen_logs();
1127
1128         DEBUG(0,("winbindd version %s started.\n", samba_version_string()));
1129         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1130
1131         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1132                 DEBUG(0, ("error opening config file\n"));
1133                 exit(1);
1134         }
1135
1136         /* Initialise messaging system */
1137
1138         if (winbind_messaging_context() == NULL) {
1139                 exit(1);
1140         }
1141
1142         if (!reload_services_file(NULL)) {
1143                 DEBUG(0, ("error opening config file\n"));
1144                 exit(1);
1145         }
1146
1147         if (!directory_exist(lp_lockdir())) {
1148                 mkdir(lp_lockdir(), 0755);
1149         }
1150
1151         /* Setup names. */
1152
1153         if (!init_names())
1154                 exit(1);
1155
1156         load_interfaces();
1157
1158         if (!secrets_init()) {
1159
1160                 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1161                 return False;
1162         }
1163
1164         /* Enable netbios namecache */
1165
1166         namecache_enable();
1167
1168         /* Unblock all signals we are interested in as they may have been
1169            blocked by the parent process. */
1170
1171         BlockSignals(False, SIGINT);
1172         BlockSignals(False, SIGQUIT);
1173         BlockSignals(False, SIGTERM);
1174         BlockSignals(False, SIGUSR1);
1175         BlockSignals(False, SIGUSR2);
1176         BlockSignals(False, SIGHUP);
1177         BlockSignals(False, SIGCHLD);
1178
1179         if (!interactive)
1180                 become_daemon(Fork, no_process_group, log_stdout);
1181
1182         pidfile_create("winbindd");
1183
1184 #if HAVE_SETPGID
1185         /*
1186          * If we're interactive we want to set our own process group for
1187          * signal management.
1188          */
1189         if (interactive && !no_process_group)
1190                 setpgid( (pid_t)0, (pid_t)0);
1191 #endif
1192
1193         TimeInit();
1194
1195         /* Don't use winbindd_reinit_after_fork here as
1196          * we're just starting up and haven't created any
1197          * winbindd-specific resources we must free yet. JRA.
1198          */
1199
1200         if (!NT_STATUS_IS_OK(reinit_after_fork(winbind_messaging_context(),
1201                                                winbind_event_context(),
1202                                                false))) {
1203                 DEBUG(0,("reinit_after_fork() failed\n"));
1204                 exit(1);
1205         }
1206
1207         /* Setup signal handlers */
1208
1209         if (!winbindd_setup_sig_term_handler(true))
1210                 exit(1);
1211         if (!winbindd_setup_sig_hup_handler(NULL))
1212                 exit(1);
1213         if (!winbindd_setup_sig_chld_handler())
1214                 exit(1);
1215         if (!winbindd_setup_sig_usr2_handler())
1216                 exit(1);
1217
1218         CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
1219
1220         /*
1221          * Ensure all cache and idmap caches are consistent
1222          * and initialized before we startup.
1223          */
1224         if (!winbindd_cache_validate_and_initialize()) {
1225                 exit(1);
1226         }
1227
1228         /* get broadcast messages */
1229
1230         if (!serverid_register_self(FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP)) {
1231                 DEBUG(1, ("Could not register myself in serverid.tdb\n"));
1232                 exit(1);
1233         }
1234
1235         /* React on 'smbcontrol winbindd reload-config' in the same way
1236            as to SIGHUP signal */
1237         messaging_register(winbind_messaging_context(), NULL,
1238                            MSG_SMB_CONF_UPDATED, msg_reload_services);
1239         messaging_register(winbind_messaging_context(), NULL,
1240                            MSG_SHUTDOWN, msg_shutdown);
1241
1242         /* Handle online/offline messages. */
1243         messaging_register(winbind_messaging_context(), NULL,
1244                            MSG_WINBIND_OFFLINE, winbind_msg_offline);
1245         messaging_register(winbind_messaging_context(), NULL,
1246                            MSG_WINBIND_ONLINE, winbind_msg_online);
1247         messaging_register(winbind_messaging_context(), NULL,
1248                            MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1249
1250         messaging_register(winbind_messaging_context(), NULL,
1251                            MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1252
1253         messaging_register(winbind_messaging_context(), NULL,
1254                            MSG_WINBIND_VALIDATE_CACHE,
1255                            winbind_msg_validate_cache);
1256
1257         messaging_register(winbind_messaging_context(), NULL,
1258                            MSG_WINBIND_DUMP_DOMAIN_LIST,
1259                            winbind_msg_dump_domain_list);
1260
1261         /* Register handler for MSG_DEBUG. */
1262         messaging_register(winbind_messaging_context(), NULL,
1263                            MSG_DEBUG,
1264                            winbind_msg_debug);
1265
1266         netsamlogon_cache_init(); /* Non-critical */
1267
1268         /* clear the cached list of trusted domains */
1269
1270         wcache_tdc_clear();     
1271
1272         if (!init_domain_list()) {
1273                 DEBUG(0,("unable to initialize domain list\n"));
1274                 exit(1);
1275         }
1276
1277         init_idmap_child();
1278         init_locator_child();
1279
1280         smb_nscd_flush_user_cache();
1281         smb_nscd_flush_group_cache();
1282
1283         /* setup listen sockets */
1284
1285         if (!winbindd_setup_listeners()) {
1286                 DEBUG(0,("winbindd_setup_listeners() failed\n"));
1287                 exit(1);
1288         }
1289
1290         te = tevent_add_timer(winbind_event_context(), NULL, timeval_zero(),
1291                               rescan_trusted_domains, NULL);
1292         if (te == NULL) {
1293                 DEBUG(0, ("Could not trigger rescan_trusted_domains()\n"));
1294                 exit(1);
1295         }
1296
1297         TALLOC_FREE(frame);
1298         /* Loop waiting for requests */
1299         while (1) {
1300                 frame = talloc_stackframe();
1301
1302                 if (tevent_loop_once(winbind_event_context()) == -1) {
1303                         DEBUG(1, ("tevent_loop_once() failed: %s\n",
1304                                   strerror(errno)));
1305                         return 1;
1306                 }
1307
1308                 TALLOC_FREE(frame);
1309         }
1310
1311         return 0;
1312 }