s3: Add wbinfo --dc-info
[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_DC_INFO, winbindd_dc_info, "DC_INFO" },
502         { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
503         { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
504           "WINBINDD_PRIV_PIPE_DIR" },
505         { WINBINDD_GETDCNAME, winbindd_getdcname, "GETDCNAME" },
506         { WINBINDD_DSGETDCNAME, winbindd_dsgetdcname, "DSGETDCNAME" },
507
508         /* Credential cache access */
509         { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
510
511         /* WINS functions */
512
513         { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
514         { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
515
516         /* End of list */
517
518         { WINBINDD_NUM_CMDS, NULL, "NONE" }
519 };
520
521 static void process_request(struct winbindd_cli_state *state)
522 {
523         struct winbindd_dispatch_table *table = dispatch_table;
524
525         /* Free response data - we may be interrupted and receive another
526            command before being able to send this data off. */
527
528         SAFE_FREE(state->response.extra_data.data);  
529
530         ZERO_STRUCT(state->response);
531
532         state->response.result = WINBINDD_PENDING;
533         state->response.length = sizeof(struct winbindd_response);
534
535         state->mem_ctx = talloc_init("winbind request");
536         if (state->mem_ctx == NULL)
537                 return;
538
539         /* Remember who asked us. */
540         state->pid = state->request.pid;
541
542         /* Process command */
543
544         for (table = dispatch_table; table->fn; table++) {
545                 if (state->request.cmd == table->cmd) {
546                         DEBUG(10,("process_request: request fn %s\n",
547                                   table->winbindd_cmd_name ));
548                         table->fn(state);
549                         break;
550                 }
551         }
552
553         if (!table->fn) {
554                 DEBUG(10,("process_request: unknown request fn number %d\n",
555                           (int)state->request.cmd ));
556                 request_error(state);
557         }
558 }
559
560 /*
561  * A list of file descriptors being monitored by select in the main processing
562  * loop. winbindd_fd_event->handler is called whenever the socket is readable/writable.
563  */
564
565 static struct winbindd_fd_event *fd_events = NULL;
566
567 void add_fd_event(struct winbindd_fd_event *ev)
568 {
569         struct winbindd_fd_event *match;
570
571         /* only add unique winbindd_fd_event structs */
572
573         for (match=fd_events; match; match=match->next ) {
574 #ifdef DEVELOPER
575                 SMB_ASSERT( match != ev );
576 #else
577                 if ( match == ev )
578                         return;
579 #endif
580         }
581
582         DLIST_ADD(fd_events, ev);
583 }
584
585 void remove_fd_event(struct winbindd_fd_event *ev)
586 {
587         DLIST_REMOVE(fd_events, ev);
588 }
589
590 /*
591  * Handler for winbindd_fd_events to complete a read/write request, set up by
592  * setup_async_read/setup_async_write.
593  */
594
595 static void rw_callback(struct winbindd_fd_event *event, int flags)
596 {
597         size_t todo;
598         ssize_t done = 0;
599
600         todo = event->length - event->done;
601
602         if (event->flags & EVENT_FD_WRITE) {
603                 SMB_ASSERT(flags == EVENT_FD_WRITE);
604                 done = sys_write(event->fd,
605                                  &((char *)event->data)[event->done],
606                                  todo);
607
608                 if (done <= 0) {
609                         event->flags = 0;
610                         event->finished(event->private_data, False);
611                         return;
612                 }
613         }
614
615         if (event->flags & EVENT_FD_READ) {
616                 SMB_ASSERT(flags == EVENT_FD_READ);
617                 done = sys_read(event->fd, &((char *)event->data)[event->done],
618                                 todo);
619
620                 if (done <= 0) {
621                         event->flags = 0;
622                         event->finished(event->private_data, False);
623                         return;
624                 }
625         }
626
627         event->done += done;
628
629         if (event->done == event->length) {
630                 event->flags = 0;
631                 event->finished(event->private_data, True);
632         }
633 }
634
635 /*
636  * Request an async read/write on a winbindd_fd_event structure. (*finished) is called
637  * when the request is completed or an error had occurred.
638  */
639
640 void setup_async_read(struct winbindd_fd_event *event, void *data, size_t length,
641                       void (*finished)(void *private_data, bool success),
642                       void *private_data)
643 {
644         SMB_ASSERT(event->flags == 0);
645         event->data = data;
646         event->length = length;
647         event->done = 0;
648         event->handler = rw_callback;
649         event->finished = finished;
650         event->private_data = private_data;
651         event->flags = EVENT_FD_READ;
652 }
653
654 void setup_async_write(struct winbindd_fd_event *event, void *data, size_t length,
655                        void (*finished)(void *private_data, bool success),
656                        void *private_data)
657 {
658         SMB_ASSERT(event->flags == 0);
659         event->data = data;
660         event->length = length;
661         event->done = 0;
662         event->handler = rw_callback;
663         event->finished = finished;
664         event->private_data = private_data;
665         event->flags = EVENT_FD_WRITE;
666 }
667
668 /*
669  * This is the main event loop of winbind requests. It goes through a
670  * state-machine of 3 read/write requests, 4 if you have extra data to send.
671  *
672  * An idle winbind client has a read request of 4 bytes outstanding,
673  * finalizing function is request_len_recv, checking the length. request_recv
674  * then processes the packet. The processing function then at some point has
675  * to call request_finished which schedules sending the response.
676  */
677
678 static void request_len_recv(void *private_data, bool success);
679 static void request_recv(void *private_data, bool success);
680 static void request_main_recv(void *private_data, bool success);
681 static void request_finished(struct winbindd_cli_state *state);
682 static void response_main_sent(void *private_data, bool success);
683 static void response_extra_sent(void *private_data, bool success);
684
685 static void response_extra_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         TALLOC_FREE(state->mem_ctx);
691
692         if (!success) {
693                 state->finished = True;
694                 return;
695         }
696
697         SAFE_FREE(state->response.extra_data.data);
698
699         setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
700                          request_len_recv, state);
701 }
702
703 static void response_main_sent(void *private_data, bool success)
704 {
705         struct winbindd_cli_state *state =
706                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
707
708         if (!success) {
709                 state->finished = True;
710                 return;
711         }
712
713         if (state->response.length == sizeof(state->response)) {
714                 TALLOC_FREE(state->mem_ctx);
715
716                 setup_async_read(&state->fd_event, &state->request,
717                                  sizeof(uint32), request_len_recv, state);
718                 return;
719         }
720
721         setup_async_write(&state->fd_event, state->response.extra_data.data,
722                           state->response.length - sizeof(state->response),
723                           response_extra_sent, state);
724 }
725
726 static void request_finished(struct winbindd_cli_state *state)
727 {
728         /* Make sure request.extra_data is freed when finish processing a request */
729         SAFE_FREE(state->request.extra_data.data);
730         setup_async_write(&state->fd_event, &state->response,
731                           sizeof(state->response), response_main_sent, state);
732 }
733
734 void request_error(struct winbindd_cli_state *state)
735 {
736         SMB_ASSERT(state->response.result == WINBINDD_PENDING);
737         state->response.result = WINBINDD_ERROR;
738         request_finished(state);
739 }
740
741 void request_ok(struct winbindd_cli_state *state)
742 {
743         SMB_ASSERT(state->response.result == WINBINDD_PENDING);
744         state->response.result = WINBINDD_OK;
745         request_finished(state);
746 }
747
748 static void request_len_recv(void *private_data, bool success)
749 {
750         struct winbindd_cli_state *state =
751                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
752
753         if (!success) {
754                 state->finished = True;
755                 return;
756         }
757
758         if (*(uint32 *)(&state->request) != sizeof(state->request)) {
759                 DEBUG(0,("request_len_recv: Invalid request size received: %d (expected %u)\n",
760                          *(uint32_t *)(&state->request), (uint32_t)sizeof(state->request)));
761                 state->finished = True;
762                 return;
763         }
764
765         setup_async_read(&state->fd_event, (uint32 *)(&state->request)+1,
766                          sizeof(state->request) - sizeof(uint32),
767                          request_main_recv, state);
768 }
769
770 static void request_main_recv(void *private_data, bool success)
771 {
772         struct winbindd_cli_state *state =
773                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
774
775         if (!success) {
776                 state->finished = True;
777                 return;
778         }
779
780         if (state->request.extra_len == 0) {
781                 state->request.extra_data.data = NULL;
782                 request_recv(state, True);
783                 return;
784         }
785
786         if ((!state->privileged) &&
787             (state->request.extra_len > WINBINDD_MAX_EXTRA_DATA)) {
788                 DEBUG(3, ("Got request with %d bytes extra data on "
789                           "unprivileged socket\n", (int)state->request.extra_len));
790                 state->request.extra_data.data = NULL;
791                 state->finished = True;
792                 return;
793         }
794
795         state->request.extra_data.data =
796                 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
797
798         if (state->request.extra_data.data == NULL) {
799                 DEBUG(0, ("malloc failed\n"));
800                 state->finished = True;
801                 return;
802         }
803
804         /* Ensure null termination */
805         state->request.extra_data.data[state->request.extra_len] = '\0';
806
807         setup_async_read(&state->fd_event, state->request.extra_data.data,
808                          state->request.extra_len, request_recv, state);
809 }
810
811 static void request_recv(void *private_data, bool success)
812 {
813         struct winbindd_cli_state *state =
814                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
815
816         if (!success) {
817                 state->finished = True;
818                 return;
819         }
820
821         process_request(state);
822 }
823
824 /* Process a new connection by adding it to the client connection list */
825
826 static void new_connection(int listen_sock, bool privileged)
827 {
828         struct sockaddr_un sunaddr;
829         struct winbindd_cli_state *state;
830         socklen_t len;
831         int sock;
832
833         /* Accept connection */
834
835         len = sizeof(sunaddr);
836
837         do {
838                 sock = accept(listen_sock, (struct sockaddr *)&sunaddr, &len);
839         } while (sock == -1 && errno == EINTR);
840
841         if (sock == -1)
842                 return;
843
844         DEBUG(6,("accepted socket %d\n", sock));
845
846         /* Create new connection structure */
847
848         if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
849                 close(sock);
850                 return;
851         }
852
853         state->sock = sock;
854
855         state->last_access = time(NULL);        
856
857         state->privileged = privileged;
858
859         state->fd_event.fd = state->sock;
860         state->fd_event.flags = 0;
861         add_fd_event(&state->fd_event);
862
863         setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
864                          request_len_recv, state);
865
866         /* Add to connection list */
867
868         winbindd_add_client(state);
869 }
870
871 /* Remove a client connection from client connection list */
872
873 static void remove_client(struct winbindd_cli_state *state)
874 {
875         char c = 0;
876         int nwritten;
877
878         /* It's a dead client - hold a funeral */
879
880         if (state == NULL) {
881                 return;
882         }
883
884         if (!state->finished) {
885                 /* tell client, we are closing ... */
886                 nwritten = write(state->sock, &c, sizeof(c));
887                 if (nwritten == -1) {
888                         DEBUG(2, ("final write to client failed: %s\n",
889                                   strerror(errno)));
890                 }
891         }
892
893         /* Close socket */
894
895         close(state->sock);
896
897         /* Free any getent state */
898
899         free_getent_state(state->getpwent_state);
900         free_getent_state(state->getgrent_state);
901
902         /* We may have some extra data that was not freed if the client was
903            killed unexpectedly */
904
905         SAFE_FREE(state->response.extra_data.data);
906
907         TALLOC_FREE(state->mem_ctx);
908
909         remove_fd_event(&state->fd_event);
910
911         /* Remove from list and free */
912
913         winbindd_remove_client(state);
914         TALLOC_FREE(state);
915 }
916
917 /* Shutdown client connection which has been idle for the longest time */
918
919 static bool remove_idle_client(void)
920 {
921         struct winbindd_cli_state *state, *remove_state = NULL;
922         time_t last_access = 0;
923         int nidle = 0;
924
925         for (state = winbindd_client_list(); state; state = state->next) {
926                 if (state->response.result != WINBINDD_PENDING &&
927                     state->fd_event.flags == EVENT_FD_READ &&
928                     !state->getpwent_state && !state->getgrent_state) {
929                         nidle++;
930                         if (!last_access || state->last_access < last_access) {
931                                 last_access = state->last_access;
932                                 remove_state = state;
933                         }
934                 }
935         }
936
937         if (remove_state) {
938                 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
939                         nidle, remove_state->sock, (unsigned int)remove_state->pid));
940                 remove_client(remove_state);
941                 return True;
942         }
943
944         return False;
945 }
946
947 struct winbindd_listen_state {
948         bool privileged;
949         int fd;
950         struct tevent_fd *fde;
951 };
952
953 static void winbindd_listen_fde_handler(struct tevent_context *ev,
954                                         struct tevent_fd *fde,
955                                         uint16_t flags,
956                                         void *private_data)
957 {
958         struct winbindd_listen_state *s = talloc_get_type_abort(private_data,
959                                           struct winbindd_listen_state);
960
961         while (winbindd_num_clients() >
962                WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
963                 DEBUG(5,("winbindd: Exceeding %d client "
964                          "connections, removing idle "
965                          "connection.\n",
966                          WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
967                 if (!remove_idle_client()) {
968                         DEBUG(0,("winbindd: Exceeding %d "
969                                  "client connections, no idle "
970                                  "connection found\n",
971                                  WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
972                         break;
973                 }
974         }
975
976         /* new, non-privileged connection */
977         new_connection(s->fd, s->privileged);
978 }
979
980 static bool winbindd_setup_listeners(void)
981 {
982         struct winbindd_listen_state *pub_state = NULL;
983         struct winbindd_listen_state *priv_state = NULL;
984
985         pub_state = talloc(winbind_event_context(),
986                            struct winbindd_listen_state);
987         if (!pub_state) {
988                 goto failed;
989         }
990
991         pub_state->privileged = false;
992         pub_state->fd = open_winbindd_socket();
993         if (pub_state->fd == -1) {
994                 goto failed;
995         }
996
997         pub_state->fde = tevent_add_fd(winbind_event_context(),
998                                        pub_state, pub_state->fd,
999                                        TEVENT_FD_READ,
1000                                        winbindd_listen_fde_handler,
1001                                        pub_state);
1002         if (!pub_state->fde) {
1003                 close(pub_state->fd);
1004                 goto failed;
1005         }
1006         tevent_fd_set_auto_close(pub_state->fde);
1007
1008         priv_state = talloc(winbind_event_context(),
1009                             struct winbindd_listen_state);
1010         if (!priv_state) {
1011                 goto failed;
1012         }
1013
1014         priv_state->privileged = true;
1015         priv_state->fd = open_winbindd_priv_socket();
1016         if (priv_state->fd == -1) {
1017                 goto failed;
1018         }
1019
1020         priv_state->fde = tevent_add_fd(winbind_event_context(),
1021                                         priv_state, priv_state->fd,
1022                                         TEVENT_FD_READ,
1023                                         winbindd_listen_fde_handler,
1024                                         priv_state);
1025         if (!priv_state->fde) {
1026                 close(priv_state->fd);
1027                 goto failed;
1028         }
1029         tevent_fd_set_auto_close(priv_state->fde);
1030
1031         return true;
1032 failed:
1033         TALLOC_FREE(pub_state);
1034         TALLOC_FREE(priv_state);
1035         return false;
1036 }
1037
1038 /* Process incoming clients on listen_sock.  We use a tricky non-blocking,
1039    non-forking, non-threaded model which allows us to handle many
1040    simultaneous connections while remaining impervious to many denial of
1041    service attacks. */
1042
1043 static void process_loop(void)
1044 {
1045         struct winbindd_fd_event *ev;
1046         fd_set r_fds, w_fds;
1047         int maxfd = 0, selret;
1048         struct timeval timeout, ev_timeout;
1049
1050         if (run_events(winbind_event_context(), 0, NULL, NULL)) {
1051                 return;
1052         }
1053
1054         /* Initialise fd lists for select() */
1055
1056         FD_ZERO(&r_fds);
1057         FD_ZERO(&w_fds);
1058
1059         timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
1060         timeout.tv_usec = 0;
1061
1062         /* Check for any event timeouts. */
1063         {
1064                 struct timeval now;
1065                 GetTimeOfDay(&now);
1066
1067                 event_add_to_select_args(winbind_event_context(), &now,
1068                                          &r_fds, &w_fds, &ev_timeout, &maxfd);
1069         }
1070         if (get_timed_events_timeout(winbind_event_context(), &ev_timeout)) {
1071                 timeout = timeval_min(&timeout, &ev_timeout);
1072         }
1073
1074         for (ev = fd_events; ev; ev = ev->next) {
1075                 if (ev->flags & EVENT_FD_READ) {
1076                         FD_SET(ev->fd, &r_fds);
1077                         maxfd = MAX(ev->fd, maxfd);
1078                 }
1079                 if (ev->flags & EVENT_FD_WRITE) {
1080                         FD_SET(ev->fd, &w_fds);
1081                         maxfd = MAX(ev->fd, maxfd);
1082                 }
1083         }
1084
1085         /* Call select */
1086
1087         selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
1088
1089         if (selret == 0) {
1090                 goto no_fds_ready;
1091         }
1092
1093         if (selret == -1) {
1094                 if (errno == EINTR) {
1095                         goto no_fds_ready;
1096                 }
1097
1098                 /* Select error, something is badly wrong */
1099
1100                 perror("select");
1101                 exit(1);
1102         }
1103
1104         /* selret > 0 */
1105
1106         if (run_events(winbind_event_context(), selret, &r_fds, &w_fds)) {
1107                 return;
1108         }
1109
1110         ev = fd_events;
1111         while (ev != NULL) {
1112                 struct winbindd_fd_event *next = ev->next;
1113                 int flags = 0;
1114                 if (FD_ISSET(ev->fd, &r_fds))
1115                         flags |= EVENT_FD_READ;
1116                 if (FD_ISSET(ev->fd, &w_fds))
1117                         flags |= EVENT_FD_WRITE;
1118                 if (flags) {
1119                         ev->handler(ev, flags);
1120                         return;
1121                 }
1122                 ev = next;
1123         }
1124
1125         return;
1126
1127  no_fds_ready:
1128
1129         run_events(winbind_event_context(), selret, &r_fds, &w_fds);
1130
1131 #if 0
1132         winbindd_check_cache_size(time(NULL));
1133 #endif
1134 }
1135
1136 bool winbindd_use_idmap_cache(void)
1137 {
1138         return !opt_nocache;
1139 }
1140
1141 bool winbindd_use_cache(void)
1142 {
1143         return !opt_nocache;
1144 }
1145
1146 /* Main function */
1147
1148 int main(int argc, char **argv, char **envp)
1149 {
1150         static bool is_daemon = False;
1151         static bool Fork = True;
1152         static bool log_stdout = False;
1153         static bool no_process_group = False;
1154         enum {
1155                 OPT_DAEMON = 1000,
1156                 OPT_FORK,
1157                 OPT_NO_PROCESS_GROUP,
1158                 OPT_LOG_STDOUT
1159         };
1160         struct poptOption long_options[] = {
1161                 POPT_AUTOHELP
1162                 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1163                 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1164                 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1165                 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1166                 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1167                 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1168                 POPT_COMMON_SAMBA
1169                 POPT_TABLEEND
1170         };
1171         poptContext pc;
1172         int opt;
1173         TALLOC_CTX *frame = talloc_stackframe();
1174
1175         /* glibc (?) likes to print "User defined signal 1" and exit if a
1176            SIGUSR[12] is received before a handler is installed */
1177
1178         CatchSignal(SIGUSR1, SIG_IGN);
1179         CatchSignal(SIGUSR2, SIG_IGN);
1180
1181         fault_setup((void (*)(void *))fault_quit );
1182         dump_core_setup("winbindd");
1183
1184         load_case_tables();
1185
1186         /* Initialise for running in non-root mode */
1187
1188         sec_init();
1189
1190         set_remote_machine_name("winbindd", False);
1191
1192         /* Set environment variable so we don't recursively call ourselves.
1193            This may also be useful interactively. */
1194
1195         if ( !winbind_off() ) {
1196                 DEBUG(0,("Failed to disable recusive winbindd calls.  Exiting.\n"));
1197                 exit(1);
1198         }
1199
1200         /* Initialise samba/rpc client stuff */
1201
1202         pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1203
1204         while ((opt = poptGetNextOpt(pc)) != -1) {
1205                 switch (opt) {
1206                         /* Don't become a daemon */
1207                 case OPT_DAEMON:
1208                         is_daemon = True;
1209                         break;
1210                 case 'i':
1211                         interactive = True;
1212                         log_stdout = True;
1213                         Fork = False;
1214                         break;
1215                 case OPT_FORK:
1216                         Fork = false;
1217                         break;
1218                 case OPT_NO_PROCESS_GROUP:
1219                         no_process_group = true;
1220                         break;
1221                 case OPT_LOG_STDOUT:
1222                         log_stdout = true;
1223                         break;
1224                 case 'n':
1225                         opt_nocache = true;
1226                         break;
1227                 default:
1228                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1229                                   poptBadOption(pc, 0), poptStrerror(opt));
1230                         poptPrintUsage(pc, stderr, 0);
1231                         exit(1);
1232                 }
1233         }
1234
1235         if (is_daemon && interactive) {
1236                 d_fprintf(stderr,"\nERROR: "
1237                           "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1238                 poptPrintUsage(pc, stderr, 0);
1239                 exit(1);
1240         }
1241
1242         if (log_stdout && Fork) {
1243                 d_fprintf(stderr, "\nERROR: "
1244                           "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1245                 poptPrintUsage(pc, stderr, 0);
1246                 exit(1);
1247         }
1248
1249         poptFreeContext(pc);
1250
1251         if (!override_logfile) {
1252                 char *lfile = NULL;
1253                 if (asprintf(&lfile,"%s/log.winbindd",
1254                                 get_dyn_LOGFILEBASE()) > 0) {
1255                         lp_set_logfile(lfile);
1256                         SAFE_FREE(lfile);
1257                 }
1258         }
1259         setup_logging("winbindd", log_stdout);
1260         reopen_logs();
1261
1262         DEBUG(0,("winbindd version %s started.\n", samba_version_string()));
1263         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1264
1265         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1266                 DEBUG(0, ("error opening config file\n"));
1267                 exit(1);
1268         }
1269
1270         /* Initialise messaging system */
1271
1272         if (winbind_messaging_context() == NULL) {
1273                 exit(1);
1274         }
1275
1276         if (!reload_services_file(NULL)) {
1277                 DEBUG(0, ("error opening config file\n"));
1278                 exit(1);
1279         }
1280
1281         if (!directory_exist(lp_lockdir())) {
1282                 mkdir(lp_lockdir(), 0755);
1283         }
1284
1285         /* Setup names. */
1286
1287         if (!init_names())
1288                 exit(1);
1289
1290         load_interfaces();
1291
1292         if (!secrets_init()) {
1293
1294                 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1295                 return False;
1296         }
1297
1298         /* Enable netbios namecache */
1299
1300         namecache_enable();
1301
1302         /* Unblock all signals we are interested in as they may have been
1303            blocked by the parent process. */
1304
1305         BlockSignals(False, SIGINT);
1306         BlockSignals(False, SIGQUIT);
1307         BlockSignals(False, SIGTERM);
1308         BlockSignals(False, SIGUSR1);
1309         BlockSignals(False, SIGUSR2);
1310         BlockSignals(False, SIGHUP);
1311         BlockSignals(False, SIGCHLD);
1312         BlockSignals(False, SIGXCPU);
1313
1314         if (!interactive)
1315                 become_daemon(Fork, no_process_group);
1316
1317         pidfile_create("winbindd");
1318
1319 #if HAVE_SETPGID
1320         /*
1321          * If we're interactive we want to set our own process group for
1322          * signal management.
1323          */
1324         if (interactive && !no_process_group)
1325                 setpgid( (pid_t)0, (pid_t)0);
1326 #endif
1327
1328         TimeInit();
1329
1330         /* Don't use winbindd_reinit_after_fork here as
1331          * we're just starting up and haven't created any
1332          * winbindd-specific resources we must free yet. JRA.
1333          */
1334
1335         if (!NT_STATUS_IS_OK(reinit_after_fork(winbind_messaging_context(),
1336                                                winbind_event_context(),
1337                                                false))) {
1338                 DEBUG(0,("reinit_after_fork() failed\n"));
1339                 exit(1);
1340         }
1341
1342         /* Setup signal handlers */
1343
1344         if (!winbindd_setup_sig_term_handler(true))
1345                 exit(1);
1346         if (!winbindd_setup_sig_hup_handler(NULL))
1347                 exit(1);
1348         if (!winbindd_setup_sig_chld_handler())
1349                 exit(1);
1350         if (!winbindd_setup_sig_usr2_handler())
1351                 exit(1);
1352
1353         CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
1354
1355         /*
1356          * Ensure all cache and idmap caches are consistent
1357          * and initialized before we startup.
1358          */
1359         if (!winbindd_cache_validate_and_initialize()) {
1360                 exit(1);
1361         }
1362
1363         /* get broadcast messages */
1364
1365         if (!serverid_register(procid_self(),
1366                                FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP)) {
1367                 DEBUG(1, ("Could not register myself in serverid.tdb\n"));
1368                 exit(1);
1369         }
1370
1371         /* React on 'smbcontrol winbindd reload-config' in the same way
1372            as to SIGHUP signal */
1373         messaging_register(winbind_messaging_context(), NULL,
1374                            MSG_SMB_CONF_UPDATED, msg_reload_services);
1375         messaging_register(winbind_messaging_context(), NULL,
1376                            MSG_SHUTDOWN, msg_shutdown);
1377
1378         /* Handle online/offline messages. */
1379         messaging_register(winbind_messaging_context(), NULL,
1380                            MSG_WINBIND_OFFLINE, winbind_msg_offline);
1381         messaging_register(winbind_messaging_context(), NULL,
1382                            MSG_WINBIND_ONLINE, winbind_msg_online);
1383         messaging_register(winbind_messaging_context(), NULL,
1384                            MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1385
1386         messaging_register(winbind_messaging_context(), NULL,
1387                            MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1388
1389         messaging_register(winbind_messaging_context(), NULL,
1390                            MSG_WINBIND_VALIDATE_CACHE,
1391                            winbind_msg_validate_cache);
1392
1393         messaging_register(winbind_messaging_context(), NULL,
1394                            MSG_WINBIND_DUMP_DOMAIN_LIST,
1395                            winbind_msg_dump_domain_list);
1396
1397         messaging_register(winbind_messaging_context(), NULL,
1398                            MSG_WINBIND_IP_DROPPED,
1399                            winbind_msg_ip_dropped_parent);
1400
1401         /* Register handler for MSG_DEBUG. */
1402         messaging_register(winbind_messaging_context(), NULL,
1403                            MSG_DEBUG,
1404                            winbind_msg_debug);
1405
1406         netsamlogon_cache_init(); /* Non-critical */
1407
1408         /* clear the cached list of trusted domains */
1409
1410         wcache_tdc_clear();     
1411
1412         if (!init_domain_list()) {
1413                 DEBUG(0,("unable to initialize domain list\n"));
1414                 exit(1);
1415         }
1416
1417         init_idmap_child();
1418         init_locator_child();
1419
1420         smb_nscd_flush_user_cache();
1421         smb_nscd_flush_group_cache();
1422
1423         /* setup listen sockets */
1424
1425         if (!winbindd_setup_listeners()) {
1426                 DEBUG(0,("winbindd_setup_listeners() failed\n"));
1427                 exit(1);
1428         }
1429
1430         TALLOC_FREE(frame);
1431         /* Loop waiting for requests */
1432         while (1) {
1433                 struct winbindd_cli_state *state;
1434
1435                 frame = talloc_stackframe();
1436
1437                 /* refresh the trusted domain cache */
1438
1439                 rescan_trusted_domains();
1440
1441                 /* Dispose of client connection if it is marked as
1442                    finished */
1443                 state = winbindd_client_list();
1444                 while (state) {
1445                         struct winbindd_cli_state *next = state->next;
1446
1447                         if (state->finished) {
1448                                 remove_client(state);
1449                         }
1450
1451                         state = next;
1452                 }
1453
1454                 process_loop();
1455
1456                 TALLOC_FREE(frame);
1457         }
1458
1459         return 0;
1460 }