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