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