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