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