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