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