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