]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/ngircd.c
Add new 'delayed' signal handlers.
[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 <fcntl.h>
33 #include <pwd.h>
34 #include <grp.h>
35
36 #if defined(DEBUG) && defined(HAVE_MTRACE)
37 #include <mcheck.h>
38 #endif
39
40 #include "defines.h"
41 #include "conn.h"
42 #include "conf-ssl.h"
43 #include "channel.h"
44 #include "conf.h"
45 #include "lists.h"
46 #include "log.h"
47 #include "parse.h"
48 #include "sighandlers.h"
49 #include "io.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 Show_Version PARAMS(( void ));
61 static void Show_Help PARAMS(( void ));
62
63 static void Pidfile_Create PARAMS(( pid_t pid ));
64 static void Pidfile_Delete PARAMS(( void ));
65
66 static void Fill_Version PARAMS(( void ));
67
68 static void Setup_FDStreams PARAMS(( int fd ));
69
70 static bool NGIRCd_Init PARAMS(( bool ));
71
72 /**
73  * The main() function of ngIRCd.
74  * Here all starts: this function is called by the operating system loader,
75  * it is the first portion of code executed of ngIRCd.
76  * @param argc The number of arguments passed to ngIRCd on the command line.
77  * @param argv An array containing all the arguments passed to ngIRCd.
78  * @return Global exit code of ngIRCd, zero on success.
79  */
80 GLOBAL int
81 main( int argc, const char *argv[] )
82 {
83         bool ok, configtest = false;
84         bool NGIRCd_NoDaemon = false;
85         int i;
86         size_t n;
87
88 #if defined(DEBUG) && defined(HAVE_MTRACE)
89         /* enable GNU libc memory tracing when running in debug mode
90          * and functionality available */
91         mtrace();
92 #endif
93
94         umask( 0077 );
95
96         NGIRCd_SignalQuit = NGIRCd_SignalRestart = NGIRCd_SignalRehash = false;
97         NGIRCd_Passive = false;
98 #ifdef DEBUG
99         NGIRCd_Debug = false;
100 #endif
101 #ifdef SNIFFER
102         NGIRCd_Sniffer = false;
103 #endif
104         strlcpy( NGIRCd_ConfFile, SYSCONFDIR, sizeof( NGIRCd_ConfFile ));
105         strlcat( NGIRCd_ConfFile, CONFIG_FILE, sizeof( NGIRCd_ConfFile ));
106
107         Fill_Version( );
108
109         /* parse conmmand line */
110         for( i = 1; i < argc; i++ )
111         {
112                 ok = false;
113                 if(( argv[i][0] == '-' ) && ( argv[i][1] == '-' ))
114                 {
115                         /* long option */
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                         /* short 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 (for IRCs "VERSION" command) */
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         if( configtest )
253         {
254                 Show_Version( ); puts( "" );
255                 exit( Conf_Test( ));
256         }
257         
258         while( ! NGIRCd_SignalQuit )
259         {
260                 /* Initialize global variables */
261                 NGIRCd_Start = time( NULL );
262                 (void)strftime( NGIRCd_StartStr, 64, "%a %b %d %Y at %H:%M:%S (%Z)", localtime( &NGIRCd_Start ));
263
264                 NGIRCd_SignalRehash = false;
265                 NGIRCd_SignalRestart = false;
266                 NGIRCd_SignalQuit = false;
267
268                 /* Initialize modules, part I */
269                 Log_Init( ! NGIRCd_NoDaemon );
270                 Conf_Init( );
271
272                 /* Initialize the "main program": chroot environment, user and
273                  * group ID, ... */
274                 if (!NGIRCd_Init(NGIRCd_NoDaemon)) {
275                         Log(LOG_ALERT, "Fatal: Initialization failed");
276                         exit(1);
277                 }
278
279                 /* Initialize modules, part II: these functions are eventually
280                  * called with already dropped privileges ... */
281                 Channel_Init( );
282                 Client_Init( );
283 #ifdef ZEROCONF
284                 Rendezvous_Init( );
285 #endif
286                 Conn_Init( );
287
288 #ifdef DEBUG
289                 /* Redirect stderr handle to "error file" for debugging
290                  * when not running in "no daemon" mode: */
291                 if( ! NGIRCd_NoDaemon ) Log_InitErrorfile( );
292 #endif
293                 if (!io_library_init(CONNECTION_POOL)) {
294                         Log(LOG_ALERT, "Fatal: Cannot initialize IO routines: %s", strerror(errno));
295                         exit(1);
296                 }
297
298                 if (!Signals_Init()) {
299                         Log(LOG_ALERT, "Fatal: Could not set up signal handlers: %s", strerror(errno));
300                         exit(1);
301                 }
302
303                 /*
304                  * create protocol and server identification.
305                  * The syntax used by ngIRCd in PASS commands and the extended flags
306                  * are described in doc/Protocol.txt
307                  */
308 #ifdef IRCPLUS
309                 snprintf( NGIRCd_ProtoID, sizeof NGIRCd_ProtoID, "%s%s %s|%s:%s", PROTOVER, PROTOIRCPLUS, PACKAGE_NAME, PACKAGE_VERSION, IRCPLUSFLAGS );
310 #ifdef ZLIB
311                 strcat( NGIRCd_ProtoID, "Z" );
312 #endif
313                 if( Conf_OperCanMode ) strcat( NGIRCd_ProtoID, "o" );
314 #else
315                 snprintf( NGIRCd_ProtoID, sizeof NGIRCd_ProtoID, "%s%s %s|%s", PROTOVER, PROTOIRC, PACKAGE_NAME, PACKAGE_VERSION );
316 #endif
317                 strlcat( NGIRCd_ProtoID, " P", sizeof NGIRCd_ProtoID );
318 #ifdef ZLIB
319                 strlcat( NGIRCd_ProtoID, "Z", sizeof NGIRCd_ProtoID );
320 #endif
321                 LogDebug("Protocol and server ID is \"%s\".", NGIRCd_ProtoID);
322
323                 Channel_InitPredefined( );
324
325                 if( Conn_InitListeners( ) < 1 )
326                 {
327                         Log( LOG_ALERT, "Server isn't listening on a single port!" );
328                         Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
329                         Pidfile_Delete( );
330                         exit( 1 );
331                 }
332                 
333                 /* Hauptschleife */
334                 Conn_Handler( );
335
336                 /* Alles abmelden */
337                 Conn_Exit( );
338 #ifdef ZEROCONF
339                 Rendezvous_Exit( );
340 #endif
341                 Client_Exit( );
342                 Channel_Exit( );
343                 Log_Exit( );
344         }
345         Pidfile_Delete( );
346
347         return 0;
348 } /* main */
349
350
351 /**
352  * Generate ngIRCd "version string".
353  * This string is generated once and then stored in NGIRCd_Version for
354  * further usage, for example by the IRC command VERSION and the --version
355  * command line switch.
356  */
357 static void
358 Fill_Version( void )
359 {
360         NGIRCd_VersionAddition[0] = '\0';
361
362 #ifdef SYSLOG
363         strlcpy( NGIRCd_VersionAddition, "SYSLOG", sizeof NGIRCd_VersionAddition );
364 #endif
365 #ifdef ZLIB
366         if( NGIRCd_VersionAddition[0] )
367                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
368         strlcat( NGIRCd_VersionAddition, "ZLIB", sizeof NGIRCd_VersionAddition );
369 #endif
370 #ifdef SSL_SUPPORT
371         if ( NGIRCd_VersionAddition[0] ) strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
372         strlcat( NGIRCd_VersionAddition, "SSL", sizeof NGIRCd_VersionAddition );
373 #endif
374 #ifdef TCPWRAP
375         if( NGIRCd_VersionAddition[0] )
376                         strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
377         strlcat( NGIRCd_VersionAddition, "TCPWRAP", sizeof NGIRCd_VersionAddition );
378 #endif
379 #ifdef ZEROCONF
380         if( NGIRCd_VersionAddition[0] )
381                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
382         strlcat( NGIRCd_VersionAddition, "ZEROCONF", sizeof NGIRCd_VersionAddition );
383 #endif
384 #ifdef IDENTAUTH
385         if( NGIRCd_VersionAddition[0] )
386                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
387         strlcat( NGIRCd_VersionAddition, "IDENT", sizeof NGIRCd_VersionAddition );
388 #endif
389 #ifdef PAM
390         if (NGIRCd_VersionAddition[0])
391                 strlcat(NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition);
392         strlcat(NGIRCd_VersionAddition, "PAM", sizeof NGIRCd_VersionAddition);
393 #endif
394 #ifdef DEBUG
395         if( NGIRCd_VersionAddition[0] )
396                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
397         strlcat( NGIRCd_VersionAddition, "DEBUG", sizeof NGIRCd_VersionAddition );
398 #endif
399 #ifdef SNIFFER
400         if( NGIRCd_VersionAddition[0] )
401                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
402         strlcat( NGIRCd_VersionAddition, "SNIFFER", sizeof NGIRCd_VersionAddition );
403 #endif
404 #ifdef STRICT_RFC
405         if( NGIRCd_VersionAddition[0] )
406                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
407         strlcat( NGIRCd_VersionAddition, "RFC", sizeof NGIRCd_VersionAddition );
408 #endif
409 #ifdef IRCPLUS
410         if( NGIRCd_VersionAddition[0] )
411                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
412         strlcat( NGIRCd_VersionAddition, "IRCPLUS", sizeof NGIRCd_VersionAddition );
413 #endif
414 #ifdef WANT_IPV6
415         if (NGIRCd_VersionAddition[0])
416                 strlcat(NGIRCd_VersionAddition, "+", sizeof(NGIRCd_VersionAddition));
417         strlcat(NGIRCd_VersionAddition, "IPv6", sizeof(NGIRCd_VersionAddition));
418 #endif
419         if( NGIRCd_VersionAddition[0] )
420                 strlcat( NGIRCd_VersionAddition, "-", sizeof( NGIRCd_VersionAddition ));
421
422         strlcat( NGIRCd_VersionAddition, TARGET_CPU, sizeof( NGIRCd_VersionAddition ));
423         strlcat( NGIRCd_VersionAddition, "/", sizeof( NGIRCd_VersionAddition ));
424         strlcat( NGIRCd_VersionAddition, TARGET_VENDOR, sizeof( NGIRCd_VersionAddition ));
425         strlcat( NGIRCd_VersionAddition, "/", sizeof( NGIRCd_VersionAddition ));
426         strlcat( NGIRCd_VersionAddition, TARGET_OS, sizeof( NGIRCd_VersionAddition ));
427
428         snprintf(NGIRCd_Version, sizeof NGIRCd_Version, "%s %s-%s",
429                  PACKAGE_NAME, PACKAGE_VERSION, NGIRCd_VersionAddition);
430         } /* Fill_Version */
431
432
433 /**
434  * Reload the server configuration file.
435  */
436 GLOBAL void
437 NGIRCd_Rehash( void )
438 {
439         char old_name[CLIENT_ID_LEN];
440         unsigned old_nicklen;
441
442         Log( LOG_NOTICE|LOG_snotice, "Re-reading configuration NOW!" );
443         NGIRCd_SignalRehash = false;
444
445         /* Remember old server name and nick name length */
446         strlcpy( old_name, Conf_ServerName, sizeof old_name );
447         old_nicklen = Conf_MaxNickLength;
448
449         /* Re-read configuration ... */
450         if (!Conf_Rehash( ))
451                 return;
452
453         /* Close down all listening sockets */
454         Conn_ExitListeners( );
455
456         /* Recover old server name and nick name length: these values can't
457          * be changed during run-time */
458         if (strcmp(old_name, Conf_ServerName) != 0 ) {
459                 strlcpy(Conf_ServerName, old_name, sizeof Conf_ServerName);
460                 Log(LOG_ERR, "Can't change \"ServerName\" on runtime! Ignored new name.");
461         }
462         if (old_nicklen != Conf_MaxNickLength) {
463                 Conf_MaxNickLength = old_nicklen;
464                 Log(LOG_ERR, "Can't change \"MaxNickLength\" on runtime! Ignored new value.");
465         }
466
467         /* Create new pre-defined channels */
468         Channel_InitPredefined( );
469
470         if (!ConnSSL_InitLibrary())
471                 Log(LOG_WARNING, "Re-Initializing SSL failed, using old keys");
472
473         /* Start listening on sockets */
474         Conn_InitListeners( );
475
476         /* Sync configuration with established connections */
477         Conn_SyncServerStruct( );
478
479         Log( LOG_NOTICE|LOG_snotice, "Re-reading of configuration done." );
480 } /* NGIRCd_Rehash */
481
482
483 /**
484  * Display copyright and version information of ngIRCd on the console.
485  */
486 static void
487 Show_Version( void )
488 {
489         puts( NGIRCd_Version );
490         puts( "Copyright (c)2001-2010 Alexander Barton (<alex@barton.de>) and Contributors." );
491         puts( "Homepage: <http://ngircd.barton.de/>\n" );
492         puts( "This is free software; see the source for copying conditions. There is NO" );
493         puts( "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." );
494 } /* Show_Version */
495
496
497 /**
498  * Display a short help text on the console.
499  * This help depends on the configuration of the executable and only shows
500  * options that are actually enabled.
501  */
502 static void
503 Show_Help( void )
504 {
505 #ifdef DEBUG
506         puts( "  -d, --debug        log extra debug messages" );
507 #endif
508         puts( "  -f, --config <f>   use file <f> as configuration file" );
509         puts( "  -n, --nodaemon     don't fork and don't detach from controlling terminal" );
510         puts( "  -p, --passive      disable automatic connections to other servers" );
511 #ifdef SNIFFER
512         puts( "  -s, --sniffer      enable network sniffer and display all IRC traffic" );
513 #endif
514         puts( "  -t, --configtest   read, validate and display configuration; then exit" );
515         puts( "  -V, --version      output version information and exit" );
516         puts( "  -h, --help         display this help and exit" );
517 } /* Show_Help */
518
519
520 /**
521  * Delete the file containing the process ID (PID).
522  */
523 static void
524 Pidfile_Delete( void )
525 {
526         /* Pidfile configured? */
527         if( ! Conf_PidFile[0] ) return;
528
529 #ifdef DEBUG
530         Log( LOG_DEBUG, "Removing PID file (%s) ...", Conf_PidFile );
531 #endif
532
533         if( unlink( Conf_PidFile ))
534                 Log( LOG_ERR, "Error unlinking PID file (%s): %s", Conf_PidFile, strerror( errno ));
535 } /* Pidfile_Delete */
536
537
538 /**
539  * Create the file containing the process ID of ngIRCd ("PID file").
540  * @param pid The process ID to be stored in this file.
541  */
542 static void
543 Pidfile_Create(pid_t pid)
544 {
545         int pidfd;
546         char pidbuf[64];
547         int len;
548
549         /* Pidfile configured? */
550         if( ! Conf_PidFile[0] ) return;
551
552 #ifdef DEBUG
553         Log( LOG_DEBUG, "Creating PID file (%s) ...", Conf_PidFile );
554 #endif
555
556         pidfd = open( Conf_PidFile, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
557         if ( pidfd < 0 ) {
558                 Log( LOG_ERR, "Error writing PID file (%s): %s", Conf_PidFile, strerror( errno ));
559                 return;
560         }
561
562         len = snprintf(pidbuf, sizeof pidbuf, "%ld\n", (long)pid);
563         if (len < 0 || len >= (int)sizeof pidbuf) {
564                 Log( LOG_ERR, "Error converting pid");
565                 return;
566         }
567         
568         if (write(pidfd, pidbuf, (size_t)len) != (ssize_t)len)
569                 Log( LOG_ERR, "Can't write PID file (%s): %s", Conf_PidFile, strerror( errno ));
570
571         if( close(pidfd) != 0 )
572                 Log( LOG_ERR, "Error closing PID file (%s): %s", Conf_PidFile, strerror( errno ));
573 } /* Pidfile_Create */
574
575
576 /**
577  * Redirect stdin, stdout and stderr to apropriate file handles.
578  */
579 static void
580 Setup_FDStreams(int fd)
581 {
582         if (fd < 0)
583                 return;
584
585         fflush(stdout);
586         fflush(stderr);
587
588         /* Create new stdin(0), stdout(1) and stderr(2) descriptors */
589         dup2( fd, 0 ); dup2( fd, 1 ); dup2( fd, 2 );
590 } /* Setup_FDStreams */
591
592
593 static bool
594 NGIRCd_getNobodyID(uid_t *uid, gid_t *gid )
595 {
596         struct passwd *pwd;
597
598 #ifdef __CYGWIN__
599         /* Cygwin kludge.
600          * It can return EINVAL instead of EPERM
601          * so, if we are already unprivileged,
602          * use id of current user.
603          */
604         if (geteuid() && getuid()) {
605                 *uid = getuid();
606                 *gid = getgid();
607                 return true;
608         }
609 #endif
610
611         pwd = getpwnam("nobody");
612         if (!pwd) return false;
613
614         if ( !pwd->pw_uid || !pwd->pw_gid)
615                 return false;
616
617         *uid = pwd->pw_uid;     
618         *gid = pwd->pw_gid;
619         endpwent();
620
621         return true;    
622 }
623
624
625 static bool
626 NGIRCd_Init( bool NGIRCd_NoDaemon ) 
627 {
628         static bool initialized;
629         bool chrooted = false;
630         struct passwd *pwd;
631         struct group *grp;
632         int real_errno, fd = -1;
633         pid_t pid;
634
635         if (initialized)
636                 return true;
637
638         if (!NGIRCd_NoDaemon) {
639                 /* open /dev/null before chroot() */
640                 fd = open( "/dev/null", O_RDWR);
641                 if (fd < 0)
642                         Log(LOG_WARNING, "Could not open /dev/null: %s", strerror(errno));
643         }
644
645         if (!ConnSSL_InitLibrary())
646                 Log(LOG_WARNING,
647                     "Warning: Error during SSL initialization, continuing ...");
648
649         if( Conf_Chroot[0] ) {
650                 if( chdir( Conf_Chroot ) != 0 ) {
651                         Log( LOG_ERR, "Can't chdir() in ChrootDir (%s): %s", Conf_Chroot, strerror( errno ));
652                         goto out;
653                 }
654
655                 if( chroot( Conf_Chroot ) != 0 ) {
656                         if (errno != EPERM) {
657                                 Log( LOG_ERR, "Can't change root directory to \"%s\": %s",
658                                                                 Conf_Chroot, strerror( errno ));
659                                 goto out;
660                         }
661                 } else {
662                         chrooted = true;
663                         Log( LOG_INFO, "Changed root and working directory to \"%s\".", Conf_Chroot );
664                 }
665         }
666
667         if (Conf_UID == 0) {
668                 Log(LOG_INFO, "ServerUID must not be 0, using \"nobody\" instead.", Conf_UID);
669
670                 if (! NGIRCd_getNobodyID(&Conf_UID, &Conf_GID)) {
671                         Log(LOG_WARNING, "Could not get user/group ID of user \"nobody\": %s",
672                                         errno ? strerror(errno) : "not found" );
673                         goto out;
674                 }
675         }
676
677         if (getgid() != Conf_GID) {
678                 /* Change group ID */
679                 if (setgid(Conf_GID) != 0) {
680                         real_errno = errno;
681                         Log( LOG_ERR, "Can't change group ID to %u: %s", Conf_GID, strerror( errno ));
682                         if (real_errno != EPERM) 
683                                 goto out;
684                 }
685         }
686
687         if (getuid() != Conf_UID) {
688                 /* Change user ID */
689                 if (setuid(Conf_UID) != 0) {
690                         real_errno = errno;
691                         Log(LOG_ERR, "Can't change user ID to %u: %s", Conf_UID, strerror(errno));
692                         if (real_errno != EPERM) 
693                                 goto out;
694                 }
695         }
696
697         initialized = true;
698
699         /* Normally a child process is forked which isn't any longer
700          * connected to ther controlling terminal. Use "--nodaemon"
701          * to disable this "daemon mode" (useful for debugging). */
702         if ( ! NGIRCd_NoDaemon ) {
703                 pid = fork( );
704                 if( pid > 0 ) {
705                         /* "Old" process: exit. */
706                         exit( 0 );
707                 }
708                 if( pid < 0 ) {
709                         /* Error!? */
710                         fprintf( stderr, "%s: Can't fork: %s!\nFatal error, exiting now ...\n",
711                                                                 PACKAGE_NAME, strerror( errno ));
712                         exit( 1 );
713                 }
714
715                 /* New child process */
716 #ifndef NeXT
717                 (void)setsid( );
718 #else
719                 setpgrp(0, getpid());
720 #endif
721                 if (chdir( "/" ) != 0)
722                         Log(LOG_ERR, "Can't change directory to '/': %s",
723                                      strerror(errno));
724
725                 /* Detach stdin, stdout and stderr */
726                 Setup_FDStreams(fd);
727                 if (fd > 2) {
728                         close(fd);
729                         fd = -1;
730                 }
731         }
732         pid = getpid();
733
734         Pidfile_Create( pid );
735
736         /* Check UID/GID we are running as, can be different from values
737          * configured (e. g. if we were already started with a UID>0. */
738         Conf_UID = getuid();
739         Conf_GID = getgid();
740
741         pwd = getpwuid( Conf_UID );
742         grp = getgrgid( Conf_GID );
743
744         Log(LOG_INFO, "Running as user %s(%ld), group %s(%ld), with PID %ld.",
745                                 pwd ? pwd->pw_name : "unknown", (long)Conf_UID,
746                                 grp ? grp->gr_name : "unknown", (long)Conf_GID, (long)pid);
747
748         if (chrooted) {
749                 Log(LOG_INFO, "Running with root directory \"%s\".",
750                     Conf_Chroot );
751                 return true;
752         } else
753                 Log(LOG_INFO, "Not running with changed root directory.");
754
755         /* Change working directory to home directory of the user
756          * we are running as (only when running in daemon mode and not in chroot) */
757
758         if (pwd) {
759                 if (!NGIRCd_NoDaemon ) {
760                         if( chdir( pwd->pw_dir ) == 0 ) 
761                                 Log( LOG_DEBUG, "Changed working directory to \"%s\" ...", pwd->pw_dir );
762                         else 
763                                 Log( LOG_INFO, "Notice: Can't change working directory to \"%s\": %s",
764                                                                 pwd->pw_dir, strerror( errno ));
765                 }
766         } else {
767                 Log( LOG_ERR, "Can't get user informaton for UID %d!?", Conf_UID );
768         }
769
770         return true;
771  out:
772         if (fd > 2)
773                 close(fd);
774         return false;
775 }
776
777 /* -eof- */