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