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