2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2010 Alexander Barton (alex@barton.de).
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.
17 * The main program, including the C function main() which is called
18 * by the loader of the operating system.
30 #include <sys/types.h>
37 #if defined(DEBUG) && defined(HAVE_MTRACE)
52 #include "rendezvous.h"
59 static void Initialize_Signal_Handler PARAMS(( void ));
60 static void Signal_Handler PARAMS(( int Signal ));
62 static void Show_Version PARAMS(( void ));
63 static void Show_Help PARAMS(( void ));
65 static void Pidfile_Create PARAMS(( pid_t pid ));
66 static void Pidfile_Delete PARAMS(( void ));
68 static void Fill_Version PARAMS(( void ));
70 static void Setup_FDStreams PARAMS(( void ));
72 static bool NGIRCd_Init PARAMS(( bool ));
75 * The main() function of ngIRCd.
76 * Here all starts: this function is called by the operating system loader,
77 * it is the first portion of code executed of ngIRCd.
78 * @param argc The number of arguments passed to ngIRCd on the command line.
79 * @param argv An array containing all the arguments passed to ngIRCd.
80 * @return Global exit code of ngIRCd, zero on success.
83 main( int argc, const char *argv[] )
85 bool ok, configtest = false;
86 bool NGIRCd_NoDaemon = false;
90 #if defined(DEBUG) && defined(HAVE_MTRACE)
91 /* enable GNU libc memory tracing when running in debug mode
92 * and functionality available */
98 NGIRCd_SignalQuit = NGIRCd_SignalRestart = NGIRCd_SignalRehash = false;
99 NGIRCd_Passive = false;
101 NGIRCd_Debug = false;
104 NGIRCd_Sniffer = false;
106 strlcpy( NGIRCd_ConfFile, SYSCONFDIR, sizeof( NGIRCd_ConfFile ));
107 strlcat( NGIRCd_ConfFile, CONFIG_FILE, sizeof( NGIRCd_ConfFile ));
111 /* parse conmmand line */
112 for( i = 1; i < argc; i++ )
115 if(( argv[i][0] == '-' ) && ( argv[i][1] == '-' ))
118 if( strcmp( argv[i], "--config" ) == 0 )
122 /* Ok, there's an parameter left */
123 strlcpy( NGIRCd_ConfFile, argv[i + 1], sizeof( NGIRCd_ConfFile ));
129 if( strcmp( argv[i], "--configtest" ) == 0 )
135 if( strcmp( argv[i], "--debug" ) == 0 )
141 if( strcmp( argv[i], "--help" ) == 0 )
144 puts( "" ); Show_Help( ); puts( "" );
147 if( strcmp( argv[i], "--nodaemon" ) == 0 )
149 NGIRCd_NoDaemon = true;
152 if( strcmp( argv[i], "--passive" ) == 0 )
154 NGIRCd_Passive = true;
158 if( strcmp( argv[i], "--sniffer" ) == 0 )
160 NGIRCd_Sniffer = true;
164 if( strcmp( argv[i], "--version" ) == 0 )
170 else if(( argv[i][0] == '-' ) && ( argv[i][1] != '-' ))
173 for( n = 1; n < strlen( argv[i] ); n++ )
177 if (argv[i][n] == 'd') {
182 if (argv[i][n] == 'f') {
183 if(( ! argv[i][n + 1] ) && ( i + 1 < argc ))
185 /* Ok, next character is a blank */
186 strlcpy( NGIRCd_ConfFile, argv[i + 1], sizeof( NGIRCd_ConfFile ));
188 /* go to the following parameter */
190 n = strlen( argv[i] );
195 if (argv[i][n] == 'h') {
197 puts(""); Show_Help(); puts("");
201 if (argv[i][n] == 'n') {
202 NGIRCd_NoDaemon = true;
205 if (argv[i][n] == 'p') {
206 NGIRCd_Passive = true;
210 if (argv[i][n] == 's') {
211 NGIRCd_Sniffer = true;
215 if (argv[i][n] == 't') {
220 if (argv[i][n] == 'V') {
226 printf( "%s: invalid option \"-%c\"!\n", PACKAGE_NAME, argv[i][n] );
227 printf( "Try \"%s --help\" for more information.\n", PACKAGE_NAME );
235 printf( "%s: invalid option \"%s\"!\n", PACKAGE_NAME, argv[i] );
236 printf( "Try \"%s --help\" for more information.\n", PACKAGE_NAME );
241 /* Debug-Level (for IRCs "VERSION" command) */
242 NGIRCd_DebugLevel[0] = '\0';
244 if( NGIRCd_Debug ) strcpy( NGIRCd_DebugLevel, "1" );
250 strcpy( NGIRCd_DebugLevel, "2" );
256 Show_Version( ); puts( "" );
260 while( ! NGIRCd_SignalQuit )
262 /* Initialize global variables */
263 NGIRCd_Start = time( NULL );
264 (void)strftime( NGIRCd_StartStr, 64, "%a %b %d %Y at %H:%M:%S (%Z)", localtime( &NGIRCd_Start ));
266 NGIRCd_SignalRehash = false;
267 NGIRCd_SignalRestart = false;
268 NGIRCd_SignalQuit = false;
270 /* Initialize modules, part I */
271 Log_Init( ! NGIRCd_NoDaemon );
274 /* Initialize the "main program": chroot environment, user and
276 if (!NGIRCd_Init(NGIRCd_NoDaemon)) {
277 Log(LOG_ALERT, "Fatal: Initialization failed");
281 /* Initialize modules, part II: these functions are eventually
282 * called with already dropped privileges ... */
291 /* Redirect stderr handle to "error file" for debugging
292 * when not running in "no daemon" mode: */
293 if( ! NGIRCd_NoDaemon ) Log_InitErrorfile( );
296 Initialize_Signal_Handler( );
299 * create protocol and server identification.
300 * The syntax used by ngIRCd in PASS commands and the extended flags
301 * are described in doc/Protocol.txt
304 snprintf( NGIRCd_ProtoID, sizeof NGIRCd_ProtoID, "%s%s %s|%s:%s", PROTOVER, PROTOIRCPLUS, PACKAGE_NAME, PACKAGE_VERSION, IRCPLUSFLAGS );
306 strcat( NGIRCd_ProtoID, "Z" );
308 if( Conf_OperCanMode ) strcat( NGIRCd_ProtoID, "o" );
310 snprintf( NGIRCd_ProtoID, sizeof NGIRCd_ProtoID, "%s%s %s|%s", PROTOVER, PROTOIRC, PACKAGE_NAME, PACKAGE_VERSION );
312 strlcat( NGIRCd_ProtoID, " P", sizeof NGIRCd_ProtoID );
314 strlcat( NGIRCd_ProtoID, "Z", sizeof NGIRCd_ProtoID );
316 LogDebug("Protocol and server ID is \"%s\".", NGIRCd_ProtoID);
318 Channel_InitPredefined( );
320 if( Conn_InitListeners( ) < 1 )
322 Log( LOG_ALERT, "Server isn't listening on a single port!" );
323 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
347 * Generate ngIRCd "version string".
348 * This string is generated once and then stored in NGIRCd_Version for
349 * further usage, for example by the IRC command VERSION and the --version
350 * command line switch.
355 NGIRCd_VersionAddition[0] = '\0';
358 strlcpy( NGIRCd_VersionAddition, "SYSLOG", sizeof NGIRCd_VersionAddition );
361 if( NGIRCd_VersionAddition[0] )
362 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
363 strlcat( NGIRCd_VersionAddition, "ZLIB", sizeof NGIRCd_VersionAddition );
366 if ( NGIRCd_VersionAddition[0] ) strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
367 strlcat( NGIRCd_VersionAddition, "SSL", sizeof NGIRCd_VersionAddition );
370 if( NGIRCd_VersionAddition[0] )
371 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
372 strlcat( NGIRCd_VersionAddition, "TCPWRAP", sizeof NGIRCd_VersionAddition );
375 if( NGIRCd_VersionAddition[0] )
376 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
377 strlcat( NGIRCd_VersionAddition, "ZEROCONF", sizeof NGIRCd_VersionAddition );
380 if( NGIRCd_VersionAddition[0] )
381 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
382 strlcat( NGIRCd_VersionAddition, "IDENT", sizeof NGIRCd_VersionAddition );
385 if (NGIRCd_VersionAddition[0])
386 strlcat(NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition);
387 strlcat(NGIRCd_VersionAddition, "PAM", sizeof NGIRCd_VersionAddition);
390 if( NGIRCd_VersionAddition[0] )
391 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
392 strlcat( NGIRCd_VersionAddition, "DEBUG", sizeof NGIRCd_VersionAddition );
395 if( NGIRCd_VersionAddition[0] )
396 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
397 strlcat( NGIRCd_VersionAddition, "SNIFFER", sizeof NGIRCd_VersionAddition );
400 if( NGIRCd_VersionAddition[0] )
401 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
402 strlcat( NGIRCd_VersionAddition, "RFC", sizeof NGIRCd_VersionAddition );
405 if( NGIRCd_VersionAddition[0] )
406 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
407 strlcat( NGIRCd_VersionAddition, "IRCPLUS", sizeof NGIRCd_VersionAddition );
410 if (NGIRCd_VersionAddition[0])
411 strlcat(NGIRCd_VersionAddition, "+", sizeof(NGIRCd_VersionAddition));
412 strlcat(NGIRCd_VersionAddition, "IPv6", sizeof(NGIRCd_VersionAddition));
414 if( NGIRCd_VersionAddition[0] )
415 strlcat( NGIRCd_VersionAddition, "-", sizeof( NGIRCd_VersionAddition ));
417 strlcat( NGIRCd_VersionAddition, TARGET_CPU, sizeof( NGIRCd_VersionAddition ));
418 strlcat( NGIRCd_VersionAddition, "/", sizeof( NGIRCd_VersionAddition ));
419 strlcat( NGIRCd_VersionAddition, TARGET_VENDOR, sizeof( NGIRCd_VersionAddition ));
420 strlcat( NGIRCd_VersionAddition, "/", sizeof( NGIRCd_VersionAddition ));
421 strlcat( NGIRCd_VersionAddition, TARGET_OS, sizeof( NGIRCd_VersionAddition ));
423 snprintf(NGIRCd_Version, sizeof NGIRCd_Version, "%s %s-%s",
424 PACKAGE_NAME, PACKAGE_VERSION, NGIRCd_VersionAddition);
429 * Reload the server configuration file.
432 NGIRCd_Rehash( void )
434 char old_name[CLIENT_ID_LEN];
435 unsigned old_nicklen;
437 Log( LOG_NOTICE|LOG_snotice, "Re-reading configuration NOW!" );
438 NGIRCd_SignalRehash = false;
440 /* Remember old server name and nick name length */
441 strlcpy( old_name, Conf_ServerName, sizeof old_name );
442 old_nicklen = Conf_MaxNickLength;
444 /* Re-read configuration ... */
448 /* Close down all listening sockets */
449 Conn_ExitListeners( );
451 /* Recover old server name and nick name length: these values can't
452 * be changed during run-time */
453 if (strcmp(old_name, Conf_ServerName) != 0 ) {
454 strlcpy(Conf_ServerName, old_name, sizeof Conf_ServerName);
455 Log(LOG_ERR, "Can't change \"ServerName\" on runtime! Ignored new name.");
457 if (old_nicklen != Conf_MaxNickLength) {
458 Conf_MaxNickLength = old_nicklen;
459 Log(LOG_ERR, "Can't change \"MaxNickLength\" on runtime! Ignored new value.");
462 /* Create new pre-defined channels */
463 Channel_InitPredefined( );
465 if (!ConnSSL_InitLibrary())
466 Log(LOG_WARNING, "Re-Initializing SSL failed, using old keys");
468 /* Start listening on sockets */
469 Conn_InitListeners( );
471 /* Sync configuration with established connections */
472 Conn_SyncServerStruct( );
474 Log( LOG_NOTICE|LOG_snotice, "Re-reading of configuration done." );
475 } /* NGIRCd_Rehash */
479 * Initialize the signal handler.
482 Initialize_Signal_Handler( void )
484 #ifdef HAVE_SIGACTION
485 struct sigaction saction;
487 memset( &saction, 0, sizeof( saction ));
488 saction.sa_handler = Signal_Handler;
490 saction.sa_flags |= SA_RESTART;
493 saction.sa_flags |= SA_NOCLDWAIT;
496 sigaction(SIGINT, &saction, NULL);
497 sigaction(SIGQUIT, &saction, NULL);
498 sigaction(SIGTERM, &saction, NULL);
499 sigaction(SIGHUP, &saction, NULL);
500 sigaction(SIGCHLD, &saction, NULL);
502 /* we handle write errors properly; ignore SIGPIPE */
503 saction.sa_handler = SIG_IGN;
504 sigaction(SIGPIPE, &saction, NULL);
506 signal(SIGINT, Signal_Handler);
507 signal(SIGQUIT, Signal_Handler);
508 signal(SIGTERM, Signal_Handler);
509 signal(SIGHUP, Signal_Handler);
510 signal(SIGCHLD, Signal_Handler);
512 signal(SIGPIPE, SIG_IGN);
514 } /* Initialize_Signal_Handler */
518 * Signal handler of ngIRCd.
519 * This function is called whenever ngIRCd catches a signal sent by the
520 * user and/or the system to it. For example SIGTERM and SIGHUP.
521 * @param Signal Number of the signal to handle.
524 Signal_Handler( int Signal )
531 /* shut down sever */
532 NGIRCd_SignalQuit = true;
535 /* re-read configuration */
536 NGIRCd_SignalRehash = true;
539 /* child-process exited, avoid zombies */
540 while (waitpid( -1, NULL, WNOHANG) > 0)
545 /* unbekanntes bzw. unbehandeltes Signal */
546 Log( LOG_DEBUG, "Got signal %d! Ignored.", Signal );
549 } /* Signal_Handler */
553 * Display copyright and version information of ngIRCd on the console.
558 puts( NGIRCd_Version );
559 puts( "Copyright (c)2001-2010 Alexander Barton (<alex@barton.de>) and Contributors." );
560 puts( "Homepage: <http://ngircd.barton.de/>\n" );
561 puts( "This is free software; see the source for copying conditions. There is NO" );
562 puts( "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." );
567 * Display a short help text on the console.
568 * This help depends on the configuration of the executable and only shows
569 * options that are actually enabled.
575 puts( " -d, --debug log extra debug messages" );
577 puts( " -f, --config <f> use file <f> as configuration file" );
578 puts( " -n, --nodaemon don't fork and don't detach from controlling terminal" );
579 puts( " -p, --passive disable automatic connections to other servers" );
581 puts( " -s, --sniffer enable network sniffer and display all IRC traffic" );
583 puts( " -t, --configtest read, validate and display configuration; then exit" );
584 puts( " -V, --version output version information and exit" );
585 puts( " -h, --help display this help and exit" );
590 * Delete the file containing the process ID (PID).
593 Pidfile_Delete( void )
595 /* Pidfile configured? */
596 if( ! Conf_PidFile[0] ) return;
599 Log( LOG_DEBUG, "Removing PID file (%s) ...", Conf_PidFile );
602 if( unlink( Conf_PidFile ))
603 Log( LOG_ERR, "Error unlinking PID file (%s): %s", Conf_PidFile, strerror( errno ));
604 } /* Pidfile_Delete */
608 * Create the file containing the process ID of ngIRCd ("PID file").
609 * @param pid The process ID to be stored in this file.
612 Pidfile_Create(pid_t pid)
618 /* Pidfile configured? */
619 if( ! Conf_PidFile[0] ) return;
622 Log( LOG_DEBUG, "Creating PID file (%s) ...", Conf_PidFile );
625 pidfd = open( Conf_PidFile, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
627 Log( LOG_ERR, "Error writing PID file (%s): %s", Conf_PidFile, strerror( errno ));
631 len = snprintf(pidbuf, sizeof pidbuf, "%ld\n", (long)pid);
632 if (len < 0 || len >= (int)sizeof pidbuf) {
633 Log( LOG_ERR, "Error converting pid");
637 if (write(pidfd, pidbuf, (size_t)len) != (ssize_t)len)
638 Log( LOG_ERR, "Can't write PID file (%s): %s", Conf_PidFile, strerror( errno ));
640 if( close(pidfd) != 0 )
641 Log( LOG_ERR, "Error closing PID file (%s): %s", Conf_PidFile, strerror( errno ));
642 } /* Pidfile_Create */
646 * Redirect stdin, stdout and stderr to apropriate file handles.
649 Setup_FDStreams( void )
653 /* Test if we can open /dev/null for reading and writing. If not
654 * we are most probably chrooted already and the server has been
655 * restarted. So we simply don't try to redirect stdXXX ... */
656 fd = open( "/dev/null", O_RDWR );
658 Log(LOG_WARNING, "Could not open /dev/null: %s", strerror(errno));
665 /* Create new stdin(0), stdout(1) and stderr(2) descriptors */
666 dup2( fd, 0 ); dup2( fd, 1 ); dup2( fd, 2 );
668 /* Close newly opened file descriptor if not stdin/out/err */
669 if( fd > 2 ) close( fd );
670 } /* Setup_FDStreams */
674 NGIRCd_getNobodyID(uid_t *uid, gid_t *gid )
680 * It can return EINVAL instead of EPERM
681 * so, if we are already unprivileged,
682 * use id of current user.
684 if (geteuid() && getuid()) {
691 pwd = getpwnam("nobody");
692 if (!pwd) return false;
694 if ( !pwd->pw_uid || !pwd->pw_gid)
706 NGIRCd_Init( bool NGIRCd_NoDaemon )
708 static bool initialized;
709 bool chrooted = false;
718 if (!ConnSSL_InitLibrary())
720 "Warning: Error during SSL initialization, continuing ...");
722 if( Conf_Chroot[0] ) {
723 if( chdir( Conf_Chroot ) != 0 ) {
724 Log( LOG_ERR, "Can't chdir() in ChrootDir (%s): %s", Conf_Chroot, strerror( errno ));
728 if( chroot( Conf_Chroot ) != 0 ) {
729 if (errno != EPERM) {
730 Log( LOG_ERR, "Can't change root directory to \"%s\": %s",
731 Conf_Chroot, strerror( errno ));
737 Log( LOG_INFO, "Changed root and working directory to \"%s\".", Conf_Chroot );
742 Log(LOG_INFO, "ServerUID must not be 0, using \"nobody\" instead.", Conf_UID);
744 if (! NGIRCd_getNobodyID(&Conf_UID, &Conf_GID)) {
745 Log(LOG_WARNING, "Could not get user/group ID of user \"nobody\": %s",
746 errno ? strerror(errno) : "not found" );
751 if (getgid() != Conf_GID) {
752 /* Change group ID */
753 if (setgid(Conf_GID) != 0) {
755 Log( LOG_ERR, "Can't change group ID to %u: %s", Conf_GID, strerror( errno ));
756 if (real_errno != EPERM)
761 if (getuid() != Conf_UID) {
763 if (setuid(Conf_UID) != 0) {
765 Log(LOG_ERR, "Can't change user ID to %u: %s", Conf_UID, strerror(errno));
766 if (real_errno != EPERM)
773 /* Normally a child process is forked which isn't any longer
774 * connected to ther controlling terminal. Use "--nodaemon"
775 * to disable this "daemon mode" (useful for debugging). */
776 if ( ! NGIRCd_NoDaemon ) {
779 /* "Old" process: exit. */
784 fprintf( stderr, "%s: Can't fork: %s!\nFatal error, exiting now ...\n",
785 PACKAGE_NAME, strerror( errno ));
789 /* New child process */
793 setpgrp(0, getpid());
795 if (chdir( "/" ) != 0)
796 Log(LOG_ERR, "Can't change directory to '/': %s",
799 /* Detach stdin, stdout and stderr */
804 Pidfile_Create( pid );
806 /* Check UID/GID we are running as, can be different from values
807 * configured (e. g. if we were already started with a UID>0. */
811 pwd = getpwuid( Conf_UID );
812 grp = getgrgid( Conf_GID );
814 Log(LOG_INFO, "Running as user %s(%ld), group %s(%ld), with PID %ld.",
815 pwd ? pwd->pw_name : "unknown", (long)Conf_UID,
816 grp ? grp->gr_name : "unknown", (long)Conf_GID, (long)pid);
819 Log(LOG_INFO, "Running with root directory \"%s\".",
823 Log(LOG_INFO, "Not running with changed root directory.");
825 /* Change working directory to home directory of the user
826 * we are running as (only when running in daemon mode and not in chroot) */
829 if (!NGIRCd_NoDaemon ) {
830 if( chdir( pwd->pw_dir ) == 0 )
831 Log( LOG_DEBUG, "Changed working directory to \"%s\" ...", pwd->pw_dir );
833 Log( LOG_INFO, "Notice: Can't change working directory to \"%s\": %s",
834 pwd->pw_dir, strerror( errno ));
837 Log( LOG_ERR, "Can't get user informaton for UID %d!?", Conf_UID );