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