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