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