]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/ngircd.c
Add new class.{c|h} to project
[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 "class.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 #include "exp.h"
53 #include "ngircd.h"
54
55
56 static void Show_Version PARAMS(( void ));
57 static void Show_Help PARAMS(( void ));
58
59 static void Pidfile_Create PARAMS(( pid_t pid ));
60 static void Pidfile_Delete PARAMS(( void ));
61
62 static void Fill_Version PARAMS(( void ));
63
64 static void Random_Init PARAMS(( void ));
65
66 static void Setup_FDStreams PARAMS(( int fd ));
67
68 static bool NGIRCd_Init PARAMS(( bool ));
69
70
71 /**
72  * The main() function of ngIRCd.
73  *
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  *
77  * @param argc  The number of arguments passed to ngIRCd on the command line.
78  * @param argv  An array containing all the arguments passed to ngIRCd.
79  * @return      Global exit code of ngIRCd, zero on success.
80  */
81 GLOBAL int
82 main( int argc, const char *argv[] )
83 {
84         bool ok, configtest = false;
85         bool NGIRCd_NoDaemon = false;
86         int i;
87         size_t n;
88
89 #if defined(DEBUG) && defined(HAVE_MTRACE)
90         /* enable GNU libc memory tracing when running in debug mode
91          * and functionality available */
92         mtrace();
93 #endif
94
95         umask( 0077 );
96
97         NGIRCd_SignalQuit = NGIRCd_SignalRestart = false;
98         NGIRCd_Passive = false;
99 #ifdef DEBUG
100         NGIRCd_Debug = false;
101 #endif
102 #ifdef SNIFFER
103         NGIRCd_Sniffer = false;
104 #endif
105         strlcpy( NGIRCd_ConfFile, SYSCONFDIR, sizeof( NGIRCd_ConfFile ));
106         strlcat( NGIRCd_ConfFile, CONFIG_FILE, sizeof( NGIRCd_ConfFile ));
107
108         Fill_Version( );
109
110         /* parse conmmand line */
111         for( i = 1; i < argc; i++ )
112         {
113                 ok = false;
114                 if(( argv[i][0] == '-' ) && ( argv[i][1] == '-' ))
115                 {
116                         /* long option */
117                         if( strcmp( argv[i], "--config" ) == 0 )
118                         {
119                                 if( i + 1 < argc )
120                                 {
121                                         /* Ok, there's an parameter left */
122                                         strlcpy( NGIRCd_ConfFile, argv[i + 1], sizeof( NGIRCd_ConfFile ));
123
124                                         /* next parameter */
125                                         i++; ok = true;
126                                 }
127                         }
128                         if( strcmp( argv[i], "--configtest" ) == 0 )
129                         {
130                                 configtest = true;
131                                 ok = true;
132                         }
133 #ifdef DEBUG
134                         if( strcmp( argv[i], "--debug" ) == 0 )
135                         {
136                                 NGIRCd_Debug = true;
137                                 ok = true;
138                         }
139 #endif
140                         if( strcmp( argv[i], "--help" ) == 0 )
141                         {
142                                 Show_Version( );
143                                 puts( "" ); Show_Help( ); puts( "" );
144                                 exit( 1 );
145                         }
146                         if( strcmp( argv[i], "--nodaemon" ) == 0 )
147                         {
148                                 NGIRCd_NoDaemon = true;
149                                 ok = true;
150                         }
151                         if( strcmp( argv[i], "--passive" ) == 0 )
152                         {
153                                 NGIRCd_Passive = true;
154                                 ok = true;
155                         }
156 #ifdef SNIFFER
157                         if( strcmp( argv[i], "--sniffer" ) == 0 )
158                         {
159                                 NGIRCd_Sniffer = true;
160                                 ok = true;
161                         }
162 #endif
163                         if( strcmp( argv[i], "--version" ) == 0 )
164                         {
165                                 Show_Version( );
166                                 exit( 1 );
167                         }
168                 }
169                 else if(( argv[i][0] == '-' ) && ( argv[i][1] != '-' ))
170                 {
171                         /* short option */
172                         for( n = 1; n < strlen( argv[i] ); n++ )
173                         {
174                                 ok = false;
175 #ifdef DEBUG
176                                 if (argv[i][n] == 'd') {
177                                         NGIRCd_Debug = true;
178                                         ok = true;
179                                 }
180 #endif
181                                 if (argv[i][n] == 'f') {
182                                         if(( ! argv[i][n + 1] ) && ( i + 1 < argc ))
183                                         {
184                                                 /* Ok, next character is a blank */
185                                                 strlcpy( NGIRCd_ConfFile, argv[i + 1], sizeof( NGIRCd_ConfFile ));
186
187                                                 /* go to the following parameter */
188                                                 i++;
189                                                 n = strlen( argv[i] );
190                                                 ok = true;
191                                         }
192                                 }
193
194                                 if (argv[i][n] == 'h') {
195                                         Show_Version();
196                                         puts(""); Show_Help(); puts("");
197                                         exit(1);
198                                 }
199
200                                 if (argv[i][n] == 'n') {
201                                         NGIRCd_NoDaemon = true;
202                                         ok = true;
203                                 }
204                                 if (argv[i][n] == 'p') {
205                                         NGIRCd_Passive = true;
206                                         ok = true;
207                                 }
208 #ifdef SNIFFER
209                                 if (argv[i][n] == 's') {
210                                         NGIRCd_Sniffer = true;
211                                         ok = true;
212                                 }
213 #endif
214                                 if (argv[i][n] == 't') {
215                                         configtest = true;
216                                         ok = true;
217                                 }
218
219                                 if (argv[i][n] == 'V') {
220                                         Show_Version();
221                                         exit(1);
222                                 }
223
224                                 if (! ok) {
225                                         printf( "%s: invalid option \"-%c\"!\n", PACKAGE_NAME, argv[i][n] );
226                                         printf( "Try \"%s --help\" for more information.\n", PACKAGE_NAME );
227                                         exit( 1 );
228                                 }
229                         }
230
231                 }
232                 if( ! ok )
233                 {
234                         printf( "%s: invalid option \"%s\"!\n", PACKAGE_NAME, argv[i] );
235                         printf( "Try \"%s --help\" for more information.\n", PACKAGE_NAME );
236                         exit( 1 );
237                 }
238         }
239
240         /* Debug level for "VERSION" command */
241         NGIRCd_DebugLevel[0] = '\0';
242 #ifdef DEBUG
243         if( NGIRCd_Debug ) strcpy( NGIRCd_DebugLevel, "1" );
244 #endif
245 #ifdef SNIFFER
246         if( NGIRCd_Sniffer )
247         {
248                 NGIRCd_Debug = true;
249                 strcpy( NGIRCd_DebugLevel, "2" );
250         }
251 #endif
252
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_SignalRestart = false;
266                 NGIRCd_SignalQuit = false;
267
268                 Random_Init();
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                 Conn_Init( );
286                 Class_Init( );
287
288                 if (!io_library_init(CONNECTION_POOL)) {
289                         Log(LOG_ALERT, "Fatal: Cannot initialize IO routines: %s", strerror(errno));
290                         exit(1);
291                 }
292
293                 if (!Signals_Init()) {
294                         Log(LOG_ALERT, "Fatal: Could not set up signal handlers: %s", strerror(errno));
295                         exit(1);
296                 }
297
298                 /* Create protocol and server identification. The syntax
299                  * used by ngIRCd in PASS commands and the known "extended
300                  * flags" are described in doc/Protocol.txt. */
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                 LogDebug("Protocol and server ID is \"%s\".", NGIRCd_ProtoID);
315
316                 Channel_InitPredefined( );
317
318                 if( Conn_InitListeners( ) < 1 )
319                 {
320                         Log( LOG_ALERT, "Server isn't listening on a single port!" );
321                         Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
322                         Pidfile_Delete( );
323                         exit( 1 );
324                 }
325
326                 /* Main Run Loop */
327                 Conn_Handler( );
328
329                 Conn_Exit( );
330                 Client_Exit( );
331                 Channel_Exit( );
332                 Class_Exit( );
333                 Log_Exit( );
334         }
335         Pidfile_Delete( );
336
337         return 0;
338 } /* main */
339
340
341 /**
342  * Generate ngIRCd "version strings".
343  *
344  * The ngIRCd version information is generated once and then stored in the
345  * NGIRCd_Version and NGIRCd_VersionAddition string variables for further
346  * usage, for example by the IRC command "VERSION" and the --version command
347  * line switch.
348  */
349 static void
350 Fill_Version( void )
351 {
352         NGIRCd_VersionAddition[0] = '\0';
353
354 #ifdef SYSLOG
355         strlcpy( NGIRCd_VersionAddition, "SYSLOG", sizeof NGIRCd_VersionAddition );
356 #endif
357 #ifdef ZLIB
358         if( NGIRCd_VersionAddition[0] )
359                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
360         strlcat( NGIRCd_VersionAddition, "ZLIB", sizeof NGIRCd_VersionAddition );
361 #endif
362 #ifdef SSL_SUPPORT
363         if ( NGIRCd_VersionAddition[0] ) strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
364         strlcat( NGIRCd_VersionAddition, "SSL", sizeof NGIRCd_VersionAddition );
365 #endif
366 #ifdef TCPWRAP
367         if( NGIRCd_VersionAddition[0] )
368                         strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
369         strlcat( NGIRCd_VersionAddition, "TCPWRAP", sizeof NGIRCd_VersionAddition );
370 #endif
371 #ifdef IDENTAUTH
372         if( NGIRCd_VersionAddition[0] )
373                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
374         strlcat( NGIRCd_VersionAddition, "IDENT", sizeof NGIRCd_VersionAddition );
375 #endif
376 #ifdef PAM
377         if (NGIRCd_VersionAddition[0])
378                 strlcat(NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition);
379         strlcat(NGIRCd_VersionAddition, "PAM", sizeof NGIRCd_VersionAddition);
380 #endif
381 #ifdef DEBUG
382         if( NGIRCd_VersionAddition[0] )
383                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
384         strlcat( NGIRCd_VersionAddition, "DEBUG", sizeof NGIRCd_VersionAddition );
385 #endif
386 #ifdef SNIFFER
387         if( NGIRCd_VersionAddition[0] )
388                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
389         strlcat( NGIRCd_VersionAddition, "SNIFFER", sizeof NGIRCd_VersionAddition );
390 #endif
391 #ifdef STRICT_RFC
392         if( NGIRCd_VersionAddition[0] )
393                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
394         strlcat( NGIRCd_VersionAddition, "RFC", sizeof NGIRCd_VersionAddition );
395 #endif
396 #ifdef IRCPLUS
397         if( NGIRCd_VersionAddition[0] )
398                 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
399         strlcat( NGIRCd_VersionAddition, "IRCPLUS", sizeof NGIRCd_VersionAddition );
400 #endif
401 #ifdef WANT_IPV6
402         if (NGIRCd_VersionAddition[0])
403                 strlcat(NGIRCd_VersionAddition, "+", sizeof(NGIRCd_VersionAddition));
404         strlcat(NGIRCd_VersionAddition, "IPv6", sizeof(NGIRCd_VersionAddition));
405 #endif
406         if( NGIRCd_VersionAddition[0] )
407                 strlcat( NGIRCd_VersionAddition, "-", sizeof( NGIRCd_VersionAddition ));
408
409         strlcat( NGIRCd_VersionAddition, TARGET_CPU, sizeof( NGIRCd_VersionAddition ));
410         strlcat( NGIRCd_VersionAddition, "/", sizeof( NGIRCd_VersionAddition ));
411         strlcat( NGIRCd_VersionAddition, TARGET_VENDOR, sizeof( NGIRCd_VersionAddition ));
412         strlcat( NGIRCd_VersionAddition, "/", sizeof( NGIRCd_VersionAddition ));
413         strlcat( NGIRCd_VersionAddition, TARGET_OS, sizeof( NGIRCd_VersionAddition ));
414
415         snprintf(NGIRCd_Version, sizeof NGIRCd_Version, "%s %s-%s",
416                  PACKAGE_NAME, PACKAGE_VERSION, NGIRCd_VersionAddition);
417 } /* Fill_Version */
418
419
420 /**
421  * Display copyright and version information of ngIRCd on the console.
422  */
423 static void
424 Show_Version( void )
425 {
426         puts( NGIRCd_Version );
427         puts( "Copyright (c)2001-2011 Alexander Barton (<alex@barton.de>) and Contributors." );
428         puts( "Homepage: <http://ngircd.barton.de/>\n" );
429         puts( "This is free software; see the source for copying conditions. There is NO" );
430         puts( "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." );
431 } /* Show_Version */
432
433
434 /**
435  * Display a short help text on the console.
436  * This help depends on the configuration of the executable and only shows
437  * options that are actually enabled.
438  */
439 static void
440 Show_Help( void )
441 {
442 #ifdef DEBUG
443         puts( "  -d, --debug        log extra debug messages" );
444 #endif
445         puts( "  -f, --config <f>   use file <f> as configuration file" );
446         puts( "  -n, --nodaemon     don't fork and don't detach from controlling terminal" );
447         puts( "  -p, --passive      disable automatic connections to other servers" );
448 #ifdef SNIFFER
449         puts( "  -s, --sniffer      enable network sniffer and display all IRC traffic" );
450 #endif
451         puts( "  -t, --configtest   read, validate and display configuration; then exit" );
452         puts( "  -V, --version      output version information and exit" );
453         puts( "  -h, --help         display this help and exit" );
454 } /* Show_Help */
455
456
457 /**
458  * Delete the file containing the process ID (PID).
459  */
460 static void
461 Pidfile_Delete( void )
462 {
463         /* Pidfile configured? */
464         if( ! Conf_PidFile[0] ) return;
465
466 #ifdef DEBUG
467         Log( LOG_DEBUG, "Removing PID file (%s) ...", Conf_PidFile );
468 #endif
469
470         if( unlink( Conf_PidFile ))
471                 Log( LOG_ERR, "Error unlinking PID file (%s): %s", Conf_PidFile, strerror( errno ));
472 } /* Pidfile_Delete */
473
474
475 /**
476  * Create the file containing the process ID of ngIRCd ("PID file").
477  *
478  * @param pid   The process ID to be stored in this file.
479  */
480 static void
481 Pidfile_Create(pid_t pid)
482 {
483         int pidfd;
484         char pidbuf[64];
485         int len;
486
487         /* Pidfile configured? */
488         if( ! Conf_PidFile[0] ) return;
489
490 #ifdef DEBUG
491         Log( LOG_DEBUG, "Creating PID file (%s) ...", Conf_PidFile );
492 #endif
493
494         pidfd = open( Conf_PidFile, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
495         if ( pidfd < 0 ) {
496                 Log( LOG_ERR, "Error writing PID file (%s): %s", Conf_PidFile, strerror( errno ));
497                 return;
498         }
499
500         len = snprintf(pidbuf, sizeof pidbuf, "%ld\n", (long)pid);
501         if (len < 0 || len >= (int)sizeof pidbuf) {
502                 Log( LOG_ERR, "Error converting pid");
503                 return;
504         }
505         
506         if (write(pidfd, pidbuf, (size_t)len) != (ssize_t)len)
507                 Log( LOG_ERR, "Can't write PID file (%s): %s", Conf_PidFile, strerror( errno ));
508
509         if( close(pidfd) != 0 )
510                 Log( LOG_ERR, "Error closing PID file (%s): %s", Conf_PidFile, strerror( errno ));
511 } /* Pidfile_Create */
512
513
514 /**
515  * Redirect stdin, stdout and stderr to apropriate file handles.
516  *
517  * @param fd    The file handle stdin, stdout and stderr should be redirected to.
518  */
519 static void
520 Setup_FDStreams(int fd)
521 {
522         if (fd < 0)
523                 return;
524
525         fflush(stdout);
526         fflush(stderr);
527
528         /* Create new stdin(0), stdout(1) and stderr(2) descriptors */
529         dup2( fd, 0 ); dup2( fd, 1 ); dup2( fd, 2 );
530 } /* Setup_FDStreams */
531
532
533 /**
534  * Get user and group ID of unprivileged "nobody" user.
535  *
536  * @param uid   User ID
537  * @param gid   Group ID
538  * @return      true on success.
539  */
540 static bool
541 NGIRCd_getNobodyID(uid_t *uid, gid_t *gid )
542 {
543         struct passwd *pwd;
544
545 #ifdef __CYGWIN__
546         /* Cygwin kludge.
547          * It can return EINVAL instead of EPERM
548          * so, if we are already unprivileged,
549          * use id of current user.
550          */
551         if (geteuid() && getuid()) {
552                 *uid = getuid();
553                 *gid = getgid();
554                 return true;
555         }
556 #endif
557
558         pwd = getpwnam("nobody");
559         if (!pwd) return false;
560
561         if ( !pwd->pw_uid || !pwd->pw_gid)
562                 return false;
563
564         *uid = pwd->pw_uid;
565         *gid = pwd->pw_gid;
566         endpwent();
567
568         return true;
569 } /* NGIRCd_getNobodyID */
570
571
572 static bool
573 Random_Init_Kern(const char *file)
574 {
575         unsigned int seed;
576         bool ret = false;
577         int fd = open(file, O_RDONLY);
578         if (fd >= 0) {
579                 if (read(fd, &seed, sizeof(seed)) == sizeof(seed))
580                         ret = true;
581                 close(fd);
582                 srand(seed);
583         }
584         return ret;
585 }
586
587 /**
588  * Initialize libc rand(3) number generator
589  */
590 static void
591 Random_Init(void)
592 {
593         if (Random_Init_Kern("/dev/urandom"))
594                 return;
595         if (Random_Init_Kern("/dev/random"))
596                 return;
597         if (Random_Init_Kern("/dev/arandom"))
598                 return;
599         srand(rand() ^ (unsigned)getpid() ^ (unsigned)time(NULL));
600 }
601
602
603 /**
604  * Initialize ngIRCd daemon.
605  *
606  * @param NGIRCd_NoDaemon       Set to true if ngIRCd should run in the
607  *                              foreground and not as a daemon.
608  * @return                      true on success.
609  */
610 static bool
611 NGIRCd_Init( bool NGIRCd_NoDaemon ) 
612 {
613         static bool initialized;
614         bool chrooted = false;
615         struct passwd *pwd;
616         struct group *grp;
617         int real_errno, fd = -1;
618         pid_t pid;
619
620         if (initialized)
621                 return true;
622
623         if (!NGIRCd_NoDaemon) {
624                 /* open /dev/null before chroot() */
625                 fd = open( "/dev/null", O_RDWR);
626                 if (fd < 0)
627                         Log(LOG_WARNING, "Could not open /dev/null: %s", strerror(errno));
628         }
629
630         if (!ConnSSL_InitLibrary())
631                 Log(LOG_WARNING,
632                     "Warning: Error during SSL initialization, continuing ...");
633
634         if( Conf_Chroot[0] ) {
635                 if( chdir( Conf_Chroot ) != 0 ) {
636                         Log( LOG_ERR, "Can't chdir() in ChrootDir (%s): %s", Conf_Chroot, strerror( errno ));
637                         goto out;
638                 }
639
640                 if( chroot( Conf_Chroot ) != 0 ) {
641                         if (errno != EPERM) {
642                                 Log( LOG_ERR, "Can't change root directory to \"%s\": %s",
643                                                                 Conf_Chroot, strerror( errno ));
644                                 goto out;
645                         }
646                 } else {
647                         chrooted = true;
648                         Log( LOG_INFO, "Changed root and working directory to \"%s\".", Conf_Chroot );
649                 }
650         }
651
652         if (Conf_UID == 0) {
653                 Log(LOG_INFO, "ServerUID must not be 0, using \"nobody\" instead.", Conf_UID);
654
655                 if (! NGIRCd_getNobodyID(&Conf_UID, &Conf_GID)) {
656                         Log(LOG_WARNING, "Could not get user/group ID of user \"nobody\": %s",
657                                         errno ? strerror(errno) : "not found" );
658                         goto out;
659                 }
660         }
661
662         if (getgid() != Conf_GID) {
663                 /* Change group ID */
664                 if (setgid(Conf_GID) != 0) {
665                         real_errno = errno;
666                         Log( LOG_ERR, "Can't change group ID to %u: %s", Conf_GID, strerror( errno ));
667                         if (real_errno != EPERM) 
668                                 goto out;
669                 }
670         }
671
672         if (getuid() != Conf_UID) {
673                 /* Change user ID */
674                 if (setuid(Conf_UID) != 0) {
675                         real_errno = errno;
676                         Log(LOG_ERR, "Can't change user ID to %u: %s", Conf_UID, strerror(errno));
677                         if (real_errno != EPERM) 
678                                 goto out;
679                 }
680         }
681
682         initialized = true;
683
684         /* Normally a child process is forked which isn't any longer
685          * connected to ther controlling terminal. Use "--nodaemon"
686          * to disable this "daemon mode" (useful for debugging). */
687         if ( ! NGIRCd_NoDaemon ) {
688                 pid = fork( );
689                 if( pid > 0 ) {
690                         /* "Old" process: exit. */
691                         exit( 0 );
692                 }
693                 if( pid < 0 ) {
694                         /* Error!? */
695                         fprintf( stderr, "%s: Can't fork: %s!\nFatal error, exiting now ...\n",
696                                                                 PACKAGE_NAME, strerror( errno ));
697                         exit( 1 );
698                 }
699
700                 /* New child process */
701 #ifndef NeXT
702                 (void)setsid( );
703 #else
704                 setpgrp(0, getpid());
705 #endif
706                 if (chdir( "/" ) != 0)
707                         Log(LOG_ERR, "Can't change directory to '/': %s",
708                                      strerror(errno));
709
710                 /* Detach stdin, stdout and stderr */
711                 Setup_FDStreams(fd);
712                 if (fd > 2)
713                         close(fd);
714         }
715         pid = getpid();
716
717         Pidfile_Create( pid );
718
719         /* Check UID/GID we are running as, can be different from values
720          * configured (e. g. if we were already started with a UID>0. */
721         Conf_UID = getuid();
722         Conf_GID = getgid();
723
724         pwd = getpwuid( Conf_UID );
725         grp = getgrgid( Conf_GID );
726
727         Log(LOG_INFO, "Running as user %s(%ld), group %s(%ld), with PID %ld.",
728                                 pwd ? pwd->pw_name : "unknown", (long)Conf_UID,
729                                 grp ? grp->gr_name : "unknown", (long)Conf_GID, (long)pid);
730
731         if (chrooted) {
732                 Log(LOG_INFO, "Running with root directory \"%s\".",
733                     Conf_Chroot );
734                 return true;
735         } else
736                 Log(LOG_INFO, "Not running with changed root directory.");
737
738         /* Change working directory to home directory of the user
739          * we are running as (only when running in daemon mode and not in chroot) */
740
741         if (pwd) {
742                 if (!NGIRCd_NoDaemon ) {
743                         if( chdir( pwd->pw_dir ) == 0 ) 
744                                 Log( LOG_DEBUG, "Changed working directory to \"%s\" ...", pwd->pw_dir );
745                         else 
746                                 Log( LOG_INFO, "Notice: Can't change working directory to \"%s\": %s",
747                                                                 pwd->pw_dir, strerror( errno ));
748                 }
749         } else {
750                 Log( LOG_ERR, "Can't get user informaton for UID %d!?", Conf_UID );
751         }
752
753         return true;
754  out:
755         if (fd > 2)
756                 close(fd);
757         return false;
758 } /* NGIRCd_Init */
759
760
761 /* -eof- */