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