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