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