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