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