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