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