2 * ngIRCd -- The Next Generation IRC Daemon
3 * Copyright (c)2001-2008 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)
54 #include "rendezvous.h"
61 static void Initialize_Signal_Handler PARAMS(( void ));
62 static void Signal_Handler PARAMS(( int Signal ));
64 static void Show_Version PARAMS(( void ));
65 static void Show_Help PARAMS(( void ));
67 static void Pidfile_Create PARAMS(( pid_t pid ));
68 static void Pidfile_Delete PARAMS(( void ));
70 static void Fill_Version PARAMS(( void ));
72 static void Setup_FDStreams PARAMS(( void ));
74 static bool NGIRCd_Init PARAMS(( bool ));
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.
85 main( int argc, const char *argv[] )
87 bool ok, configtest = false;
88 bool NGIRCd_NoDaemon = false;
92 #if defined(DEBUG) && defined(HAVE_MTRACE)
93 /* enable GNU libc memory tracing when running in debug mode
94 * and functionality available */
100 NGIRCd_SignalQuit = NGIRCd_SignalRestart = NGIRCd_SignalRehash = false;
101 NGIRCd_Passive = false;
103 NGIRCd_Debug = false;
106 NGIRCd_Sniffer = false;
108 strlcpy( NGIRCd_ConfFile, SYSCONFDIR, sizeof( NGIRCd_ConfFile ));
109 strlcat( NGIRCd_ConfFile, CONFIG_FILE, sizeof( NGIRCd_ConfFile ));
113 /* parse conmmand line */
114 for( i = 1; i < argc; i++ )
117 if(( argv[i][0] == '-' ) && ( argv[i][1] == '-' ))
120 if( strcmp( argv[i], "--config" ) == 0 )
124 /* Ok, there's an parameter left */
125 strlcpy( NGIRCd_ConfFile, argv[i + 1], sizeof( NGIRCd_ConfFile ));
131 if( strcmp( argv[i], "--configtest" ) == 0 )
137 if( strcmp( argv[i], "--debug" ) == 0 )
143 if( strcmp( argv[i], "--help" ) == 0 )
146 puts( "" ); Show_Help( ); puts( "" );
149 if( strcmp( argv[i], "--nodaemon" ) == 0 )
151 NGIRCd_NoDaemon = true;
154 if( strcmp( argv[i], "--passive" ) == 0 )
156 NGIRCd_Passive = true;
160 if( strcmp( argv[i], "--sniffer" ) == 0 )
162 NGIRCd_Sniffer = true;
166 if( strcmp( argv[i], "--version" ) == 0 )
172 else if(( argv[i][0] == '-' ) && ( argv[i][1] != '-' ))
175 for( n = 1; n < strlen( argv[i] ); n++ )
179 if (argv[i][n] == 'd') {
184 if (argv[i][n] == 'f') {
185 if(( ! argv[i][n + 1] ) && ( i + 1 < argc ))
187 /* Ok, next character is a blank */
188 strlcpy( NGIRCd_ConfFile, argv[i + 1], sizeof( NGIRCd_ConfFile ));
190 /* go to the following parameter */
192 n = strlen( argv[i] );
197 if (argv[i][n] == 'h') {
199 puts(""); Show_Help(); puts("");
203 if (argv[i][n] == 'n') {
204 NGIRCd_NoDaemon = true;
207 if (argv[i][n] == 'p') {
208 NGIRCd_Passive = true;
212 if (argv[i][n] == 's') {
213 NGIRCd_Sniffer = true;
217 if (argv[i][n] == 't') {
222 if (argv[i][n] == 'V') {
228 printf( "%s: invalid option \"-%c\"!\n", PACKAGE_NAME, argv[i][n] );
229 printf( "Try \"%s --help\" for more information.\n", PACKAGE_NAME );
237 printf( "%s: invalid option \"%s\"!\n", PACKAGE_NAME, argv[i] );
238 printf( "Try \"%s --help\" for more information.\n", PACKAGE_NAME );
243 /* Debug-Level (for IRCs "VERSION" command) */
244 NGIRCd_DebugLevel[0] = '\0';
246 if( NGIRCd_Debug ) strcpy( NGIRCd_DebugLevel, "1" );
252 strcpy( NGIRCd_DebugLevel, "2" );
258 Show_Version( ); puts( "" );
262 while( ! NGIRCd_SignalQuit )
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 ));
268 NGIRCd_SignalRehash = false;
269 NGIRCd_SignalRestart = false;
270 NGIRCd_SignalQuit = false;
272 /* Initialize modules, part I */
273 Log_Init( ! NGIRCd_NoDaemon );
276 /* Initialize the "main program": chroot environment, user and
278 if (!NGIRCd_Init(NGIRCd_NoDaemon)) {
279 Log(LOG_ALERT, "Fatal: Initialization failed");
283 /* Initialize modules, part II: these functions are eventually
284 * called with already dropped privileges ... */
293 /* Redirect stderr handle to "error file" for debugging
294 * when not running in "no daemon" mode: */
295 if( ! NGIRCd_NoDaemon ) Log_InitErrorfile( );
298 Initialize_Signal_Handler( );
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
306 snprintf( NGIRCd_ProtoID, sizeof NGIRCd_ProtoID, "%s%s %s|%s:%s", PROTOVER, PROTOIRCPLUS, PACKAGE_NAME, PACKAGE_VERSION, IRCPLUSFLAGS );
308 strcat( NGIRCd_ProtoID, "Z" );
310 if( Conf_OperCanMode ) strcat( NGIRCd_ProtoID, "o" );
312 snprintf( NGIRCd_ProtoID, sizeof NGIRCd_ProtoID, "%s%s %s|%s", PROTOVER, PROTOIRC, PACKAGE_NAME, PACKAGE_VERSION );
314 strlcat( NGIRCd_ProtoID, " P", sizeof NGIRCd_ProtoID );
316 strlcat( NGIRCd_ProtoID, "Z", sizeof NGIRCd_ProtoID );
318 LogDebug("Protocol and server ID is \"%s\".", NGIRCd_ProtoID);
320 Channel_InitPredefined( );
322 if( Conn_InitListeners( ) < 1 )
324 Log( LOG_ALERT, "Server isn't listening on a single port!" );
325 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
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.
357 NGIRCd_VersionAddition[0] = '\0';
360 strlcpy( NGIRCd_VersionAddition, "SYSLOG", sizeof NGIRCd_VersionAddition );
363 if( NGIRCd_VersionAddition[0] )
364 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
366 strlcat( NGIRCd_VersionAddition, "ZLIB", sizeof NGIRCd_VersionAddition );
369 if ( NGIRCd_VersionAddition[0] ) strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
370 strlcat( NGIRCd_VersionAddition, "SSL", sizeof NGIRCd_VersionAddition );
373 if( NGIRCd_VersionAddition[0] )
374 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
376 strlcat( NGIRCd_VersionAddition, "TCPWRAP", sizeof NGIRCd_VersionAddition );
379 if( NGIRCd_VersionAddition[0] )
380 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
382 strlcat( NGIRCd_VersionAddition, "ZEROCONF", sizeof NGIRCd_VersionAddition );
385 if( NGIRCd_VersionAddition[0] )
386 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
388 strlcat( NGIRCd_VersionAddition, "IDENT", sizeof NGIRCd_VersionAddition );
391 if( NGIRCd_VersionAddition[0] )
392 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
394 strlcat( NGIRCd_VersionAddition, "DEBUG", sizeof NGIRCd_VersionAddition );
397 if( NGIRCd_VersionAddition[0] )
398 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
400 strlcat( NGIRCd_VersionAddition, "SNIFFER", sizeof NGIRCd_VersionAddition );
403 if( NGIRCd_VersionAddition[0] )
404 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
406 strlcat( NGIRCd_VersionAddition, "RFC", sizeof NGIRCd_VersionAddition );
409 if( NGIRCd_VersionAddition[0] )
410 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
412 strlcat( NGIRCd_VersionAddition, "IRCPLUS", sizeof NGIRCd_VersionAddition );
415 if (NGIRCd_VersionAddition[0])
416 strlcat(NGIRCd_VersionAddition, "+", sizeof(NGIRCd_VersionAddition));
418 strlcat(NGIRCd_VersionAddition, "IPv6", sizeof(NGIRCd_VersionAddition));
420 if( NGIRCd_VersionAddition[0] )
421 strlcat( NGIRCd_VersionAddition, "-", sizeof( NGIRCd_VersionAddition ));
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 ));
429 snprintf(NGIRCd_Version, sizeof NGIRCd_Version, "%s %s-%s",
430 PACKAGE_NAME, PACKAGE_VERSION, NGIRCd_VersionAddition);
435 * Reload the server configuration file.
438 NGIRCd_Rehash( void )
440 char old_name[CLIENT_ID_LEN];
441 unsigned old_nicklen;
443 Log( LOG_NOTICE|LOG_snotice, "Re-reading configuration NOW!" );
444 NGIRCd_SignalRehash = false;
446 /* Remember old server name and nick name length */
447 strlcpy( old_name, Conf_ServerName, sizeof old_name );
448 old_nicklen = Conf_MaxNickLength;
450 /* Re-read configuration ... */
454 /* Close down all listening sockets */
455 Conn_ExitListeners( );
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.");
463 if (old_nicklen != Conf_MaxNickLength) {
464 Conf_MaxNickLength = old_nicklen;
465 Log(LOG_ERR, "Can't change \"MaxNickLength\" on runtime! Ignored new value.");
468 /* Create new pre-defined channels */
469 Channel_InitPredefined( );
471 if (!ConnSSL_InitLibrary())
472 Log(LOG_WARNING, "Re-Initializing SSL failed, using old keys");
474 /* Start listening on sockets */
475 Conn_InitListeners( );
477 /* Sync configuration with established connections */
478 Conn_SyncServerStruct( );
480 Log( LOG_NOTICE|LOG_snotice, "Re-reading of configuration done." );
481 } /* NGIRCd_Rehash */
485 * Initialize the signal handler.
488 Initialize_Signal_Handler( void )
490 #ifdef HAVE_SIGACTION
491 struct sigaction saction;
493 memset( &saction, 0, sizeof( saction ));
494 saction.sa_handler = Signal_Handler;
496 saction.sa_flags |= SA_RESTART;
499 saction.sa_flags |= SA_NOCLDWAIT;
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);
508 /* we handle write errors properly; ignore SIGPIPE */
509 saction.sa_handler = SIG_IGN;
510 sigaction(SIGPIPE, &saction, NULL);
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);
518 signal(SIGPIPE, SIG_IGN);
520 } /* Initialize_Signal_Handler */
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.
530 Signal_Handler( int Signal )
537 /* shut down sever */
538 NGIRCd_SignalQuit = true;
541 /* re-read configuration */
542 NGIRCd_SignalRehash = true;
545 /* child-process exited, avoid zombies */
546 while (waitpid( -1, NULL, WNOHANG) > 0)
551 /* unbekanntes bzw. unbehandeltes Signal */
552 Log( LOG_DEBUG, "Got signal %d! Ignored.", Signal );
555 } /* Signal_Handler */
559 * Display copyright and version information of ngIRCd on the console.
564 puts( NGIRCd_Version );
565 puts( "Copyright (c)2001-2008 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." );
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.
581 puts( " -d, --debug log extra debug messages" );
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" );
587 puts( " -s, --sniffer enable network sniffer and display all IRC traffic" );
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" );
596 * Delete the file containing the process ID (PID).
599 Pidfile_Delete( void )
601 /* Pidfile configured? */
602 if( ! Conf_PidFile[0] ) return;
605 Log( LOG_DEBUG, "Removing PID file (%s) ...", Conf_PidFile );
608 if( unlink( Conf_PidFile ))
609 Log( LOG_ERR, "Error unlinking PID file (%s): %s", Conf_PidFile, strerror( errno ));
610 } /* Pidfile_Delete */
614 * Create the file containing the process ID of ngIRCd ("PID file").
615 * @param pid The process ID to be stored in this file.
618 Pidfile_Create(pid_t pid)
624 /* Pidfile configured? */
625 if( ! Conf_PidFile[0] ) return;
628 Log( LOG_DEBUG, "Creating PID file (%s) ...", Conf_PidFile );
631 pidfd = open( Conf_PidFile, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
633 Log( LOG_ERR, "Error writing PID file (%s): %s", Conf_PidFile, strerror( errno ));
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");
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 ));
646 if( close(pidfd) != 0 )
647 Log( LOG_ERR, "Error closing PID file (%s): %s", Conf_PidFile, strerror( errno ));
648 } /* Pidfile_Create */
652 * Redirect stdin, stdout and stderr to apropriate file handles.
655 Setup_FDStreams( void )
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 );
664 Log(LOG_WARNING, "Could not open /dev/null: %s", strerror(errno));
671 /* Create new stdin(0), stdout(1) and stderr(2) descriptors */
672 dup2( fd, 0 ); dup2( fd, 1 ); dup2( fd, 2 );
674 /* Close newly opened file descriptor if not stdin/out/err */
675 if( fd > 2 ) close( fd );
676 } /* Setup_FDStreams */
680 NGIRCd_getNobodyID(uid_t *uid, gid_t *gid )
686 * It can return EINVAL instead of EPERM
687 * so, if we are already unprivileged,
688 * use id of current user.
690 if (geteuid() && getuid()) {
697 pwd = getpwnam("nobody");
698 if (!pwd) return false;
700 if ( !pwd->pw_uid || !pwd->pw_gid)
712 NGIRCd_Init( bool NGIRCd_NoDaemon )
714 static bool initialized;
715 bool chrooted = false;
724 if (!ConnSSL_InitLibrary())
726 "Warning: Error during SSL initialization, continuing ...");
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 ));
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 ));
743 Log( LOG_INFO, "Changed root and working directory to \"%s\".", Conf_Chroot );
748 Log(LOG_INFO, "ServerUID must not be 0, using \"nobody\" instead.", Conf_UID);
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" );
757 if (getgid() != Conf_GID) {
758 /* Change group ID */
759 if (setgid(Conf_GID) != 0) {
761 Log( LOG_ERR, "Can't change group ID to %u: %s", Conf_GID, strerror( errno ));
762 if (real_errno != EPERM)
767 if (getuid() != Conf_UID) {
769 if (setuid(Conf_UID) != 0) {
771 Log(LOG_ERR, "Can't change user ID to %u: %s", Conf_UID, strerror(errno));
772 if (real_errno != EPERM)
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 ) {
785 /* "Old" process: exit. */
790 fprintf( stderr, "%s: Can't fork: %s!\nFatal error, exiting now ...\n",
791 PACKAGE_NAME, strerror( errno ));
795 /* New child process */
799 setpgrp(0, getpid());
803 /* Detach stdin, stdout and stderr */
808 Pidfile_Create( pid );
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. */
815 pwd = getpwuid( Conf_UID );
816 grp = getgrgid( Conf_GID );
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);
823 Log(LOG_INFO, "Running with root directory \"%s\".",
827 Log(LOG_INFO, "Not running with changed root directory.");
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) */
833 if (!NGIRCd_NoDaemon ) {
834 if( chdir( pwd->pw_dir ) == 0 )
835 Log( LOG_DEBUG, "Changed working directory to \"%s\" ...", pwd->pw_dir );
837 Log( LOG_INFO, "Notice: Can't change working directory to \"%s\": %s",
838 pwd->pw_dir, strerror( errno ));
841 Log( LOG_ERR, "Can't get user informaton for UID %d!?", Conf_UID );