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