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