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