]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/ngircd.c
startup: fork only once, never run with uid 0.
[ngircd-alex.git] / src / ngircd / ngircd.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2005 by Alexander Barton (alex@barton.de)
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  * Please read the file COPYING, README and AUTHORS for more information.
10  */
11
12
13 #include "portab.h"
14
15 static char UNUSED id[] = "$Id: ngircd.c,v 1.97 2005/06/17 18:22:45 fw Exp $";
16
17 /**
18  * @file
19  * The main program, including the C function main() which is called
20  * by the loader of the operating system.
21  */
22
23 #include "imp.h"
24 #include <assert.h>
25 #include <errno.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <signal.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <time.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/wait.h>
35 #include <fcntl.h>
36 #include <pwd.h>
37 #include <grp.h>
38
39 #include "defines.h"
40 #include "resolve.h"
41 #include "conn.h"
42 #include "client.h"
43 #include "channel.h"
44 #include "conf.h"
45 #include "cvs-version.h"
46 #include "lists.h"
47 #include "log.h"
48 #include "parse.h"
49 #include "irc.h"
50
51 #ifdef RENDEZVOUS
52 #include "rendezvous.h"
53 #endif
54
55 #include "exp.h"
56 #include "ngircd.h"
57
58
59 LOCAL void Initialize_Signal_Handler PARAMS(( void ));
60 LOCAL void Signal_Handler PARAMS(( int Signal ));
61
62 LOCAL void Show_Version PARAMS(( void ));
63 LOCAL void Show_Help PARAMS(( void ));
64
65 LOCAL void Pidfile_Create PARAMS(( long ));
66 LOCAL void Pidfile_Delete PARAMS(( void ));
67
68 LOCAL void Fill_Version PARAMS(( void ));
69
70 LOCAL void Setup_FDStreams PARAMS(( void ));
71
72 LOCAL bool NGIRCd_Init PARAMS(( bool ));
73
74 /**
75  * The main() function of ngIRCd.
76  * Here all starts: this function is called by the operating system loader,
77  * it is the first portion of code executed of ngIRCd.
78  * @param argc The number of arguments passed to ngIRCd on the command line.
79  * @param argv An array containing all the arguments passed to ngIRCd.
80  * @return Global exit code of ngIRCd, zero on success.
81  */
82 GLOBAL int
83 main( int argc, const char *argv[] )
84 {
85         bool ok, configtest = false;
86         int i;
87         size_t n;
88
89         umask( 0077 );
90
91         NGIRCd_SignalQuit = NGIRCd_SignalRestart = NGIRCd_SignalRehash = false;
92         NGIRCd_NoDaemon = NGIRCd_Passive = false;
93 #ifdef DEBUG
94         NGIRCd_Debug = false;
95 #endif
96 #ifdef SNIFFER
97         NGIRCd_Sniffer = false;
98 #endif
99         strlcpy( NGIRCd_ConfFile, SYSCONFDIR, sizeof( NGIRCd_ConfFile ));
100         strlcat( NGIRCd_ConfFile, CONFIG_FILE, sizeof( NGIRCd_ConfFile ));
101
102         Fill_Version( );
103
104         /* Kommandozeile parsen */
105         for( i = 1; i < argc; i++ )
106         {
107                 ok = false;
108                 if(( argv[i][0] == '-' ) && ( argv[i][1] == '-' ))
109                 {
110                         /* Lange Option */
111
112                         if( strcmp( argv[i], "--config" ) == 0 )
113                         {
114                                 if( i + 1 < argc )
115                                 {
116                                         /* Ok, there's an parameter left */
117                                         strlcpy( NGIRCd_ConfFile, argv[i + 1], sizeof( NGIRCd_ConfFile ));
118
119                                         /* next parameter */
120                                         i++; ok = true;
121                                 }
122                         }
123                         if( strcmp( argv[i], "--configtest" ) == 0 )
124                         {
125                                 configtest = true;
126                                 ok = true;
127                         }
128 #ifdef DEBUG
129                         if( strcmp( argv[i], "--debug" ) == 0 )
130                         {
131                                 NGIRCd_Debug = true;
132                                 ok = true;
133                         }
134 #endif
135                         if( strcmp( argv[i], "--help" ) == 0 )
136                         {
137                                 Show_Version( );
138                                 puts( "" ); Show_Help( ); puts( "" );
139                                 exit( 1 );
140                         }
141                         if( strcmp( argv[i], "--nodaemon" ) == 0 )
142                         {
143                                 NGIRCd_NoDaemon = true;
144                                 ok = true;
145                         }
146                         if( strcmp( argv[i], "--passive" ) == 0 )
147                         {
148                                 NGIRCd_Passive = true;
149                                 ok = true;
150                         }
151 #ifdef SNIFFER
152                         if( strcmp( argv[i], "--sniffer" ) == 0 )
153                         {
154                                 NGIRCd_Sniffer = true;
155                                 ok = true;
156                         }
157 #endif
158                         if( strcmp( argv[i], "--version" ) == 0 )
159                         {
160                                 Show_Version( );
161                                 exit( 1 );
162                         }
163                 }
164                 else if(( argv[i][0] == '-' ) && ( argv[i][1] != '-' ))
165                 {
166                         /* Kurze Option */
167                         for( n = 1; n < strlen( argv[i] ); n++ )
168                         {
169                                 ok = false;
170 #ifdef DEBUG
171                                 if( argv[i][n] == 'd' )
172                                 {
173                                         NGIRCd_Debug = true;
174                                         ok = true;
175                                 }
176 #endif
177                                 if( argv[i][n] == 'f' )
178                                 {
179                                         if(( ! argv[i][n + 1] ) && ( i + 1 < argc ))
180                                         {
181                                                 /* Ok, next character is a blank */
182                                                 strlcpy( NGIRCd_ConfFile, argv[i + 1], sizeof( NGIRCd_ConfFile ));
183
184                                                 /* go to the following parameter */
185                                                 i++;
186                                                 n = strlen( argv[i] );
187                                                 ok = true;
188                                         }
189                                 }
190                                 if( argv[i][n] == 'n' )
191                                 {
192                                         NGIRCd_NoDaemon = true;
193                                         ok = true;
194                                 }
195                                 if( argv[i][n] == 'p' )
196                                 {
197                                         NGIRCd_Passive = true;
198                                         ok = true;
199                                 }
200 #ifdef SNIFFER
201                                 if( argv[i][n] == 's' )
202                                 {
203                                         NGIRCd_Sniffer = true;
204                                         ok = true;
205                                 }
206 #endif
207                                 if( argv[i][n] == 't' )
208                                 {
209                                         configtest = true;
210                                         ok = true;
211                                 }
212
213                                 if( ! ok )
214                                 {
215                                         printf( "%s: invalid option \"-%c\"!\n", PACKAGE_NAME, argv[i][n] );
216                                         printf( "Try \"%s --help\" for more information.\n", PACKAGE_NAME );
217                                         exit( 1 );
218                                 }
219                         }
220
221                 }
222                 if( ! ok )
223                 {
224                         printf( "%s: invalid option \"%s\"!\n", PACKAGE_NAME, argv[i] );
225                         printf( "Try \"%s --help\" for more information.\n", PACKAGE_NAME );
226                         exit( 1 );
227                 }
228         }
229
230         /* Debug-Level (fuer IRC-Befehl "VERSION") ermitteln */
231         NGIRCd_DebugLevel[0] = '\0';
232 #ifdef DEBUG
233         if( NGIRCd_Debug ) strcpy( NGIRCd_DebugLevel, "1" );
234 #endif
235 #ifdef SNIFFER
236         if( NGIRCd_Sniffer )
237         {
238                 NGIRCd_Debug = true;
239                 strcpy( NGIRCd_DebugLevel, "2" );
240         }
241 #endif
242
243         /* Soll nur die Konfigurations ueberprueft und ausgegeben werden? */
244         if( configtest )
245         {
246                 Show_Version( ); puts( "" );
247                 exit( Conf_Test( ));
248         }
249         
250         while( ! NGIRCd_SignalQuit )
251         {
252                 /* Initialize global variables */
253                 NGIRCd_Start = time( NULL );
254                 (void)strftime( NGIRCd_StartStr, 64, "%a %b %d %Y at %H:%M:%S (%Z)", localtime( &NGIRCd_Start ));
255
256                 NGIRCd_SignalRehash = false;
257                 NGIRCd_SignalRestart = false;
258                 NGIRCd_SignalQuit = false;
259
260                 /* Initialize modules, part I */
261                 Log_Init( );
262                 Conf_Init( );
263
264                 if (!NGIRCd_Init( NGIRCd_NoDaemon )) {
265                         Log(LOG_WARNING, "Fatal: Initialization failed");
266                         exit(1);
267                 }
268
269                 /* Initialize modules, part II: these functions are eventually
270                  * called with already dropped privileges ... */
271                 Resolve_Init( );
272                 Lists_Init( );
273                 Channel_Init( );
274                 Client_Init( );
275 #ifdef RENDEZVOUS
276                 Rendezvous_Init( );
277 #endif
278                 Conn_Init( );
279
280 #ifdef DEBUG
281                 /* Redirect stderr handle to "error file" for debugging
282                  * when not running in "no daemon" mode: */
283                 if( ! NGIRCd_NoDaemon ) Log_InitErrorfile( );
284 #endif
285
286                 /* Signal-Handler initialisieren */
287                 Initialize_Signal_Handler( );
288
289                 /* Protokoll- und Server-Identifikation erzeugen. Die vom ngIRCd
290                  * beim PASS-Befehl verwendete Syntax sowie die erweiterten Flags
291                  * sind in doc/Protocol.txt beschrieben. */
292 #ifdef IRCPLUS
293                 snprintf( NGIRCd_ProtoID, sizeof NGIRCd_ProtoID, "%s%s %s|%s:%s", PROTOVER, PROTOIRCPLUS, PACKAGE_NAME, PACKAGE_VERSION, IRCPLUSFLAGS );
294 #ifdef ZLIB
295                 strcat( NGIRCd_ProtoID, "Z" );
296 #endif
297                 if( Conf_OperCanMode ) strcat( NGIRCd_ProtoID, "o" );
298 #else
299                 snprintf( NGIRCd_ProtoID, sizeof NGIRCd_ProtoID, "%s%s %s|%s", PROTOVER, PROTOIRC, PACKAGE_NAME, PACKAGE_VERSION );
300 #endif
301                 strlcat( NGIRCd_ProtoID, " P", sizeof NGIRCd_ProtoID );
302 #ifdef ZLIB
303                 strlcat( NGIRCd_ProtoID, "Z", sizeof NGIRCd_ProtoID );
304 #endif
305                 Log( LOG_DEBUG, "Protocol and server ID is \"%s\".", NGIRCd_ProtoID );
306
307                 /* Vordefinierte Channels anlegen */
308                 Channel_InitPredefined( );
309
310                 /* Listen-Ports initialisieren */
311                 if( Conn_InitListeners( ) < 1 )
312                 {
313                         Log( LOG_ALERT, "Server isn't listening on a single port!" );
314                         Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
315                         Pidfile_Delete( );
316                         exit( 1 );
317                 }
318                 
319                 /* Hauptschleife */
320                 Conn_Handler( );
321
322                 /* Alles abmelden */
323                 Conn_Exit( );
324 #ifdef RENDEZVOUS
325                 Rendezvous_Exit( );
326 #endif
327                 Client_Exit( );
328                 Channel_Exit( );
329                 Lists_Exit( );
330                 Log_Exit( );
331         }
332         Pidfile_Delete( );
333
334         return 0;
335 } /* main */
336
337
338 /**
339  * Generate ngIRCd "version string".
340  * This string is generated once and then stored in NGIRCd_Version for
341  * further usage, for example by the IRC command VERSION and the --version
342  * command line switch.
343  */
344 LOCAL void
345 Fill_Version( void )
346 {
347         NGIRCd_VersionAddition[0] = '\0';
348
349 #ifdef SYSLOG
350         strlcpy( NGIRCd_VersionAddition, "SYSLOG", sizeof NGIRCd_VersionAddition );
351 #endif
352 #ifdef ZLIB
353         if( NGIRCd_VersionAddition[0] )
354                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
355
356         strlcat( NGIRCd_VersionAddition, "ZLIB", sizeof NGIRCd_VersionAddition );
357 #endif
358 #ifdef TCPWRAP
359         if( NGIRCd_VersionAddition[0] )
360                         strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
361
362         strlcat( NGIRCd_VersionAddition, "TCPWRAP", sizeof NGIRCd_VersionAddition );
363 #endif
364 #ifdef RENDEZVOUS
365         if( NGIRCd_VersionAddition[0] )
366                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
367
368         strlcat( NGIRCd_VersionAddition, "RENDEZVOUS", sizeof NGIRCd_VersionAddition );
369 #endif
370 #ifdef IDENTAUTH
371         if( NGIRCd_VersionAddition[0] )
372                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
373
374         strlcat( NGIRCd_VersionAddition, "IDENT", sizeof NGIRCd_VersionAddition );
375 #endif
376 #ifdef DEBUG
377         if( NGIRCd_VersionAddition[0] )
378                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
379
380         strlcat( NGIRCd_VersionAddition, "DEBUG", sizeof NGIRCd_VersionAddition );
381 #endif
382 #ifdef SNIFFER
383         if( NGIRCd_VersionAddition[0] )
384                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
385
386         strlcat( NGIRCd_VersionAddition, "SNIFFER", sizeof NGIRCd_VersionAddition );
387 #endif
388 #ifdef STRICT_RFC
389         if( NGIRCd_VersionAddition[0] )
390                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
391
392         strlcat( NGIRCd_VersionAddition, "RFC", sizeof NGIRCd_VersionAddition );
393 #endif
394 #ifdef IRCPLUS
395         if( NGIRCd_VersionAddition[0] )
396                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
397
398         strlcat( NGIRCd_VersionAddition, "IRCPLUS", sizeof NGIRCd_VersionAddition );
399 #endif
400
401         if( NGIRCd_VersionAddition[0] )
402                 strlcat( NGIRCd_VersionAddition, "-", sizeof( NGIRCd_VersionAddition ));
403
404         strlcat( NGIRCd_VersionAddition, TARGET_CPU, sizeof( NGIRCd_VersionAddition ));
405         strlcat( NGIRCd_VersionAddition, "/", sizeof( NGIRCd_VersionAddition ));
406         strlcat( NGIRCd_VersionAddition, TARGET_VENDOR, sizeof( NGIRCd_VersionAddition ));
407         strlcat( NGIRCd_VersionAddition, "/", sizeof( NGIRCd_VersionAddition ));
408         strlcat( NGIRCd_VersionAddition, TARGET_OS, sizeof( NGIRCd_VersionAddition ));
409
410 #ifdef CVSDATE
411         snprintf( NGIRCd_Version, sizeof NGIRCd_Version,"%s %s(%s)-%s", PACKAGE_NAME, PACKAGE_VERSION, CVSDATE, NGIRCd_VersionAddition);
412 #else
413         snprintf( NGIRCd_Version, sizeof NGIRCd_Version, "%s %s-%s", PACKAGE_NAME, PACKAGE_VERSION, NGIRCd_VersionAddition);
414 #endif
415 } /* Fill_Version */
416
417
418 /**
419  * Reload the server configuration file.
420  */
421 GLOBAL void
422 NGIRCd_Rehash( void )
423 {
424         char old_name[CLIENT_ID_LEN];
425
426         Log( LOG_NOTICE|LOG_snotice, "Re-reading configuration NOW!" );
427         NGIRCd_SignalRehash = false;
428
429         /* Close down all listening sockets */
430         Conn_ExitListeners( );
431
432         /* Remember old server name */
433         strlcpy( old_name, Conf_ServerName, sizeof old_name );
434
435         /* Re-read configuration ... */
436         Conf_Rehash( );
437
438         /* Recover old server name: it can't be changed during run-time */
439         if( strcmp( old_name, Conf_ServerName ) != 0 )
440         {
441                 strcpy( Conf_ServerName, old_name );
442                 Log( LOG_ERR, "Can't change \"ServerName\" on runtime! Ignored new name." );
443         }
444
445         /* Create new pre-defined channels */
446         Channel_InitPredefined( );
447         
448         /* Start listening on sockets */
449         Conn_InitListeners( );
450
451         /* Sync configuration with established connections */
452         Conn_SyncServerStruct( );
453
454         Log( LOG_NOTICE|LOG_snotice, "Re-reading of configuration done." );
455 } /* NGIRCd_Rehash */
456
457
458 /**
459  * Initialize the signal handler.
460  */
461 LOCAL void
462 Initialize_Signal_Handler( void )
463 {
464         /* Signal-Handler initialisieren: einige Signale
465          * werden ignoriert, andere speziell behandelt. */
466
467 #ifdef HAVE_SIGACTION
468         /* sigaction() ist vorhanden */
469
470         struct sigaction saction;
471
472         /* Signal-Struktur initialisieren */
473         memset( &saction, 0, sizeof( saction ));
474         saction.sa_handler = Signal_Handler;
475 #ifdef SA_RESTART
476         saction.sa_flags |= SA_RESTART;
477 #endif
478 #ifdef SA_NOCLDWAIT
479         saction.sa_flags |= SA_NOCLDWAIT;
480 #endif
481
482         /* Signal-Handler einhaengen */
483         sigaction( SIGINT, &saction, NULL );
484         sigaction( SIGQUIT, &saction, NULL );
485         sigaction( SIGTERM, &saction, NULL);
486         sigaction( SIGHUP, &saction, NULL);
487         sigaction( SIGCHLD, &saction, NULL);
488
489         /* einige Signale ignorieren */
490         saction.sa_handler = SIG_IGN;
491         sigaction( SIGPIPE, &saction, NULL );
492 #else
493         /* kein sigaction() vorhanden */
494
495         /* Signal-Handler einhaengen */
496         signal( SIGINT, Signal_Handler );
497         signal( SIGQUIT, Signal_Handler );
498         signal( SIGTERM, Signal_Handler );
499         signal( SIGHUP, Signal_Handler );
500         signal( SIGCHLD, Signal_Handler );
501
502         /* einige Signale ignorieren */
503         signal( SIGPIPE, SIG_IGN );
504 #endif
505 } /* Initialize_Signal_Handler */
506
507
508 /**
509  * Signal handler of ngIRCd.
510  * This function is called whenever ngIRCd catches a signal sent by the
511  * user and/or the system to it. For example SIGTERM and SIGHUP.
512  * @param Signal Number of the signal to handle.
513  */
514 LOCAL void
515 Signal_Handler( int Signal )
516 {
517         switch( Signal )
518         {
519                 case SIGTERM:
520                 case SIGINT:
521                 case SIGQUIT:
522                         /* wir soll(t)en uns wohl beenden ... */
523                         NGIRCd_SignalQuit = true;
524                         break;
525                 case SIGHUP:
526                         /* Konfiguration neu einlesen: */
527                         NGIRCd_SignalRehash = true;
528                         break;
529                 case SIGCHLD:
530                         /* Child-Prozess wurde beendet. Zombies vermeiden: */
531                         while( waitpid( -1, NULL, WNOHANG ) > 0);
532                         break;
533 #ifdef DEBUG
534                 default:
535                         /* unbekanntes bzw. unbehandeltes Signal */
536                         Log( LOG_DEBUG, "Got signal %d! Ignored.", Signal );
537 #endif
538         }
539 } /* Signal_Handler */
540
541
542 /**
543  * Display copyright and version information of ngIRCd on the console.
544  */
545 LOCAL void
546 Show_Version( void )
547 {
548         puts( NGIRCd_Version );
549         puts( "Copyright (c)2001-2005 by Alexander Barton (<alex@barton.de>)." );
550         puts( "Homepage: <http://arthur.ath.cx/~alex/ngircd/>\n" );
551         puts( "This is free software; see the source for copying conditions. There is NO" );
552         puts( "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." );
553 } /* Show_Version */
554
555
556 /**
557  * Display a short help text on the console.
558  * This help depends on the configuration of the executable and only shows
559  * options that are actually enabled.
560  */
561 LOCAL void
562 Show_Help( void )
563 {
564 #ifdef DEBUG
565         puts( "  -d, --debug        log extra debug messages" );
566 #endif
567         puts( "  -f, --config <f>   use file <f> as configuration file" );
568         puts( "  -n, --nodaemon     don't fork and don't detach from controlling terminal" );
569         puts( "  -p, --passive      disable automatic connections to other servers" );
570 #ifdef SNIFFER
571         puts( "  -s, --sniffer      enable network sniffer and display all IRC traffic" );
572 #endif
573         puts( "  -t, --configtest   read, validate and display configuration; then exit" );
574         puts( "      --version      output version information and exit" );
575         puts( "      --help         display this help and exit" );
576 } /* Show_Help */
577
578
579 /**
580  * Delete the file containing the process ID (PID).
581  */
582 LOCAL void
583 Pidfile_Delete( void )
584 {
585         /* Pidfile configured? */
586         if( ! Conf_PidFile[0] ) return;
587
588 #ifdef DEBUG
589         Log( LOG_DEBUG, "Removing PID file (%s) ...", Conf_PidFile );
590 #endif
591
592         if( unlink( Conf_PidFile ))
593                 Log( LOG_ERR, "Error unlinking PID file (%s): %s", Conf_PidFile, strerror( errno ));
594 } /* Pidfile_Delete */
595
596
597 /**
598  * Create the file containing the process ID of ngIRCd ("PID file").
599  * @param pid The process ID to be stored in this file.
600  */
601 LOCAL void
602 Pidfile_Create( long pid )
603 {
604         int pidfd;
605         char pidbuf[64];
606         int len;
607
608         /* Pidfile configured? */
609         if( ! Conf_PidFile[0] ) return;
610
611 #ifdef DEBUG
612         Log( LOG_DEBUG, "Creating PID file (%s) ...", Conf_PidFile );
613 #endif
614
615         pidfd = open( Conf_PidFile, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
616         if ( pidfd < 0 ) {
617                 Log( LOG_ERR, "Error writing PID file (%s): %s", Conf_PidFile, strerror( errno ));
618                 return;
619         }
620
621         len = snprintf( pidbuf, sizeof pidbuf, "%ld\n", pid );
622         if (len < 0|| len < (int)sizeof pid) {
623                 Log( LOG_ERR, "Error converting pid");
624                 return;
625         }
626         
627         if( write( pidfd, pidbuf, len) != len)
628                 Log( LOG_ERR, "Can't write PID file (%s): %s", Conf_PidFile, strerror( errno ));
629
630         if( close(pidfd) != 0 )
631                 Log( LOG_ERR, "Error closing PID file (%s): %s", Conf_PidFile, strerror( errno ));
632 } /* Pidfile_Create */
633
634
635 /**
636  * Redirect stdin, stdout and stderr to apropriate file handles.
637  */
638 LOCAL void
639 Setup_FDStreams( void )
640 {
641         int fd;
642
643         /* Test if we can open /dev/null for reading and writing. If not
644          * we are most probably chrooted already and the server has been
645          * restarted. So we simply don't try to redirect stdXXX ... */
646         fd = open( "/dev/null", O_RDWR );
647         if ( fd < 0 ) {
648                 Log(LOG_WARNING, "Could not open /dev/null: %s", strerror(errno));      
649                 return;
650         } 
651
652         fflush(stdout);
653         fflush(stderr);
654
655         /* Create new stdin(0), stdout(1) and stderr(2) descriptors */
656         dup2( fd, 0 ); dup2( fd, 1 ); dup2( fd, 2 );
657
658         /* Close newly opened file descriptor if not stdin/out/err */
659         if( fd > 2 ) close( fd );
660 } /* Setup_FDStreams */
661
662
663 LOCAL bool
664 NGIRCd_getNobodyID(unsigned int *uid, unsigned int *gid )
665 {
666         struct passwd *pwd;
667
668         pwd = getpwnam("nobody");
669         if (!pwd) return false;
670
671         if ( !pwd->pw_uid || !pwd->pw_gid)
672                 return false;
673
674         *uid = pwd->pw_uid;     
675         *gid = pwd->pw_gid;
676         endpwent();
677
678         return true;    
679 }
680
681
682 LOCAL bool
683 NGIRCd_Init( bool NGIRCd_NoDaemon ) 
684 {
685         static bool initialized;
686         bool chrooted = false;
687         struct passwd *pwd;
688         struct group *grp;
689         int real_errno;
690         long pid;
691
692         if (initialized)
693                 return true;
694
695         if( Conf_Chroot[0] ) {
696                 if( chdir( Conf_Chroot ) != 0 ) {
697                         Log( LOG_ERR, "Can't chdir() in ChrootDir (%s): %s", Conf_Chroot, strerror( errno ));
698                         return false;
699                 }
700
701                 if( chroot( Conf_Chroot ) != 0 ) {
702                         if (errno != EPERM) {
703                                 Log( LOG_ERR, "Can't change root directory to \"%s\": %s",
704                                                                 Conf_Chroot, strerror( errno ));
705
706                                 return false;
707                         }
708                 } else {
709                         chrooted = true;
710                         Log( LOG_INFO, "Changed root and working directory to \"%s\".", Conf_Chroot );
711                 }
712         }
713
714         if ( Conf_UID == 0 ) {
715                 Log( LOG_INFO, "Conf_UID must not be 0, switching to user nobody", Conf_UID );
716
717                 if (!NGIRCd_getNobodyID(&Conf_UID, &Conf_GID )) {
718                         Log( LOG_WARNING, "Could not get uid/gid of user nobody: %s",
719                                         errno ? strerror(errno) : "not found" );
720                         return false;
721                 }
722         }
723
724         if( setgid( Conf_GID ) != 0 ) {
725                 real_errno = errno;
726                 Log( LOG_ERR, "Can't change group ID to %u: %s", Conf_GID, strerror( errno ));
727                 if (real_errno != EPERM) 
728                         return false;
729         }
730
731         if( setuid( Conf_UID ) != 0 ) {
732                 real_errno = errno;
733                 Log( LOG_ERR, "Can't change user ID to %u: %s", Conf_UID, strerror( errno ));
734                 if (real_errno != EPERM) 
735                         return false;
736         }
737
738         initialized = true;
739
740         /* Normally a child process is forked which isn't any longer
741          * connected to ther controlling terminal. Use "--nodaemon"
742          * to disable this "daemon mode" (useful for debugging). */
743         if ( ! NGIRCd_NoDaemon ) {
744                 initialized = true;
745                 pid = (long)fork( );
746                 if( pid > 0 ) {
747                         /* "Old" process: exit. */
748                         exit( 0 );
749                 }
750                 if( pid < 0 ) {
751                         /* Error!? */
752                         fprintf( stderr, "%s: Can't fork: %s!\nFatal error, exiting now ...\n",
753                                                                 PACKAGE_NAME, strerror( errno ));
754                         exit( 1 );
755                 }
756
757                 /* New child process */
758                 (void)setsid( );
759                 chdir( "/" );
760
761                 /* Detach stdin, stdout and stderr */
762                 Setup_FDStreams( );
763         }
764         pid = getpid();
765
766         Pidfile_Create( pid );
767
768         /* check uid we are running as, can be different from values configured (e.g. if we were already
769         started with a uid > 0 */
770         Conf_UID = getuid();
771         Conf_GID = getgid();
772
773         assert( Conf_GID > 0);
774         assert( Conf_UID > 0);
775
776         pwd = getpwuid( Conf_UID );
777         grp = getgrgid( Conf_GID );
778         Log( LOG_INFO, "Running as user %s(%ld), group %s(%ld), with PID %ld.",
779                                 pwd ? pwd->pw_name : "unknown", Conf_UID,
780                                 grp ? grp->gr_name : "unknown", Conf_GID, pid);
781
782         if ( chrooted ) {
783                 Log( LOG_INFO, "Running chrooted, chrootdir \"%s\".",  Conf_Chroot );
784                 return true;
785         } else {
786                 Log( LOG_INFO, "Not running chrooted." );
787         }
788
789         /* Change working directory to home directory of the user
790          * we are running as (when not running chroot()'ed!) */
791         
792         if ( pwd ) {
793                 if( chdir( pwd->pw_dir ) == 0 ) 
794                         Log( LOG_DEBUG, "Changed working directory to \"%s\" ...", pwd->pw_dir );
795                 else 
796                         Log( LOG_ERR, "Can't change working directory to \"%s\": %s",
797                                                         pwd->pw_dir, strerror( errno ));
798         } else {
799                 Log( LOG_ERR, "Can't get user informaton for UID %d!?", Conf_UID );
800         }
801
802 return true;
803 }
804
805 /* -eof- */