]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/ngircd.c
fix clang warning about dead stores
[ngircd-alex.git] / src / ngircd / ngircd.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2011 Alexander Barton (alex@barton.de) and Contributors.
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 #include "portab.h"
13
14 /**
15  * @file
16  * The main program, including the C function main() which is called
17  * by the loader of the operating system.
18  */
19
20 #include "imp.h"
21 #include <assert.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <signal.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <time.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <fcntl.h>
32 #include <pwd.h>
33 #include <grp.h>
34
35 #if defined(DEBUG) && defined(HAVE_MTRACE)
36 #include <mcheck.h>
37 #endif
38
39 #include "defines.h"
40 #include "conn.h"
41 #include "conf-ssl.h"
42 #include "channel.h"
43 #include "conf.h"
44 #include "lists.h"
45 #include "log.h"
46 #include "parse.h"
47 #include "sighandlers.h"
48 #include "io.h"
49 #include "irc.h"
50
51 #include "exp.h"
52 #include "ngircd.h"
53
54
55 static void Show_Version PARAMS(( void ));
56 static void Show_Help PARAMS(( void ));
57
58 static void Pidfile_Create PARAMS(( pid_t pid ));
59 static void Pidfile_Delete PARAMS(( void ));
60
61 static void Fill_Version PARAMS(( void ));
62
63 static void Random_Init PARAMS(( void ));
64
65 static void Setup_FDStreams PARAMS(( int fd ));
66
67 static bool NGIRCd_Init PARAMS(( bool ));
68
69
70 /**
71  * The main() function of ngIRCd.
72  *
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  *
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 = 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 "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_SignalRestart = false;
265                 NGIRCd_SignalQuit = false;
266
267                 Random_Init();
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                 Conn_Init( );
285
286                 if (!io_library_init(CONNECTION_POOL)) {
287                         Log(LOG_ALERT, "Fatal: Cannot initialize IO routines: %s", strerror(errno));
288                         exit(1);
289                 }
290
291                 if (!Signals_Init()) {
292                         Log(LOG_ALERT, "Fatal: Could not set up signal handlers: %s", strerror(errno));
293                         exit(1);
294                 }
295
296                 /* Create protocol and server identification. The syntax
297                  * used by ngIRCd in PASS commands and the known "extended
298                  * flags" are described in doc/Protocol.txt. */
299 #ifdef IRCPLUS
300                 snprintf( NGIRCd_ProtoID, sizeof NGIRCd_ProtoID, "%s%s %s|%s:%s", PROTOVER, PROTOIRCPLUS, PACKAGE_NAME, PACKAGE_VERSION, IRCPLUSFLAGS );
301 #ifdef ZLIB
302                 strcat( NGIRCd_ProtoID, "Z" );
303 #endif
304                 if( Conf_OperCanMode ) strcat( NGIRCd_ProtoID, "o" );
305 #else
306                 snprintf( NGIRCd_ProtoID, sizeof NGIRCd_ProtoID, "%s%s %s|%s", PROTOVER, PROTOIRC, PACKAGE_NAME, PACKAGE_VERSION );
307 #endif
308                 strlcat( NGIRCd_ProtoID, " P", sizeof NGIRCd_ProtoID );
309 #ifdef ZLIB
310                 strlcat( NGIRCd_ProtoID, "Z", sizeof NGIRCd_ProtoID );
311 #endif
312                 LogDebug("Protocol and server ID is \"%s\".", NGIRCd_ProtoID);
313
314                 Channel_InitPredefined( );
315
316                 if( Conn_InitListeners( ) < 1 )
317                 {
318                         Log( LOG_ALERT, "Server isn't listening on a single port!" );
319                         Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
320                         Pidfile_Delete( );
321                         exit( 1 );
322                 }
323
324                 /* Main Run Loop */
325                 Conn_Handler( );
326
327                 Conn_Exit( );
328                 Client_Exit( );
329                 Channel_Exit( );
330                 Log_Exit( );
331         }
332         Pidfile_Delete( );
333
334         return 0;
335 } /* main */
336
337
338 /**
339  * Generate ngIRCd "version strings".
340  *
341  * The ngIRCd version information is generated once and then stored in the
342  * NGIRCd_Version and NGIRCd_VersionAddition string variables for further
343  * usage, for example by the IRC command "VERSION" and the --version command
344  * line switch.
345  */
346 static void
347 Fill_Version( void )
348 {
349         NGIRCd_VersionAddition[0] = '\0';
350
351 #ifdef SYSLOG
352         strlcpy( NGIRCd_VersionAddition, "SYSLOG", sizeof NGIRCd_VersionAddition );
353 #endif
354 #ifdef ZLIB
355         if( NGIRCd_VersionAddition[0] )
356                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
357         strlcat( NGIRCd_VersionAddition, "ZLIB", sizeof NGIRCd_VersionAddition );
358 #endif
359 #ifdef SSL_SUPPORT
360         if ( NGIRCd_VersionAddition[0] ) strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
361         strlcat( NGIRCd_VersionAddition, "SSL", sizeof NGIRCd_VersionAddition );
362 #endif
363 #ifdef TCPWRAP
364         if( NGIRCd_VersionAddition[0] )
365                         strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
366         strlcat( NGIRCd_VersionAddition, "TCPWRAP", sizeof NGIRCd_VersionAddition );
367 #endif
368 #ifdef IDENTAUTH
369         if( NGIRCd_VersionAddition[0] )
370                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
371         strlcat( NGIRCd_VersionAddition, "IDENT", sizeof NGIRCd_VersionAddition );
372 #endif
373 #ifdef PAM
374         if (NGIRCd_VersionAddition[0])
375                 strlcat(NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition);
376         strlcat(NGIRCd_VersionAddition, "PAM", sizeof NGIRCd_VersionAddition);
377 #endif
378 #ifdef DEBUG
379         if( NGIRCd_VersionAddition[0] )
380                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
381         strlcat( NGIRCd_VersionAddition, "DEBUG", sizeof NGIRCd_VersionAddition );
382 #endif
383 #ifdef SNIFFER
384         if( NGIRCd_VersionAddition[0] )
385                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
386         strlcat( NGIRCd_VersionAddition, "SNIFFER", sizeof NGIRCd_VersionAddition );
387 #endif
388 #ifdef STRICT_RFC
389         if( NGIRCd_VersionAddition[0] )
390                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
391         strlcat( NGIRCd_VersionAddition, "RFC", sizeof NGIRCd_VersionAddition );
392 #endif
393 #ifdef IRCPLUS
394         if( NGIRCd_VersionAddition[0] )
395                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
396         strlcat( NGIRCd_VersionAddition, "IRCPLUS", sizeof NGIRCd_VersionAddition );
397 #endif
398 #ifdef WANT_IPV6
399         if (NGIRCd_VersionAddition[0])
400                 strlcat(NGIRCd_VersionAddition, "+", sizeof(NGIRCd_VersionAddition));
401         strlcat(NGIRCd_VersionAddition, "IPv6", sizeof(NGIRCd_VersionAddition));
402 #endif
403         if( NGIRCd_VersionAddition[0] )
404                 strlcat( NGIRCd_VersionAddition, "-", sizeof( NGIRCd_VersionAddition ));
405
406         strlcat( NGIRCd_VersionAddition, TARGET_CPU, sizeof( NGIRCd_VersionAddition ));
407         strlcat( NGIRCd_VersionAddition, "/", sizeof( NGIRCd_VersionAddition ));
408         strlcat( NGIRCd_VersionAddition, TARGET_VENDOR, sizeof( NGIRCd_VersionAddition ));
409         strlcat( NGIRCd_VersionAddition, "/", sizeof( NGIRCd_VersionAddition ));
410         strlcat( NGIRCd_VersionAddition, TARGET_OS, sizeof( NGIRCd_VersionAddition ));
411
412         snprintf(NGIRCd_Version, sizeof NGIRCd_Version, "%s %s-%s",
413                  PACKAGE_NAME, PACKAGE_VERSION, NGIRCd_VersionAddition);
414 } /* Fill_Version */
415
416
417 /**
418  * Display copyright and version information of ngIRCd on the console.
419  */
420 static void
421 Show_Version( void )
422 {
423         puts( NGIRCd_Version );
424         puts( "Copyright (c)2001-2011 Alexander Barton (<alex@barton.de>) and Contributors." );
425         puts( "Homepage: <http://ngircd.barton.de/>\n" );
426         puts( "This is free software; see the source for copying conditions. There is NO" );
427         puts( "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." );
428 } /* Show_Version */
429
430
431 /**
432  * Display a short help text on the console.
433  * This help depends on the configuration of the executable and only shows
434  * options that are actually enabled.
435  */
436 static void
437 Show_Help( void )
438 {
439 #ifdef DEBUG
440         puts( "  -d, --debug        log extra debug messages" );
441 #endif
442         puts( "  -f, --config <f>   use file <f> as configuration file" );
443         puts( "  -n, --nodaemon     don't fork and don't detach from controlling terminal" );
444         puts( "  -p, --passive      disable automatic connections to other servers" );
445 #ifdef SNIFFER
446         puts( "  -s, --sniffer      enable network sniffer and display all IRC traffic" );
447 #endif
448         puts( "  -t, --configtest   read, validate and display configuration; then exit" );
449         puts( "  -V, --version      output version information and exit" );
450         puts( "  -h, --help         display this help and exit" );
451 } /* Show_Help */
452
453
454 /**
455  * Delete the file containing the process ID (PID).
456  */
457 static void
458 Pidfile_Delete( void )
459 {
460         /* Pidfile configured? */
461         if( ! Conf_PidFile[0] ) return;
462
463 #ifdef DEBUG
464         Log( LOG_DEBUG, "Removing PID file (%s) ...", Conf_PidFile );
465 #endif
466
467         if( unlink( Conf_PidFile ))
468                 Log( LOG_ERR, "Error unlinking PID file (%s): %s", Conf_PidFile, strerror( errno ));
469 } /* Pidfile_Delete */
470
471
472 /**
473  * Create the file containing the process ID of ngIRCd ("PID file").
474  *
475  * @param pid   The process ID to be stored in this file.
476  */
477 static void
478 Pidfile_Create(pid_t pid)
479 {
480         int pidfd;
481         char pidbuf[64];
482         int len;
483
484         /* Pidfile configured? */
485         if( ! Conf_PidFile[0] ) return;
486
487 #ifdef DEBUG
488         Log( LOG_DEBUG, "Creating PID file (%s) ...", Conf_PidFile );
489 #endif
490
491         pidfd = open( Conf_PidFile, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
492         if ( pidfd < 0 ) {
493                 Log( LOG_ERR, "Error writing PID file (%s): %s", Conf_PidFile, strerror( errno ));
494                 return;
495         }
496
497         len = snprintf(pidbuf, sizeof pidbuf, "%ld\n", (long)pid);
498         if (len < 0 || len >= (int)sizeof pidbuf) {
499                 Log( LOG_ERR, "Error converting pid");
500                 return;
501         }
502         
503         if (write(pidfd, pidbuf, (size_t)len) != (ssize_t)len)
504                 Log( LOG_ERR, "Can't write PID file (%s): %s", Conf_PidFile, strerror( errno ));
505
506         if( close(pidfd) != 0 )
507                 Log( LOG_ERR, "Error closing PID file (%s): %s", Conf_PidFile, strerror( errno ));
508 } /* Pidfile_Create */
509
510
511 /**
512  * Redirect stdin, stdout and stderr to apropriate file handles.
513  *
514  * @param fd    The file handle stdin, stdout and stderr should be redirected to.
515  */
516 static void
517 Setup_FDStreams(int fd)
518 {
519         if (fd < 0)
520                 return;
521
522         fflush(stdout);
523         fflush(stderr);
524
525         /* Create new stdin(0), stdout(1) and stderr(2) descriptors */
526         dup2( fd, 0 ); dup2( fd, 1 ); dup2( fd, 2 );
527 } /* Setup_FDStreams */
528
529
530 /**
531  * Get user and group ID of unprivileged "nobody" user.
532  *
533  * @param uid   User ID
534  * @param gid   Group ID
535  * @return      true on success.
536  */
537 static bool
538 NGIRCd_getNobodyID(uid_t *uid, gid_t *gid )
539 {
540         struct passwd *pwd;
541
542 #ifdef __CYGWIN__
543         /* Cygwin kludge.
544          * It can return EINVAL instead of EPERM
545          * so, if we are already unprivileged,
546          * use id of current user.
547          */
548         if (geteuid() && getuid()) {
549                 *uid = getuid();
550                 *gid = getgid();
551                 return true;
552         }
553 #endif
554
555         pwd = getpwnam("nobody");
556         if (!pwd) return false;
557
558         if ( !pwd->pw_uid || !pwd->pw_gid)
559                 return false;
560
561         *uid = pwd->pw_uid;
562         *gid = pwd->pw_gid;
563         endpwent();
564
565         return true;
566 } /* NGIRCd_getNobodyID */
567
568
569 static bool
570 Random_Init_Kern(const char *file)
571 {
572         unsigned int seed;
573         bool ret = false;
574         int fd = open(file, O_RDONLY);
575         if (fd >= 0) {
576                 if (read(fd, &seed, sizeof(seed)) == sizeof(seed))
577                         ret = true;
578                 close(fd);
579                 srandom(seed);
580         }
581         return ret;
582 }
583
584 /**
585  * Initialize libc random(3) number generator
586  */
587 static void
588 Random_Init(void)
589 {
590         if (Random_Init_Kern("/dev/urandom"))
591                 return;
592         if (Random_Init_Kern("/dev/random"))
593                 return;
594         if (Random_Init_Kern("/dev/arandom"))
595                 return;
596         srandom(random() ^ getpid() ^ time(NULL));
597 }
598
599
600 /**
601  * Initialize ngIRCd daemon.
602  *
603  * @param NGIRCd_NoDaemon       Set to true if ngIRCd should run in the
604  *                              foreground and not as a daemon.
605  * @return                      true on success.
606  */
607 static bool
608 NGIRCd_Init( bool NGIRCd_NoDaemon ) 
609 {
610         static bool initialized;
611         bool chrooted = false;
612         struct passwd *pwd;
613         struct group *grp;
614         int real_errno, fd = -1;
615         pid_t pid;
616
617         if (initialized)
618                 return true;
619
620         if (!NGIRCd_NoDaemon) {
621                 /* open /dev/null before chroot() */
622                 fd = open( "/dev/null", O_RDWR);
623                 if (fd < 0)
624                         Log(LOG_WARNING, "Could not open /dev/null: %s", strerror(errno));
625         }
626
627         if (!ConnSSL_InitLibrary())
628                 Log(LOG_WARNING,
629                     "Warning: Error during SSL initialization, continuing ...");
630
631         if( Conf_Chroot[0] ) {
632                 if( chdir( Conf_Chroot ) != 0 ) {
633                         Log( LOG_ERR, "Can't chdir() in ChrootDir (%s): %s", Conf_Chroot, strerror( errno ));
634                         goto out;
635                 }
636
637                 if( chroot( Conf_Chroot ) != 0 ) {
638                         if (errno != EPERM) {
639                                 Log( LOG_ERR, "Can't change root directory to \"%s\": %s",
640                                                                 Conf_Chroot, strerror( errno ));
641                                 goto out;
642                         }
643                 } else {
644                         chrooted = true;
645                         Log( LOG_INFO, "Changed root and working directory to \"%s\".", Conf_Chroot );
646                 }
647         }
648
649         if (Conf_UID == 0) {
650                 Log(LOG_INFO, "ServerUID must not be 0, using \"nobody\" instead.", Conf_UID);
651
652                 if (! NGIRCd_getNobodyID(&Conf_UID, &Conf_GID)) {
653                         Log(LOG_WARNING, "Could not get user/group ID of user \"nobody\": %s",
654                                         errno ? strerror(errno) : "not found" );
655                         goto out;
656                 }
657         }
658
659         if (getgid() != Conf_GID) {
660                 /* Change group ID */
661                 if (setgid(Conf_GID) != 0) {
662                         real_errno = errno;
663                         Log( LOG_ERR, "Can't change group ID to %u: %s", Conf_GID, strerror( errno ));
664                         if (real_errno != EPERM) 
665                                 goto out;
666                 }
667         }
668
669         if (getuid() != Conf_UID) {
670                 /* Change user ID */
671                 if (setuid(Conf_UID) != 0) {
672                         real_errno = errno;
673                         Log(LOG_ERR, "Can't change user ID to %u: %s", Conf_UID, strerror(errno));
674                         if (real_errno != EPERM) 
675                                 goto out;
676                 }
677         }
678
679         initialized = true;
680
681         /* Normally a child process is forked which isn't any longer
682          * connected to ther controlling terminal. Use "--nodaemon"
683          * to disable this "daemon mode" (useful for debugging). */
684         if ( ! NGIRCd_NoDaemon ) {
685                 pid = fork( );
686                 if( pid > 0 ) {
687                         /* "Old" process: exit. */
688                         exit( 0 );
689                 }
690                 if( pid < 0 ) {
691                         /* Error!? */
692                         fprintf( stderr, "%s: Can't fork: %s!\nFatal error, exiting now ...\n",
693                                                                 PACKAGE_NAME, strerror( errno ));
694                         exit( 1 );
695                 }
696
697                 /* New child process */
698 #ifndef NeXT
699                 (void)setsid( );
700 #else
701                 setpgrp(0, getpid());
702 #endif
703                 if (chdir( "/" ) != 0)
704                         Log(LOG_ERR, "Can't change directory to '/': %s",
705                                      strerror(errno));
706
707                 /* Detach stdin, stdout and stderr */
708                 Setup_FDStreams(fd);
709                 if (fd > 2)
710                         close(fd);
711         }
712         pid = getpid();
713
714         Pidfile_Create( pid );
715
716         /* Check UID/GID we are running as, can be different from values
717          * configured (e. g. if we were already started with a UID>0. */
718         Conf_UID = getuid();
719         Conf_GID = getgid();
720
721         pwd = getpwuid( Conf_UID );
722         grp = getgrgid( Conf_GID );
723
724         Log(LOG_INFO, "Running as user %s(%ld), group %s(%ld), with PID %ld.",
725                                 pwd ? pwd->pw_name : "unknown", (long)Conf_UID,
726                                 grp ? grp->gr_name : "unknown", (long)Conf_GID, (long)pid);
727
728         if (chrooted) {
729                 Log(LOG_INFO, "Running with root directory \"%s\".",
730                     Conf_Chroot );
731                 return true;
732         } else
733                 Log(LOG_INFO, "Not running with changed root directory.");
734
735         /* Change working directory to home directory of the user
736          * we are running as (only when running in daemon mode and not in chroot) */
737
738         if (pwd) {
739                 if (!NGIRCd_NoDaemon ) {
740                         if( chdir( pwd->pw_dir ) == 0 ) 
741                                 Log( LOG_DEBUG, "Changed working directory to \"%s\" ...", pwd->pw_dir );
742                         else 
743                                 Log( LOG_INFO, "Notice: Can't change working directory to \"%s\": %s",
744                                                                 pwd->pw_dir, strerror( errno ));
745                 }
746         } else {
747                 Log( LOG_ERR, "Can't get user informaton for UID %d!?", Conf_UID );
748         }
749
750         return true;
751  out:
752         if (fd > 2)
753                 close(fd);
754         return false;
755 } /* NGIRCd_Init */
756
757
758 /* -eof- */