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