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