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