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