Try to set the socket options early for some OSs (like Sol 8) where they
[ira/wip.git] / source3 / smbd / server.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Main SMB server routines
5    Copyright (C) Andrew Tridgell 1992-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23
24 pstring servicesf = CONFIGFILE;
25 extern pstring debugf;
26 extern fstring global_myworkgroup;
27 extern pstring global_myname;
28
29 int am_parent = 1;
30
31 /* the last message the was processed */
32 int last_message = -1;
33
34 /* a useful macro to debug the last message processed */
35 #define LAST_MESSAGE() smb_fn_name(last_message)
36
37 extern int DEBUGLEVEL;
38
39 extern pstring user_socket_options;
40
41 #ifdef WITH_DFS
42 extern int dcelogin_atmost_once;
43 #endif /* WITH_DFS */
44
45 extern fstring remote_machine;
46
47 /* really we should have a top level context structure that has the
48    client file descriptor as an element. That would require a major rewrite :(
49
50    the following 2 functions are an alternative - they make the file
51    descriptor private to smbd
52  */
53 static int server_fd = -1;
54
55 int smbd_server_fd(void)
56 {
57         return server_fd;
58 }
59
60 void smbd_set_server_fd(int fd)
61 {
62         server_fd = fd;
63         client_setfd(fd);
64 }
65
66 /****************************************************************************
67   when exiting, take the whole family
68 ****************************************************************************/
69 static void *dflt_sig(void)
70 {
71         exit_server("caught signal");
72         return NULL;
73 }
74
75 /****************************************************************************
76   Send a SIGTERM to our process group.
77 *****************************************************************************/
78 static void  killkids(void)
79 {
80         if(am_parent) kill(0,SIGTERM);
81 }
82
83
84 /****************************************************************************
85   open the socket communication
86 ****************************************************************************/
87 static BOOL open_sockets_inetd(void)
88 {
89         /* Started from inetd. fd 0 is the socket. */
90         /* We will abort gracefully when the client or remote system 
91            goes away */
92         smbd_set_server_fd(dup(0));
93         
94         /* close our standard file descriptors */
95         close_low_fds();
96         
97         set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
98         set_socket_options(smbd_server_fd(),user_socket_options);
99
100         return True;
101 }
102
103
104 /****************************************************************************
105   open the socket communication
106 ****************************************************************************/
107 static BOOL open_sockets(BOOL is_daemon,int port)
108 {
109         int num_interfaces = iface_count();
110         int fd_listenset[FD_SETSIZE];
111         fd_set listen_set;
112         int s;
113         int i;
114
115         if (!is_daemon) {
116                 return open_sockets_inetd();
117         }
118
119                 
120 #ifdef HAVE_ATEXIT
121         {
122                 static int atexit_set;
123                 if(atexit_set == 0) {
124                         atexit_set=1;
125                         atexit(killkids);
126                 }
127         }
128 #endif
129
130         /* Stop zombies */
131         CatchChild();
132                 
133                 
134         FD_ZERO(&listen_set);
135
136         if(lp_interfaces() && lp_bind_interfaces_only()) {
137                 /* We have been given an interfaces line, and been 
138                    told to only bind to those interfaces. Create a
139                    socket per interface and bind to only these.
140                 */
141                 
142                 if(num_interfaces > FD_SETSIZE) {
143                         DEBUG(0,("open_sockets: Too many interfaces specified to bind to. Number was %d \
144 max can be %d\n", 
145                                  num_interfaces, FD_SETSIZE));
146                         return False;
147                 }
148                 
149                 /* Now open a listen socket for each of the
150                    interfaces. */
151                 for(i = 0; i < num_interfaces; i++) {
152                         struct in_addr *ifip = iface_n_ip(i);
153                         
154                         if(ifip == NULL) {
155                                 DEBUG(0,("open_sockets: interface %d has NULL IP address !\n", i));
156                                 continue;
157                         }
158                         s = fd_listenset[i] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
159                         if(s == -1)
160                                 return False;
161
162                         /* ready to listen */
163                         set_socket_options(s,"SO_KEEPALIVE"); 
164                         set_socket_options(s,user_socket_options);
165       
166                         if (listen(s, 5) == -1) {
167                                 DEBUG(0,("listen: %s\n",strerror(errno)));
168                                 close(s);
169                                 return False;
170                         }
171                         FD_SET(s,&listen_set);
172                 }
173         } else {
174                 /* Just bind to 0.0.0.0 - accept connections
175                    from anywhere. */
176                 num_interfaces = 1;
177                 
178                 /* open an incoming socket */
179                 s = open_socket_in(SOCK_STREAM, port, 0,
180                                    interpret_addr(lp_socket_address()),True);
181                 if (s == -1)
182                         return(False);
183                 
184                 /* ready to listen */
185                 set_socket_options(s,"SO_KEEPALIVE"); 
186                 set_socket_options(s,user_socket_options);
187
188                 if (listen(s, 5) == -1) {
189                         DEBUG(0,("open_sockets: listen: %s\n",
190                                  strerror(errno)));
191                         close(s);
192                         return False;
193                 }
194                 
195                 fd_listenset[0] = s;
196                 FD_SET(s,&listen_set);
197         } 
198
199         /* now accept incoming connections - forking a new process
200            for each incoming connection */
201         DEBUG(2,("waiting for a connection\n"));
202         while (1) {
203                 fd_set lfds;
204                 int num;
205                 
206                 /* Free up temporary memory from the main smbd. */
207                 lp_talloc_free();
208
209                 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
210                 message_dispatch();
211
212                 memcpy((char *)&lfds, (char *)&listen_set, 
213                        sizeof(listen_set));
214                 
215                 num = sys_select(FD_SETSIZE,&lfds,NULL);
216                 
217                 if (num == -1 && errno == EINTR) {
218                         extern VOLATILE sig_atomic_t reload_after_sighup;
219
220                         /* check for sighup processing */
221                         if (reload_after_sighup) {
222                                 unbecome_user();
223                                 DEBUG(1,("Reloading services after SIGHUP\n"));
224                                 reload_services(False);
225                                 reload_after_sighup = False;
226                         }
227
228                         continue;
229                 }
230                 
231                 /* check if we need to reload services */
232                 check_reload(time(NULL));
233
234                 /* Find the sockets that are read-ready -
235                    accept on these. */
236                 for( ; num > 0; num--) {
237                         struct sockaddr addr;
238                         socklen_t in_addrlen = sizeof(addr);
239                         
240                         s = -1;
241                         for(i = 0; i < num_interfaces; i++) {
242                                 if(FD_ISSET(fd_listenset[i],&lfds)) {
243                                         s = fd_listenset[i];
244                                         /* Clear this so we don't look
245                                            at it again. */
246                                         FD_CLR(fd_listenset[i],&lfds);
247                                         break;
248                                 }
249                         }
250
251                         smbd_set_server_fd(accept(s,&addr,&in_addrlen));
252                         
253                         if (smbd_server_fd() == -1 && errno == EINTR)
254                                 continue;
255                         
256                         if (smbd_server_fd() == -1) {
257                                 DEBUG(0,("open_sockets: accept: %s\n",
258                                          strerror(errno)));
259                                 continue;
260                         }
261                         
262                         if (smbd_server_fd() != -1 && sys_fork()==0) {
263                                 /* Child code ... */
264                                 
265                                 /* close the listening socket(s) */
266                                 for(i = 0; i < num_interfaces; i++)
267                                         close(fd_listenset[i]);
268                                 
269                                 /* close our standard file
270                                    descriptors */
271                                 close_low_fds();
272                                 am_parent = 0;
273                                 
274                                 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
275                                 set_socket_options(smbd_server_fd(),user_socket_options);
276                                 
277                                 /* Reset global variables in util.c so
278                                    that client substitutions will be
279                                    done correctly in the process.  */
280                                 reset_globals_after_fork();
281
282                                 return True; 
283                         }
284                         /* The parent doesn't need this socket */
285                         close(smbd_server_fd()); 
286
287                         /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
288                                 Clear the closed fd info out of server_fd --
289                                 and more importantly, out of client_fd in
290                                 util_sock.c, to avoid a possible
291                                 getpeername failure if we reopen the logs
292                                 and use %I in the filename.
293                         */
294
295                         smbd_set_server_fd(-1);
296
297                         /* Force parent to check log size after
298                          * spawning child.  Fix from
299                          * klausr@ITAP.Physik.Uni-Stuttgart.De.  The
300                          * parent smbd will log to logserver.smb.  It
301                          * writes only two messages for each child
302                          * started/finished. But each child writes,
303                          * say, 50 messages also in logserver.smb,
304                          * begining with the debug_count of the
305                          * parent, before the child opens its own log
306                          * file logserver.client. In a worst case
307                          * scenario the size of logserver.smb would be
308                          * checked after about 50*50=2500 messages
309                          * (ca. 100kb).
310                          * */
311                         force_check_log_size();
312  
313                 } /* end for num */
314         } /* end while 1 */
315
316 /* NOTREACHED   return True; */
317 }
318
319 /****************************************************************************
320   reload the services file
321   **************************************************************************/
322 BOOL reload_services(BOOL test)
323 {
324         BOOL ret;
325         
326         if (lp_loaded()) {
327                 pstring fname;
328                 pstrcpy(fname,lp_configfile());
329                 if (file_exist(fname,NULL) && !strcsequal(fname,servicesf)) {
330                         pstrcpy(servicesf,fname);
331                         test = False;
332                 }
333         }
334
335         reopen_logs();
336
337         if (test && !lp_file_list_changed())
338                 return(True);
339
340         lp_killunused(conn_snum_used);
341         
342         ret = lp_load(servicesf,False,False,True);
343
344         load_printers();
345
346         /* perhaps the config filename is now set */
347         if (!test)
348                 reload_services(True);
349
350         reopen_logs();
351
352         load_interfaces();
353
354         {
355                 if (smbd_server_fd() != -1) {      
356                         set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
357                         set_socket_options(smbd_server_fd(),user_socket_options);
358                 }
359         }
360
361         reset_mangled_cache();
362         reset_stat_cache();
363
364         /* this forces service parameters to be flushed */
365         become_service(NULL,True);
366
367         return(ret);
368 }
369
370
371
372 /****************************************************************************
373  Catch a sighup.
374 ****************************************************************************/
375
376 VOLATILE sig_atomic_t reload_after_sighup = False;
377
378 static void sig_hup(int sig)
379 {
380         BlockSignals(True,SIGHUP);
381         DEBUG(0,("Got SIGHUP\n"));
382
383         sys_select_signal();
384         reload_after_sighup = True;
385         BlockSignals(False,SIGHUP);
386 }
387
388
389
390 #if DUMP_CORE
391 /*******************************************************************
392 prepare to dump a core file - carefully!
393 ********************************************************************/
394 static BOOL dump_core(void)
395 {
396         char *p;
397         pstring dname;
398         pstrcpy(dname,debugf);
399         if ((p=strrchr_m(dname,'/'))) *p=0;
400         pstrcat(dname,"/corefiles");
401         mkdir(dname,0700);
402         sys_chown(dname,getuid(),getgid());
403         chmod(dname,0700);
404         if (chdir(dname)) return(False);
405         umask(~(0700));
406
407 #ifdef HAVE_GETRLIMIT
408 #ifdef RLIMIT_CORE
409         {
410                 struct rlimit rlp;
411                 getrlimit(RLIMIT_CORE, &rlp);
412                 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
413                 setrlimit(RLIMIT_CORE, &rlp);
414                 getrlimit(RLIMIT_CORE, &rlp);
415                 DEBUG(3,("Core limits now %d %d\n",
416                          (int)rlp.rlim_cur,(int)rlp.rlim_max));
417         }
418 #endif
419 #endif
420
421
422         DEBUG(0,("Dumping core in %s\n",dname));
423         abort();
424         return(True);
425 }
426 #endif
427
428 /****************************************************************************
429 update the current smbd process count
430 ****************************************************************************/
431
432 static void decrement_smbd_process_count(void)
433 {
434         int total_smbds;
435
436         if (lp_max_smbd_processes()) {
437                 total_smbds = 0;
438                 tdb_change_int_atomic(conn_tdb_ctx(), "INFO/total_smbds", &total_smbds, -1);
439         }
440 }
441
442 /****************************************************************************
443 exit the server
444 ****************************************************************************/
445 void exit_server(char *reason)
446 {
447         static int firsttime=1;
448         extern char *last_inbuf;
449
450
451         if (!firsttime) exit(0);
452         firsttime = 0;
453
454         unbecome_user();
455         DEBUG(2,("Closing connections\n"));
456
457         conn_close_all();
458
459         invalidate_all_vuids();
460
461         /* delete our entry in the connections database. */
462         if (lp_status(-1)) {
463                 yield_connection(NULL,"",MAXSTATUS);
464         }
465
466         respond_to_all_remaining_local_messages();
467         decrement_smbd_process_count();
468
469 #ifdef WITH_DFS
470         if (dcelogin_atmost_once) {
471                 dfs_unlogin();
472         }
473 #endif
474
475         if (!reason) {   
476                 int oldlevel = DEBUGLEVEL;
477                 DEBUGLEVEL = 10;
478                 DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
479                 if (last_inbuf)
480                         show_msg(last_inbuf);
481                 DEBUGLEVEL = oldlevel;
482                 DEBUG(0,("===============================================================\n"));
483 #if DUMP_CORE
484                 if (dump_core()) return;
485 #endif
486         }    
487
488         locking_end();
489
490         DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
491         exit(0);
492 }
493
494 /****************************************************************************
495   initialise connect, service and file structs
496 ****************************************************************************/
497 static void init_structs(void )
498 {
499         /*
500          * Set the machine NETBIOS name if not already
501          * set from the config file.
502          */
503
504         if (!*global_myname) {
505                 char *p;
506                 fstrcpy( global_myname, myhostname() );
507                 p = strchr_m( global_myname, '.' );
508                 if (p) 
509                         *p = 0;
510         }
511
512         strupper( global_myname );
513
514         conn_init();
515
516         file_init();
517
518         /* for RPC pipes */
519         init_rpc_pipe_hnd();
520
521         init_dptrs();
522
523         secrets_init();
524 }
525
526 /****************************************************************************
527 usage on the program
528 ****************************************************************************/
529 static void usage(char *pname)
530 {
531
532         printf("Usage: %s [-DaoPh?V] [-d debuglevel] [-l log basename] [-p port]\n", pname);
533         printf("       [-O socket options] [-s services file]\n");
534         printf("\t-D                    Become a daemon\n");
535         printf("\t-a                    Append to log file (default)\n");
536         printf("\t-o                    Overwrite log file, don't append\n");
537         printf("\t-h                    Print usage\n");
538         printf("\t-?                    Print usage\n");
539         printf("\t-V                    Print version\n");
540         printf("\t-d debuglevel         Set the debuglevel\n");
541         printf("\t-l log basename.      Basename for log/debug files\n");
542         printf("\t-p port               Listen on the specified port\n");
543         printf("\t-O socket options     Socket options\n");
544         printf("\t-s services file.     Filename of services file\n");
545         printf("\n");
546 }
547
548
549 /****************************************************************************
550   main program
551 ****************************************************************************/
552  int main(int argc,char *argv[])
553 {
554         extern BOOL append_log;
555         /* shall I run as a daemon */
556         BOOL is_daemon = False;
557         BOOL specified_logfile = False;
558         int port = SMB_PORT;
559         int opt;
560         extern char *optarg;
561         
562 #ifdef HAVE_SET_AUTH_PARAMETERS
563         set_auth_parameters(argc,argv);
564 #endif
565
566         /* this is for people who can't start the program correctly */
567         while (argc > 1 && (*argv[1] != '-')) {
568                 argv++;
569                 argc--;
570         }
571
572         while ( EOF != (opt = getopt(argc, argv, "O:l:s:d:Dp:h?Vaof:")) )
573                 switch (opt)  {
574                 case 'O':
575                         pstrcpy(user_socket_options,optarg);
576                         break;
577
578                 case 's':
579                         pstrcpy(servicesf,optarg);
580                         break;
581
582                 case 'l':
583                         specified_logfile = True;
584                         slprintf(debugf, sizeof(debugf)-1, "%s/log.smbd", optarg);
585                         break;
586
587                 case 'a':
588                         append_log = True;
589                         break;
590
591                 case 'o':
592                         append_log = False;
593                         break;
594
595                 case 'D':
596                         is_daemon = True;
597                         break;
598
599                 case 'd':
600                         if (*optarg == 'A')
601                                 DEBUGLEVEL = 10000;
602                         else
603                                 DEBUGLEVEL = atoi(optarg);
604                         break;
605
606                 case 'p':
607                         port = atoi(optarg);
608                         break;
609
610                 case 'h':
611                 case '?':
612                         usage(argv[0]);
613                         exit(0);
614                         break;
615
616                 case 'V':
617                         printf("Version %s\n",VERSION);
618                         exit(0);
619                         break;
620                 default:
621                         DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
622                         usage(argv[0]);
623                         exit(1);
624                 }
625
626 #ifdef HAVE_SETLUID
627         /* needed for SecureWare on SCO */
628         setluid(0);
629 #endif
630
631         sec_init();
632
633         append_log = True;
634
635         TimeInit();
636
637         if(!specified_logfile) {
638                 slprintf(debugf, sizeof(debugf)-1, "%s/log.smbd", LOGFILEBASE);
639         }
640
641         pstrcpy(remote_machine, "smbd");
642
643         setup_logging(argv[0],False);
644
645         /* we want to re-seed early to prevent time delays causing
646            client problems at a later date. (tridge) */
647         generate_random_buffer(NULL, 0, False);
648
649         /* make absolutely sure we run as root - to handle cases where people
650            are crazy enough to have it setuid */
651
652         gain_root_privilege();
653         gain_root_group_privilege();
654
655         fault_setup((void (*)(void *))exit_server);
656         CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
657
658         /* we are never interested in SIGPIPE */
659         BlockSignals(True,SIGPIPE);
660
661 #if defined(SIGFPE)
662         /* we are never interested in SIGFPE */
663         BlockSignals(True,SIGFPE);
664 #endif
665
666 #if defined(SIGUSR2)
667         /* We are no longer interested in USR2 */
668         BlockSignals(True,SIGUSR2);
669 #endif
670
671         /* POSIX demands that signals are inherited. If the invoking process has
672          * these signals masked, we will have problems, as we won't recieve them. */
673         BlockSignals(False, SIGHUP);
674         BlockSignals(False, SIGUSR1);
675
676         /* we want total control over the permissions on created files,
677            so set our umask to 0 */
678         umask(0);
679
680         init_sec_ctx();
681
682         reopen_logs();
683
684         DEBUG(1,( "smbd version %s started.\n", VERSION));
685         DEBUGADD(1,( "Copyright Andrew Tridgell 1992-1998\n"));
686
687         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
688                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
689
690         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
691                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
692                 exit(1);
693         }
694
695         /*
696          * Do this before reload_services.
697          */
698
699         if (!reload_services(False))
700                 return(-1);     
701
702         init_structs();
703
704         /* don't call winbind for our domain if we are the DC */
705         if (lp_domain_logons()) {
706                 winbind_exclude_domain(lp_workgroup());
707         }
708         
709 #ifdef WITH_PROFILE
710         if (!profile_setup(False)) {
711                 DEBUG(0,("ERROR: failed to setup profiling\n"));
712                 return -1;
713         }
714 #endif
715
716 #ifdef WITH_SSL
717         {
718                 extern BOOL sslEnabled;
719                 sslEnabled = lp_ssl_enabled();
720                 if(sslEnabled)
721                         sslutil_init(True);
722         }
723 #endif        /* WITH_SSL */
724
725         fstrcpy(global_myworkgroup, lp_workgroup());
726
727         CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
728         
729         DEBUG(3,( "loaded services\n"));
730
731         if (!is_daemon && !is_a_socket(0)) {
732                 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
733                 is_daemon = True;
734         }
735
736         if (is_daemon) {
737                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
738                 become_daemon();
739         }
740
741         if (!directory_exist(lp_lockdir(), NULL)) {
742                 mkdir(lp_lockdir(), 0755);
743         }
744
745         if (is_daemon) {
746                 pidfile_create("smbd");
747         }
748
749         if (!message_init()) {
750                 exit(1);
751         }
752
753         /* Setup the main smbd so that we can get messages. */
754         if (lp_status(-1)) {
755                 claim_connection(NULL,"",MAXSTATUS,True);
756         }
757
758         /* Attempt to migrate from an old 2.0.x machine account file. */
759         if (!migrate_from_old_password_file(global_myworkgroup)) {
760                 DEBUG(0,("Failed to migrate from old MAC file.\n"));
761         }
762
763         if (!open_sockets(is_daemon,port))
764                 exit(1);
765
766         /*
767          * everything after this point is run after the fork()
768          */ 
769
770         if (!locking_init(0)) {
771                 exit(1);
772         }
773
774         if (!print_backend_init()) {
775                 exit(1);
776         }
777
778         if (!share_info_db_init()) {
779                 exit(1);
780         }
781
782         if(!initialize_password_db(False)) {
783                 exit(1);
784         }
785
786         /* possibly reload the services file. */
787         reload_services(True);
788
789         if (init_group_mapping()==False) {
790                 printf("Could not open tdb mapping file.\n");
791                 return 0;
792         }
793
794         if(!pdb_generate_sam_sid()) {
795                 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
796                 exit(1);
797         }
798
799         if (*lp_rootdir()) {
800                 if (sys_chroot(lp_rootdir()) == 0)
801                         DEBUG(2,("Changed root to %s\n", lp_rootdir()));
802         }
803
804         /* Setup oplocks */
805         if (!init_oplocks()) {
806                 exit(1);
807         }
808
809         /* Setup change notify */
810         if (!init_change_notify()) {
811                 exit(1);
812         }
813
814         smbd_process();
815         
816         exit_server("normal exit");
817         return(0);
818 }