e4c22a610af58ecff0271231c1c1cef173a83c69
[ira/wip.git] / source3 / winbindd / winbindd.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind daemon for ntdom nss module
5
6    Copyright (C) by Tim Potter 2000-2002
7    Copyright (C) Andrew Tridgell 2002
8    Copyright (C) Jelmer Vernooij 2003
9    Copyright (C) Volker Lendecke 2004
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26 #include "winbindd.h"
27 #include "../../nsswitch/libwbclient/wbc_async.h"
28
29 #undef DBGC_CLASS
30 #define DBGC_CLASS DBGC_WINBIND
31
32 static void remove_client(struct winbindd_cli_state *state);
33
34 static bool opt_nocache = False;
35 static bool interactive = False;
36
37 extern bool override_logfile;
38
39 struct event_context *winbind_event_context(void)
40 {
41         static struct event_context *ctx;
42
43         if (!ctx && !(ctx = event_context_init(NULL))) {
44                 smb_panic("Could not init winbind event context");
45         }
46         return ctx;
47 }
48
49 struct messaging_context *winbind_messaging_context(void)
50 {
51         static struct messaging_context *ctx;
52
53         if (ctx == NULL) {
54                 ctx = messaging_init(NULL, server_id_self(),
55                                      winbind_event_context());
56         }
57         if (ctx == NULL) {
58                 DEBUG(0, ("Could not init winbind messaging context.\n"));
59         }
60         return ctx;
61 }
62
63 /* Reload configuration */
64
65 static bool reload_services_file(const char *lfile)
66 {
67         bool ret;
68
69         if (lp_loaded()) {
70                 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         /* Process command */
597
598         for (atable = async_nonpriv_table; atable->send_req; atable += 1) {
599                 if (state->request->cmd == atable->cmd) {
600                         break;
601                 }
602         }
603
604         if ((atable->send_req == NULL) && state->privileged) {
605                 for (atable = async_priv_table; atable->send_req;
606                      atable += 1) {
607                         if (state->request->cmd == atable->cmd) {
608                                 break;
609                         }
610                 }
611         }
612
613         if (atable->send_req != NULL) {
614                 struct tevent_req *req;
615
616                 DEBUG(10, ("process_request: Handling async request %s\n",
617                            atable->cmd_name));
618
619                 req = atable->send_req(state->mem_ctx, winbind_event_context(),
620                                        state, state->request);
621                 if (req == NULL) {
622                         DEBUG(0, ("process_request: atable->send failed for "
623                                   "%s\n", atable->cmd_name));
624                         request_error(state);
625                         return;
626                 }
627                 tevent_req_set_callback(req, wb_request_done, state);
628                 state->recv_fn = atable->recv_req;
629                 return;
630         }
631
632         state->response = talloc_zero(state->mem_ctx,
633                                       struct winbindd_response);
634         if (state->response == NULL) {
635                 DEBUG(10, ("talloc failed\n"));
636                 remove_client(state);
637                 return;
638         }
639         state->response->result = WINBINDD_PENDING;
640         state->response->length = sizeof(struct winbindd_response);
641
642         for (table = dispatch_table; table->fn; table++) {
643                 if (state->request->cmd == table->cmd) {
644                         DEBUG(10,("process_request: request fn %s\n",
645                                   table->winbindd_cmd_name ));
646                         table->fn(state);
647                         break;
648                 }
649         }
650
651         if (!table->fn) {
652                 DEBUG(10,("process_request: unknown request fn number %d\n",
653                           (int)state->request->cmd ));
654                 request_error(state);
655         }
656 }
657
658 static void wb_request_done(struct tevent_req *req)
659 {
660         struct winbindd_cli_state *state = tevent_req_callback_data(
661                 req, struct winbindd_cli_state);
662         NTSTATUS status;
663
664         state->response = talloc_zero(state, struct winbindd_response);
665         if (state->response == NULL) {
666                 remove_client(state);
667                 return;
668         }
669         state->response->result = WINBINDD_PENDING;
670         state->response->length = sizeof(struct winbindd_response);
671
672         status = state->recv_fn(req, state->response);
673         TALLOC_FREE(req);
674         if (!NT_STATUS_IS_OK(status)) {
675                 DEBUG(10, ("returning %s\n", nt_errstr(status)));
676                 request_error(state);
677                 return;
678         }
679         request_ok(state);
680 }
681
682 /*
683  * This is the main event loop of winbind requests. It goes through a
684  * state-machine of 3 read/write requests, 4 if you have extra data to send.
685  *
686  * An idle winbind client has a read request of 4 bytes outstanding,
687  * finalizing function is request_len_recv, checking the length. request_recv
688  * then processes the packet. The processing function then at some point has
689  * to call request_finished which schedules sending the response.
690  */
691
692 static void request_finished(struct winbindd_cli_state *state);
693
694 static void winbind_client_request_read(struct tevent_req *req);
695 static void winbind_client_response_written(struct tevent_req *req);
696
697 static void request_finished(struct winbindd_cli_state *state)
698 {
699         struct tevent_req *req;
700
701         TALLOC_FREE(state->request);
702
703         req = wb_resp_write_send(state, winbind_event_context(),
704                                  state->out_queue, state->sock,
705                                  state->response);
706         if (req == NULL) {
707                 remove_client(state);
708                 return;
709         }
710         tevent_req_set_callback(req, winbind_client_response_written, state);
711 }
712
713 static void winbind_client_response_written(struct tevent_req *req)
714 {
715         struct winbindd_cli_state *state = tevent_req_callback_data(
716                 req, struct winbindd_cli_state);
717         ssize_t ret;
718         int err;
719
720         ret = wb_resp_write_recv(req, &err);
721         TALLOC_FREE(req);
722         if (ret == -1) {
723                 close(state->sock);
724                 state->sock = -1;
725                 DEBUG(2, ("Could not write response to client: %s\n",
726                           strerror(err)));
727                 remove_client(state);
728                 return;
729         }
730
731         TALLOC_FREE(state->mem_ctx);
732         state->response = NULL;
733
734         req = wb_req_read_send(state, winbind_event_context(), state->sock,
735                                WINBINDD_MAX_EXTRA_DATA);
736         if (req == NULL) {
737                 remove_client(state);
738                 return;
739         }
740         tevent_req_set_callback(req, winbind_client_request_read, state);
741 }
742
743 void request_error(struct winbindd_cli_state *state)
744 {
745         SMB_ASSERT(state->response->result == WINBINDD_PENDING);
746         state->response->result = WINBINDD_ERROR;
747         request_finished(state);
748 }
749
750 void request_ok(struct winbindd_cli_state *state)
751 {
752         SMB_ASSERT(state->response->result == WINBINDD_PENDING);
753         state->response->result = WINBINDD_OK;
754         request_finished(state);
755 }
756
757 /* Process a new connection by adding it to the client connection list */
758
759 static void new_connection(int listen_sock, bool privileged)
760 {
761         struct sockaddr_un sunaddr;
762         struct winbindd_cli_state *state;
763         struct tevent_req *req;
764         socklen_t len;
765         int sock;
766
767         /* Accept connection */
768
769         len = sizeof(sunaddr);
770
771         do {
772                 sock = accept(listen_sock, (struct sockaddr *)(void *)&sunaddr,
773                               &len);
774         } while (sock == -1 && errno == EINTR);
775
776         if (sock == -1)
777                 return;
778
779         DEBUG(6,("accepted socket %d\n", sock));
780
781         /* Create new connection structure */
782
783         if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
784                 close(sock);
785                 return;
786         }
787
788         state->sock = sock;
789
790         state->out_queue = tevent_queue_create(state, "winbind client reply");
791         if (state->out_queue == NULL) {
792                 close(sock);
793                 TALLOC_FREE(state);
794                 return;
795         }
796
797         state->last_access = time(NULL);        
798
799         state->privileged = privileged;
800
801         req = wb_req_read_send(state, winbind_event_context(), state->sock,
802                                WINBINDD_MAX_EXTRA_DATA);
803         if (req == NULL) {
804                 TALLOC_FREE(state);
805                 close(sock);
806                 return;
807         }
808         tevent_req_set_callback(req, winbind_client_request_read, state);
809
810         /* Add to connection list */
811
812         winbindd_add_client(state);
813 }
814
815 static void winbind_client_request_read(struct tevent_req *req)
816 {
817         struct winbindd_cli_state *state = tevent_req_callback_data(
818                 req, struct winbindd_cli_state);
819         ssize_t ret;
820         int err;
821
822         ret = wb_req_read_recv(req, state, &state->request, &err);
823         TALLOC_FREE(req);
824         if (ret == -1) {
825                 if (err == EPIPE) {
826                         DEBUG(6, ("closing socket %d, client exited\n",
827                                   state->sock));
828                 } else {
829                         DEBUG(2, ("Could not read client request from fd %d: "
830                                   "%s\n", state->sock, strerror(err)));
831                 }
832                 close(state->sock);
833                 state->sock = -1;
834                 remove_client(state);
835                 return;
836         }
837         process_request(state);
838 }
839
840 /* Remove a client connection from client connection list */
841
842 static void remove_client(struct winbindd_cli_state *state)
843 {
844         char c = 0;
845         int nwritten;
846
847         /* It's a dead client - hold a funeral */
848
849         if (state == NULL) {
850                 return;
851         }
852
853         if (state->sock != -1) {
854                 /* tell client, we are closing ... */
855                 nwritten = write(state->sock, &c, sizeof(c));
856                 if (nwritten == -1) {
857                         DEBUG(2, ("final write to client failed: %s\n",
858                                 strerror(errno)));
859                 }
860
861                 /* Close socket */
862
863                 close(state->sock);
864                 state->sock = -1;
865         }
866
867         TALLOC_FREE(state->mem_ctx);
868
869         /* Remove from list and free */
870
871         winbindd_remove_client(state);
872         TALLOC_FREE(state);
873 }
874
875 /* Shutdown client connection which has been idle for the longest time */
876
877 static bool remove_idle_client(void)
878 {
879         struct winbindd_cli_state *state, *remove_state = NULL;
880         time_t last_access = 0;
881         int nidle = 0;
882
883         for (state = winbindd_client_list(); state; state = state->next) {
884                 if (state->response == NULL &&
885                     !state->pwent_state && !state->grent_state) {
886                         nidle++;
887                         if (!last_access || state->last_access < last_access) {
888                                 last_access = state->last_access;
889                                 remove_state = state;
890                         }
891                 }
892         }
893
894         if (remove_state) {
895                 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
896                         nidle, remove_state->sock, (unsigned int)remove_state->pid));
897                 remove_client(remove_state);
898                 return True;
899         }
900
901         return False;
902 }
903
904 struct winbindd_listen_state {
905         bool privileged;
906         int fd;
907 };
908
909 static void winbindd_listen_fde_handler(struct tevent_context *ev,
910                                         struct tevent_fd *fde,
911                                         uint16_t flags,
912                                         void *private_data)
913 {
914         struct winbindd_listen_state *s = talloc_get_type_abort(private_data,
915                                           struct winbindd_listen_state);
916
917         while (winbindd_num_clients() >
918                WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
919                 DEBUG(5,("winbindd: Exceeding %d client "
920                          "connections, removing idle "
921                          "connection.\n",
922                          WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
923                 if (!remove_idle_client()) {
924                         DEBUG(0,("winbindd: Exceeding %d "
925                                  "client connections, no idle "
926                                  "connection found\n",
927                                  WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
928                         break;
929                 }
930         }
931         new_connection(s->fd, s->privileged);
932 }
933
934 static bool winbindd_setup_listeners(void)
935 {
936         struct winbindd_listen_state *pub_state = NULL;
937         struct winbindd_listen_state *priv_state = NULL;
938         struct tevent_fd *fde;
939
940         pub_state = talloc(winbind_event_context(),
941                            struct winbindd_listen_state);
942         if (!pub_state) {
943                 goto failed;
944         }
945
946         pub_state->privileged = false;
947         pub_state->fd = open_winbindd_socket();
948         if (pub_state->fd == -1) {
949                 goto failed;
950         }
951
952         fde = tevent_add_fd(winbind_event_context(), pub_state, pub_state->fd,
953                             TEVENT_FD_READ, winbindd_listen_fde_handler,
954                             pub_state);
955         if (fde == NULL) {
956                 close(pub_state->fd);
957                 goto failed;
958         }
959         tevent_fd_set_auto_close(fde);
960
961         priv_state = talloc(winbind_event_context(),
962                             struct winbindd_listen_state);
963         if (!priv_state) {
964                 goto failed;
965         }
966
967         priv_state->privileged = true;
968         priv_state->fd = open_winbindd_priv_socket();
969         if (priv_state->fd == -1) {
970                 goto failed;
971         }
972
973         fde = tevent_add_fd(winbind_event_context(), priv_state,
974                             priv_state->fd, TEVENT_FD_READ,
975                             winbindd_listen_fde_handler, priv_state);
976         if (fde == NULL) {
977                 close(priv_state->fd);
978                 goto failed;
979         }
980         tevent_fd_set_auto_close(fde);
981
982         return true;
983 failed:
984         TALLOC_FREE(pub_state);
985         TALLOC_FREE(priv_state);
986         return false;
987 }
988
989 bool winbindd_use_idmap_cache(void)
990 {
991         return !opt_nocache;
992 }
993
994 bool winbindd_use_cache(void)
995 {
996         return !opt_nocache;
997 }
998
999 /* Main function */
1000
1001 int main(int argc, char **argv, char **envp)
1002 {
1003         static bool is_daemon = False;
1004         static bool Fork = True;
1005         static bool log_stdout = False;
1006         static bool no_process_group = False;
1007         enum {
1008                 OPT_DAEMON = 1000,
1009                 OPT_FORK,
1010                 OPT_NO_PROCESS_GROUP,
1011                 OPT_LOG_STDOUT
1012         };
1013         struct poptOption long_options[] = {
1014                 POPT_AUTOHELP
1015                 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1016                 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1017                 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1018                 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1019                 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1020                 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1021                 POPT_COMMON_SAMBA
1022                 POPT_TABLEEND
1023         };
1024         poptContext pc;
1025         int opt;
1026         TALLOC_CTX *frame = talloc_stackframe();
1027         struct tevent_timer *te;
1028
1029         /* glibc (?) likes to print "User defined signal 1" and exit if a
1030            SIGUSR[12] is received before a handler is installed */
1031
1032         CatchSignal(SIGUSR1, SIG_IGN);
1033         CatchSignal(SIGUSR2, SIG_IGN);
1034
1035         fault_setup((void (*)(void *))fault_quit );
1036         dump_core_setup("winbindd");
1037
1038         load_case_tables();
1039
1040         /* Initialise for running in non-root mode */
1041
1042         sec_init();
1043
1044         set_remote_machine_name("winbindd", False);
1045
1046         /* Set environment variable so we don't recursively call ourselves.
1047            This may also be useful interactively. */
1048
1049         if ( !winbind_off() ) {
1050                 DEBUG(0,("Failed to disable recusive winbindd calls.  Exiting.\n"));
1051                 exit(1);
1052         }
1053
1054         /* Initialise samba/rpc client stuff */
1055
1056         pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1057
1058         while ((opt = poptGetNextOpt(pc)) != -1) {
1059                 switch (opt) {
1060                         /* Don't become a daemon */
1061                 case OPT_DAEMON:
1062                         is_daemon = True;
1063                         break;
1064                 case 'i':
1065                         interactive = True;
1066                         log_stdout = True;
1067                         Fork = False;
1068                         break;
1069                 case OPT_FORK:
1070                         Fork = false;
1071                         break;
1072                 case OPT_NO_PROCESS_GROUP:
1073                         no_process_group = true;
1074                         break;
1075                 case OPT_LOG_STDOUT:
1076                         log_stdout = true;
1077                         break;
1078                 case 'n':
1079                         opt_nocache = true;
1080                         break;
1081                 default:
1082                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1083                                   poptBadOption(pc, 0), poptStrerror(opt));
1084                         poptPrintUsage(pc, stderr, 0);
1085                         exit(1);
1086                 }
1087         }
1088
1089         if (is_daemon && interactive) {
1090                 d_fprintf(stderr,"\nERROR: "
1091                           "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1092                 poptPrintUsage(pc, stderr, 0);
1093                 exit(1);
1094         }
1095
1096         if (log_stdout && Fork) {
1097                 d_fprintf(stderr, "\nERROR: "
1098                           "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1099                 poptPrintUsage(pc, stderr, 0);
1100                 exit(1);
1101         }
1102
1103         poptFreeContext(pc);
1104
1105         if (!override_logfile) {
1106                 char *lfile = NULL;
1107                 if (asprintf(&lfile,"%s/log.winbindd",
1108                                 get_dyn_LOGFILEBASE()) > 0) {
1109                         lp_set_logfile(lfile);
1110                         SAFE_FREE(lfile);
1111                 }
1112         }
1113         setup_logging("winbindd", log_stdout);
1114         reopen_logs();
1115
1116         DEBUG(0,("winbindd version %s started.\n", samba_version_string()));
1117         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1118
1119         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1120                 DEBUG(0, ("error opening config file\n"));
1121                 exit(1);
1122         }
1123
1124         /* Initialise messaging system */
1125
1126         if (winbind_messaging_context() == NULL) {
1127                 exit(1);
1128         }
1129
1130         if (!reload_services_file(NULL)) {
1131                 DEBUG(0, ("error opening config file\n"));
1132                 exit(1);
1133         }
1134
1135         if (!directory_exist(lp_lockdir())) {
1136                 mkdir(lp_lockdir(), 0755);
1137         }
1138
1139         /* Setup names. */
1140
1141         if (!init_names())
1142                 exit(1);
1143
1144         load_interfaces();
1145
1146         if (!secrets_init()) {
1147
1148                 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1149                 return False;
1150         }
1151
1152         /* Enable netbios namecache */
1153
1154         namecache_enable();
1155
1156         /* Unblock all signals we are interested in as they may have been
1157            blocked by the parent process. */
1158
1159         BlockSignals(False, SIGINT);
1160         BlockSignals(False, SIGQUIT);
1161         BlockSignals(False, SIGTERM);
1162         BlockSignals(False, SIGUSR1);
1163         BlockSignals(False, SIGUSR2);
1164         BlockSignals(False, SIGHUP);
1165         BlockSignals(False, SIGCHLD);
1166
1167         if (!interactive)
1168                 become_daemon(Fork, no_process_group);
1169
1170         pidfile_create("winbindd");
1171
1172 #if HAVE_SETPGID
1173         /*
1174          * If we're interactive we want to set our own process group for
1175          * signal management.
1176          */
1177         if (interactive && !no_process_group)
1178                 setpgid( (pid_t)0, (pid_t)0);
1179 #endif
1180
1181         TimeInit();
1182
1183         /* Don't use winbindd_reinit_after_fork here as
1184          * we're just starting up and haven't created any
1185          * winbindd-specific resources we must free yet. JRA.
1186          */
1187
1188         if (!NT_STATUS_IS_OK(reinit_after_fork(winbind_messaging_context(),
1189                                                winbind_event_context(),
1190                                                false))) {
1191                 DEBUG(0,("reinit_after_fork() failed\n"));
1192                 exit(1);
1193         }
1194
1195         /* Setup signal handlers */
1196
1197         if (!winbindd_setup_sig_term_handler(true))
1198                 exit(1);
1199         if (!winbindd_setup_sig_hup_handler(NULL))
1200                 exit(1);
1201         if (!winbindd_setup_sig_chld_handler())
1202                 exit(1);
1203         if (!winbindd_setup_sig_usr2_handler())
1204                 exit(1);
1205
1206         CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
1207
1208         /*
1209          * Ensure all cache and idmap caches are consistent
1210          * and initialized before we startup.
1211          */
1212         if (!winbindd_cache_validate_and_initialize()) {
1213                 exit(1);
1214         }
1215
1216         /* get broadcast messages */
1217         claim_connection(NULL,"",FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP);
1218
1219         /* React on 'smbcontrol winbindd reload-config' in the same way
1220            as to SIGHUP signal */
1221         messaging_register(winbind_messaging_context(), NULL,
1222                            MSG_SMB_CONF_UPDATED, msg_reload_services);
1223         messaging_register(winbind_messaging_context(), NULL,
1224                            MSG_SHUTDOWN, msg_shutdown);
1225
1226         /* Handle online/offline messages. */
1227         messaging_register(winbind_messaging_context(), NULL,
1228                            MSG_WINBIND_OFFLINE, winbind_msg_offline);
1229         messaging_register(winbind_messaging_context(), NULL,
1230                            MSG_WINBIND_ONLINE, winbind_msg_online);
1231         messaging_register(winbind_messaging_context(), NULL,
1232                            MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1233
1234         messaging_register(winbind_messaging_context(), NULL,
1235                            MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1236
1237         messaging_register(winbind_messaging_context(), NULL,
1238                            MSG_WINBIND_VALIDATE_CACHE,
1239                            winbind_msg_validate_cache);
1240
1241         messaging_register(winbind_messaging_context(), NULL,
1242                            MSG_WINBIND_DUMP_DOMAIN_LIST,
1243                            winbind_msg_dump_domain_list);
1244
1245         /* Register handler for MSG_DEBUG. */
1246         messaging_register(winbind_messaging_context(), NULL,
1247                            MSG_DEBUG,
1248                            winbind_msg_debug);
1249
1250         netsamlogon_cache_init(); /* Non-critical */
1251
1252         /* clear the cached list of trusted domains */
1253
1254         wcache_tdc_clear();     
1255
1256         if (!init_domain_list()) {
1257                 DEBUG(0,("unable to initialize domain list\n"));
1258                 exit(1);
1259         }
1260
1261         init_idmap_child();
1262         init_locator_child();
1263
1264         smb_nscd_flush_user_cache();
1265         smb_nscd_flush_group_cache();
1266
1267         /* setup listen sockets */
1268
1269         if (!winbindd_setup_listeners()) {
1270                 DEBUG(0,("winbindd_setup_listeners() failed\n"));
1271                 exit(1);
1272         }
1273
1274         te = tevent_add_timer(winbind_event_context(), NULL, timeval_zero(),
1275                               rescan_trusted_domains, NULL);
1276         if (te == NULL) {
1277                 DEBUG(0, ("Could not trigger rescan_trusted_domains()\n"));
1278                 exit(1);
1279         }
1280
1281         TALLOC_FREE(frame);
1282         /* Loop waiting for requests */
1283         while (1) {
1284                 frame = talloc_stackframe();
1285
1286                 if (tevent_loop_once(winbind_event_context()) == -1) {
1287                         DEBUG(1, ("tevent_loop_once() failed: %s\n",
1288                                   strerror(errno)));
1289                         return 1;
1290                 }
1291
1292                 TALLOC_FREE(frame);
1293         }
1294
1295         return 0;
1296 }