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