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)
53 #include "rendezvous.h"
60 static void Initialize_Signal_Handler PARAMS(( void ));
61 static void Signal_Handler PARAMS(( int Signal ));
63 static void Show_Version PARAMS(( void ));
64 static void Show_Help PARAMS(( void ));
66 static void Pidfile_Create PARAMS(( pid_t pid ));
67 static void Pidfile_Delete PARAMS(( void ));
69 static void Fill_Version PARAMS(( void ));
71 static void Setup_FDStreams PARAMS(( void ));
73 static bool NGIRCd_Init PARAMS(( bool ));
76 * The main() function of ngIRCd.
77 * Here all starts: this function is called by the operating system loader,
78 * it is the first portion of code executed of ngIRCd.
79 * @param argc The number of arguments passed to ngIRCd on the command line.
80 * @param argv An array containing all the arguments passed to ngIRCd.
81 * @return Global exit code of ngIRCd, zero on success.
84 main( int argc, const char *argv[] )
86 bool ok, configtest = false;
87 bool NGIRCd_NoDaemon = false;
91 #if defined(DEBUG) && defined(HAVE_MTRACE)
92 /* enable GNU libc memory tracing when running in debug mode
93 * and functionality available */
99 NGIRCd_SignalQuit = NGIRCd_SignalRestart = NGIRCd_SignalRehash = false;
100 NGIRCd_Passive = false;
102 NGIRCd_Debug = false;
105 NGIRCd_Sniffer = false;
107 strlcpy( NGIRCd_ConfFile, SYSCONFDIR, sizeof( NGIRCd_ConfFile ));
108 strlcat( NGIRCd_ConfFile, CONFIG_FILE, sizeof( NGIRCd_ConfFile ));
112 /* parse conmmand line */
113 for( i = 1; i < argc; i++ )
116 if(( argv[i][0] == '-' ) && ( argv[i][1] == '-' ))
119 if( strcmp( argv[i], "--config" ) == 0 )
123 /* Ok, there's an parameter left */
124 strlcpy( NGIRCd_ConfFile, argv[i + 1], sizeof( NGIRCd_ConfFile ));
130 if( strcmp( argv[i], "--configtest" ) == 0 )
136 if( strcmp( argv[i], "--debug" ) == 0 )
142 if( strcmp( argv[i], "--help" ) == 0 )
145 puts( "" ); Show_Help( ); puts( "" );
148 if( strcmp( argv[i], "--nodaemon" ) == 0 )
150 NGIRCd_NoDaemon = true;
153 if( strcmp( argv[i], "--passive" ) == 0 )
155 NGIRCd_Passive = true;
159 if( strcmp( argv[i], "--sniffer" ) == 0 )
161 NGIRCd_Sniffer = true;
165 if( strcmp( argv[i], "--version" ) == 0 )
171 else if(( argv[i][0] == '-' ) && ( argv[i][1] != '-' ))
174 for( n = 1; n < strlen( argv[i] ); n++ )
178 if (argv[i][n] == 'd') {
183 if (argv[i][n] == 'f') {
184 if(( ! argv[i][n + 1] ) && ( i + 1 < argc ))
186 /* Ok, next character is a blank */
187 strlcpy( NGIRCd_ConfFile, argv[i + 1], sizeof( NGIRCd_ConfFile ));
189 /* go to the following parameter */
191 n = strlen( argv[i] );
196 if (argv[i][n] == 'h') {
198 puts(""); Show_Help(); puts("");
202 if (argv[i][n] == 'n') {
203 NGIRCd_NoDaemon = true;
206 if (argv[i][n] == 'p') {
207 NGIRCd_Passive = true;
211 if (argv[i][n] == 's') {
212 NGIRCd_Sniffer = true;
216 if (argv[i][n] == 't') {
221 if (argv[i][n] == 'V') {
227 printf( "%s: invalid option \"-%c\"!\n", PACKAGE_NAME, argv[i][n] );
228 printf( "Try \"%s --help\" for more information.\n", PACKAGE_NAME );
236 printf( "%s: invalid option \"%s\"!\n", PACKAGE_NAME, argv[i] );
237 printf( "Try \"%s --help\" for more information.\n", PACKAGE_NAME );
242 /* Debug-Level (for IRCs "VERSION" command) */
243 NGIRCd_DebugLevel[0] = '\0';
245 if( NGIRCd_Debug ) strcpy( NGIRCd_DebugLevel, "1" );
251 strcpy( NGIRCd_DebugLevel, "2" );
257 Show_Version( ); puts( "" );
261 while( ! NGIRCd_SignalQuit )
263 /* Initialize global variables */
264 NGIRCd_Start = time( NULL );
265 (void)strftime( NGIRCd_StartStr, 64, "%a %b %d %Y at %H:%M:%S (%Z)", localtime( &NGIRCd_Start ));
267 NGIRCd_SignalRehash = false;
268 NGIRCd_SignalRestart = false;
269 NGIRCd_SignalQuit = false;
271 /* Initialize modules, part I */
272 Log_Init( ! NGIRCd_NoDaemon );
275 /* Initialize the "main program": chroot environment, user and
277 if (!NGIRCd_Init(NGIRCd_NoDaemon)) {
278 Log(LOG_ALERT, "Fatal: Initialization failed");
282 /* Initialize modules, part II: these functions are eventually
283 * called with already dropped privileges ... */
292 /* Redirect stderr handle to "error file" for debugging
293 * when not running in "no daemon" mode: */
294 if( ! NGIRCd_NoDaemon ) Log_InitErrorfile( );
297 Initialize_Signal_Handler( );
300 * create protocol and server identification.
301 * The syntax used by ngIRCd in PASS commands and the extended flags
302 * are described in doc/Protocol.txt
305 snprintf( NGIRCd_ProtoID, sizeof NGIRCd_ProtoID, "%s%s %s|%s:%s", PROTOVER, PROTOIRCPLUS, PACKAGE_NAME, PACKAGE_VERSION, IRCPLUSFLAGS );
307 strcat( NGIRCd_ProtoID, "Z" );
309 if( Conf_OperCanMode ) strcat( NGIRCd_ProtoID, "o" );
311 snprintf( NGIRCd_ProtoID, sizeof NGIRCd_ProtoID, "%s%s %s|%s", PROTOVER, PROTOIRC, PACKAGE_NAME, PACKAGE_VERSION );
313 strlcat( NGIRCd_ProtoID, " P", sizeof NGIRCd_ProtoID );
315 strlcat( NGIRCd_ProtoID, "Z", sizeof NGIRCd_ProtoID );
317 LogDebug("Protocol and server ID is \"%s\".", NGIRCd_ProtoID);
319 Channel_InitPredefined( );
321 if( Conn_InitListeners( ) < 1 )
323 Log( LOG_ALERT, "Server isn't listening on a single port!" );
324 Log( LOG_ALERT, "%s exiting due to fatal errors!", PACKAGE_NAME );
348 * Generate ngIRCd "version string".
349 * This string is generated once and then stored in NGIRCd_Version for
350 * further usage, for example by the IRC command VERSION and the --version
351 * command line switch.
356 NGIRCd_VersionAddition[0] = '\0';
359 strlcpy( NGIRCd_VersionAddition, "SYSLOG", sizeof NGIRCd_VersionAddition );
362 if( NGIRCd_VersionAddition[0] )
363 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
365 strlcat( NGIRCd_VersionAddition, "ZLIB", sizeof NGIRCd_VersionAddition );
368 if ( NGIRCd_VersionAddition[0] ) strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
369 strlcat( NGIRCd_VersionAddition, "SSL", sizeof NGIRCd_VersionAddition );
372 if( NGIRCd_VersionAddition[0] )
373 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
375 strlcat( NGIRCd_VersionAddition, "TCPWRAP", sizeof NGIRCd_VersionAddition );
378 if( NGIRCd_VersionAddition[0] )
379 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
381 strlcat( NGIRCd_VersionAddition, "ZEROCONF", sizeof NGIRCd_VersionAddition );
384 if( NGIRCd_VersionAddition[0] )
385 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
387 strlcat( NGIRCd_VersionAddition, "IDENT", sizeof NGIRCd_VersionAddition );
390 if( NGIRCd_VersionAddition[0] )
391 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
393 strlcat( NGIRCd_VersionAddition, "DEBUG", sizeof NGIRCd_VersionAddition );
396 if( NGIRCd_VersionAddition[0] )
397 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
399 strlcat( NGIRCd_VersionAddition, "SNIFFER", sizeof NGIRCd_VersionAddition );
402 if( NGIRCd_VersionAddition[0] )
403 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
405 strlcat( NGIRCd_VersionAddition, "RFC", sizeof NGIRCd_VersionAddition );
408 if( NGIRCd_VersionAddition[0] )
409 strlcat( NGIRCd_VersionAddition, "+", sizeof NGIRCd_VersionAddition );
411 strlcat( NGIRCd_VersionAddition, "IRCPLUS", sizeof NGIRCd_VersionAddition );
414 if (NGIRCd_VersionAddition[0])
415 strlcat(NGIRCd_VersionAddition, "+", sizeof(NGIRCd_VersionAddition));
417 strlcat(NGIRCd_VersionAddition, "IPv6", sizeof(NGIRCd_VersionAddition));
419 if( NGIRCd_VersionAddition[0] )
420 strlcat( NGIRCd_VersionAddition, "-", sizeof( NGIRCd_VersionAddition ));
422 strlcat( NGIRCd_VersionAddition, TARGET_CPU, sizeof( NGIRCd_VersionAddition ));
423 strlcat( NGIRCd_VersionAddition, "/", sizeof( NGIRCd_VersionAddition ));
424 strlcat( NGIRCd_VersionAddition, TARGET_VENDOR, sizeof( NGIRCd_VersionAddition ));
425 strlcat( NGIRCd_VersionAddition, "/", sizeof( NGIRCd_VersionAddition ));
426 strlcat( NGIRCd_VersionAddition, TARGET_OS, sizeof( NGIRCd_VersionAddition ));
428 snprintf(NGIRCd_Version, sizeof NGIRCd_Version, "%s %s-%s",
429 PACKAGE_NAME, PACKAGE_VERSION, NGIRCd_VersionAddition);
434 * Reload the server configuration file.
437 NGIRCd_Rehash( void )
439 char old_name[CLIENT_ID_LEN];
440 unsigned old_nicklen;
442 Log( LOG_NOTICE|LOG_snotice, "Re-reading configuration NOW!" );
443 NGIRCd_SignalRehash = false;
445 /* Remember old server name and nick name length */
446 strlcpy( old_name, Conf_ServerName, sizeof old_name );
447 old_nicklen = Conf_MaxNickLength;
449 /* Re-read configuration ... */
453 /* Close down all listening sockets */
454 Conn_ExitListeners( );
456 /* Recover old server name and nick name length: these values can't
457 * be changed during run-time */
458 if (strcmp(old_name, Conf_ServerName) != 0 ) {
459 strlcpy(Conf_ServerName, old_name, sizeof Conf_ServerName);
460 Log(LOG_ERR, "Can't change \"ServerName\" on runtime! Ignored new name.");
462 if (old_nicklen != Conf_MaxNickLength) {
463 Conf_MaxNickLength = old_nicklen;
464 Log(LOG_ERR, "Can't change \"MaxNickLength\" on runtime! Ignored new value.");
467 /* Create new pre-defined channels */
468 Channel_InitPredefined( );
470 if (!ConnSSL_InitLibrary())
471 Log(LOG_WARNING, "Re-Initializing SSL failed, using old keys");
473 /* Start listening on sockets */
474 Conn_InitListeners( );
476 /* Sync configuration with established connections */
477 Conn_SyncServerStruct( );
479 Log( LOG_NOTICE|LOG_snotice, "Re-reading of configuration done." );
480 } /* NGIRCd_Rehash */
484 * Initialize the signal handler.
487 Initialize_Signal_Handler( void )
489 #ifdef HAVE_SIGACTION
490 struct sigaction saction;
492 memset( &saction, 0, sizeof( saction ));
493 saction.sa_handler = Signal_Handler;
495 saction.sa_flags |= SA_RESTART;
498 saction.sa_flags |= SA_NOCLDWAIT;
501 sigaction(SIGINT, &saction, NULL);
502 sigaction(SIGQUIT, &saction, NULL);
503 sigaction(SIGTERM, &saction, NULL);
504 sigaction(SIGHUP, &saction, NULL);
505 sigaction(SIGCHLD, &saction, NULL);
507 /* we handle write errors properly; ignore SIGPIPE */
508 saction.sa_handler = SIG_IGN;
509 sigaction(SIGPIPE, &saction, NULL);
511 signal(SIGINT, Signal_Handler);
512 signal(SIGQUIT, Signal_Handler);
513 signal(SIGTERM, Signal_Handler);
514 signal(SIGHUP, Signal_Handler);
515 signal(SIGCHLD, Signal_Handler);
517 signal(SIGPIPE, SIG_IGN);
519 } /* Initialize_Signal_Handler */
523 * Signal handler of ngIRCd.
524 * This function is called whenever ngIRCd catches a signal sent by the
525 * user and/or the system to it. For example SIGTERM and SIGHUP.
526 * @param Signal Number of the signal to handle.
529 Signal_Handler( int Signal )
536 /* shut down sever */
537 NGIRCd_SignalQuit = true;
540 /* re-read configuration */
541 NGIRCd_SignalRehash = true;
544 /* child-process exited, avoid zombies */
545 while (waitpid( -1, NULL, WNOHANG) > 0)
550 /* unbekanntes bzw. unbehandeltes Signal */
551 Log( LOG_DEBUG, "Got signal %d! Ignored.", Signal );
554 } /* Signal_Handler */
558 * Display copyright and version information of ngIRCd on the console.
563 puts( NGIRCd_Version );
564 puts( "Copyright (c)2001-2010 Alexander Barton (<alex@barton.de>) and Contributors." );
565 puts( "Homepage: <http://ngircd.barton.de/>\n" );
566 puts( "This is free software; see the source for copying conditions. There is NO" );
567 puts( "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." );
572 * Display a short help text on the console.
573 * This help depends on the configuration of the executable and only shows
574 * options that are actually enabled.
580 puts( " -d, --debug log extra debug messages" );
582 puts( " -f, --config <f> use file <f> as configuration file" );
583 puts( " -n, --nodaemon don't fork and don't detach from controlling terminal" );
584 puts( " -p, --passive disable automatic connections to other servers" );
586 puts( " -s, --sniffer enable network sniffer and display all IRC traffic" );
588 puts( " -t, --configtest read, validate and display configuration; then exit" );
589 puts( " -V, --version output version information and exit" );
590 puts( " -h, --help display this help and exit" );
595 * Delete the file containing the process ID (PID).
598 Pidfile_Delete( void )
600 /* Pidfile configured? */
601 if( ! Conf_PidFile[0] ) return;
604 Log( LOG_DEBUG, "Removing PID file (%s) ...", Conf_PidFile );
607 if( unlink( Conf_PidFile ))
608 Log( LOG_ERR, "Error unlinking PID file (%s): %s", Conf_PidFile, strerror( errno ));
609 } /* Pidfile_Delete */
613 * Create the file containing the process ID of ngIRCd ("PID file").
614 * @param pid The process ID to be stored in this file.
617 Pidfile_Create(pid_t pid)
623 /* Pidfile configured? */
624 if( ! Conf_PidFile[0] ) return;
627 Log( LOG_DEBUG, "Creating PID file (%s) ...", Conf_PidFile );
630 pidfd = open( Conf_PidFile, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
632 Log( LOG_ERR, "Error writing PID file (%s): %s", Conf_PidFile, strerror( errno ));
636 len = snprintf(pidbuf, sizeof pidbuf, "%ld\n", (long)pid);
637 if (len < 0 || len >= (int)sizeof pidbuf) {
638 Log( LOG_ERR, "Error converting pid");
642 if (write(pidfd, pidbuf, (size_t)len) != (ssize_t)len)
643 Log( LOG_ERR, "Can't write PID file (%s): %s", Conf_PidFile, strerror( errno ));
645 if( close(pidfd) != 0 )
646 Log( LOG_ERR, "Error closing PID file (%s): %s", Conf_PidFile, strerror( errno ));
647 } /* Pidfile_Create */
651 * Redirect stdin, stdout and stderr to apropriate file handles.
654 Setup_FDStreams( void )
658 /* Test if we can open /dev/null for reading and writing. If not
659 * we are most probably chrooted already and the server has been
660 * restarted. So we simply don't try to redirect stdXXX ... */
661 fd = open( "/dev/null", O_RDWR );
663 Log(LOG_WARNING, "Could not open /dev/null: %s", strerror(errno));
670 /* Create new stdin(0), stdout(1) and stderr(2) descriptors */
671 dup2( fd, 0 ); dup2( fd, 1 ); dup2( fd, 2 );
673 /* Close newly opened file descriptor if not stdin/out/err */
674 if( fd > 2 ) close( fd );
675 } /* Setup_FDStreams */
679 NGIRCd_getNobodyID(uid_t *uid, gid_t *gid )
685 * It can return EINVAL instead of EPERM
686 * so, if we are already unprivileged,
687 * use id of current user.
689 if (geteuid() && getuid()) {
696 pwd = getpwnam("nobody");
697 if (!pwd) return false;
699 if ( !pwd->pw_uid || !pwd->pw_gid)
711 NGIRCd_Init( bool NGIRCd_NoDaemon )
713 static bool initialized;
714 bool chrooted = false;
723 if (!ConnSSL_InitLibrary())
725 "Warning: Error during SSL initialization, continuing ...");
727 if( Conf_Chroot[0] ) {
728 if( chdir( Conf_Chroot ) != 0 ) {
729 Log( LOG_ERR, "Can't chdir() in ChrootDir (%s): %s", Conf_Chroot, strerror( errno ));
733 if( chroot( Conf_Chroot ) != 0 ) {
734 if (errno != EPERM) {
735 Log( LOG_ERR, "Can't change root directory to \"%s\": %s",
736 Conf_Chroot, strerror( errno ));
742 Log( LOG_INFO, "Changed root and working directory to \"%s\".", Conf_Chroot );
747 Log(LOG_INFO, "ServerUID must not be 0, using \"nobody\" instead.", Conf_UID);
749 if (! NGIRCd_getNobodyID(&Conf_UID, &Conf_GID)) {
750 Log(LOG_WARNING, "Could not get user/group ID of user \"nobody\": %s",
751 errno ? strerror(errno) : "not found" );
756 if (getgid() != Conf_GID) {
757 /* Change group ID */
758 if (setgid(Conf_GID) != 0) {
760 Log( LOG_ERR, "Can't change group ID to %u: %s", Conf_GID, strerror( errno ));
761 if (real_errno != EPERM)
766 if (getuid() != Conf_UID) {
768 if (setuid(Conf_UID) != 0) {
770 Log(LOG_ERR, "Can't change user ID to %u: %s", Conf_UID, strerror(errno));
771 if (real_errno != EPERM)
778 /* Normally a child process is forked which isn't any longer
779 * connected to ther controlling terminal. Use "--nodaemon"
780 * to disable this "daemon mode" (useful for debugging). */
781 if ( ! NGIRCd_NoDaemon ) {
784 /* "Old" process: exit. */
789 fprintf( stderr, "%s: Can't fork: %s!\nFatal error, exiting now ...\n",
790 PACKAGE_NAME, strerror( errno ));
794 /* New child process */
798 setpgrp(0, getpid());
800 if (chdir( "/" ) != 0)
801 Log(LOG_ERR, "Can't change directory to '/': %s",
804 /* Detach stdin, stdout and stderr */
809 Pidfile_Create( pid );
811 /* Check UID/GID we are running as, can be different from values
812 * configured (e. g. if we were already started with a UID>0. */
816 pwd = getpwuid( Conf_UID );
817 grp = getgrgid( Conf_GID );
819 Log(LOG_INFO, "Running as user %s(%ld), group %s(%ld), with PID %ld.",
820 pwd ? pwd->pw_name : "unknown", (long)Conf_UID,
821 grp ? grp->gr_name : "unknown", (long)Conf_GID, (long)pid);
824 Log(LOG_INFO, "Running with root directory \"%s\".",
828 Log(LOG_INFO, "Not running with changed root directory.");
830 /* Change working directory to home directory of the user
831 * we are running as (only when running in daemon mode and not in chroot) */
834 if (!NGIRCd_NoDaemon ) {
835 if( chdir( pwd->pw_dir ) == 0 )
836 Log( LOG_DEBUG, "Changed working directory to \"%s\" ...", pwd->pw_dir );
838 Log( LOG_INFO, "Notice: Can't change working directory to \"%s\": %s",
839 pwd->pw_dir, strerror( errno ));
842 Log( LOG_ERR, "Can't get user informaton for UID %d!?", Conf_UID );