s3:winbindd: remove unused variables
[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
400         DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
401                    "message.\n"));
402
403         /*
404          * call the validation code from a child:
405          * so we don't block the main winbindd and the validation
406          * code can safely use fork/waitpid...
407          */
408         child_pid = sys_fork();
409
410         if (child_pid == -1) {
411                 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
412                           strerror(errno)));
413                 return;
414         }
415
416         if (child_pid != 0) {
417                 /* parent */
418                 DEBUG(5, ("winbind_msg_validate_cache: child created with "
419                           "pid %d.\n", (int)child_pid));
420                 return;
421         }
422
423         /* child */
424
425         if (!winbindd_reinit_after_fork(NULL)) {
426                 _exit(0);
427         }
428
429         ret = (uint8)winbindd_validate_cache_nobackup();
430         DEBUG(10, ("winbindd_msg_validata_cache: got return value %d\n", ret));
431         messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_VALIDATE_CACHE, &ret,
432                            (size_t)1);
433         _exit(0);
434 }
435
436 static struct winbindd_dispatch_table {
437         enum winbindd_cmd cmd;
438         void (*fn)(struct winbindd_cli_state *state);
439         const char *winbindd_cmd_name;
440 } dispatch_table[] = {
441
442         /* PAM auth functions */
443
444         { WINBINDD_PAM_AUTH, winbindd_pam_auth, "PAM_AUTH" },
445         { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap, "AUTH_CRAP" },
446         { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok, "CHAUTHTOK" },
447         { WINBINDD_PAM_LOGOFF, winbindd_pam_logoff, "PAM_LOGOFF" },
448         { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, winbindd_pam_chng_pswd_auth_crap, "CHNG_PSWD_AUTH_CRAP" },
449
450         /* Enumeration functions */
451
452         { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
453           "LIST_TRUSTDOM" },
454
455         /* Miscellaneous */
456
457         { WINBINDD_INFO, winbindd_info, "INFO" },
458         { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
459           "INTERFACE_VERSION" },
460         { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
461         { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
462         { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
463         { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
464           "WINBINDD_PRIV_PIPE_DIR" },
465
466         /* Credential cache access */
467         { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
468         { WINBINDD_CCACHE_SAVE, winbindd_ccache_save, "CCACHE_SAVE" },
469
470         /* WINS functions */
471
472         { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
473         { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
474
475         /* End of list */
476
477         { WINBINDD_NUM_CMDS, NULL, "NONE" }
478 };
479
480 struct winbindd_async_dispatch_table {
481         enum winbindd_cmd cmd;
482         const char *cmd_name;
483         struct tevent_req *(*send_req)(TALLOC_CTX *mem_ctx,
484                                        struct tevent_context *ev,
485                                        struct winbindd_cli_state *cli,
486                                        struct winbindd_request *request);
487         NTSTATUS (*recv_req)(struct tevent_req *req,
488                              struct winbindd_response *presp);
489 };
490
491 static struct winbindd_async_dispatch_table async_nonpriv_table[] = {
492         { WINBINDD_PING, "PING",
493           wb_ping_send, wb_ping_recv },
494         { WINBINDD_LOOKUPSID, "LOOKUPSID",
495           winbindd_lookupsid_send, winbindd_lookupsid_recv },
496         { WINBINDD_LOOKUPNAME, "LOOKUPNAME",
497           winbindd_lookupname_send, winbindd_lookupname_recv },
498         { WINBINDD_SID_TO_UID, "SID_TO_UID",
499           winbindd_sid_to_uid_send, winbindd_sid_to_uid_recv },
500         { WINBINDD_SID_TO_GID, "SID_TO_GID",
501           winbindd_sid_to_gid_send, winbindd_sid_to_gid_recv },
502         { WINBINDD_UID_TO_SID, "UID_TO_SID",
503           winbindd_uid_to_sid_send, winbindd_uid_to_sid_recv },
504         { WINBINDD_GID_TO_SID, "GID_TO_SID",
505           winbindd_gid_to_sid_send, winbindd_gid_to_sid_recv },
506         { WINBINDD_GETPWSID, "GETPWSID",
507           winbindd_getpwsid_send, winbindd_getpwsid_recv },
508         { WINBINDD_GETPWNAM, "GETPWNAM",
509           winbindd_getpwnam_send, winbindd_getpwnam_recv },
510         { WINBINDD_GETPWUID, "GETPWUID",
511           winbindd_getpwuid_send, winbindd_getpwuid_recv },
512         { WINBINDD_GETSIDALIASES, "GETSIDALIASES",
513           winbindd_getsidaliases_send, winbindd_getsidaliases_recv },
514         { WINBINDD_GETUSERDOMGROUPS, "GETUSERDOMGROUPS",
515           winbindd_getuserdomgroups_send, winbindd_getuserdomgroups_recv },
516         { WINBINDD_GETGROUPS, "GETGROUPS",
517           winbindd_getgroups_send, winbindd_getgroups_recv },
518         { WINBINDD_SHOW_SEQUENCE, "SHOW_SEQUENCE",
519           winbindd_show_sequence_send, winbindd_show_sequence_recv },
520         { WINBINDD_GETGRGID, "GETGRGID",
521           winbindd_getgrgid_send, winbindd_getgrgid_recv },
522         { WINBINDD_GETGRNAM, "GETGRNAM",
523           winbindd_getgrnam_send, winbindd_getgrnam_recv },
524         { WINBINDD_GETUSERSIDS, "GETUSERSIDS",
525           winbindd_getusersids_send, winbindd_getusersids_recv },
526         { WINBINDD_LOOKUPRIDS, "LOOKUPRIDS",
527           winbindd_lookuprids_send, winbindd_lookuprids_recv },
528         { WINBINDD_SETPWENT, "SETPWENT",
529           winbindd_setpwent_send, winbindd_setpwent_recv },
530         { WINBINDD_GETPWENT, "GETPWENT",
531           winbindd_getpwent_send, winbindd_getpwent_recv },
532         { WINBINDD_ENDPWENT, "ENDPWENT",
533           winbindd_endpwent_send, winbindd_endpwent_recv },
534         { WINBINDD_DSGETDCNAME, "DSGETDCNAME",
535           winbindd_dsgetdcname_send, winbindd_dsgetdcname_recv },
536         { WINBINDD_GETDCNAME, "GETDCNAME",
537           winbindd_getdcname_send, winbindd_getdcname_recv },
538         { WINBINDD_SETGRENT, "SETGRENT",
539           winbindd_setgrent_send, winbindd_setgrent_recv },
540         { WINBINDD_GETGRENT, "GETGRENT",
541           winbindd_getgrent_send, winbindd_getgrent_recv },
542         { WINBINDD_ENDGRENT, "ENDGRENT",
543           winbindd_endgrent_send, winbindd_endgrent_recv },
544         { WINBINDD_LIST_USERS, "LIST_USERS",
545           winbindd_list_users_send, winbindd_list_users_recv },
546         { WINBINDD_LIST_GROUPS, "LIST_GROUPS",
547           winbindd_list_groups_send, winbindd_list_groups_recv },
548         { WINBINDD_CHECK_MACHACC, "CHECK_MACHACC",
549           winbindd_check_machine_acct_send, winbindd_check_machine_acct_recv },
550         { WINBINDD_PING_DC, "PING_DC",
551           winbindd_ping_dc_send, winbindd_ping_dc_recv },
552
553         { 0, NULL, NULL, NULL }
554 };
555
556 static struct winbindd_async_dispatch_table async_priv_table[] = {
557         { WINBINDD_ALLOCATE_UID, "ALLOCATE_UID",
558           winbindd_allocate_uid_send, winbindd_allocate_uid_recv },
559         { WINBINDD_ALLOCATE_GID, "ALLOCATE_GID",
560           winbindd_allocate_gid_send, winbindd_allocate_gid_recv },
561         { WINBINDD_SET_MAPPING, "SET_MAPPING",
562           winbindd_set_mapping_send, winbindd_set_mapping_recv },
563         { WINBINDD_REMOVE_MAPPING, "SET_MAPPING",
564           winbindd_remove_mapping_send, winbindd_remove_mapping_recv },
565         { WINBINDD_SET_HWM, "SET_HWM",
566           winbindd_set_hwm_send, winbindd_set_hwm_recv },
567         { WINBINDD_CHANGE_MACHACC, "CHANGE_MACHACC",
568           winbindd_change_machine_acct_send, winbindd_change_machine_acct_recv },
569
570         { 0, NULL, NULL, NULL }
571 };
572
573 static void wb_request_done(struct tevent_req *req);
574
575 static void process_request(struct winbindd_cli_state *state)
576 {
577         struct winbindd_dispatch_table *table = dispatch_table;
578         struct winbindd_async_dispatch_table *atable;
579
580         state->mem_ctx = talloc_init("winbind request");
581         if (state->mem_ctx == NULL)
582                 return;
583
584         /* Remember who asked us. */
585         state->pid = state->request->pid;
586
587         state->cmd_name = "unknown request";
588         state->recv_fn = NULL;
589
590         /* Process command */
591
592         for (atable = async_nonpriv_table; atable->send_req; atable += 1) {
593                 if (state->request->cmd == atable->cmd) {
594                         break;
595                 }
596         }
597
598         if ((atable->send_req == NULL) && state->privileged) {
599                 for (atable = async_priv_table; atable->send_req;
600                      atable += 1) {
601                         if (state->request->cmd == atable->cmd) {
602                                 break;
603                         }
604                 }
605         }
606
607         if (atable->send_req != NULL) {
608                 struct tevent_req *req;
609
610                 state->cmd_name = atable->cmd_name;
611                 state->recv_fn = atable->recv_req;
612
613                 DEBUG(10, ("process_request: Handling async request %d:%s\n",
614                            (int)state->pid, state->cmd_name));
615
616                 req = atable->send_req(state->mem_ctx, winbind_event_context(),
617                                        state, state->request);
618                 if (req == NULL) {
619                         DEBUG(0, ("process_request: atable->send failed for "
620                                   "%s\n", atable->cmd_name));
621                         request_error(state);
622                         return;
623                 }
624                 tevent_req_set_callback(req, wb_request_done, state);
625                 return;
626         }
627
628         state->response = talloc_zero(state->mem_ctx,
629                                       struct winbindd_response);
630         if (state->response == NULL) {
631                 DEBUG(10, ("talloc failed\n"));
632                 remove_client(state);
633                 return;
634         }
635         state->response->result = WINBINDD_PENDING;
636         state->response->length = sizeof(struct winbindd_response);
637
638         for (table = dispatch_table; table->fn; table++) {
639                 if (state->request->cmd == table->cmd) {
640                         DEBUG(10,("process_request: request fn %s\n",
641                                   table->winbindd_cmd_name ));
642                         state->cmd_name = table->winbindd_cmd_name;
643                         table->fn(state);
644                         break;
645                 }
646         }
647
648         if (!table->fn) {
649                 DEBUG(10,("process_request: unknown request fn number %d\n",
650                           (int)state->request->cmd ));
651                 request_error(state);
652         }
653 }
654
655 static void wb_request_done(struct tevent_req *req)
656 {
657         struct winbindd_cli_state *state = tevent_req_callback_data(
658                 req, struct winbindd_cli_state);
659         NTSTATUS status;
660
661         state->response = talloc_zero(state->mem_ctx,
662                                       struct winbindd_response);
663         if (state->response == NULL) {
664                 DEBUG(0, ("wb_request_done[%d:%s]: talloc_zero failed - removing client\n",
665                           (int)state->pid, state->cmd_name));
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
675         DEBUG(10,("wb_request_done[%d:%s]: %s\n",
676                   (int)state->pid, state->cmd_name, nt_errstr(status)));
677
678         if (!NT_STATUS_IS_OK(status)) {
679                 request_error(state);
680                 return;
681         }
682         request_ok(state);
683 }
684
685 /*
686  * This is the main event loop of winbind requests. It goes through a
687  * state-machine of 3 read/write requests, 4 if you have extra data to send.
688  *
689  * An idle winbind client has a read request of 4 bytes outstanding,
690  * finalizing function is request_len_recv, checking the length. request_recv
691  * then processes the packet. The processing function then at some point has
692  * to call request_finished which schedules sending the response.
693  */
694
695 static void request_finished(struct winbindd_cli_state *state);
696
697 static void winbind_client_request_read(struct tevent_req *req);
698 static void winbind_client_response_written(struct tevent_req *req);
699
700 static void request_finished(struct winbindd_cli_state *state)
701 {
702         struct tevent_req *req;
703
704         TALLOC_FREE(state->request);
705
706         req = wb_resp_write_send(state, winbind_event_context(),
707                                  state->out_queue, state->sock,
708                                  state->response);
709         if (req == NULL) {
710                 DEBUG(10,("request_finished[%d:%s]: wb_resp_write_send() failed\n",
711                           (int)state->pid, state->cmd_name));
712                 remove_client(state);
713                 return;
714         }
715         tevent_req_set_callback(req, winbind_client_response_written, state);
716 }
717
718 static void winbind_client_response_written(struct tevent_req *req)
719 {
720         struct winbindd_cli_state *state = tevent_req_callback_data(
721                 req, struct winbindd_cli_state);
722         ssize_t ret;
723         int err;
724
725         ret = wb_resp_write_recv(req, &err);
726         TALLOC_FREE(req);
727         if (ret == -1) {
728                 close(state->sock);
729                 state->sock = -1;
730                 DEBUG(2, ("Could not write response[%d:%s] to client: %s\n",
731                           (int)state->pid, state->cmd_name, strerror(err)));
732                 remove_client(state);
733                 return;
734         }
735
736         DEBUG(10,("winbind_client_response_written[%d:%s]: delivered response "
737                   "to client\n", (int)state->pid, state->cmd_name));
738
739         TALLOC_FREE(state->mem_ctx);
740         state->response = NULL;
741         state->cmd_name = "no request";
742         state->recv_fn = NULL;
743
744         req = wb_req_read_send(state, winbind_event_context(), state->sock,
745                                WINBINDD_MAX_EXTRA_DATA);
746         if (req == NULL) {
747                 remove_client(state);
748                 return;
749         }
750         tevent_req_set_callback(req, winbind_client_request_read, state);
751 }
752
753 void request_error(struct winbindd_cli_state *state)
754 {
755         SMB_ASSERT(state->response->result == WINBINDD_PENDING);
756         state->response->result = WINBINDD_ERROR;
757         request_finished(state);
758 }
759
760 void request_ok(struct winbindd_cli_state *state)
761 {
762         SMB_ASSERT(state->response->result == WINBINDD_PENDING);
763         state->response->result = WINBINDD_OK;
764         request_finished(state);
765 }
766
767 /* Process a new connection by adding it to the client connection list */
768
769 static void new_connection(int listen_sock, bool privileged)
770 {
771         struct sockaddr_un sunaddr;
772         struct winbindd_cli_state *state;
773         struct tevent_req *req;
774         socklen_t len;
775         int sock;
776
777         /* Accept connection */
778
779         len = sizeof(sunaddr);
780
781         do {
782                 sock = accept(listen_sock, (struct sockaddr *)(void *)&sunaddr,
783                               &len);
784         } while (sock == -1 && errno == EINTR);
785
786         if (sock == -1)
787                 return;
788
789         DEBUG(6,("accepted socket %d\n", sock));
790
791         /* Create new connection structure */
792
793         if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
794                 close(sock);
795                 return;
796         }
797
798         state->sock = sock;
799
800         state->out_queue = tevent_queue_create(state, "winbind client reply");
801         if (state->out_queue == NULL) {
802                 close(sock);
803                 TALLOC_FREE(state);
804                 return;
805         }
806
807         state->last_access = time(NULL);        
808
809         state->privileged = privileged;
810
811         req = wb_req_read_send(state, winbind_event_context(), state->sock,
812                                WINBINDD_MAX_EXTRA_DATA);
813         if (req == NULL) {
814                 TALLOC_FREE(state);
815                 close(sock);
816                 return;
817         }
818         tevent_req_set_callback(req, winbind_client_request_read, state);
819
820         /* Add to connection list */
821
822         winbindd_add_client(state);
823 }
824
825 static void winbind_client_request_read(struct tevent_req *req)
826 {
827         struct winbindd_cli_state *state = tevent_req_callback_data(
828                 req, struct winbindd_cli_state);
829         ssize_t ret;
830         int err;
831
832         ret = wb_req_read_recv(req, state, &state->request, &err);
833         TALLOC_FREE(req);
834         if (ret == -1) {
835                 if (err == EPIPE) {
836                         DEBUG(6, ("closing socket %d, client exited\n",
837                                   state->sock));
838                 } else {
839                         DEBUG(2, ("Could not read client request from fd %d: "
840                                   "%s\n", state->sock, strerror(err)));
841                 }
842                 close(state->sock);
843                 state->sock = -1;
844                 remove_client(state);
845                 return;
846         }
847         process_request(state);
848 }
849
850 /* Remove a client connection from client connection list */
851
852 static void remove_client(struct winbindd_cli_state *state)
853 {
854         char c = 0;
855         int nwritten;
856
857         /* It's a dead client - hold a funeral */
858
859         if (state == NULL) {
860                 return;
861         }
862
863         if (state->sock != -1) {
864                 /* tell client, we are closing ... */
865                 nwritten = write(state->sock, &c, sizeof(c));
866                 if (nwritten == -1) {
867                         DEBUG(2, ("final write to client failed: %s\n",
868                                 strerror(errno)));
869                 }
870
871                 /* Close socket */
872
873                 close(state->sock);
874                 state->sock = -1;
875         }
876
877         TALLOC_FREE(state->mem_ctx);
878
879         /* Remove from list and free */
880
881         winbindd_remove_client(state);
882         TALLOC_FREE(state);
883 }
884
885 /* Shutdown client connection which has been idle for the longest time */
886
887 static bool remove_idle_client(void)
888 {
889         struct winbindd_cli_state *state, *remove_state = NULL;
890         time_t last_access = 0;
891         int nidle = 0;
892
893         for (state = winbindd_client_list(); state; state = state->next) {
894                 if (state->response == NULL &&
895                     !state->pwent_state && !state->grent_state) {
896                         nidle++;
897                         if (!last_access || state->last_access < last_access) {
898                                 last_access = state->last_access;
899                                 remove_state = state;
900                         }
901                 }
902         }
903
904         if (remove_state) {
905                 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
906                         nidle, remove_state->sock, (unsigned int)remove_state->pid));
907                 remove_client(remove_state);
908                 return True;
909         }
910
911         return False;
912 }
913
914 struct winbindd_listen_state {
915         bool privileged;
916         int fd;
917 };
918
919 static void winbindd_listen_fde_handler(struct tevent_context *ev,
920                                         struct tevent_fd *fde,
921                                         uint16_t flags,
922                                         void *private_data)
923 {
924         struct winbindd_listen_state *s = talloc_get_type_abort(private_data,
925                                           struct winbindd_listen_state);
926
927         while (winbindd_num_clients() >
928                WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
929                 DEBUG(5,("winbindd: Exceeding %d client "
930                          "connections, removing idle "
931                          "connection.\n",
932                          WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
933                 if (!remove_idle_client()) {
934                         DEBUG(0,("winbindd: Exceeding %d "
935                                  "client connections, no idle "
936                                  "connection found\n",
937                                  WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
938                         break;
939                 }
940         }
941         new_connection(s->fd, s->privileged);
942 }
943
944 static bool winbindd_setup_listeners(void)
945 {
946         struct winbindd_listen_state *pub_state = NULL;
947         struct winbindd_listen_state *priv_state = NULL;
948         struct tevent_fd *fde;
949
950         pub_state = talloc(winbind_event_context(),
951                            struct winbindd_listen_state);
952         if (!pub_state) {
953                 goto failed;
954         }
955
956         pub_state->privileged = false;
957         pub_state->fd = open_winbindd_socket();
958         if (pub_state->fd == -1) {
959                 goto failed;
960         }
961
962         fde = tevent_add_fd(winbind_event_context(), pub_state, pub_state->fd,
963                             TEVENT_FD_READ, winbindd_listen_fde_handler,
964                             pub_state);
965         if (fde == NULL) {
966                 close(pub_state->fd);
967                 goto failed;
968         }
969         tevent_fd_set_auto_close(fde);
970
971         priv_state = talloc(winbind_event_context(),
972                             struct winbindd_listen_state);
973         if (!priv_state) {
974                 goto failed;
975         }
976
977         priv_state->privileged = true;
978         priv_state->fd = open_winbindd_priv_socket();
979         if (priv_state->fd == -1) {
980                 goto failed;
981         }
982
983         fde = tevent_add_fd(winbind_event_context(), priv_state,
984                             priv_state->fd, TEVENT_FD_READ,
985                             winbindd_listen_fde_handler, priv_state);
986         if (fde == NULL) {
987                 close(priv_state->fd);
988                 goto failed;
989         }
990         tevent_fd_set_auto_close(fde);
991
992         return true;
993 failed:
994         TALLOC_FREE(pub_state);
995         TALLOC_FREE(priv_state);
996         return false;
997 }
998
999 bool winbindd_use_idmap_cache(void)
1000 {
1001         return !opt_nocache;
1002 }
1003
1004 bool winbindd_use_cache(void)
1005 {
1006         return !opt_nocache;
1007 }
1008
1009 /* Main function */
1010
1011 int main(int argc, char **argv, char **envp)
1012 {
1013         static bool is_daemon = False;
1014         static bool Fork = True;
1015         static bool log_stdout = False;
1016         static bool no_process_group = False;
1017         enum {
1018                 OPT_DAEMON = 1000,
1019                 OPT_FORK,
1020                 OPT_NO_PROCESS_GROUP,
1021                 OPT_LOG_STDOUT
1022         };
1023         struct poptOption long_options[] = {
1024                 POPT_AUTOHELP
1025                 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1026                 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1027                 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1028                 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1029                 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1030                 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1031                 POPT_COMMON_SAMBA
1032                 POPT_TABLEEND
1033         };
1034         poptContext pc;
1035         int opt;
1036         TALLOC_CTX *frame = talloc_stackframe();
1037         struct tevent_timer *te;
1038
1039         /* glibc (?) likes to print "User defined signal 1" and exit if a
1040            SIGUSR[12] is received before a handler is installed */
1041
1042         CatchSignal(SIGUSR1, SIG_IGN);
1043         CatchSignal(SIGUSR2, SIG_IGN);
1044
1045         fault_setup((void (*)(void *))fault_quit );
1046         dump_core_setup("winbindd");
1047
1048         load_case_tables();
1049
1050         /* Initialise for running in non-root mode */
1051
1052         sec_init();
1053
1054         set_remote_machine_name("winbindd", False);
1055
1056         /* Set environment variable so we don't recursively call ourselves.
1057            This may also be useful interactively. */
1058
1059         if ( !winbind_off() ) {
1060                 DEBUG(0,("Failed to disable recusive winbindd calls.  Exiting.\n"));
1061                 exit(1);
1062         }
1063
1064         /* Initialise samba/rpc client stuff */
1065
1066         pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1067
1068         while ((opt = poptGetNextOpt(pc)) != -1) {
1069                 switch (opt) {
1070                         /* Don't become a daemon */
1071                 case OPT_DAEMON:
1072                         is_daemon = True;
1073                         break;
1074                 case 'i':
1075                         interactive = True;
1076                         log_stdout = True;
1077                         Fork = False;
1078                         break;
1079                 case OPT_FORK:
1080                         Fork = false;
1081                         break;
1082                 case OPT_NO_PROCESS_GROUP:
1083                         no_process_group = true;
1084                         break;
1085                 case OPT_LOG_STDOUT:
1086                         log_stdout = true;
1087                         break;
1088                 case 'n':
1089                         opt_nocache = true;
1090                         break;
1091                 default:
1092                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1093                                   poptBadOption(pc, 0), poptStrerror(opt));
1094                         poptPrintUsage(pc, stderr, 0);
1095                         exit(1);
1096                 }
1097         }
1098
1099         if (is_daemon && interactive) {
1100                 d_fprintf(stderr,"\nERROR: "
1101                           "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1102                 poptPrintUsage(pc, stderr, 0);
1103                 exit(1);
1104         }
1105
1106         if (log_stdout && Fork) {
1107                 d_fprintf(stderr, "\nERROR: "
1108                           "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1109                 poptPrintUsage(pc, stderr, 0);
1110                 exit(1);
1111         }
1112
1113         poptFreeContext(pc);
1114
1115         if (!override_logfile) {
1116                 char *lfile = NULL;
1117                 if (asprintf(&lfile,"%s/log.winbindd",
1118                                 get_dyn_LOGFILEBASE()) > 0) {
1119                         lp_set_logfile(lfile);
1120                         SAFE_FREE(lfile);
1121                 }
1122         }
1123         setup_logging("winbindd", log_stdout);
1124         reopen_logs();
1125
1126         DEBUG(0,("winbindd version %s started.\n", samba_version_string()));
1127         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1128
1129         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1130                 DEBUG(0, ("error opening config file\n"));
1131                 exit(1);
1132         }
1133
1134         /* Initialise messaging system */
1135
1136         if (winbind_messaging_context() == NULL) {
1137                 exit(1);
1138         }
1139
1140         if (!reload_services_file(NULL)) {
1141                 DEBUG(0, ("error opening config file\n"));
1142                 exit(1);
1143         }
1144
1145         if (!directory_exist(lp_lockdir())) {
1146                 mkdir(lp_lockdir(), 0755);
1147         }
1148
1149         /* Setup names. */
1150
1151         if (!init_names())
1152                 exit(1);
1153
1154         load_interfaces();
1155
1156         if (!secrets_init()) {
1157
1158                 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1159                 return False;
1160         }
1161
1162         /* Enable netbios namecache */
1163
1164         namecache_enable();
1165
1166         /* Unblock all signals we are interested in as they may have been
1167            blocked by the parent process. */
1168
1169         BlockSignals(False, SIGINT);
1170         BlockSignals(False, SIGQUIT);
1171         BlockSignals(False, SIGTERM);
1172         BlockSignals(False, SIGUSR1);
1173         BlockSignals(False, SIGUSR2);
1174         BlockSignals(False, SIGHUP);
1175         BlockSignals(False, SIGCHLD);
1176
1177         if (!interactive)
1178                 become_daemon(Fork, no_process_group, log_stdout);
1179
1180         pidfile_create("winbindd");
1181
1182 #if HAVE_SETPGID
1183         /*
1184          * If we're interactive we want to set our own process group for
1185          * signal management.
1186          */
1187         if (interactive && !no_process_group)
1188                 setpgid( (pid_t)0, (pid_t)0);
1189 #endif
1190
1191         TimeInit();
1192
1193         /* Don't use winbindd_reinit_after_fork here as
1194          * we're just starting up and haven't created any
1195          * winbindd-specific resources we must free yet. JRA.
1196          */
1197
1198         if (!NT_STATUS_IS_OK(reinit_after_fork(winbind_messaging_context(),
1199                                                winbind_event_context(),
1200                                                false))) {
1201                 DEBUG(0,("reinit_after_fork() failed\n"));
1202                 exit(1);
1203         }
1204
1205         /* Setup signal handlers */
1206
1207         if (!winbindd_setup_sig_term_handler(true))
1208                 exit(1);
1209         if (!winbindd_setup_sig_hup_handler(NULL))
1210                 exit(1);
1211         if (!winbindd_setup_sig_chld_handler())
1212                 exit(1);
1213         if (!winbindd_setup_sig_usr2_handler())
1214                 exit(1);
1215
1216         CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
1217
1218         /*
1219          * Ensure all cache and idmap caches are consistent
1220          * and initialized before we startup.
1221          */
1222         if (!winbindd_cache_validate_and_initialize()) {
1223                 exit(1);
1224         }
1225
1226         /* get broadcast messages */
1227
1228         if (!serverid_register_self(FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP)) {
1229                 DEBUG(1, ("Could not register myself in serverid.tdb\n"));
1230                 exit(1);
1231         }
1232
1233         /* React on 'smbcontrol winbindd reload-config' in the same way
1234            as to SIGHUP signal */
1235         messaging_register(winbind_messaging_context(), NULL,
1236                            MSG_SMB_CONF_UPDATED, msg_reload_services);
1237         messaging_register(winbind_messaging_context(), NULL,
1238                            MSG_SHUTDOWN, msg_shutdown);
1239
1240         /* Handle online/offline messages. */
1241         messaging_register(winbind_messaging_context(), NULL,
1242                            MSG_WINBIND_OFFLINE, winbind_msg_offline);
1243         messaging_register(winbind_messaging_context(), NULL,
1244                            MSG_WINBIND_ONLINE, winbind_msg_online);
1245         messaging_register(winbind_messaging_context(), NULL,
1246                            MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1247
1248         messaging_register(winbind_messaging_context(), NULL,
1249                            MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1250
1251         messaging_register(winbind_messaging_context(), NULL,
1252                            MSG_WINBIND_VALIDATE_CACHE,
1253                            winbind_msg_validate_cache);
1254
1255         messaging_register(winbind_messaging_context(), NULL,
1256                            MSG_WINBIND_DUMP_DOMAIN_LIST,
1257                            winbind_msg_dump_domain_list);
1258
1259         /* Register handler for MSG_DEBUG. */
1260         messaging_register(winbind_messaging_context(), NULL,
1261                            MSG_DEBUG,
1262                            winbind_msg_debug);
1263
1264         netsamlogon_cache_init(); /* Non-critical */
1265
1266         /* clear the cached list of trusted domains */
1267
1268         wcache_tdc_clear();     
1269
1270         if (!init_domain_list()) {
1271                 DEBUG(0,("unable to initialize domain list\n"));
1272                 exit(1);
1273         }
1274
1275         init_idmap_child();
1276         init_locator_child();
1277
1278         smb_nscd_flush_user_cache();
1279         smb_nscd_flush_group_cache();
1280
1281         /* setup listen sockets */
1282
1283         if (!winbindd_setup_listeners()) {
1284                 DEBUG(0,("winbindd_setup_listeners() failed\n"));
1285                 exit(1);
1286         }
1287
1288         te = tevent_add_timer(winbind_event_context(), NULL, timeval_zero(),
1289                               rescan_trusted_domains, NULL);
1290         if (te == NULL) {
1291                 DEBUG(0, ("Could not trigger rescan_trusted_domains()\n"));
1292                 exit(1);
1293         }
1294
1295         TALLOC_FREE(frame);
1296         /* Loop waiting for requests */
1297         while (1) {
1298                 frame = talloc_stackframe();
1299
1300                 if (tevent_loop_once(winbind_event_context()) == -1) {
1301                         DEBUG(1, ("tevent_loop_once() failed: %s\n",
1302                                   strerror(errno)));
1303                         return 1;
1304                 }
1305
1306                 TALLOC_FREE(frame);
1307         }
1308
1309         return 0;
1310 }