Merge branch 'master' of ssh://git.samba.org/data/git/samba
[sfrench/samba-autobuild/.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 *lfile)
63 {
64         bool ret;
65
66         if (lp_loaded()) {
67                 const char *fname = lp_configfile();
68
69                 if (file_exist(fname) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
70                         set_dyn_CONFIGFILE(fname);
71                 }
72         }
73
74         /* if this is a child, restore the logfile to the special
75            name - <domain>, idmap, etc. */
76         if (lfile && *lfile) {
77                 lp_set_logfile(lfile);
78         }
79
80         reopen_logs();
81         ret = lp_load(get_dyn_CONFIGFILE(),False,False,True,True);
82
83         reopen_logs();
84         load_interfaces();
85
86         return(ret);
87 }
88
89
90 /**************************************************************************** **
91  Handle a fault..
92  **************************************************************************** */
93
94 static void fault_quit(void)
95 {
96         dump_core();
97 }
98
99 static void winbindd_status(void)
100 {
101         struct winbindd_cli_state *tmp;
102
103         DEBUG(0, ("winbindd status:\n"));
104
105         /* Print client state information */
106         
107         DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
108         
109         if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
110                 DEBUG(2, ("\tclient list:\n"));
111                 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
112                         DEBUGADD(2, ("\t\tpid %lu, sock %d\n",
113                                   (unsigned long)tmp->pid, tmp->sock));
114                 }
115         }
116 }
117
118 /* Print winbindd status to log file */
119
120 static void print_winbindd_status(void)
121 {
122         winbindd_status();
123 }
124
125 /* Flush client cache */
126
127 static void flush_caches(void)
128 {
129         /* We need to invalidate cached user list entries on a SIGHUP 
130            otherwise cached access denied errors due to restrict anonymous
131            hang around until the sequence number changes. */
132
133         if (!wcache_invalidate_cache()) {
134                 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
135                 if (!winbindd_cache_validate_and_initialize()) {
136                         exit(1);
137                 }
138         }
139 }
140
141 /* Handle the signal by unlinking socket and exiting */
142
143 static void terminate(bool is_parent)
144 {
145         if (is_parent) {
146                 /* When parent goes away we should
147                  * remove the socket file. Not so
148                  * when children terminate.
149                  */ 
150                 char *path = NULL;
151
152                 if (asprintf(&path, "%s/%s",
153                         get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME) > 0) {
154                         unlink(path);
155                         SAFE_FREE(path);
156                 }
157         }
158
159         idmap_close();
160         
161         trustdom_cache_shutdown();
162
163 #if 0
164         if (interactive) {
165                 TALLOC_CTX *mem_ctx = talloc_init("end_description");
166                 char *description = talloc_describe_all(mem_ctx);
167
168                 DEBUG(3, ("tallocs left:\n%s\n", description));
169                 talloc_destroy(mem_ctx);
170         }
171 #endif
172
173         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         { WINBINDD_ALLOCATE_UID, winbindd_allocate_uid, "ALLOCATE_UID" },
344         { WINBINDD_ALLOCATE_GID, winbindd_allocate_gid, "ALLOCATE_GID" },
345         { WINBINDD_SET_MAPPING, winbindd_set_mapping, "SET_MAPPING" },
346         { WINBINDD_REMOVE_MAPPING, winbindd_remove_mapping, "REMOVE_MAPPING" },
347         { WINBINDD_SET_HWM, winbindd_set_hwm, "SET_HWMS" },
348
349         /* Miscellaneous */
350
351         { WINBINDD_CHECK_MACHACC, winbindd_check_machine_acct, "CHECK_MACHACC" },
352         { WINBINDD_PING, winbindd_ping, "PING" },
353         { WINBINDD_INFO, winbindd_info, "INFO" },
354         { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
355           "INTERFACE_VERSION" },
356         { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
357         { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
358         { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
359         { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
360           "WINBINDD_PRIV_PIPE_DIR" },
361         { WINBINDD_GETDCNAME, winbindd_getdcname, "GETDCNAME" },
362         { WINBINDD_DSGETDCNAME, winbindd_dsgetdcname, "DSGETDCNAME" },
363
364         /* Credential cache access */
365         { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
366
367         /* WINS functions */
368
369         { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
370         { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
371
372         /* End of list */
373
374         { WINBINDD_NUM_CMDS, NULL, "NONE" }
375 };
376
377 static void process_request(struct winbindd_cli_state *state)
378 {
379         struct winbindd_dispatch_table *table = dispatch_table;
380
381         /* Free response data - we may be interrupted and receive another
382            command before being able to send this data off. */
383
384         SAFE_FREE(state->response.extra_data.data);  
385
386         ZERO_STRUCT(state->response);
387
388         state->response.result = WINBINDD_PENDING;
389         state->response.length = sizeof(struct winbindd_response);
390
391         state->mem_ctx = talloc_init("winbind request");
392         if (state->mem_ctx == NULL)
393                 return;
394
395         /* Remember who asked us. */
396         state->pid = state->request.pid;
397
398         /* Process command */
399
400         for (table = dispatch_table; table->fn; table++) {
401                 if (state->request.cmd == table->cmd) {
402                         DEBUG(10,("process_request: request fn %s\n",
403                                   table->winbindd_cmd_name ));
404                         table->fn(state);
405                         break;
406                 }
407         }
408
409         if (!table->fn) {
410                 DEBUG(10,("process_request: unknown request fn number %d\n",
411                           (int)state->request.cmd ));
412                 request_error(state);
413         }
414 }
415
416 /*
417  * A list of file descriptors being monitored by select in the main processing
418  * loop. fd_event->handler is called whenever the socket is readable/writable.
419  */
420
421 static struct fd_event *fd_events = NULL;
422
423 void add_fd_event(struct fd_event *ev)
424 {
425         struct fd_event *match;
426
427         /* only add unique fd_event structs */
428
429         for (match=fd_events; match; match=match->next ) {
430 #ifdef DEVELOPER
431                 SMB_ASSERT( match != ev );
432 #else
433                 if ( match == ev )
434                         return;
435 #endif
436         }
437
438         DLIST_ADD(fd_events, ev);
439 }
440
441 void remove_fd_event(struct fd_event *ev)
442 {
443         DLIST_REMOVE(fd_events, ev);
444 }
445
446 /*
447  * Handler for fd_events to complete a read/write request, set up by
448  * setup_async_read/setup_async_write.
449  */
450
451 static void rw_callback(struct fd_event *event, int flags)
452 {
453         size_t todo;
454         ssize_t done = 0;
455
456         todo = event->length - event->done;
457
458         if (event->flags & EVENT_FD_WRITE) {
459                 SMB_ASSERT(flags == EVENT_FD_WRITE);
460                 done = sys_write(event->fd,
461                                  &((char *)event->data)[event->done],
462                                  todo);
463
464                 if (done <= 0) {
465                         event->flags = 0;
466                         event->finished(event->private_data, False);
467                         return;
468                 }
469         }
470
471         if (event->flags & EVENT_FD_READ) {
472                 SMB_ASSERT(flags == EVENT_FD_READ);
473                 done = sys_read(event->fd, &((char *)event->data)[event->done],
474                                 todo);
475
476                 if (done <= 0) {
477                         event->flags = 0;
478                         event->finished(event->private_data, False);
479                         return;
480                 }
481         }
482
483         event->done += done;
484
485         if (event->done == event->length) {
486                 event->flags = 0;
487                 event->finished(event->private_data, True);
488         }
489 }
490
491 /*
492  * Request an async read/write on a fd_event structure. (*finished) is called
493  * when the request is completed or an error had occurred.
494  */
495
496 void setup_async_read(struct fd_event *event, void *data, size_t length,
497                       void (*finished)(void *private_data, bool success),
498                       void *private_data)
499 {
500         SMB_ASSERT(event->flags == 0);
501         event->data = data;
502         event->length = length;
503         event->done = 0;
504         event->handler = rw_callback;
505         event->finished = finished;
506         event->private_data = private_data;
507         event->flags = EVENT_FD_READ;
508 }
509
510 void setup_async_write(struct fd_event *event, void *data, size_t length,
511                        void (*finished)(void *private_data, bool success),
512                        void *private_data)
513 {
514         SMB_ASSERT(event->flags == 0);
515         event->data = data;
516         event->length = length;
517         event->done = 0;
518         event->handler = rw_callback;
519         event->finished = finished;
520         event->private_data = private_data;
521         event->flags = EVENT_FD_WRITE;
522 }
523
524 /*
525  * This is the main event loop of winbind requests. It goes through a
526  * state-machine of 3 read/write requests, 4 if you have extra data to send.
527  *
528  * An idle winbind client has a read request of 4 bytes outstanding,
529  * finalizing function is request_len_recv, checking the length. request_recv
530  * then processes the packet. The processing function then at some point has
531  * to call request_finished which schedules sending the response.
532  */
533
534 static void request_len_recv(void *private_data, bool success);
535 static void request_recv(void *private_data, bool success);
536 static void request_main_recv(void *private_data, bool success);
537 static void request_finished(struct winbindd_cli_state *state);
538 static void response_main_sent(void *private_data, bool success);
539 static void response_extra_sent(void *private_data, bool success);
540
541 static void response_extra_sent(void *private_data, bool success)
542 {
543         struct winbindd_cli_state *state =
544                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
545
546         TALLOC_FREE(state->mem_ctx);
547
548         if (!success) {
549                 state->finished = True;
550                 return;
551         }
552
553         SAFE_FREE(state->response.extra_data.data);
554
555         setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
556                          request_len_recv, state);
557 }
558
559 static void response_main_sent(void *private_data, bool success)
560 {
561         struct winbindd_cli_state *state =
562                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
563
564         if (!success) {
565                 state->finished = True;
566                 return;
567         }
568
569         if (state->response.length == sizeof(state->response)) {
570                 TALLOC_FREE(state->mem_ctx);
571
572                 setup_async_read(&state->fd_event, &state->request,
573                                  sizeof(uint32), request_len_recv, state);
574                 return;
575         }
576
577         setup_async_write(&state->fd_event, state->response.extra_data.data,
578                           state->response.length - sizeof(state->response),
579                           response_extra_sent, state);
580 }
581
582 static void request_finished(struct winbindd_cli_state *state)
583 {
584         /* Make sure request.extra_data is freed when finish processing a request */
585         SAFE_FREE(state->request.extra_data.data);
586         setup_async_write(&state->fd_event, &state->response,
587                           sizeof(state->response), response_main_sent, state);
588 }
589
590 void request_error(struct winbindd_cli_state *state)
591 {
592         SMB_ASSERT(state->response.result == WINBINDD_PENDING);
593         state->response.result = WINBINDD_ERROR;
594         request_finished(state);
595 }
596
597 void request_ok(struct winbindd_cli_state *state)
598 {
599         SMB_ASSERT(state->response.result == WINBINDD_PENDING);
600         state->response.result = WINBINDD_OK;
601         request_finished(state);
602 }
603
604 static void request_len_recv(void *private_data, bool success)
605 {
606         struct winbindd_cli_state *state =
607                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
608
609         if (!success) {
610                 state->finished = True;
611                 return;
612         }
613
614         if (*(uint32 *)(&state->request) != sizeof(state->request)) {
615                 DEBUG(0,("request_len_recv: Invalid request size received: %d (expected %u)\n",
616                          *(uint32_t *)(&state->request), (uint32_t)sizeof(state->request)));
617                 state->finished = True;
618                 return;
619         }
620
621         setup_async_read(&state->fd_event, (uint32 *)(&state->request)+1,
622                          sizeof(state->request) - sizeof(uint32),
623                          request_main_recv, state);
624 }
625
626 static void request_main_recv(void *private_data, bool success)
627 {
628         struct winbindd_cli_state *state =
629                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
630
631         if (!success) {
632                 state->finished = True;
633                 return;
634         }
635
636         if (state->request.extra_len == 0) {
637                 state->request.extra_data.data = NULL;
638                 request_recv(state, True);
639                 return;
640         }
641
642         if ((!state->privileged) &&
643             (state->request.extra_len > WINBINDD_MAX_EXTRA_DATA)) {
644                 DEBUG(3, ("Got request with %d bytes extra data on "
645                           "unprivileged socket\n", (int)state->request.extra_len));
646                 state->request.extra_data.data = NULL;
647                 state->finished = True;
648                 return;
649         }
650
651         state->request.extra_data.data =
652                 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
653
654         if (state->request.extra_data.data == NULL) {
655                 DEBUG(0, ("malloc failed\n"));
656                 state->finished = True;
657                 return;
658         }
659
660         /* Ensure null termination */
661         state->request.extra_data.data[state->request.extra_len] = '\0';
662
663         setup_async_read(&state->fd_event, state->request.extra_data.data,
664                          state->request.extra_len, request_recv, state);
665 }
666
667 static void request_recv(void *private_data, bool success)
668 {
669         struct winbindd_cli_state *state =
670                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
671
672         if (!success) {
673                 state->finished = True;
674                 return;
675         }
676
677         process_request(state);
678 }
679
680 /* Process a new connection by adding it to the client connection list */
681
682 static void new_connection(int listen_sock, bool privileged)
683 {
684         struct sockaddr_un sunaddr;
685         struct winbindd_cli_state *state;
686         socklen_t len;
687         int sock;
688         
689         /* Accept connection */
690         
691         len = sizeof(sunaddr);
692
693         do {
694                 sock = accept(listen_sock, (struct sockaddr *)&sunaddr, &len);
695         } while (sock == -1 && errno == EINTR);
696
697         if (sock == -1)
698                 return;
699         
700         DEBUG(6,("accepted socket %d\n", sock));
701         
702         /* Create new connection structure */
703         
704         if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
705                 close(sock);
706                 return;
707         }
708         
709         state->sock = sock;
710
711         state->last_access = time(NULL);        
712
713         state->privileged = privileged;
714
715         state->fd_event.fd = state->sock;
716         state->fd_event.flags = 0;
717         add_fd_event(&state->fd_event);
718
719         setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
720                          request_len_recv, state);
721
722         /* Add to connection list */
723         
724         winbindd_add_client(state);
725 }
726
727 /* Remove a client connection from client connection list */
728
729 static void remove_client(struct winbindd_cli_state *state)
730 {
731         char c = 0;
732
733         /* It's a dead client - hold a funeral */
734         
735         if (state == NULL) {
736                 return;
737         }
738
739         /* tell client, we are closing ... */
740         write(state->sock, &c, sizeof(c));
741
742         /* Close socket */
743                 
744         close(state->sock);
745                 
746         /* Free any getent state */
747                 
748         free_getent_state(state->getpwent_state);
749         free_getent_state(state->getgrent_state);
750                 
751         /* We may have some extra data that was not freed if the client was
752            killed unexpectedly */
753
754         SAFE_FREE(state->response.extra_data.data);
755
756         TALLOC_FREE(state->mem_ctx);
757
758         remove_fd_event(&state->fd_event);
759                 
760         /* Remove from list and free */
761                 
762         winbindd_remove_client(state);
763         TALLOC_FREE(state);
764 }
765
766 /* Shutdown client connection which has been idle for the longest time */
767
768 static bool remove_idle_client(void)
769 {
770         struct winbindd_cli_state *state, *remove_state = NULL;
771         time_t last_access = 0;
772         int nidle = 0;
773
774         for (state = winbindd_client_list(); state; state = state->next) {
775                 if (state->response.result != WINBINDD_PENDING &&
776                     !state->getpwent_state && !state->getgrent_state) {
777                         nidle++;
778                         if (!last_access || state->last_access < last_access) {
779                                 last_access = state->last_access;
780                                 remove_state = state;
781                         }
782                 }
783         }
784
785         if (remove_state) {
786                 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
787                         nidle, remove_state->sock, (unsigned int)remove_state->pid));
788                 remove_client(remove_state);
789                 return True;
790         }
791
792         return False;
793 }
794
795 /* check if HUP has been received and reload files */
796 void winbind_check_sighup(const char *lfile)
797 {
798         if (do_sighup) {
799
800                 DEBUG(3, ("got SIGHUP\n"));
801
802                 flush_caches();
803                 reload_services_file(lfile);
804
805                 do_sighup = False;
806         }
807 }
808
809 /* check if TERM has been received */
810 void winbind_check_sigterm(bool is_parent)
811 {
812         if (do_sigterm)
813                 terminate(is_parent);
814 }
815
816 /* Process incoming clients on listen_sock.  We use a tricky non-blocking,
817    non-forking, non-threaded model which allows us to handle many
818    simultaneous connections while remaining impervious to many denial of
819    service attacks. */
820
821 static void process_loop(void)
822 {
823         struct winbindd_cli_state *state;
824         struct fd_event *ev;
825         fd_set r_fds, w_fds;
826         int maxfd, listen_sock, listen_priv_sock, selret;
827         struct timeval timeout, ev_timeout;
828
829         /* Open Sockets here to get stuff going ASAP */
830         listen_sock = open_winbindd_socket();
831         listen_priv_sock = open_winbindd_priv_socket();
832
833         if (listen_sock == -1 || listen_priv_sock == -1) {
834                 perror("open_winbind_socket");
835                 exit(1);
836         }
837
838         /* We'll be doing this a lot */
839
840         /* Handle messages */
841
842         message_dispatch(winbind_messaging_context());
843
844         run_events(winbind_event_context(), 0, NULL, NULL);
845
846         /* refresh the trusted domain cache */
847
848         rescan_trusted_domains();
849
850         /* Initialise fd lists for select() */
851
852         maxfd = MAX(listen_sock, listen_priv_sock);
853
854         FD_ZERO(&r_fds);
855         FD_ZERO(&w_fds);
856         FD_SET(listen_sock, &r_fds);
857         FD_SET(listen_priv_sock, &r_fds);
858
859         timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
860         timeout.tv_usec = 0;
861
862         /* Check for any event timeouts. */
863         if (get_timed_events_timeout(winbind_event_context(), &ev_timeout)) {
864                 timeout = timeval_min(&timeout, &ev_timeout);
865         }
866
867         /* Set up client readers and writers */
868
869         state = winbindd_client_list();
870
871         while (state) {
872
873                 struct winbindd_cli_state *next = state->next;
874
875                 /* Dispose of client connection if it is marked as 
876                    finished */ 
877
878                 if (state->finished)
879                         remove_client(state);
880
881                 state = next;
882         }
883
884         for (ev = fd_events; ev; ev = ev->next) {
885                 if (ev->flags & EVENT_FD_READ) {
886                         FD_SET(ev->fd, &r_fds);
887                         maxfd = MAX(ev->fd, maxfd);
888                 }
889                 if (ev->flags & EVENT_FD_WRITE) {
890                         FD_SET(ev->fd, &w_fds);
891                         maxfd = MAX(ev->fd, maxfd);
892                 }
893         }
894
895         /* Call select */
896         
897         selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
898
899         if (selret == 0) {
900                 goto no_fds_ready;
901         }
902
903         if (selret == -1) {
904                 if (errno == EINTR) {
905                         goto no_fds_ready;
906                 }
907
908                 /* Select error, something is badly wrong */
909
910                 perror("select");
911                 exit(1);
912         }
913
914         /* selret > 0 */
915
916         ev = fd_events;
917         while (ev != NULL) {
918                 struct fd_event *next = ev->next;
919                 int flags = 0;
920                 if (FD_ISSET(ev->fd, &r_fds))
921                         flags |= EVENT_FD_READ;
922                 if (FD_ISSET(ev->fd, &w_fds))
923                         flags |= EVENT_FD_WRITE;
924                 if (flags)
925                         ev->handler(ev, flags);
926                 ev = next;
927         }
928
929         if (FD_ISSET(listen_sock, &r_fds)) {
930                 while (winbindd_num_clients() >
931                        WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
932                         DEBUG(5,("winbindd: Exceeding %d client "
933                                  "connections, removing idle "
934                                  "connection.\n",
935                                  WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
936                         if (!remove_idle_client()) {
937                                 DEBUG(0,("winbindd: Exceeding %d "
938                                          "client connections, no idle "
939                                          "connection found\n",
940                                          WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
941                                 break;
942                         }
943                 }
944                 /* new, non-privileged connection */
945                 new_connection(listen_sock, False);
946         }
947             
948         if (FD_ISSET(listen_priv_sock, &r_fds)) {
949                 while (winbindd_num_clients() >
950                        WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
951                         DEBUG(5,("winbindd: Exceeding %d client "
952                                  "connections, removing idle "
953                                  "connection.\n",
954                                  WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
955                         if (!remove_idle_client()) {
956                                 DEBUG(0,("winbindd: Exceeding %d "
957                                          "client connections, no idle "
958                                          "connection found\n",
959                                          WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
960                                 break;
961                         }
962                 }
963                 /* new, privileged connection */
964                 new_connection(listen_priv_sock, True);
965         }
966
967  no_fds_ready:
968
969 #if 0
970         winbindd_check_cache_size(time(NULL));
971 #endif
972
973         /* Check signal handling things */
974
975         winbind_check_sigterm(true);
976         winbind_check_sighup(NULL);
977
978         if (do_sigusr2) {
979                 print_winbindd_status();
980                 do_sigusr2 = False;
981         }
982
983         if (do_sigchld) {
984                 pid_t pid;
985
986                 do_sigchld = False;
987
988                 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
989                         winbind_child_died(pid);
990                 }
991         }
992 }
993
994 /* Main function */
995
996 int main(int argc, char **argv, char **envp)
997 {
998         static bool is_daemon = False;
999         static bool Fork = True;
1000         static bool log_stdout = False;
1001         static bool no_process_group = False;
1002         enum {
1003                 OPT_DAEMON = 1000,
1004                 OPT_FORK,
1005                 OPT_NO_PROCESS_GROUP,
1006                 OPT_LOG_STDOUT
1007         };
1008         struct poptOption long_options[] = {
1009                 POPT_AUTOHELP
1010                 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1011                 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1012                 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1013                 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1014                 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1015                 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1016                 POPT_COMMON_SAMBA
1017                 POPT_TABLEEND
1018         };
1019         poptContext pc;
1020         int opt;
1021         TALLOC_CTX *frame = talloc_stackframe();
1022
1023         /* glibc (?) likes to print "User defined signal 1" and exit if a
1024            SIGUSR[12] is received before a handler is installed */
1025
1026         CatchSignal(SIGUSR1, SIG_IGN);
1027         CatchSignal(SIGUSR2, SIG_IGN);
1028
1029         fault_setup((void (*)(void *))fault_quit );
1030         dump_core_setup("winbindd");
1031
1032         load_case_tables();
1033
1034         /* Initialise for running in non-root mode */
1035
1036         sec_init();
1037
1038         set_remote_machine_name("winbindd", False);
1039
1040         /* Set environment variable so we don't recursively call ourselves.
1041            This may also be useful interactively. */
1042
1043         if ( !winbind_off() ) {
1044                 DEBUG(0,("Failed to disable recusive winbindd calls.  Exiting.\n"));
1045                 exit(1);
1046         }
1047
1048         /* Initialise samba/rpc client stuff */
1049
1050         pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1051
1052         while ((opt = poptGetNextOpt(pc)) != -1) {
1053                 switch (opt) {
1054                         /* Don't become a daemon */
1055                 case OPT_DAEMON:
1056                         is_daemon = True;
1057                         break;
1058                 case 'i':
1059                         interactive = True;
1060                         log_stdout = True;
1061                         Fork = False;
1062                         break;
1063                 case OPT_FORK:
1064                         Fork = false;
1065                         break;
1066                 case OPT_NO_PROCESS_GROUP:
1067                         no_process_group = true;
1068                         break;
1069                 case OPT_LOG_STDOUT:
1070                         log_stdout = true;
1071                         break;
1072                 case 'n':
1073                         opt_nocache = true;
1074                         break;
1075                 default:
1076                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1077                                   poptBadOption(pc, 0), poptStrerror(opt));
1078                         poptPrintUsage(pc, stderr, 0);
1079                         exit(1);
1080                 }
1081         }
1082
1083         if (is_daemon && interactive) {
1084                 d_fprintf(stderr,"\nERROR: "
1085                           "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1086                 poptPrintUsage(pc, stderr, 0);
1087                 exit(1);
1088         }
1089
1090         if (log_stdout && Fork) {
1091                 d_fprintf(stderr, "\nERROR: "
1092                           "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1093                 poptPrintUsage(pc, stderr, 0);
1094                 exit(1);
1095         }
1096
1097         poptFreeContext(pc);
1098
1099         if (!override_logfile) {
1100                 char *lfile = NULL;
1101                 if (asprintf(&lfile,"%s/log.winbindd",
1102                                 get_dyn_LOGFILEBASE()) > 0) {
1103                         lp_set_logfile(lfile);
1104                         SAFE_FREE(lfile);
1105                 }
1106         }
1107         setup_logging("winbindd", log_stdout);
1108         reopen_logs();
1109
1110         DEBUG(0,("winbindd version %s started.\n", SAMBA_VERSION_STRING));
1111         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1112
1113         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1114                 DEBUG(0, ("error opening config file\n"));
1115                 exit(1);
1116         }
1117
1118         /* Initialise messaging system */
1119
1120         if (winbind_messaging_context() == NULL) {
1121                 exit(1);
1122         }
1123
1124         if (!reload_services_file(NULL)) {
1125                 DEBUG(0, ("error opening config file\n"));
1126                 exit(1);
1127         }
1128
1129         if (!directory_exist(lp_lockdir())) {
1130                 mkdir(lp_lockdir(), 0755);
1131         }
1132
1133         /* Setup names. */
1134
1135         if (!init_names())
1136                 exit(1);
1137
1138         load_interfaces();
1139
1140         if (!secrets_init()) {
1141
1142                 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1143                 return False;
1144         }
1145
1146         /* Enable netbios namecache */
1147
1148         namecache_enable();
1149
1150         /* Unblock all signals we are interested in as they may have been
1151            blocked by the parent process. */
1152
1153         BlockSignals(False, SIGINT);
1154         BlockSignals(False, SIGQUIT);
1155         BlockSignals(False, SIGTERM);
1156         BlockSignals(False, SIGUSR1);
1157         BlockSignals(False, SIGUSR2);
1158         BlockSignals(False, SIGHUP);
1159         BlockSignals(False, SIGCHLD);
1160
1161         /* Setup signal handlers */
1162         
1163         CatchSignal(SIGINT, termination_handler);      /* Exit on these sigs */
1164         CatchSignal(SIGQUIT, termination_handler);
1165         CatchSignal(SIGTERM, termination_handler);
1166         CatchSignal(SIGCHLD, sigchld_handler);
1167
1168         CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
1169
1170         CatchSignal(SIGUSR2, sigusr2_handler);         /* Debugging sigs */
1171         CatchSignal(SIGHUP, sighup_handler);
1172
1173         if (!interactive)
1174                 become_daemon(Fork, no_process_group);
1175
1176         pidfile_create("winbindd");
1177
1178 #if HAVE_SETPGID
1179         /*
1180          * If we're interactive we want to set our own process group for
1181          * signal management.
1182          */
1183         if (interactive && !no_process_group)
1184                 setpgid( (pid_t)0, (pid_t)0);
1185 #endif
1186
1187         TimeInit();
1188
1189         if (!reinit_after_fork(winbind_messaging_context(), false)) {
1190                 DEBUG(0,("reinit_after_fork() failed\n"));
1191                 exit(1);
1192         }
1193
1194         /*
1195          * Ensure all cache and idmap caches are consistent
1196          * and initialized before we startup.
1197          */
1198         if (!winbindd_cache_validate_and_initialize()) {
1199                 exit(1);
1200         }
1201
1202         /* get broadcast messages */
1203         claim_connection(NULL,"",FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP);
1204
1205         /* React on 'smbcontrol winbindd reload-config' in the same way
1206            as to SIGHUP signal */
1207         messaging_register(winbind_messaging_context(), NULL,
1208                            MSG_SMB_CONF_UPDATED, msg_reload_services);
1209         messaging_register(winbind_messaging_context(), NULL,
1210                            MSG_SHUTDOWN, msg_shutdown);
1211
1212         /* Handle online/offline messages. */
1213         messaging_register(winbind_messaging_context(), NULL,
1214                            MSG_WINBIND_OFFLINE, winbind_msg_offline);
1215         messaging_register(winbind_messaging_context(), NULL,
1216                            MSG_WINBIND_ONLINE, winbind_msg_online);
1217         messaging_register(winbind_messaging_context(), NULL,
1218                            MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1219
1220         messaging_register(winbind_messaging_context(), NULL,
1221                            MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1222
1223         messaging_register(winbind_messaging_context(), NULL,
1224                            MSG_WINBIND_VALIDATE_CACHE,
1225                            winbind_msg_validate_cache);
1226
1227         messaging_register(winbind_messaging_context(), NULL,
1228                            MSG_WINBIND_DUMP_DOMAIN_LIST,
1229                            winbind_msg_dump_domain_list);
1230
1231         /* Register handler for MSG_DEBUG. */
1232         messaging_register(winbind_messaging_context(), NULL,
1233                            MSG_DEBUG,
1234                            winbind_msg_debug);
1235         
1236         netsamlogon_cache_init(); /* Non-critical */
1237         
1238         /* clear the cached list of trusted domains */
1239
1240         wcache_tdc_clear();     
1241         
1242         if (!init_domain_list()) {
1243                 DEBUG(0,("unable to initialize domain list\n"));
1244                 exit(1);
1245         }
1246
1247         init_idmap_child();
1248         init_locator_child();
1249
1250         smb_nscd_flush_user_cache();
1251         smb_nscd_flush_group_cache();
1252
1253         /* Loop waiting for requests */
1254
1255         TALLOC_FREE(frame);
1256         while (1) {
1257                 frame = talloc_stackframe();
1258                 process_loop();
1259                 TALLOC_FREE(frame);
1260         }
1261
1262         return 0;
1263 }