final part of "first" phase converting over to msrpc daemon architecture.
[sfrench/samba-autobuild/.git] / source3 / msrpc / msrpcd.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 #include "trans2.h"
24
25 extern pstring servicesf;
26 extern pstring debugf;
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 pstring scope;
38 extern int DEBUGLEVEL;
39
40 extern fstring remote_machine;
41 extern pstring myhostname;
42 extern pstring pipe_name;
43
44 extern pstring OriginalDir;
45
46 /****************************************************************************
47   when exiting, take the whole family
48 ****************************************************************************/
49 static void *dflt_sig(void)
50 {
51         exit_server("caught signal");
52         return NULL;
53 }
54
55 /****************************************************************************
56   Send a SIGTERM to our process group.
57 *****************************************************************************/
58 static void  killkids(void)
59 {
60         if(am_parent) kill(0,SIGTERM);
61 }
62
63
64 /****************************************************************************
65   open and listen to a socket
66 ****************************************************************************/
67 static int open_server_socket(void)
68 {
69         int s;
70         fstring dir;
71         fstring path;
72
73         slprintf(dir, sizeof(dir)-1, "/tmp/.msrpc");
74         slprintf(path, sizeof(path)-1, "%s/%s", dir, pipe_name);
75
76         s = create_pipe_socket(dir, 0777, path, 0777);
77
78         if (s == -1)
79                 return -1;
80                 /* ready to listen */
81         if (listen(s, 5) == -1) {
82                 DEBUG(0,("listen: %s\n", strerror(errno)));
83                 close(s);
84                 return -1;
85         }
86         return s;
87 }
88
89 /****************************************************************************
90   open the socket communication
91 ****************************************************************************/
92 static int open_sockets(BOOL is_daemon)
93 {
94         int ClientMSRPC;
95         int num_interfaces = iface_count();
96         int fd_listenset;
97         fd_set listen_set;
98         int s;
99
100         memset(&fd_listenset, 0, sizeof(fd_listenset));
101
102 #ifdef HAVE_ATEXIT
103         {
104                 static int atexit_set;
105                 if(atexit_set == 0) {
106                         atexit_set=1;
107                         atexit(killkids);
108                 }
109         }
110 #endif
111
112         /* Stop zombies */
113         CatchChild();
114                 
115                 
116         FD_ZERO(&listen_set);
117
118         /* Just bind to 0.0.0.0 - accept connections
119            from anywhere. */
120         num_interfaces = 1;
121         
122         /* open an incoming socket */
123         s = open_server_socket();
124         if (s == -1)
125                 return -1;
126         fd_listenset = s;
127         FD_SET(s,&listen_set);
128
129         /* now accept incoming connections - forking a new process
130            for each incoming connection */
131         DEBUG(2,("waiting for a connection\n"));
132         while (1)
133         {
134                 struct sockaddr_un addr;
135                 int in_addrlen = sizeof(addr);
136                 fd_set lfds;
137                 int num;
138                 
139                 memcpy((char *)&lfds, (char *)&listen_set, 
140                        sizeof(listen_set));
141                 
142                 num = sys_select(256,&lfds,NULL, NULL);
143                 
144                 if (num == -1 && errno == EINTR)
145                         continue;
146                 
147                 /* Find the sockets that are read-ready -
148                    accept on these. */
149                         
150                 s = -1;
151                 if(FD_ISSET(fd_listenset,&lfds))
152                 {
153                         s = fd_listenset;
154                 }
155
156                 /* Clear this so we don't look at it again. */
157                 FD_CLR(s,&lfds);
158
159                 ClientMSRPC = accept(s,(struct sockaddr*)&addr,&in_addrlen);
160                 
161                 if (ClientMSRPC == -1 && errno == EINTR)
162                         continue;
163                 
164                 if (ClientMSRPC == -1)
165                 {
166                         DEBUG(0,("open_sockets: accept: %s\n",
167                                  strerror(errno)));
168                         continue;
169                 }
170                 
171                 if (ClientMSRPC != -1 && fork()==0)
172                 {
173                         /* Child code ... */
174                         
175                         /* close the listening socket(s) */
176                         close(fd_listenset);
177                         
178                         /* close our standard file
179                            descriptors */
180                         close_low_fds();
181                         am_parent = 0;
182                         
183                         /* Reset global variables in util.c so
184                            that client substitutions will be
185                            done correctly in the process.  */
186                         reset_globals_after_fork();
187
188                         return ClientMSRPC; 
189                 }
190                 /* The parent doesn't need this socket */
191                 close(ClientMSRPC); 
192
193                 /* Force parent to check log size after
194                  * spawning child.  Fix from
195                  * klausr@ITAP.Physik.Uni-Stuttgart.De.  The
196                  * parent daemon will log to logserver.smb.  It
197                  * writes only two messages for each child
198                  * started/finished. But each child writes,
199                  * say, 50 messages also in logserver.smb,
200                  * begining with the debug_count of the
201                  * parent, before the child opens its own log
202                  * file logserver.client. In a worst case
203                  * scenario the size of logserver.smb would be
204                  * checked after about 50*50=2500 messages
205                  * (ca. 100kb).
206                  * */
207                 force_check_log_size();
208
209         } /* end while 1 */
210
211 /* NOTREACHED */
212 }
213
214
215 /****************************************************************************
216 this prevents zombie child processes
217 ****************************************************************************/
218 BOOL reload_after_sighup = False;
219
220 static void sig_hup(int sig)
221 {
222         BlockSignals(True,SIGHUP);
223         DEBUG(0,("Got SIGHUP\n"));
224
225         /*
226          * Fix from <branko.cibej@hermes.si> here.
227          * We used to reload in the signal handler - this
228          * is a *BIG* no-no.
229          */
230
231         reload_after_sighup = True;
232         BlockSignals(False,SIGHUP);
233 }
234
235
236
237 #if DUMP_CORE
238 /*******************************************************************
239 prepare to dump a core file - carefully!
240 ********************************************************************/
241 static BOOL dump_core(void)
242 {
243         char *p;
244         pstring dname;
245         pstrcpy(dname,debugf);
246         if ((p=strrchr(dname,'/'))) *p=0;
247         pstrcat(dname,"/corefiles");
248         mkdir(dname,0700);
249         sys_chown(dname,getuid(),getgid());
250         chmod(dname,0700);
251         if (chdir(dname)) return(False);
252         umask(~(0700));
253
254 #ifdef HAVE_GETRLIMIT
255 #ifdef RLIMIT_CORE
256         {
257                 struct rlimit rlp;
258                 getrlimit(RLIMIT_CORE, &rlp);
259                 rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
260                 setrlimit(RLIMIT_CORE, &rlp);
261                 getrlimit(RLIMIT_CORE, &rlp);
262                 DEBUG(3,("Core limits now %d %d\n",
263                          (int)rlp.rlim_cur,(int)rlp.rlim_max));
264         }
265 #endif
266 #endif
267
268
269         DEBUG(0,("Dumping core in %s\n",dname));
270         abort();
271         return(True);
272 }
273 #endif
274
275
276 /****************************************************************************
277 exit the server
278 ****************************************************************************/
279 void exit_server(char *reason)
280 {
281         static int firsttime=1;
282         extern char *last_inbuf;
283
284
285         if (!firsttime) exit(0);
286         firsttime = 0;
287
288         unbecome_vuser();
289         DEBUG(2,("Closing connections\n"));
290
291 #ifdef WITH_DFS
292         if (dcelogin_atmost_once) {
293                 dfs_unlogin();
294         }
295 #endif
296
297         if (!reason) {   
298                 int oldlevel = DEBUGLEVEL;
299                 DEBUGLEVEL = 10;
300                 if (last_inbuf)
301                         show_msg(last_inbuf);
302                 DEBUGLEVEL = oldlevel;
303                 DEBUG(0,("===============================================================\n"));
304 #if DUMP_CORE
305                 if (dump_core()) return;
306 #endif
307         }    
308
309         locking_end();
310
311         DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
312 #ifdef MEM_MAN
313         {
314                 extern FILE *dbf;
315                 smb_mem_write_verbose(dbf);
316                 dbgflush();
317         }
318 #endif
319         exit(0);
320 }
321
322
323
324 /****************************************************************************
325   initialise connect, service and file structs
326 ****************************************************************************/
327 static void init_structs(void)
328 {
329 #if 0
330         conn_init();
331 #endif
332         init_rpc_pipe_hnd(); /* for RPC pipes */
333         if (!init_policy_hnd(MAX_SERVER_POLICY_HANDLES)) 
334         {
335                 exit_server("could not allocate policy handles\n");
336         }
337 }
338
339 /****************************************************************************
340 usage on the program
341 ****************************************************************************/
342 static void usage(char *pname)
343 {
344         DEBUG(0,("Incorrect program usage - are you sure the command line is correct?\n"));
345
346         printf("Usage: %s [-D] [-p port] [-d debuglevel] ", pname);
347         printf("[-l log basename] [-s services file]\n" );
348         printf("Version %s\n",VERSION);
349         printf("\t-D                    become a daemon\n");
350         printf("\t-p port               listen on the specified port\n");
351         printf("\t-d debuglevel         set the debuglevel\n");
352         printf("\t-l log basename.      Basename for log/debug files\n");
353         printf("\t-s services file.     Filename of services file\n");
354         printf("\t-P                    passive only\n");
355         printf("\t-a                    append to log file (default)\n");
356         printf("\t-o                    overwrite log file, don't append\n");
357         printf("\t-i scope              NetBIOS scope to use (default none)\n");
358         printf("\n");
359 }
360
361
362 /****************************************************************************
363   main program
364 ****************************************************************************/
365 int msrpc_main(int argc,char *argv[])
366 {
367         extern BOOL append_log;
368         /* shall I run as a daemon */
369         BOOL is_daemon = False;
370         int opt;
371         extern char *optarg;
372         int ClientMSRPC = -1;
373         pipes_struct static_pipe;
374         
375         pstrcpy(remote_machine, pipe_name);
376
377         charset_initialise();
378
379         /* make absolutely sure we run as root - to handle cases where people
380            are crazy enough to have it setuid */
381 #ifdef HAVE_SETRESUID
382         setresuid(0,0,0);
383 #else
384         setuid(0);
385         seteuid(0);
386         setuid(0);
387         seteuid(0);
388 #endif
389
390         fault_setup((void (*)(void *))exit_server);
391         CatchSignal(SIGTERM , SIGNAL_CAST dflt_sig);
392
393         /* we are never interested in SIGPIPE */
394         BlockSignals(True,SIGPIPE);
395
396         /* we want total control over the permissions on created files,
397            so set our umask to 0 */
398         umask(0);
399
400         dos_GetWd(OriginalDir);
401
402         init_uid();
403
404         /* this is for people who can't start the program correctly */
405         while (argc > 1 && (*argv[1] != '-')) {
406                 argv++;
407                 argc--;
408         }
409
410         while ( EOF != (opt = getopt(argc, argv, "i:l:s:d:Dh?Paof:")) )
411                 switch (opt)  {
412                 case 'i':
413                         pstrcpy(scope,optarg);
414                         break;
415
416                 case 'P':
417                         {
418                                 extern BOOL passive;
419                                 passive = True;
420                         }
421                         break;  
422
423                 case 's':
424                         pstrcpy(servicesf,optarg);
425                         break;
426
427                 case 'l':
428                         pstrcpy(debugf,optarg);
429                         break;
430
431                 case 'a':
432                         append_log = True;
433                         break;
434
435                 case 'o':
436                         append_log = False;
437                         break;
438
439                 case 'D':
440                         is_daemon = True;
441                         break;
442
443                 case 'd':
444                         if (*optarg == 'A')
445                                 DEBUGLEVEL = 10000;
446                         else
447                                 DEBUGLEVEL = atoi(optarg);
448                         break;
449
450                 case 'h':
451                 case '?':
452                         usage(argv[0]);
453                         exit(0);
454                         break;
455
456                 default:
457                         usage(argv[0]);
458                         exit(1);
459                 }
460
461         reopen_logs();
462
463         DEBUG(1,( "%s version %s started.\n", argv[0], VERSION));
464         DEBUGADD(1,( "Copyright Andrew Tridgell 1992-1999\n"));
465
466         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
467                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
468
469         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
470                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
471                 exit(1);
472         }
473
474         get_myname(myhostname,NULL);
475
476         if (!reload_services(False))
477                 return(-1);     
478
479         init_structs();
480
481 #ifdef WITH_PROFILE
482         if (!profile_setup(False)) {
483                 DEBUG(0,("ERROR: failed to setup profiling\n"));
484                 return -1;
485         }
486 #endif
487
488         /*
489          * Set the machine NETBIOS name if not already
490          * set from the config file.
491          */
492         if (!*global_myname)
493         {
494                 fstrcpy(global_myname, dns_to_netbios_name(myhostname));
495         }
496         strupper(global_myname);
497
498         codepage_initialise(lp_client_code_page());
499
500         CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
501         
502         /* Setup the signals that allow the debug log level
503            to by dynamically changed. */
504  
505         /* If we are using the malloc debug code we can't use
506            SIGUSR1 and SIGUSR2 to do debug level changes. */
507         
508 #ifndef MEM_MAN
509 #if defined(SIGUSR1)
510         CatchSignal( SIGUSR1, SIGNAL_CAST sig_usr1 );
511 #endif /* SIGUSR1 */
512    
513 #if defined(SIGUSR2)
514         CatchSignal( SIGUSR2, SIGNAL_CAST sig_usr2 );
515 #endif /* SIGUSR2 */
516 #endif /* MEM_MAN */
517
518         DEBUG(3,( "loaded services\n"));
519
520         if (!is_daemon && !is_a_socket(0)) {
521                 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
522                 is_daemon = True;
523         }
524
525         if (is_daemon) {
526                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
527                 become_daemon();
528         }
529
530         if (!directory_exist(lp_lockdir(), NULL)) {
531                 mkdir(lp_lockdir(), 0755);
532         }
533
534         if (is_daemon) {
535                 pidfile_create(pipe_name);
536         }
537
538         ClientMSRPC = open_sockets(is_daemon);
539         if (ClientMSRPC == -1)
540         {
541                 exit_server("open socket failed");
542         }
543
544         if (!locking_init(0))
545                 exit(1);
546
547         /* possibly reload the services file. */
548         reload_services(True);
549         
550         if (*lp_rootdir()) {
551                 if (sys_chroot(lp_rootdir()) == 0)
552                         DEBUG(2,("Changed root to %s\n", lp_rootdir()));
553         }
554
555         msrpc_service_init();
556
557         ZERO_STRUCT(static_pipe);
558         fstrcpy(static_pipe.name, pipe_name);
559         if (msrpcd_init(ClientMSRPC, &static_pipe))
560         {
561                 reload_services(False);
562                 msrpcd_process(ClientMSRPC, &static_pipe);
563         }
564         if (ClientMSRPC != -1)
565         {
566                 close(ClientMSRPC);
567         }
568         
569         exit_server("normal exit");
570         return(0);
571 }