2 * IRC - Internet Relay Chat, ircd/ircd.c
3 * Copyright (C) 1990 Jarkko Oikarinen and
4 * University of Oulu, Computing Center
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 1, or (at your option)
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 * @brief Entry point and other initialization functions for the daemon.
31 #include "destruct_event.h"
33 #include "ircd_alloc.h"
34 #include "ircd_events.h"
35 #include "ircd_features.h"
37 #include "ircd_reply.h"
38 #include "ircd_signal.h"
39 #include "ircd_string.h"
40 #include "ircd_crypt.h"
72 #include <sys/socket.h>
74 #include <sys/types.h>
79 /*----------------------------------------------------------------------------
81 *--------------------------------------------------------------------------*/
82 extern void init_counters(void);
83 extern void mem_dbg_initialise(void);
85 /*----------------------------------------------------------------------------
87 *--------------------------------------------------------------------------*/
89 BOOT_DEBUG = 1, /**< Enable debug output. */
90 BOOT_TTY = 2, /**< Stay connected to TTY. */
91 BOOT_CHKCONF = 4 /**< Exit after reading configuration file. */
95 /*----------------------------------------------------------------------------
97 *--------------------------------------------------------------------------*/
98 struct Client me; /**< That's me */
99 struct Connection me_con; /**< That's me too */
100 struct Client *GlobalClientList = &me; /**< Pointer to beginning of
102 time_t TSoffset = 0; /**< Offset of timestamps to system clock */
103 int GlobalRehashFlag = 0; /**< do a rehash if set */
104 int GlobalRestartFlag = 0; /**< do a restart if set */
105 time_t CurrentTime; /**< Updated every time we leave select() */
107 char *configfile = CPATH; /**< Server configuration file */
108 int debuglevel = -1; /**< Server debug level */
109 char *debugmode = ""; /**< Server debug level */
110 static char *dpath = DPATH; /**< Working directory for daemon */
112 static struct Timer connect_timer; /**< timer structure for try_connections() */
113 static struct Timer ping_timer; /**< timer structure for check_pings() */
114 static struct Timer destruct_event_timer; /**< timer structure for exec_expired_destruct_events() */
116 /** Daemon information. */
117 static struct Daemon thisServer = { 0, 0, 0, 0, 0, 0, -1 };
119 /** Non-zero until we want to exit. */
123 /*----------------------------------------------------------------------------
125 *--------------------------------------------------------------------------*/
126 /** Terminate the server with a message.
127 * @param[in] message Message to log and send to operators.
129 void server_die(const char *message)
131 /* log_write will send out message to both log file and as server notice */
132 log_write(LS_SYSTEM, L_CRIT, 0, "Server terminating: %s", message);
133 flush_connections(0);
134 close_connections(1);
138 /*----------------------------------------------------------------------------
140 *--------------------------------------------------------------------------*/
141 /** Immediately terminate the server with a message.
142 * @param[in] message Message to log, but not send to operators.
144 void server_panic(const char *message)
146 /* inhibit sending server notice--we may be panicing due to low memory */
147 log_write(LS_SYSTEM, L_CRIT, LOG_NOSNOTICE, "Server panic: %s", message);
148 flush_connections(0);
150 close_connections(1);
154 /*----------------------------------------------------------------------------
155 * API: server_restart
156 *--------------------------------------------------------------------------*/
157 /** Restart the server with a message.
158 * @param[in] message Message to log and send to operators.
160 void server_restart(const char *message)
162 static int restarting = 0;
164 /* inhibit sending any server notices; we may be in a loop */
165 log_write(LS_SYSTEM, L_WARNING, LOG_NOSNOTICE, "Restarting Server: %s",
167 if (restarting++) /* increment restarting to prevent looping */
170 sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
171 Debug((DEBUG_NOTICE, "Restarting server..."));
172 flush_connections(0);
176 close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG | BOOT_CHKCONF)));
178 execv(SPATH, thisServer.argv);
180 /* Have to reopen since it has been closed above */
183 log_write(LS_SYSTEM, L_CRIT, 0, "execv(%s,%s) failed: %m", SPATH,
186 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
187 SPATH, (strerror(errno)) ? strerror(errno) : ""));
192 /*----------------------------------------------------------------------------
193 * outofmemory: Handler for out of memory conditions...
194 *--------------------------------------------------------------------------*/
195 /** Handle out-of-memory condition. */
196 static void outofmemory(void) {
197 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
198 server_restart("Out of Memory");
202 /*----------------------------------------------------------------------------
204 *--------------------------------------------------------------------------*/
205 /** Write process ID to PID file. */
206 static void write_pidfile(void) {
209 if (thisServer.pid_fd >= 0) {
210 memset(buff, 0, sizeof(buff));
211 sprintf(buff, "%5d\n", (int)getpid());
212 if (write(thisServer.pid_fd, buff, strlen(buff)) == -1)
213 Debug((DEBUG_NOTICE, "Error writing to pid file %s: %m",
214 feature_str(FEAT_PPATH)));
217 Debug((DEBUG_NOTICE, "Error opening pid file %s: %m",
218 feature_str(FEAT_PPATH)));
221 /** Try to create the PID file.
222 * @return Zero on success; non-zero on any error.
224 static int check_pid(void)
228 lock.l_type = F_WRLCK;
230 lock.l_whence = SEEK_SET;
233 if ((thisServer.pid_fd = open(feature_str(FEAT_PPATH), O_CREAT | O_RDWR,
235 return fcntl(thisServer.pid_fd, F_SETLK, &lock) == -1;
241 /** Look for any connections that we should try to initiate.
242 * Reschedules itself to run again at the appropriate time.
243 * @param[in] ev Timer event (ignored).
245 static void try_connections(struct Event* ev) {
246 struct ConfItem* aconf;
248 struct ConfItem** pconf;
252 struct ConnectionClass* cltmp;
253 struct ConfItem* con_conf = 0;
255 const char* con_class = NULL;
257 assert(ET_EXPIRE == ev_type(ev));
258 assert(0 != ev_timer(ev));
261 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
262 for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
263 /* Also when already connecting! (update holdtimes) --SRB */
264 if (!(aconf->status & CONF_SERVER) || aconf->address.port == 0 || aconf->hold == 0)
267 /* Also skip juped servers */
268 if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
271 /* Skip this entry if the use of it is still on hold until
272 * future. Otherwise handle this entry (and set it on hold until next
273 * time). Will reset only hold times, if already made one successfull
274 * connection... [this algorithm is a bit fuzzy... -- msa >;) ]
276 if (aconf->hold > CurrentTime && (next > aconf->hold || next == 0)) {
281 cltmp = aconf->conn_class;
282 confrq = get_con_freq(cltmp);
284 aconf->hold = next = 0;
286 aconf->hold = CurrentTime + confrq;
288 /* Found a CONNECT config with port specified, scan clients and see if
289 * this server is already connected?
291 cptr = FindServer(aconf->name);
293 if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
294 (!connecting /*|| (ConClass(cltmp) > con_class)*/)) {
296 * Check connect rules to see if we're allowed to try
298 if (0 == conf_eval_crule(aconf->name, CRULE_MASK)) {
299 con_class = ConClass(cltmp);
301 /* We connect only one at time... */
305 if ((next > aconf->hold) || (next == 0))
309 if (con_conf->next) { /* are we already last? */
310 /* Put the current one at the end and make sure we try all connections */
311 for (pconf = &GlobalConfList; (aconf = *pconf); pconf = &(aconf->next))
312 if (aconf == con_conf)
313 *pconf = aconf->next;
314 (*pconf = con_conf)->next = 0;
317 if (connect_server(con_conf, 0))
318 sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
323 next = CurrentTime + feature_int(FEAT_CONNECTFREQUENCY);
325 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
327 timer_add(&connect_timer, try_connections, 0, TT_ABSOLUTE, next);
331 /** Check for clients that have not sent a ping response recently.
332 * Reschedules itself to run again at the appropriate time.
333 * @param[in] ev Timer event (ignored).
335 static void check_pings(struct Event* ev) {
337 int next_check = CurrentTime;
341 assert(ET_EXPIRE == ev_type(ev));
342 assert(0 != ev_timer(ev));
344 next_check += feature_int(FEAT_PINGFREQUENCY);
346 /* Scan through the client table */
347 for (i=0; i <= HighestFd; i++) {
348 struct Client *cptr = LocalClientArray[i];
353 assert(&me != cptr); /* I should never be in the local client array! */
356 /* Remove dead clients. */
358 exit_client(cptr, cptr, &me, cli_info(cptr));
362 max_ping = IsRegistered(cptr) ? client_get_ping(cptr) :
363 feature_int(FEAT_CONNECTTIMEOUT);
365 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
367 IsPingSent(cptr) ? "[Ping Sent]" : "[]",
368 max_ping, (int)(CurrentTime - cli_lasttime(cptr))));
370 /* Ok, the thing that will happen most frequently, is that someone will
371 * have sent something recently. Cover this first for speed.
373 * If it's an unregisterd client and hasn't managed to register within
374 * max_ping then it's obviously having problems (broken client) or it's
375 * just up to no good, so we won't skip it, even if its been sending
379 if ((CurrentTime-cli_lasttime(cptr) < max_ping) && IsRegistered(cptr)) {
380 expire = cli_lasttime(cptr) + max_ping;
381 if (expire < next_check)
386 /* Unregistered clients pingout after max_ping seconds, they don't
387 * get given a second chance - if they were then people could not quite
388 * finish registration and hold resources without being subject to k/g
391 if (!IsRegistered(cptr)) {
392 assert(!IsServer(cptr));
393 if ((CurrentTime-cli_firsttime(cptr) >= max_ping)) {
394 /* Display message if they have sent a NICK and a USER but no
397 if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
398 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
399 ":Your client may not be compatible with this server.");
400 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
401 ":Compatible clients are available at %s",
402 feature_str(FEAT_URL_CLIENTS));
404 exit_client_msg(cptr,cptr,&me, "Registration Timeout");
407 /* OK, they still have enough time left, so we'll just skip to the
408 * next client. Set the next check to be when their time is up, if
409 * that's before the currently scheduled next check -- hikari */
410 expire = cli_firsttime(cptr) + max_ping;
411 if (expire < next_check)
417 /* Quit the client after max_ping*2 - they should have answered by now */
418 if (CurrentTime-cli_lasttime(cptr) >= (max_ping*2) )
420 /* If it was a server, then tell ops about it. */
421 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
422 sendto_opmask_butone(0, SNO_OLDSNO,
423 "No response from %s, closing link",
425 exit_client_msg(cptr, cptr, &me, "Ping timeout");
429 if (!IsPingSent(cptr))
431 /* If we havent PINGed the connection and we havent heard from it in a
432 * while, PING it to make sure it is still alive.
436 /* If we're late in noticing don't hold it against them :) */
437 cli_lasttime(cptr) = CurrentTime - max_ping;
440 sendrawto_one(cptr, MSG_PING " :%s", cli_name(&me));
443 char *asll_ts = militime_float(NULL);
444 sendcmdto_one(&me, CMD_PING, cptr, "!%s %s %s", asll_ts,
445 cli_name(cptr), asll_ts);
449 expire = cli_lasttime(cptr) + max_ping * 2;
450 if (expire < next_check)
454 assert(next_check >= CurrentTime);
456 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
457 CurrentTime, next_check-CurrentTime));
459 timer_add(&ping_timer, check_pings, 0, TT_ABSOLUTE, next_check);
463 /** Parse command line arguments.
464 * Global variables are updated to reflect the arguments.
465 * As a side effect, makes sure the process's effective user id is the
466 * same as the real user id.
467 * @param[in] argc Number of arguments on command line.
468 * @param[in,out] argv Command-lne arguments.
470 static void parse_command_line(int argc, char** argv) {
471 const char *options = "d:f:h:nktvx:";
474 if (thisServer.euid != thisServer.uid)
475 setuid(thisServer.uid);
477 /* Do we really need to santiy check the non-NULLness of optarg? That's
478 * getopt()'s job... Removing those... -zs
480 while ((opt = getopt(argc, argv, options)) != EOF)
482 case 'k': thisServer.bootopt |= BOOT_CHKCONF; break;
484 case 't': thisServer.bootopt |= BOOT_TTY; break;
485 case 'd': dpath = optarg; break;
486 case 'f': configfile = optarg; break;
487 case 'h': ircd_strncpy(cli_name(&me), optarg, HOSTLEN); break;
489 printf("ircd %s\n", version);
490 printf("Event engines: ");
495 printf("/dev/poll ");
502 printf("\nCompiled for a maximum of %d connections.\n", MAXCONNECTIONS);
509 debuglevel = atoi(optarg);
513 thisServer.bootopt |= BOOT_DEBUG;
517 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntvk]\n");
518 printf("\n -n -t\t Don't detach\n -v\t display version\n -k\t exit after checking config\n\n");
519 printf("Server not started.\n");
526 * @param[in] no_fork If non-zero, do not fork into the background.
528 static void daemon_init(int no_fork) {
538 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
539 ioctl(fd, TIOCNOTTY, 0);
548 /** Check that we have access to a particular file.
549 * If we do not have access to the file, complain on stderr.
550 * @param[in] path File name to check for access.
551 * @param[in] which Configuration character associated with file.
552 * @param[in] mode Bitwise combination of R_OK, W_OK, X_OK and/or F_OK.
553 * @return Non-zero if we have the necessary access, zero if not.
555 static char check_file_access(const char *path, char which, int mode) {
556 if (!access(path, mode))
560 "Check on %cPATH (%s) failed: %s\n"
561 "Please create this file and/or rerun `configure' "
562 "using --with-%cpath and recompile to correct this.\n",
563 which, path, strerror(errno), which);
569 /*----------------------------------------------------------------------------
571 *--------------------------------------------------------------------------*/
572 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
573 /** Set the core size soft limit to the same as the hard limit. */
574 static void set_core_limit(void) {
575 struct rlimit corelim;
577 if (getrlimit(RLIMIT_CORE, &corelim)) {
578 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
579 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
582 corelim.rlim_cur = corelim.rlim_max;
583 if (setrlimit(RLIMIT_CORE, &corelim))
584 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
590 /** Complain to stderr if any user or group ID belongs to the superuser.
591 * @return Non-zero if all IDs are okay, zero if some are 0.
593 static int set_userid_if_needed(void) {
594 if (getuid() == 0 || geteuid() == 0 ||
595 getgid() == 0 || getegid() == 0) {
596 fprintf(stderr, "ERROR: This server will not run as superuser.\n");
604 /*----------------------------------------------------------------------------
607 * TODO: This should set the basic environment up and start the main loop.
608 * we're doing waaaaaaaaay too much server initialization here. I hate
609 * long and ugly control paths... -smd
610 *--------------------------------------------------------------------------*/
612 * @param[in] argc Number of arguments in \a argv.
613 * @param[in] argv Arguments to program execution.
615 int main(int argc, char **argv) {
616 CurrentTime = time(NULL);
618 thisServer.argc = argc;
619 thisServer.argv = argv;
620 thisServer.uid = getuid();
621 thisServer.euid = geteuid();
624 mem_dbg_initialise();
627 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
631 umask(077); /* better safe than sorry --SRB */
632 memset(&me, 0, sizeof(me));
633 memset(&me_con, 0, sizeof(me_con));
634 cli_connect(&me) = &me_con;
637 parse_command_line(argc, argv);
640 fprintf(stderr, "Fail: Cannot chdir(%s): %s, check DPATH\n", dpath, strerror(errno));
644 if (!set_userid_if_needed())
647 /* Check paths for accessibility */
648 if (!check_file_access(SPATH, 'S', X_OK) ||
649 !check_file_access(configfile, 'C', R_OK))
652 if (!init_connection_limits())
655 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY | BOOT_CHKCONF)));
657 event_init(MAXCONNECTIONS);
660 feature_init(); /* initialize features... */
662 set_nomem_handler(outofmemory);
664 if (!init_string()) {
665 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to initialize string module");
679 /* we need this for now, when we're modular this
680 should be removed -- hikari */
686 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to read configuration file %s",
691 if (thisServer.bootopt & BOOT_CHKCONF) {
692 fprintf(stderr, "Configuration file %s checked okay.\n", configfile);
696 debug_init(thisServer.bootopt & BOOT_TTY);
697 daemon_init(thisServer.bootopt & BOOT_TTY);
699 Debug((DEBUG_FATAL, "Failed to acquire PID file lock after fork"));
703 init_server_identity();
710 timer_add(timer_init(&connect_timer), try_connections, 0, TT_RELATIVE, 1);
711 timer_add(timer_init(&ping_timer), check_pings, 0, TT_RELATIVE, 1);
712 timer_add(timer_init(&destruct_event_timer), exec_expired_destruct_events, 0, TT_PERIODIC, 60);
714 CurrentTime = time(NULL);
717 cli_magic(&me) = CLIENT_MAGIC;
721 cli_serv(&me)->timestamp = TStime(); /* Abuse own link timestamp as start TS */
722 cli_serv(&me)->prot = atoi(MAJOR_PROTOCOL);
723 cli_serv(&me)->up = &me;
724 cli_serv(&me)->down = NULL;
725 cli_handler(&me) = SERVER_HANDLER;
727 SetYXXCapacity(&me, MAXCLIENTS);
729 cli_lasttime(&me) = cli_since(&me) = cli_firsttime(&me) = CurrentTime;
736 Debug((DEBUG_NOTICE, "Server ready..."));
737 log_write(LS_SYSTEM, L_NOTICE, 0, "Server Ready");