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