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