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