r1557: Add sigchld handling to winbindd. Next step is to have the child restarted if
[sfrench/samba-autobuild/.git] / source / 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    
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26 #include "winbindd.h"
27
28 BOOL opt_nocache = False;
29 BOOL opt_dual_daemon = True;
30
31 /* Reload configuration */
32
33 static BOOL reload_services_file(void)
34 {
35         BOOL ret;
36
37         if (lp_loaded()) {
38                 pstring fname;
39
40                 pstrcpy(fname,lp_configfile());
41                 if (file_exist(fname,NULL) && !strcsequal(fname,dyn_CONFIGFILE)) {
42                         pstrcpy(dyn_CONFIGFILE,fname);
43                 }
44         }
45
46         reopen_logs();
47         ret = lp_load(dyn_CONFIGFILE,False,False,True);
48
49         reopen_logs();
50         load_interfaces();
51
52         return(ret);
53 }
54
55
56 #if DUMP_CORE
57
58 /**************************************************************************** **
59  Prepare to dump a core file - carefully!
60  **************************************************************************** */
61
62 static BOOL dump_core(void)
63 {
64         char *p;
65         pstring dname;
66         pstrcpy( dname, lp_logfile() );
67         if ((p=strrchr(dname,'/')))
68                 *p=0;
69         pstrcat( dname, "/corefiles" );
70         mkdir( dname, 0700 );
71         sys_chown( dname, getuid(), getgid() );
72         chmod( dname, 0700 );
73         if ( chdir(dname) )
74                 return( False );
75         umask( ~(0700) );
76  
77 #ifdef HAVE_GETRLIMIT
78 #ifdef RLIMIT_CORE
79         {
80                 struct rlimit rlp;
81                 getrlimit( RLIMIT_CORE, &rlp );
82                 rlp.rlim_cur = MAX( 4*1024*1024, rlp.rlim_cur );
83                 setrlimit( RLIMIT_CORE, &rlp );
84                 getrlimit( RLIMIT_CORE, &rlp );
85                 DEBUG( 3, ( "Core limits now %d %d\n", (int)rlp.rlim_cur, (int)rlp.rlim_max ) );
86         }
87 #endif
88 #endif
89  
90         DEBUG(0,("Dumping core in %s\n",dname));
91         abort();
92         return( True );
93 } /* dump_core */
94 #endif
95
96 /**************************************************************************** **
97  Handle a fault..
98  **************************************************************************** */
99
100 static void fault_quit(void)
101 {
102 #if DUMP_CORE
103         dump_core();
104 #endif
105 }
106
107 static void winbindd_status(void)
108 {
109         struct winbindd_cli_state *tmp;
110
111         DEBUG(0, ("winbindd status:\n"));
112
113         /* Print client state information */
114         
115         DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
116         
117         if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
118                 DEBUG(2, ("\tclient list:\n"));
119                 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
120                         DEBUG(2, ("\t\tpid %lu, sock %d, rbl %d, wbl %d\n",
121                                   (unsigned long)tmp->pid, tmp->sock, tmp->read_buf_len, 
122                                   tmp->write_buf_len));
123                 }
124         }
125 }
126
127 /* Print winbindd status to log file */
128
129 static void print_winbindd_status(void)
130 {
131         winbindd_status();
132         winbindd_cm_status();
133 }
134
135 /* Flush client cache */
136
137 static void flush_caches(void)
138 {
139 #if 0
140         /* Clear cached user and group enumation info */        
141         if (!opt_dual_daemon) /* Until we have coherent cache flush. */
142                 wcache_flush_cache();
143 #endif
144
145         /* We need to invalidate cached user list entries on a SIGHUP 
146            otherwise cached access denied errors due to restrict anonymous
147            hang around until the sequence number changes. */
148
149         wcache_invalidate_cache();
150 }
151
152 /* Handle the signal by unlinking socket and exiting */
153
154 static void terminate(void)
155 {
156         pstring path;
157
158         idmap_close();
159         
160         /* Remove socket file */
161         pstr_sprintf(path, "%s/%s", 
162                  WINBINDD_SOCKET_DIR, WINBINDD_SOCKET_NAME);
163         unlink(path);
164         exit(0);
165 }
166
167 static BOOL do_sigterm;
168
169 static void termination_handler(int signum)
170 {
171         do_sigterm = True;
172         sys_select_signal();
173 }
174
175 static BOOL do_sigusr2;
176
177 static void sigusr2_handler(int signum)
178 {
179         do_sigusr2 = True;
180         sys_select_signal();
181 }
182
183 static BOOL do_sighup;
184
185 static void sighup_handler(int signum)
186 {
187         do_sighup = True;
188         sys_select_signal();
189 }
190
191 static void sigchld_handler(int signum)
192 {
193         pid_t pid;
194         int status;
195
196         while ((pid = wait(&status)) != -1 || errno == EINTR) {
197                 continue; /* Reap children */
198         }
199         sys_select_signal();
200 }
201
202 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
203 static void msg_reload_services(int msg_type, pid_t src, void *buf, size_t len)
204 {
205         /* Flush various caches */
206         flush_caches();
207         reload_services_file();
208 }
209
210 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
211 static void msg_shutdown(int msg_type, pid_t src, void *buf, size_t len)
212 {
213         terminate();
214 }
215
216 struct dispatch_table {
217         enum winbindd_cmd cmd;
218         enum winbindd_result (*fn)(struct winbindd_cli_state *state);
219         const char *winbindd_cmd_name;
220 };
221
222 static struct dispatch_table dispatch_table[] = {
223         
224         /* User functions */
225
226         { WINBINDD_GETPWNAM, winbindd_getpwnam, "GETPWNAM" },
227         { WINBINDD_GETPWUID, winbindd_getpwuid, "GETPWUID" },
228
229         { WINBINDD_SETPWENT, winbindd_setpwent, "SETPWENT" },
230         { WINBINDD_ENDPWENT, winbindd_endpwent, "ENDPWENT" },
231         { WINBINDD_GETPWENT, winbindd_getpwent, "GETPWENT" },
232
233         { WINBINDD_GETGROUPS, winbindd_getgroups, "GETGROUPS" },
234         { WINBINDD_GETUSERSIDS, winbindd_getusersids, "GETUSERSIDS" },
235
236         /* Group functions */
237
238         { WINBINDD_GETGRNAM, winbindd_getgrnam, "GETGRNAM" },
239         { WINBINDD_GETGRGID, winbindd_getgrgid, "GETGRGID" },
240         { WINBINDD_SETGRENT, winbindd_setgrent, "SETGRENT" },
241         { WINBINDD_ENDGRENT, winbindd_endgrent, "ENDGRENT" },
242         { WINBINDD_GETGRENT, winbindd_getgrent, "GETGRENT" },
243         { WINBINDD_GETGRLST, winbindd_getgrent, "GETGRLST" },
244
245         /* PAM auth functions */
246
247         { WINBINDD_PAM_AUTH, winbindd_pam_auth, "PAM_AUTH" },
248         { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap, "AUTH_CRAP" },
249         { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok, "CHAUTHTOK" },
250
251         /* Enumeration functions */
252
253         { WINBINDD_LIST_USERS, winbindd_list_users, "LIST_USERS" },
254         { WINBINDD_LIST_GROUPS, winbindd_list_groups, "LIST_GROUPS" },
255         { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains, "LIST_TRUSTDOM" },
256         { WINBINDD_SHOW_SEQUENCE, winbindd_show_sequence, "SHOW_SEQUENCE" },
257
258         /* SID related functions */
259
260         { WINBINDD_LOOKUPSID, winbindd_lookupsid, "LOOKUPSID" },
261         { WINBINDD_LOOKUPNAME, winbindd_lookupname, "LOOKUPNAME" },
262
263         /* Lookup related functions */
264
265         { WINBINDD_SID_TO_UID, winbindd_sid_to_uid, "SID_TO_UID" },
266         { WINBINDD_SID_TO_GID, winbindd_sid_to_gid, "SID_TO_GID" },
267         { WINBINDD_GID_TO_SID, winbindd_gid_to_sid, "GID_TO_SID" },
268         { WINBINDD_UID_TO_SID, winbindd_uid_to_sid, "UID_TO_SID" },
269         { WINBINDD_ALLOCATE_RID, winbindd_allocate_rid, "ALLOCATE_RID" },
270
271         /* Miscellaneous */
272
273         { WINBINDD_CHECK_MACHACC, winbindd_check_machine_acct, "CHECK_MACHACC" },
274         { WINBINDD_PING, winbindd_ping, "PING" },
275         { WINBINDD_INFO, winbindd_info, "INFO" },
276         { WINBINDD_INTERFACE_VERSION, winbindd_interface_version, "INTERFACE_VERSION" },
277         { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
278         { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
279         { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
280         { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir, "WINBINDD_PRIV_PIPE_DIR" },
281
282         /* WINS functions */
283
284         { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
285         { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
286         
287         /* UNIX account management functions */
288         { WINBINDD_CREATE_USER,                 winbindd_create_user,           "CREATE_USER"           },
289         { WINBINDD_CREATE_GROUP,                winbindd_create_group,          "CREATE_GROUP"          },
290         { WINBINDD_ADD_USER_TO_GROUP,           winbindd_add_user_to_group,     "ADD_USER_TO_GROUP"     },
291         { WINBINDD_REMOVE_USER_FROM_GROUP,      winbindd_remove_user_from_group,"REMOVE_USER_FROM_GROUP"},
292         { WINBINDD_SET_USER_PRIMARY_GROUP,      winbindd_set_user_primary_group,"SET_USER_PRIMARY_GROUP"},
293         { WINBINDD_DELETE_USER,                 winbindd_delete_user,           "DELETE_USER"           },
294         { WINBINDD_DELETE_GROUP,                winbindd_delete_group,          "DELETE_GROUP"          },
295         
296         /* End of list */
297
298         { WINBINDD_NUM_CMDS, NULL, "NONE" }
299 };
300
301 static void process_request(struct winbindd_cli_state *state)
302 {
303         struct dispatch_table *table = dispatch_table;
304
305         /* Free response data - we may be interrupted and receive another
306            command before being able to send this data off. */
307
308         SAFE_FREE(state->response.extra_data);  
309
310         ZERO_STRUCT(state->response);
311
312         state->response.result = WINBINDD_ERROR;
313         state->response.length = sizeof(struct winbindd_response);
314
315         /* Process command */
316
317         for (table = dispatch_table; table->fn; table++) {
318                 if (state->request.cmd == table->cmd) {
319                         DEBUG(10,("process_request: request fn %s\n", table->winbindd_cmd_name ));
320                         state->response.result = table->fn(state);
321                         break;
322                 }
323         }
324
325         if (!table->fn)
326                 DEBUG(10,("process_request: unknown request fn number %d\n", (int)state->request.cmd ));
327
328         /* In case extra data pointer is NULL */
329
330         if (!state->response.extra_data)
331                 state->response.length = sizeof(struct winbindd_response);
332 }
333
334 /* Process a new connection by adding it to the client connection list */
335
336 static void new_connection(int listen_sock, BOOL privileged)
337 {
338         struct sockaddr_un sunaddr;
339         struct winbindd_cli_state *state;
340         socklen_t len;
341         int sock;
342         
343         /* Accept connection */
344         
345         len = sizeof(sunaddr);
346
347         do {
348                 sock = accept(listen_sock, (struct sockaddr *)&sunaddr, &len);
349         } while (sock == -1 && errno == EINTR);
350
351         if (sock == -1)
352                 return;
353         
354         DEBUG(6,("accepted socket %d\n", sock));
355         
356         /* Create new connection structure */
357         
358         if ((state = (struct winbindd_cli_state *) 
359              malloc(sizeof(*state))) == NULL)
360                 return;
361         
362         ZERO_STRUCTP(state);
363         state->sock = sock;
364
365         state->last_access = time(NULL);        
366
367         state->privileged = privileged;
368
369         /* Add to connection list */
370         
371         winbindd_add_client(state);
372 }
373
374 /* Remove a client connection from client connection list */
375
376 static void remove_client(struct winbindd_cli_state *state)
377 {
378         /* It's a dead client - hold a funeral */
379         
380         if (state != NULL) {
381                 
382                 /* Close socket */
383                 
384                 close(state->sock);
385                 
386                 /* Free any getent state */
387                 
388                 free_getent_state(state->getpwent_state);
389                 free_getent_state(state->getgrent_state);
390                 
391                 /* We may have some extra data that was not freed if the
392                    client was killed unexpectedly */
393
394                 SAFE_FREE(state->response.extra_data);
395                 
396                 /* Remove from list and free */
397                 
398                 winbindd_remove_client(state);
399                 SAFE_FREE(state);
400         }
401 }
402
403
404 /* Shutdown client connection which has been idle for the longest time */
405
406 static BOOL remove_idle_client(void)
407 {
408         struct winbindd_cli_state *state, *remove_state = NULL;
409         time_t last_access = 0;
410         int nidle = 0;
411
412         for (state = winbindd_client_list(); state; state = state->next) {
413                 if (state->read_buf_len == 0 && state->write_buf_len == 0 &&
414                                 !state->getpwent_state && !state->getgrent_state) {
415                         nidle++;
416                         if (!last_access || state->last_access < last_access) {
417                                 last_access = state->last_access;
418                                 remove_state = state;
419                         }
420                 }
421         }
422
423         if (remove_state) {
424                 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
425                         nidle, remove_state->sock, (unsigned int)remove_state->pid));
426                 remove_client(remove_state);
427                 return True;
428         }
429
430         return False;
431 }
432
433 /* Process a complete received packet from a client */
434
435 void winbind_process_packet(struct winbindd_cli_state *state)
436 {
437         /* Process request */
438         
439         /* Ensure null termination of entire request */
440         state->request.null_term = '\0';
441
442         state->pid = state->request.pid;
443         
444         process_request(state);
445
446         /* Update client state */
447         
448         state->read_buf_len = 0;
449         state->write_buf_len = sizeof(struct winbindd_response);
450
451         /* we might need to send it to the dual daemon */
452         if (opt_dual_daemon) {
453                 dual_send_request(state);
454         }
455 }
456
457 /* Read some data from a client connection */
458
459 void winbind_client_read(struct winbindd_cli_state *state)
460 {
461         int n;
462     
463         /* Read data */
464
465         n = sys_read(state->sock, state->read_buf_len + 
466                  (char *)&state->request, 
467                  sizeof(state->request) - state->read_buf_len);
468         
469         DEBUG(10,("client_read: read %d bytes. Need %ld more for a full request.\n", n, (unsigned long)(sizeof(state->request) - n - state->read_buf_len) ));
470
471         /* Read failed, kill client */
472         
473         if (n == -1 || n == 0) {
474                 DEBUG(5,("read failed on sock %d, pid %lu: %s\n",
475                          state->sock, (unsigned long)state->pid, 
476                          (n == -1) ? strerror(errno) : "EOF"));
477                 
478                 state->finished = True;
479                 return;
480         }
481         
482         /* Update client state */
483         
484         state->read_buf_len += n;
485         state->last_access = time(NULL);
486 }
487
488 /* Write some data to a client connection */
489
490 static void client_write(struct winbindd_cli_state *state)
491 {
492         char *data;
493         int num_written;
494         
495         /* Write some data */
496         /*
497          * The fancy calculation of data below allows us to handle the 
498          * case where write (sys_write) does not write all the data we 
499          * gave it. In that case, we will come back through here again
500          * because of the loop above us, and we want to pick up where
501          * we left off.
502          */
503         
504         if (!state->write_extra_data) {
505
506                 /* Write response structure */
507                 
508                 data = (char *)&state->response + sizeof(state->response) - 
509                         state->write_buf_len;
510
511         } else {
512
513                 /* Write extra data */
514                 
515                 data = (char *)state->response.extra_data + 
516                         state->response.length - 
517                         sizeof(struct winbindd_response) - 
518                         state->write_buf_len;
519         }
520         
521         num_written = sys_write(state->sock, data, state->write_buf_len);
522         
523         DEBUG(10,("client_write: wrote %d bytes.\n", num_written ));
524
525         /* Write failed, kill cilent */
526         
527         if (num_written == -1 || num_written == 0) {
528                 
529                 DEBUG(3,("write failed on sock %d, pid %lu: %s\n",
530                          state->sock, (unsigned long)state->pid, 
531                          (num_written == -1) ? strerror(errno) : "EOF"));
532                 
533                 state->finished = True;
534
535                 SAFE_FREE(state->response.extra_data);
536
537                 return;
538         }
539         
540         /* Update client state */
541         
542         state->write_buf_len -= num_written;
543         state->last_access = time(NULL);
544
545         /* Have we written all data? */
546         
547         if (state->write_buf_len == 0) {
548                 
549                 /* Take care of extra data */
550                 
551                 if (state->write_extra_data) {
552
553                         SAFE_FREE(state->response.extra_data);
554
555                         state->write_extra_data = False;
556
557                         DEBUG(10,("client_write: client_write: complete response written.\n"));
558
559                 } else if (state->response.length > 
560                            sizeof(struct winbindd_response)) {
561                         
562                         /* Start writing extra data */
563
564                         state->write_buf_len = 
565                                 state->response.length -
566                                 sizeof(struct winbindd_response);
567                         
568                         DEBUG(10,("client_write: need to write %d extra data bytes.\n", (int)state->write_buf_len));
569
570                         state->write_extra_data = True;
571                 }
572         }
573 }
574
575 /* Process incoming clients on listen_sock.  We use a tricky non-blocking,
576    non-forking, non-threaded model which allows us to handle many
577    simultaneous connections while remaining impervious to many denial of
578    service attacks. */
579
580 static void process_loop(void)
581 {
582         /* We'll be doing this a lot */
583
584         while (1) {
585                 struct winbindd_cli_state *state;
586                 fd_set r_fds, w_fds;
587                 int maxfd, listen_sock, listen_priv_sock, selret;
588                 struct timeval timeout;
589
590                 /* Handle messages */
591
592                 message_dispatch();
593
594                 /* refresh the trusted domain cache */
595                    
596                 rescan_trusted_domains();
597
598                 /* Free up temporary memory */
599
600                 lp_talloc_free();
601                 main_loop_talloc_free();
602
603                 /* Initialise fd lists for select() */
604
605                 listen_sock = open_winbindd_socket();
606                 listen_priv_sock = open_winbindd_priv_socket();
607
608                 if (listen_sock == -1 || listen_priv_sock == -1) {
609                         perror("open_winbind_socket");
610                         exit(1);
611                 }
612
613                 maxfd = MAX(listen_sock, listen_priv_sock);
614
615                 FD_ZERO(&r_fds);
616                 FD_ZERO(&w_fds);
617                 FD_SET(listen_sock, &r_fds);
618                 FD_SET(listen_priv_sock, &r_fds);
619
620                 timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
621                 timeout.tv_usec = 0;
622
623                 if (opt_dual_daemon) {
624                         maxfd = dual_select_setup(&w_fds, maxfd);
625                 }
626
627                 /* Set up client readers and writers */
628
629                 state = winbindd_client_list();
630
631                 while (state) {
632
633                         /* Dispose of client connection if it is marked as 
634                            finished */ 
635
636                         if (state->finished) {
637                                 struct winbindd_cli_state *next = state->next;
638
639                                 remove_client(state);
640                                 state = next;
641                                 continue;
642                         }
643
644                         /* Select requires we know the highest fd used */
645
646                         if (state->sock > maxfd)
647                                 maxfd = state->sock;
648
649                         /* Add fd for reading */
650
651                         if (state->read_buf_len != sizeof(state->request))
652                                 FD_SET(state->sock, &r_fds);
653
654                         /* Add fd for writing */
655
656                         if (state->write_buf_len)
657                                 FD_SET(state->sock, &w_fds);
658
659                         state = state->next;
660                 }
661
662                 /* Call select */
663         
664                 selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
665
666                 if (selret == 0)
667                         continue;
668
669                 if ((selret == -1 && errno != EINTR) || selret == 0) {
670
671                         /* Select error, something is badly wrong */
672
673                         perror("select");
674                         exit(1);
675                 }
676
677                 /* Create a new connection if listen_sock readable */
678
679                 if (selret > 0) {
680
681                         if (opt_dual_daemon) {
682                                 dual_select(&w_fds);
683                         }
684
685                         if (FD_ISSET(listen_sock, &r_fds)) {
686                                 while (winbindd_num_clients() > WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
687                                         DEBUG(5,("winbindd: Exceeding %d client connections, removing idle connection.\n",
688                                                 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
689                                         if (!remove_idle_client()) {
690                                                 DEBUG(0,("winbindd: Exceeding %d client connections, no idle connection found\n",
691                                                         WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
692                                                 break;
693                                         }
694                                 }
695                                 /* new, non-privileged connection */
696                                 new_connection(listen_sock, False);
697                         }
698             
699                         if (FD_ISSET(listen_priv_sock, &r_fds)) {
700                                 while (winbindd_num_clients() > WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
701                                         DEBUG(5,("winbindd: Exceeding %d client connections, removing idle connection.\n",
702                                                 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
703                                         if (!remove_idle_client()) {
704                                                 DEBUG(0,("winbindd: Exceeding %d client connections, no idle connection found\n",
705                                                         WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
706                                                 break;
707                                         }
708                                 }
709                                 /* new, privileged connection */
710                                 new_connection(listen_priv_sock, True);
711                         }
712             
713                         /* Process activity on client connections */
714             
715                         for (state = winbindd_client_list(); state; 
716                              state = state->next) {
717                 
718                                 /* Data available for reading */
719                 
720                                 if (FD_ISSET(state->sock, &r_fds)) {
721                     
722                                         /* Read data */
723                     
724                                         winbind_client_read(state);
725
726                                         /* 
727                                          * If we have the start of a
728                                          * packet, then check the
729                                          * length field to make sure
730                                          * the client's not talking
731                                          * Mock Swedish.
732                                          */
733
734                                         if (state->read_buf_len >= sizeof(uint32)
735                                             && *(uint32 *) &state->request != sizeof(state->request)) {
736                                                 DEBUG(0,("process_loop: Invalid request size from pid %lu: %d bytes sent, should be %ld\n",
737                                                                 (unsigned long)state->request.pid, *(uint32 *) &state->request, (unsigned long)sizeof(state->request)));
738                                                 DEBUGADD(0, ("This usually means that you are running old wbinfo, pam_winbind or libnss_winbind clients\n"));
739
740                                                 remove_client(state);
741                                                 break;
742                                         }
743
744                                         /* A request packet might be 
745                                            complete */
746                     
747                                         if (state->read_buf_len == 
748                                             sizeof(state->request)) {
749                                                 winbind_process_packet(state);
750                                         }
751                                 }
752                 
753                                 /* Data available for writing */
754                 
755                                 if (FD_ISSET(state->sock, &w_fds))
756                                         client_write(state);
757                         }
758                 }
759
760 #if 0
761                 winbindd_check_cache_size(time(NULL));
762 #endif
763
764                 /* Check signal handling things */
765
766                 if (do_sigterm)
767                         terminate();
768
769                 if (do_sighup) {
770
771                         DEBUG(3, ("got SIGHUP\n"));
772
773                         msg_reload_services(MSG_SMB_CONF_UPDATED, (pid_t) 0, NULL, 0);
774                         do_sighup = False;
775                 }
776
777                 if (do_sigusr2) {
778                         print_winbindd_status();
779                         do_sigusr2 = False;
780                 }
781         }
782 }
783
784 /* Main function */
785
786 struct winbindd_state server_state;   /* Server state information */
787
788 int main(int argc, char **argv)
789 {
790         pstring logfile;
791         static BOOL interactive = False;
792         static BOOL Fork = True;
793         static BOOL log_stdout = False;
794         struct poptOption long_options[] = {
795                 POPT_AUTOHELP
796                 { "stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
797                 { "foreground", 'F', POPT_ARG_VAL, &Fork, False, "Daemon in foreground mode" },
798                 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
799                 { "single-daemon", 'Y', POPT_ARG_VAL, &opt_dual_daemon, False, "Single daemon mode" },
800                 { "no-caching", 'n', POPT_ARG_VAL, &opt_nocache, True, "Disable caching" },
801                 POPT_COMMON_SAMBA
802                 POPT_TABLEEND
803         };
804         poptContext pc;
805         int opt;
806
807         /* glibc (?) likes to print "User defined signal 1" and exit if a
808            SIGUSR[12] is received before a handler is installed */
809
810         CatchSignal(SIGUSR1, SIG_IGN);
811         CatchSignal(SIGUSR2, SIG_IGN);
812
813         fault_setup((void (*)(void *))fault_quit );
814
815         /* Initialise for running in non-root mode */
816
817         sec_init();
818
819         set_remote_machine_name("winbindd", False);
820
821         /* Set environment variable so we don't recursively call ourselves.
822            This may also be useful interactively. */
823
824         setenv(WINBINDD_DONT_ENV, "1", 1);
825
826         /* Initialise samba/rpc client stuff */
827
828         pc = poptGetContext("winbindd", argc, (const char **)argv, long_options,
829                                                 POPT_CONTEXT_KEEP_FIRST);
830
831         while ((opt = poptGetNextOpt(pc)) != -1) {
832                 switch (opt) {
833                         /* Don't become a daemon */
834                 case 'i':
835                         interactive = True;
836                         log_stdout = True;
837                         Fork = False;
838                         break;
839                 }
840         }
841
842
843         if (log_stdout && Fork) {
844                 printf("Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n");
845                 poptPrintUsage(pc, stderr, 0);
846                 exit(1);
847         }
848
849         pstr_sprintf(logfile, "%s/log.winbindd", dyn_LOGFILEBASE);
850         lp_set_logfile(logfile);
851         setup_logging("winbindd", log_stdout);
852         reopen_logs();
853
854         DEBUG(1, ("winbindd version %s started.\n", SAMBA_VERSION_STRING) );
855         DEBUGADD( 1, ( "Copyright The Samba Team 2000-2004\n" ) );
856
857         if (!reload_services_file()) {
858                 DEBUG(0, ("error opening config file\n"));
859                 exit(1);
860         }
861
862         /* Setup names. */
863
864         if (!init_names())
865                 exit(1);
866
867         load_interfaces();
868
869         if (!secrets_init()) {
870
871                 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
872                 return False;
873         }
874
875         /* Enable netbios namecache */
876
877         namecache_enable();
878
879         /* Check winbindd parameters are valid */
880
881         ZERO_STRUCT(server_state);
882
883         /* Winbind daemon initialisation */
884
885         if ( (!winbindd_param_init()) || (!winbindd_upgrade_idmap()) ||
886              (!idmap_init(lp_idmap_backend())) ) {
887                 DEBUG(1, ("Could not init idmap -- netlogon proxy only\n"));
888                 idmap_proxyonly();
889         }
890
891         generate_wellknown_sids();
892
893         /* Unblock all signals we are interested in as they may have been
894            blocked by the parent process. */
895
896         BlockSignals(False, SIGINT);
897         BlockSignals(False, SIGQUIT);
898         BlockSignals(False, SIGTERM);
899         BlockSignals(False, SIGUSR1);
900         BlockSignals(False, SIGUSR2);
901         BlockSignals(False, SIGHUP);
902         BlockSignals(False, SIGCHLD);
903
904         /* Setup signal handlers */
905         
906         CatchSignal(SIGINT, termination_handler);      /* Exit on these sigs */
907         CatchSignal(SIGQUIT, termination_handler);
908         CatchSignal(SIGTERM, termination_handler);
909         CatchSignal(SIGCHLD, sigchld_handler);
910
911         CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
912
913         CatchSignal(SIGUSR2, sigusr2_handler);         /* Debugging sigs */
914         CatchSignal(SIGHUP, sighup_handler);
915
916         if (!interactive)
917                 become_daemon(Fork);
918
919         pidfile_create("winbindd");
920
921 #if HAVE_SETPGID
922         /*
923          * If we're interactive we want to set our own process group for
924          * signal management.
925          */
926         if (interactive)
927                 setpgid( (pid_t)0, (pid_t)0);
928 #endif
929
930         if (opt_dual_daemon) {
931                 do_dual_daemon();
932         }
933
934         /* Initialise messaging system */
935
936         if (!message_init()) {
937                 DEBUG(0, ("unable to initialise messaging system\n"));
938                 exit(1);
939         }
940         
941         /* React on 'smbcontrol winbindd reload-config' in the same way
942            as to SIGHUP signal */
943         message_register(MSG_SMB_CONF_UPDATED, msg_reload_services);
944         message_register(MSG_SHUTDOWN, msg_shutdown);
945         
946         poptFreeContext(pc);
947
948         netsamlogon_cache_init(); /* Non-critical */
949         
950         init_domain_list();
951
952         /* Loop waiting for requests */
953
954         process_loop();
955
956         trustdom_cache_shutdown();
957
958         return 0;
959 }