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