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