Add support for MSG_SMB_CONF_UPDATED and MSG_SHUTDOWN to all daemons (smbd, nmbd...
[gd/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 "winbindd.h"
26
27 BOOL opt_nocache = False;
28 BOOL opt_dual_daemon = True;
29
30 /*****************************************************************************
31  stubb functions 
32 ****************************************************************************/
33
34 void become_root( void )
35 {
36         return;
37 }
38
39 void unbecome_root( void )
40 {
41         return;
42 }
43
44 /* Reload configuration */
45
46 static BOOL reload_services_file(BOOL test)
47 {
48         BOOL ret;
49
50         if (lp_loaded()) {
51                 pstring fname;
52
53                 pstrcpy(fname,lp_configfile());
54                 if (file_exist(fname,NULL) && !strcsequal(fname,dyn_CONFIGFILE)) {
55                         pstrcpy(dyn_CONFIGFILE,fname);
56                         test = False;
57                 }
58         }
59
60         reopen_logs();
61         ret = lp_load(dyn_CONFIGFILE,False,False,True);
62
63         reopen_logs();
64         load_interfaces();
65
66         return(ret);
67 }
68
69
70 #if DUMP_CORE
71
72 /**************************************************************************** **
73  Prepare to dump a core file - carefully!
74  **************************************************************************** */
75
76 static BOOL dump_core(void)
77 {
78         char *p;
79         pstring dname;
80         pstrcpy( dname, lp_logfile() );
81         if ((p=strrchr(dname,'/')))
82                 *p=0;
83         pstrcat( dname, "/corefiles" );
84         mkdir( dname, 0700 );
85         sys_chown( dname, getuid(), getgid() );
86         chmod( dname, 0700 );
87         if ( chdir(dname) )
88                 return( False );
89         umask( ~(0700) );
90  
91 #ifdef HAVE_GETRLIMIT
92 #ifdef RLIMIT_CORE
93         {
94                 struct rlimit rlp;
95                 getrlimit( RLIMIT_CORE, &rlp );
96                 rlp.rlim_cur = MAX( 4*1024*1024, rlp.rlim_cur );
97                 setrlimit( RLIMIT_CORE, &rlp );
98                 getrlimit( RLIMIT_CORE, &rlp );
99                 DEBUG( 3, ( "Core limits now %d %d\n", (int)rlp.rlim_cur, (int)rlp.rlim_max ) );
100         }
101 #endif
102 #endif
103  
104         DEBUG(0,("Dumping core in %s\n",dname));
105         abort();
106         return( True );
107 } /* dump_core */
108 #endif
109
110 /**************************************************************************** **
111  Handle a fault..
112  **************************************************************************** */
113
114 static void fault_quit(void)
115 {
116 #if DUMP_CORE
117         dump_core();
118 #endif
119 }
120
121 static void winbindd_status(void)
122 {
123         struct winbindd_cli_state *tmp;
124
125         DEBUG(0, ("winbindd status:\n"));
126
127         /* Print client state information */
128         
129         DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
130         
131         if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
132                 DEBUG(2, ("\tclient list:\n"));
133                 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
134                         DEBUG(2, ("\t\tpid %d, sock %d, rbl %d, wbl %d\n",
135                                   tmp->pid, tmp->sock, tmp->read_buf_len, 
136                                   tmp->write_buf_len));
137                 }
138         }
139 }
140
141 /* Print winbindd status to log file */
142
143 static void print_winbindd_status(void)
144 {
145         winbindd_status();
146         winbindd_cm_status();
147 }
148
149 /* Flush client cache */
150
151 static void flush_caches(void)
152 {
153 #if 0
154         /* Clear cached user and group enumation info */        
155         if (!opt_dual_daemon) /* Until we have coherent cache flush. */
156                 wcache_flush_cache();
157 #endif
158
159         /* We need to invalidate cached user list entries on a SIGHUP 
160            otherwise cached access denied errors due to restrict anonymous
161            hang around until the sequence number changes. */
162
163         wcache_invalidate_cache();
164 }
165
166 /* Handle the signal by unlinking socket and exiting */
167
168 static void terminate(void)
169 {
170         pstring path;
171
172         idmap_close();
173         
174         /* Remove socket file */
175         snprintf(path, sizeof(path), "%s/%s", 
176                  WINBINDD_SOCKET_DIR, WINBINDD_SOCKET_NAME);
177         unlink(path);
178         exit(0);
179 }
180
181 static BOOL do_sigterm;
182
183 static void termination_handler(int signum)
184 {
185         do_sigterm = True;
186         sys_select_signal();
187 }
188
189 static BOOL do_sigusr2;
190
191 static void sigusr2_handler(int signum)
192 {
193         do_sigusr2 = True;
194         sys_select_signal();
195 }
196
197 static BOOL do_sighup;
198
199 static void sighup_handler(int signum)
200 {
201         do_sighup = True;
202         sys_select_signal();
203 }
204
205 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
206 static void msg_reload_services(int msg_type, pid_t src, void *buf, size_t len)
207 {
208         /* Flush various caches */
209         flush_caches();
210         reload_services_file(True);
211 }
212
213 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
214 static void msg_shutdown(int msg_type, pid_t src, void *buf, size_t len)
215 {
216         terminate();
217 }
218
219 struct dispatch_table {
220         enum winbindd_cmd cmd;
221         enum winbindd_result (*fn)(struct winbindd_cli_state *state);
222         const char *winbindd_cmd_name;
223 };
224
225 static struct dispatch_table dispatch_table[] = {
226         
227         /* User functions */
228
229         { WINBINDD_GETPWNAM, winbindd_getpwnam, "GETPWNAM" },
230         { WINBINDD_GETPWUID, winbindd_getpwuid, "GETPWUID" },
231
232         { WINBINDD_SETPWENT, winbindd_setpwent, "SETPWENT" },
233         { WINBINDD_ENDPWENT, winbindd_endpwent, "ENDPWENT" },
234         { WINBINDD_GETPWENT, winbindd_getpwent, "GETPWENT" },
235
236         { WINBINDD_GETGROUPS, winbindd_getgroups, "GETGROUPS" },
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
272         /* Miscellaneous */
273
274         { WINBINDD_CHECK_MACHACC, winbindd_check_machine_acct, "CHECK_MACHACC" },
275         { WINBINDD_PING, winbindd_ping, "PING" },
276         { WINBINDD_INFO, winbindd_info, "INFO" },
277         { WINBINDD_INTERFACE_VERSION, winbindd_interface_version, "INTERFACE_VERSION" },
278         { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
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 %d more for a full request.\n", n, 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 %d: %s\n",
475                          state->sock, 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         if (!state->write_extra_data) {
498
499                 /* Write response structure */
500                 
501                 data = (char *)&state->response + sizeof(state->response) - 
502                         state->write_buf_len;
503
504         } else {
505
506                 /* Write extra data */
507                 
508                 data = (char *)state->response.extra_data + 
509                         state->response.length - 
510                         sizeof(struct winbindd_response) - 
511                         state->write_buf_len;
512         }
513         
514         num_written = sys_write(state->sock, data, state->write_buf_len);
515         
516         DEBUG(10,("client_write: wrote %d bytes.\n", num_written ));
517
518         /* Write failed, kill cilent */
519         
520         if (num_written == -1 || num_written == 0) {
521                 
522                 DEBUG(3,("write failed on sock %d, pid %d: %s\n",
523                          state->sock, state->pid, 
524                          (num_written == -1) ? strerror(errno) : "EOF"));
525                 
526                 state->finished = True;
527
528                 SAFE_FREE(state->response.extra_data);
529
530                 return;
531         }
532         
533         /* Update client state */
534         
535         state->write_buf_len -= num_written;
536         state->last_access = time(NULL);
537
538         /* Have we written all data? */
539         
540         if (state->write_buf_len == 0) {
541                 
542                 /* Take care of extra data */
543                 
544                 if (state->write_extra_data) {
545
546                         SAFE_FREE(state->response.extra_data);
547
548                         state->write_extra_data = False;
549
550                         DEBUG(10,("client_write: client_write: complete response written.\n"));
551
552                 } else if (state->response.length > 
553                            sizeof(struct winbindd_response)) {
554                         
555                         /* Start writing extra data */
556
557                         state->write_buf_len = 
558                                 state->response.length -
559                                 sizeof(struct winbindd_response);
560                         
561                         DEBUG(10,("client_write: need to write %d extra data bytes.\n", (int)state->write_buf_len));
562
563                         state->write_extra_data = True;
564                 }
565         }
566 }
567
568 /* Process incoming clients on listen_sock.  We use a tricky non-blocking,
569    non-forking, non-threaded model which allows us to handle many
570    simultaneous connections while remaining impervious to many denial of
571    service attacks. */
572
573 static void process_loop(void)
574 {
575         /* We'll be doing this a lot */
576
577         while (1) {
578                 struct winbindd_cli_state *state;
579                 fd_set r_fds, w_fds;
580                 int maxfd, listen_sock, listen_priv_sock, selret;
581                 struct timeval timeout;
582
583                 /* Handle messages */
584
585                 message_dispatch();
586
587                 /* rescan the trusted domains list. This must be done
588                    regularly to cope with transitive trusts */
589                 rescan_trusted_domains(False);
590
591                 /* Free up temporary memory */
592
593                 lp_talloc_free();
594                 main_loop_talloc_free();
595
596                 /* Initialise fd lists for select() */
597
598                 listen_sock = open_winbindd_socket();
599                 listen_priv_sock = open_winbindd_priv_socket();
600
601                 if (listen_sock == -1 || listen_priv_sock == -1) {
602                         perror("open_winbind_socket");
603                         exit(1);
604                 }
605
606                 maxfd = MAX(listen_sock, listen_priv_sock);
607
608                 FD_ZERO(&r_fds);
609                 FD_ZERO(&w_fds);
610                 FD_SET(listen_sock, &r_fds);
611                 FD_SET(listen_priv_sock, &r_fds);
612
613                 timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
614                 timeout.tv_usec = 0;
615
616                 if (opt_dual_daemon) {
617                         maxfd = dual_select_setup(&w_fds, maxfd);
618                 }
619
620                 /* Set up client readers and writers */
621
622                 state = winbindd_client_list();
623
624                 while (state) {
625
626                         /* Dispose of client connection if it is marked as 
627                            finished */ 
628
629                         if (state->finished) {
630                                 struct winbindd_cli_state *next = state->next;
631
632                                 remove_client(state);
633                                 state = next;
634                                 continue;
635                         }
636
637                         /* Select requires we know the highest fd used */
638
639                         if (state->sock > maxfd)
640                                 maxfd = state->sock;
641
642                         /* Add fd for reading */
643
644                         if (state->read_buf_len != sizeof(state->request))
645                                 FD_SET(state->sock, &r_fds);
646
647                         /* Add fd for writing */
648
649                         if (state->write_buf_len)
650                                 FD_SET(state->sock, &w_fds);
651
652                         state = state->next;
653                 }
654
655                 /* Call select */
656         
657                 selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
658
659                 if (selret == 0)
660                         continue;
661
662                 if ((selret == -1 && errno != EINTR) || selret == 0) {
663
664                         /* Select error, something is badly wrong */
665
666                         perror("select");
667                         exit(1);
668                 }
669
670                 /* Create a new connection if listen_sock readable */
671
672                 if (selret > 0) {
673
674                         if (opt_dual_daemon) {
675                                 dual_select(&w_fds);
676                         }
677
678                         if (FD_ISSET(listen_sock, &r_fds)) {
679                                 while (winbindd_num_clients() > WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
680                                         DEBUG(5,("winbindd: Exceeding %d client connections, removing idle connection.\n",
681                                                 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
682                                         if (!remove_idle_client()) {
683                                                 DEBUG(0,("winbindd: Exceeding %d client connections, no idle connection found\n",
684                                                         WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
685                                                 break;
686                                         }
687                                 }
688                                 /* new, non-privileged connection */
689                                 new_connection(listen_sock, False);
690                         }
691             
692                         if (FD_ISSET(listen_priv_sock, &r_fds)) {
693                                 while (winbindd_num_clients() > WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
694                                         DEBUG(5,("winbindd: Exceeding %d client connections, removing idle connection.\n",
695                                                 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
696                                         if (!remove_idle_client()) {
697                                                 DEBUG(0,("winbindd: Exceeding %d client connections, no idle connection found\n",
698                                                         WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
699                                                 break;
700                                         }
701                                 }
702                                 /* new, privileged connection */
703                                 new_connection(listen_priv_sock, True);
704                         }
705             
706                         /* Process activity on client connections */
707             
708                         for (state = winbindd_client_list(); state; 
709                              state = state->next) {
710                 
711                                 /* Data available for reading */
712                 
713                                 if (FD_ISSET(state->sock, &r_fds)) {
714                     
715                                         /* Read data */
716                     
717                                         winbind_client_read(state);
718
719                                         /* 
720                                          * If we have the start of a
721                                          * packet, then check the
722                                          * length field to make sure
723                                          * the client's not talking
724                                          * Mock Swedish.
725                                          */
726
727                                         if (state->read_buf_len >= sizeof(uint32)
728                                             && *(uint32 *) &state->request != sizeof(state->request)) {
729                                                 DEBUG(0,("process_loop: Invalid request size from pid %d: %d bytes sent, should be %d\n",
730                                                                 state->request.pid, *(uint32 *) &state->request, sizeof(state->request)));
731
732                                                 remove_client(state);
733                                                 break;
734                                         }
735
736                                         /* A request packet might be 
737                                            complete */
738                     
739                                         if (state->read_buf_len == 
740                                             sizeof(state->request)) {
741                                                 winbind_process_packet(state);
742                                         }
743                                 }
744                 
745                                 /* Data available for writing */
746                 
747                                 if (FD_ISSET(state->sock, &w_fds))
748                                         client_write(state);
749                         }
750                 }
751
752 #if 0
753                 winbindd_check_cache_size(time(NULL));
754 #endif
755
756                 /* Check signal handling things */
757
758                 if (do_sigterm)
759                         terminate();
760
761                 if (do_sighup) {
762
763                         DEBUG(3, ("got SIGHUP\n"));
764
765                         msg_reload_services(MSG_SMB_CONF_UPDATED, (pid_t) 0, NULL, 0);
766                         do_sighup = False;
767                 }
768
769                 if (do_sigusr2) {
770                         print_winbindd_status();
771                         do_sigusr2 = False;
772                 }
773         }
774 }
775
776 /* Main function */
777
778 struct winbindd_state server_state;   /* Server state information */
779
780 int main(int argc, char **argv)
781 {
782         pstring logfile;
783         static BOOL interactive = False;
784         static BOOL Fork = True;
785         static BOOL log_stdout = False;
786         struct poptOption long_options[] = {
787                 POPT_AUTOHELP
788                 { "stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
789                 { "foreground", 'F', POPT_ARG_VAL, &Fork, False, "Daemon in foreground mode" },
790                 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
791                 { "single-daemon", 'Y', POPT_ARG_VAL, &opt_dual_daemon, False, "Single daemon mode" },
792                 { "no-caching", 'n', POPT_ARG_VAL, &opt_nocache, False, "Disable caching" },
793                 POPT_COMMON_SAMBA
794                 POPT_TABLEEND
795         };
796         poptContext pc;
797         int opt;
798
799         /* glibc (?) likes to print "User defined signal 1" and exit if a
800            SIGUSR[12] is received before a handler is installed */
801
802         CatchSignal(SIGUSR1, SIG_IGN);
803         CatchSignal(SIGUSR2, SIG_IGN);
804
805         fault_setup((void (*)(void *))fault_quit );
806
807         /* Initialise for running in non-root mode */
808
809         sec_init();
810
811         set_remote_machine_name("winbindd", False);
812
813         /* Set environment variable so we don't recursively call ourselves.
814            This may also be useful interactively. */
815
816         setenv(WINBINDD_DONT_ENV, "1", 1);
817
818         /* Initialise samba/rpc client stuff */
819
820         pc = poptGetContext("winbindd", argc, (const char **)argv, long_options,
821                                                 POPT_CONTEXT_KEEP_FIRST);
822
823         while ((opt = poptGetNextOpt(pc)) != -1) {
824                 switch (opt) {
825                         /* Don't become a daemon */
826                 case 'i':
827                         interactive = True;
828                         log_stdout = True;
829                         Fork = False;
830                         break;
831                 }
832         }
833
834
835         if (log_stdout && Fork) {
836                 printf("Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n");
837                 poptPrintUsage(pc, stderr, 0);
838                 exit(1);
839         }
840
841         snprintf(logfile, sizeof(logfile), "%s/log.winbindd", dyn_LOGFILEBASE);
842         lp_set_logfile(logfile);
843         setup_logging("winbindd", log_stdout);
844         reopen_logs();
845
846         DEBUG(1, ("winbindd version %s started.\n", VERSION ) );
847         DEBUGADD( 1, ( "Copyright The Samba Team 2000-2003\n" ) );
848
849         if (!reload_services_file(False)) {
850                 DEBUG(0, ("error opening config file\n"));
851                 exit(1);
852         }
853
854         /* Setup names. */
855
856         if (!init_names())
857                 exit(1);
858
859         load_interfaces();
860
861         if (!secrets_init()) {
862
863                 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
864                 return False;
865         }
866
867         /* Enable netbios namecache */
868
869         namecache_enable();
870
871         /* Check winbindd parameters are valid */
872
873         ZERO_STRUCT(server_state);
874
875         if (!winbindd_param_init())
876                 return 1;
877
878         /* Winbind daemon initialisation */
879
880         if (!winbindd_upgrade_idmap())
881                 return 1;
882
883         if (!idmap_init(lp_idmap_backend()))
884                 return 1;
885
886         if (!idmap_init_wellknown_sids())
887                 exit(1);
888
889         /* Unblock all signals we are interested in as they may have been
890            blocked by the parent process. */
891
892         BlockSignals(False, SIGINT);
893         BlockSignals(False, SIGQUIT);
894         BlockSignals(False, SIGTERM);
895         BlockSignals(False, SIGUSR1);
896         BlockSignals(False, SIGUSR2);
897         BlockSignals(False, SIGHUP);
898
899         /* Setup signal handlers */
900         
901         CatchSignal(SIGINT, termination_handler);      /* Exit on these sigs */
902         CatchSignal(SIGQUIT, termination_handler);
903         CatchSignal(SIGTERM, termination_handler);
904
905         CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
906
907         CatchSignal(SIGUSR2, sigusr2_handler);         /* Debugging sigs */
908         CatchSignal(SIGHUP, sighup_handler);
909
910         if (!interactive)
911                 become_daemon(Fork);
912
913         pidfile_create("winbindd");
914
915 #if HAVE_SETPGID
916         /*
917          * If we're interactive we want to set our own process group for
918          * signal management.
919          */
920         if (interactive)
921                 setpgid( (pid_t)0, (pid_t)0);
922 #endif
923
924         if (opt_dual_daemon) {
925                 do_dual_daemon();
926         }
927
928         /* Initialise messaging system */
929
930         if (!message_init()) {
931                 DEBUG(0, ("unable to initialise messaging system\n"));
932                 exit(1);
933         }
934         
935         /* React on 'smbcontrol winbindd reload-config' in the same way
936            as to SIGHUP signal */
937         message_register(MSG_SMB_CONF_UPDATED, msg_reload_services);
938         message_register(MSG_SHUTDOWN, msg_shutdown);
939         
940         poptFreeContext(pc);
941
942         netsamlogon_cache_init(); /* Non-critical */
943         
944         /* Loop waiting for requests */
945
946         process_loop();
947
948         trustdom_cache_shutdown();
949
950         return 0;
951 }