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