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