]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/ngircd.c
Merge branch 'katp32/master'
[ngircd-alex.git] / src / ngircd / ngircd.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2023 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         NGIRCd_Debug = false;
92 #ifdef SNIFFER
93         NGIRCd_Sniffer = false;
94 #endif
95         strlcpy(NGIRCd_ConfFile, SYSCONFDIR, sizeof(NGIRCd_ConfFile));
96         strlcat(NGIRCd_ConfFile, CONFIG_FILE, sizeof(NGIRCd_ConfFile));
97
98         Fill_Version();
99
100         /* parse conmmand line */
101         for (i = 1; i < argc; i++) {
102                 ok = false;
103                 if (argv[i][0] == '-' && argv[i][1] == '-') {
104                         /* long option */
105                         if (strcmp(argv[i], "--config") == 0) {
106                                 if (i + 1 < argc) {
107                                         /* Ok, there's an parameter left */
108                                         strlcpy(NGIRCd_ConfFile, argv[i+1],
109                                                 sizeof(NGIRCd_ConfFile));
110                                         /* next parameter */
111                                         i++; ok = true;
112                                 }
113                         }
114                         if (strcmp(argv[i], "--configtest") == 0) {
115                                 configtest = true;
116                                 ok = true;
117                         }
118                         if (strcmp(argv[i], "--debug") == 0) {
119                                 NGIRCd_Debug = true;
120                                 ok = true;
121                         }
122                         if (strcmp(argv[i], "--help") == 0) {
123                                 Show_Version();
124                                 puts(""); Show_Help( ); puts( "" );
125                                 exit(0);
126                         }
127                         if (strcmp(argv[i], "--nodaemon") == 0) {
128                                 NGIRCd_NoDaemon = true;
129                                 NGIRCd_NoSyslog = true;
130                                 ok = true;
131                         }
132                         if (strcmp(argv[i], "--passive") == 0) {
133                                 NGIRCd_Passive = true;
134                                 ok = true;
135                         }
136 #ifdef SNIFFER
137                         if (strcmp(argv[i], "--sniffer") == 0) {
138                                 NGIRCd_Sniffer = true;
139                                 ok = true;
140                         }
141 #endif
142 #ifdef SYSLOG
143                         if (strcmp(argv[i], "--syslog") == 0) {
144                                 NGIRCd_NoSyslog = false;
145                                 ok = true;
146                         }
147 #endif
148                         if (strcmp(argv[i], "--version") == 0) {
149                                 Show_Version();
150                                 exit(0);
151                         }
152                 }
153                 else if(argv[i][0] == '-' && argv[i][1] != '-') {
154                         /* short option */
155                         for (n = 1; n < strlen(argv[i]); n++) {
156                                 ok = false;
157                                 if (argv[i][n] == 'd') {
158                                         NGIRCd_Debug = true;
159                                         ok = true;
160                                 }
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 #ifdef SYSLOG
205                                 if (argv[i][n] == 'y') {
206                                         NGIRCd_NoSyslog = false;
207                                         ok = true;
208                                 }
209 #endif
210
211                                 if (!ok) {
212                                         fprintf(stderr,
213                                                 "%s: invalid option \"-%c\"!\n",
214                                                 PACKAGE_NAME, argv[i][n]);
215                                         fprintf(stderr,
216                                                 "Try \"%s --help\" for more information.\n",
217                                                 PACKAGE_NAME);
218                                         exit(2);
219                                 }
220                         }
221
222                 }
223                 if (!ok) {
224                         fprintf(stderr, "%s: invalid option \"%s\"!\n",
225                                 PACKAGE_NAME, argv[i]);
226                         fprintf(stderr, "Try \"%s --help\" for more information.\n",
227                                 PACKAGE_NAME);
228                         exit(2);
229                 }
230         }
231
232         /* Debug level for "VERSION" command */
233         NGIRCd_DebugLevel[0] = '\0';
234         if (NGIRCd_Debug)
235                 strcpy(NGIRCd_DebugLevel, "1");
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                 Log_Init(!NGIRCd_NoSyslog);
259                 Random_Init();
260                 Conf_Init();
261                 Log_ReInit();
262
263                 /* Initialize the "main program":
264                  * chroot environment, user and group ID, ... */
265                 if (!NGIRCd_Init(NGIRCd_NoDaemon)) {
266                         Log(LOG_ALERT, "Fatal: Initialization failed, exiting!");
267                         exit(1);
268                 }
269
270                 if (!io_library_init(CONNECTION_POOL)) {
271                         Log(LOG_ALERT,
272                             "Fatal: Could not initialize IO routines: %s",
273                             strerror(errno));
274                         exit(1);
275                 }
276
277                 if (!Signals_Init()) {
278                         Log(LOG_ALERT,
279                             "Fatal: Could not set up signal handlers: %s",
280                             strerror(errno));
281                         exit(1);
282                 }
283
284                 Channel_Init();
285                 Conn_Init();
286                 Class_Init();
287                 Client_Init();
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-2023 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         puts( "  -d, --debug        log extra debug messages" );
476         puts( "  -f, --config <f>   use file <f> as configuration file" );
477         puts( "  -n, --nodaemon     don't fork and don't detach from controlling terminal" );
478         puts( "  -p, --passive      disable automatic connections to other servers" );
479 #ifdef SNIFFER
480         puts( "  -s, --sniffer      enable network sniffer and display all IRC traffic" );
481 #endif
482         puts( "  -t, --configtest   read, validate and display configuration; then exit" );
483         puts( "  -V, --version      output version information and exit" );
484 #ifdef SYSLOG
485         puts( "  -y, --syslog       log to syslog even when running in the foreground (-n)" );
486 #endif
487         puts( "  -h, --help         display this help and exit" );
488 } /* Show_Help */
489
490
491 /**
492  * Delete the file containing the process ID (PID).
493  */
494 static void
495 Pidfile_Delete( void )
496 {
497         /* Pidfile configured? */
498         if( ! Conf_PidFile[0] ) return;
499
500         LogDebug( "Removing PID file (%s) ...", Conf_PidFile );
501
502         if( unlink( Conf_PidFile ))
503                 Log( LOG_ERR, "Error unlinking PID file (%s): %s", Conf_PidFile, strerror( errno ));
504 } /* Pidfile_Delete */
505
506
507 /**
508  * Create the file containing the process ID of ngIRCd ("PID file").
509  *
510  * @param pid   The process ID to be stored in this file.
511  */
512 static void
513 Pidfile_Create(pid_t pid)
514 {
515         int pidfd;
516         char pidbuf[64];
517         int len;
518
519         /* Pidfile configured? */
520         if( ! Conf_PidFile[0] ) return;
521
522         LogDebug( "Creating PID file (%s) ...", Conf_PidFile );
523
524         pidfd = open( Conf_PidFile, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
525         if ( pidfd < 0 ) {
526                 Log( LOG_ERR, "Error writing PID file (%s): %s", Conf_PidFile, strerror( errno ));
527                 return;
528         }
529
530         len = snprintf(pidbuf, sizeof pidbuf, "%ld\n", (long)pid);
531         if (len < 0 || len >= (int)sizeof pidbuf) {
532                 Log(LOG_ERR, "Error converting process ID!");
533                 close(pidfd);
534                 return;
535         }
536
537         if (write(pidfd, pidbuf, (size_t)len) != (ssize_t)len)
538                 Log(LOG_ERR, "Can't write PID file (%s): %s!", Conf_PidFile,
539                     strerror(errno));
540
541         if (close(pidfd) != 0)
542                 Log(LOG_ERR, "Error closing PID file (%s): %s!", Conf_PidFile,
543                     strerror(errno));
544 } /* Pidfile_Create */
545
546
547 /**
548  * Redirect stdin, stdout and stderr to appropriate file handles.
549  *
550  * @param fd    The file handle stdin, stdout and stderr should be redirected to.
551  */
552 static void
553 Setup_FDStreams(int fd)
554 {
555         if (fd < 0)
556                 return;
557
558         fflush(stdout);
559         fflush(stderr);
560
561         /* Create new stdin(0), stdout(1) and stderr(2) descriptors */
562         dup2( fd, 0 ); dup2( fd, 1 ); dup2( fd, 2 );
563 } /* Setup_FDStreams */
564
565
566 #if !defined(SINGLE_USER_OS)
567
568 /**
569  * Get user and group ID of unprivileged "nobody" user.
570  *
571  * @param uid   User ID
572  * @param gid   Group ID
573  * @return      true on success.
574  */
575 static bool
576 NGIRCd_getNobodyID(uid_t *uid, gid_t *gid )
577 {
578         struct passwd *pwd;
579
580 #ifdef __CYGWIN__
581         /* Cygwin kludge.
582          * It can return EINVAL instead of EPERM
583          * so, if we are already unprivileged,
584          * use id of current user.
585          */
586         if (geteuid() && getuid()) {
587                 *uid = getuid();
588                 *gid = getgid();
589                 return true;
590         }
591 #endif
592
593         pwd = getpwnam("nobody");
594         if (!pwd)
595                 return false;
596
597         if (!pwd->pw_uid || !pwd->pw_gid)
598                 return false;
599
600         *uid = pwd->pw_uid;
601         *gid = pwd->pw_gid;
602         endpwent();
603
604         return true;
605 } /* NGIRCd_getNobodyID */
606
607 #endif
608
609
610 #ifdef HAVE_ARC4RANDOM
611 static void
612 Random_Init(void)
613 {
614
615 }
616 #else
617 static bool
618 Random_Init_Kern(const char *file)
619 {
620         unsigned int seed;
621         bool ret = false;
622         int fd = open(file, O_RDONLY);
623         if (fd >= 0) {
624                 if (read(fd, &seed, sizeof(seed)) == sizeof(seed))
625                         ret = true;
626                 close(fd);
627                 srand(seed);
628         }
629         return ret;
630 }
631
632 /**
633  * Initialize libc rand(3) number generator
634  */
635 static void
636 Random_Init(void)
637 {
638         if (Random_Init_Kern("/dev/urandom"))
639                 return;
640         if (Random_Init_Kern("/dev/random"))
641                 return;
642         if (Random_Init_Kern("/dev/arandom"))
643                 return;
644         srand(rand() ^ (unsigned)getpid() ^ (unsigned)time(NULL));
645 }
646 #endif
647
648
649 /**
650  * Initialize ngIRCd daemon.
651  *
652  * @param NGIRCd_NoDaemon Set to true if ngIRCd should run in the
653  *              foreground (and not as a daemon).
654  * @return true on success.
655  */
656 static bool
657 NGIRCd_Init(bool NGIRCd_NoDaemon)
658 {
659         static bool initialized;
660         bool chrooted = false;
661         struct passwd *pwd;
662         struct group *grp;
663         int real_errno, fd = -1;
664         pid_t pid;
665
666         if (initialized)
667                 return true;
668
669         if (!NGIRCd_NoDaemon) {
670                 /* open /dev/null before chroot() */
671                 fd = open( "/dev/null", O_RDWR);
672                 if (fd < 0)
673                         Log(LOG_WARNING, "Could not open /dev/null: %s",
674                             strerror(errno));
675         }
676
677         /* SSL initialization */
678         if (!ConnSSL_InitLibrary()) {
679                 Log(LOG_ERR, "Error during SSL initialization!");
680                 goto out;
681         }
682
683         /* Change root */
684         if (Conf_Chroot[0]) {
685                 if (chdir(Conf_Chroot) != 0) {
686                         Log(LOG_ERR, "Can't chdir() in ChrootDir (%s): %s!",
687                             Conf_Chroot, strerror(errno));
688                         goto out;
689                 }
690
691                 if (chroot(Conf_Chroot) != 0) {
692                         Log(LOG_ERR,
693                             "Can't change root directory to \"%s\": %s!",
694                             Conf_Chroot, strerror(errno));
695                         goto out;
696                 } else {
697                         chrooted = true;
698                         Log(LOG_INFO,
699                             "Changed root and working directory to \"%s\".",
700                             Conf_Chroot);
701                 }
702         }
703
704 #if !defined(SINGLE_USER_OS)
705         /* Check user ID */
706         if (Conf_UID == 0) {
707                 pwd = getpwuid(0);
708                 Log(LOG_INFO,
709                     "ServerUID must not be %s(0), using \"nobody\" instead.",
710                     pwd ? pwd->pw_name : "?");
711                 if (!NGIRCd_getNobodyID(&Conf_UID, &Conf_GID)) {
712                         Log(LOG_WARNING,
713                             "Could not get user/group ID of user \"nobody\": %s",
714                             errno ? strerror(errno) : "not found" );
715                         goto out;
716                 }
717         }
718
719         /* Change group ID */
720         if (getgid() != Conf_GID) {
721                 if (setgid(Conf_GID) != 0) {
722                         real_errno = errno;
723                         grp = getgrgid(Conf_GID);
724                         Log(LOG_ERR, "Can't change group ID to %s(%u): %s!",
725                             grp ? grp->gr_name : "?", Conf_GID,
726                             strerror(real_errno));
727                         if (real_errno != EPERM)
728                                 goto out;
729                 }
730 #ifdef HAVE_SETGROUPS
731                 if (setgroups(0, NULL) != 0) {
732                         real_errno = errno;
733                         Log(LOG_ERR, "Can't drop supplementary group IDs: %s!",
734                                         strerror(errno));
735                         if (real_errno != EPERM)
736                                 goto out;
737                 }
738 #else
739                 Log(LOG_WARNING,
740                     "Can't drop supplementary group IDs: setgroups(3) missing!");
741 #endif
742         }
743 #endif
744
745         /* Change user ID */
746         if (getuid() != Conf_UID) {
747                 if (setuid(Conf_UID) != 0) {
748                         real_errno = errno;
749                         pwd = getpwuid(Conf_UID);
750                         Log(LOG_ERR, "Can't change user ID to %s(%u): %s!",
751                             pwd ? pwd->pw_name : "?", Conf_UID,
752                             strerror(real_errno));
753                         if (real_errno != EPERM)
754                                 goto out;
755                 }
756         }
757
758         initialized = true;
759
760         /* Normally a child process is forked which isn't any longer
761          * connected to ther controlling terminal. Use "--nodaemon"
762          * to disable this "daemon mode" (useful for debugging). */
763         if (!NGIRCd_NoDaemon) {
764                 pid = fork();
765                 if (pid > 0) {
766                         /* "Old" process: exit. */
767                         exit(0);
768                 }
769                 if (pid < 0) {
770                         /* Error!? */
771                         fprintf(stderr,
772                                 "%s: Can't fork: %s!\nFatal error, exiting now ...\n",
773                                 PACKAGE_NAME, strerror(errno));
774                         exit(1);
775                 }
776
777                 /* New child process */
778 #ifdef HAVE_SETSID
779                 (void)setsid();
780 #else
781                 setpgrp(0, getpid());
782 #endif
783                 if (chdir("/") != 0)
784                         Log(LOG_ERR, "Can't change directory to '/': %s!",
785                                      strerror(errno));
786
787                 /* Detach stdin, stdout and stderr */
788                 Setup_FDStreams(fd);
789                 if (fd > 2)
790                         close(fd);
791         }
792         pid = getpid();
793
794         Pidfile_Create(pid);
795
796         /* Check UID/GID we are running as, can be different from values
797          * configured (e. g. if we were already started with a UID>0. */
798         Conf_UID = getuid();
799         Conf_GID = getgid();
800
801         pwd = getpwuid(Conf_UID);
802         grp = getgrgid(Conf_GID);
803
804         Log(LOG_INFO, "Running as user %s(%ld), group %s(%ld), with PID %ld.",
805             pwd ? pwd->pw_name : "unknown", (long)Conf_UID,
806             grp ? grp->gr_name : "unknown", (long)Conf_GID, (long)pid);
807
808         if (chrooted) {
809                 Log(LOG_INFO, "Running with root directory \"%s\".",
810                     Conf_Chroot );
811                 return true;
812         } else
813                 Log(LOG_INFO, "Not running with changed root directory.");
814
815         /* Change working directory to home directory of the user we are
816          * running as (only when running in daemon mode and not in chroot) */
817
818         if (NGIRCd_NoDaemon)
819                 return true;
820
821         if (pwd) {
822                 if (chdir(pwd->pw_dir) == 0)
823                         LogDebug(
824                             "Changed working directory to \"%s\" ...",
825                             pwd->pw_dir);
826                 else
827                         Log(LOG_ERR,
828                             "Can't change working directory to \"%s\": %s!",
829                             pwd->pw_dir, strerror(errno));
830         } else
831                 Log(LOG_ERR, "Can't get user informaton for UID %d!?", Conf_UID);
832
833         return true;
834  out:
835         if (fd > 2)
836                 close(fd);
837         return false;
838 } /* NGIRCd_Init */
839
840
841 /* -eof- */