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