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.
29 #include "destruct_event.h"
31 #include "ircd_alloc.h"
32 #include "ircd_events.h"
33 #include "ircd_features.h"
35 #include "ircd_reply.h"
36 #include "ircd_signal.h"
37 #include "ircd_string.h"
38 #include "ircd_crypt.h"
70 #include <sys/socket.h>
72 #include <sys/types.h>
77 /*----------------------------------------------------------------------------
79 *--------------------------------------------------------------------------*/
80 extern void init_counters(void);
81 extern void mem_dbg_initialise(void);
83 /*----------------------------------------------------------------------------
85 *--------------------------------------------------------------------------*/
92 /*----------------------------------------------------------------------------
94 *--------------------------------------------------------------------------*/
95 struct Client me; /* That's me */
96 struct Connection me_con; /* That's me too */
97 struct Client *GlobalClientList = &me; /* Pointer to beginning of
99 time_t TSoffset = 0;/* Offset of timestamps to system clock */
100 int GlobalRehashFlag = 0; /* do a rehash if set */
101 int GlobalRestartFlag = 0; /* do a restart if set */
102 time_t CurrentTime; /* Updated every time we leave select() */
104 char *configfile = CPATH; /* Server configuration file */
105 int debuglevel = -1; /* Server debug level */
106 char *debugmode = ""; /* Server debug level */
107 static char *dpath = DPATH;
109 static struct Timer connect_timer; /* timer structure for try_connections() */
110 static struct Timer ping_timer; /* timer structure for check_pings() */
111 static struct Timer destruct_event_timer; /* timer structure for exec_expired_destruct_events() */
113 static struct Daemon thisServer = { 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0 };
118 /*----------------------------------------------------------------------------
120 *--------------------------------------------------------------------------*/
121 void server_die(const char *message)
123 /* log_write will send out message to both log file and as server notice */
124 log_write(LS_SYSTEM, L_CRIT, 0, "Server terminating: %s", message);
125 flush_connections(0);
126 close_connections(1);
130 /*----------------------------------------------------------------------------
132 *--------------------------------------------------------------------------*/
133 void server_panic(const char *message)
135 /* inhibit sending server notice--we may be panicing due to low memory */
136 log_write(LS_SYSTEM, L_CRIT, LOG_NOSNOTICE, "Server panic: %s", message);
137 flush_connections(0);
139 close_connections(1);
143 /*----------------------------------------------------------------------------
144 * API: server_restart
145 *--------------------------------------------------------------------------*/
146 void server_restart(const char *message)
148 static int restarting = 0;
150 /* inhibit sending any server notices; we may be in a loop */
151 log_write(LS_SYSTEM, L_WARNING, LOG_NOSNOTICE, "Restarting Server: %s",
153 if (restarting++) /* increment restarting to prevent looping */
156 sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
157 Debug((DEBUG_NOTICE, "Restarting server..."));
158 flush_connections(0);
162 close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG)));
164 execv(SPATH, thisServer.argv);
166 /* Have to reopen since it has been closed above */
169 log_write(LS_SYSTEM, L_CRIT, 0, "execv(%s,%s) failed: %m", SPATH,
172 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
173 SPATH, (strerror(errno)) ? strerror(errno) : ""));
178 /*----------------------------------------------------------------------------
179 * outofmemory: Handler for out of memory conditions...
180 *--------------------------------------------------------------------------*/
181 static void outofmemory(void) {
182 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
183 server_restart("Out of Memory");
187 /*----------------------------------------------------------------------------
189 *--------------------------------------------------------------------------*/
190 static void write_pidfile(void) {
193 if (thisServer.pid_fd >= 0) {
194 memset(buff, 0, sizeof(buff));
195 sprintf(buff, "%5d\n", (int)getpid());
196 if (write(thisServer.pid_fd, buff, strlen(buff)) == -1)
197 Debug((DEBUG_NOTICE, "Error writing to pid file %s: %m",
198 feature_str(FEAT_PPATH)));
201 Debug((DEBUG_NOTICE, "Error opening pid file %s: %m",
202 feature_str(FEAT_PPATH)));
210 * true - if the pid file exists (and is readable), and the pid refered
211 * to in the file is still running.
214 static int check_pid(void)
218 lock.l_type = F_WRLCK;
220 lock.l_whence = SEEK_SET;
223 if ((thisServer.pid_fd = open(feature_str(FEAT_PPATH), O_CREAT | O_RDWR,
225 return fcntl(thisServer.pid_fd, F_SETLK, &lock);
231 /*----------------------------------------------------------------------------
234 * Scan through configuration and try new connections.
236 * Returns the calendar time when the next call to this
237 * function should be made latest. (No harm done if this
238 * is called earlier or later...)
239 *--------------------------------------------------------------------------*/
240 static void try_connections(struct Event* ev) {
241 struct ConfItem* aconf;
243 struct ConfItem** pconf;
247 struct ConnectionClass* cltmp;
248 struct ConfItem* con_conf = 0;
250 const char* con_class = NULL;
252 assert(ET_EXPIRE == ev_type(ev));
253 assert(0 != ev_timer(ev));
256 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
257 for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
258 /* Also when already connecting! (update holdtimes) --SRB */
259 if (!(aconf->status & CONF_SERVER) || aconf->address.port == 0 || aconf->hold == 0)
262 /* Also skip juped servers */
263 if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
266 /* Skip this entry if the use of it is still on hold until
267 * future. Otherwise handle this entry (and set it on hold until next
268 * time). Will reset only hold times, if already made one successfull
269 * connection... [this algorithm is a bit fuzzy... -- msa >;) ]
271 if (aconf->hold > CurrentTime && (next > aconf->hold || next == 0)) {
276 cltmp = aconf->conn_class;
277 confrq = get_con_freq(cltmp);
279 aconf->hold = next = 0;
281 aconf->hold = CurrentTime + confrq;
283 /* Found a CONNECT config with port specified, scan clients and see if
284 * this server is already connected?
286 cptr = FindServer(aconf->name);
288 if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
289 (!connecting /*|| (ConClass(cltmp) > con_class)*/)) {
291 * Check connect rules to see if we're allowed to try
293 if (0 == conf_eval_crule(aconf->name, CRULE_MASK)) {
294 con_class = ConClass(cltmp);
296 /* We connect only one at time... */
300 if ((next > aconf->hold) || (next == 0))
304 if (con_conf->next) { /* are we already last? */
305 /* Put the current one at the end and make sure we try all connections */
306 for (pconf = &GlobalConfList; (aconf = *pconf); pconf = &(aconf->next))
307 if (aconf == con_conf)
308 *pconf = aconf->next;
309 (*pconf = con_conf)->next = 0;
312 if (connect_server(con_conf, 0))
313 sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
318 next = CurrentTime + feature_int(FEAT_CONNECTFREQUENCY);
320 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
322 timer_add(&connect_timer, try_connections, 0, TT_ABSOLUTE, next);
326 /*----------------------------------------------------------------------------
329 * TODO: This should be moved out of ircd.c. It's protocol-specific when you
330 * get right down to it. Can't really be done until the server is more
331 * modular, however...
332 *--------------------------------------------------------------------------*/
333 static void check_pings(struct Event* ev) {
335 int next_check = CurrentTime;
339 assert(ET_EXPIRE == ev_type(ev));
340 assert(0 != ev_timer(ev));
342 next_check += feature_int(FEAT_PINGFREQUENCY);
344 /* Scan through the client table */
345 for (i=0; i <= HighestFd; i++) {
346 struct Client *cptr = LocalClientArray[i];
351 assert(&me != cptr); /* I should never be in the local client array! */
354 /* Remove dead clients. */
356 exit_client(cptr, cptr, &me, cli_info(cptr));
360 max_ping = IsRegistered(cptr) ? client_get_ping(cptr) :
361 feature_int(FEAT_CONNECTTIMEOUT);
363 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
365 IsPingSent(cptr) ? "[Ping Sent]" : "[]",
366 max_ping, (int)(CurrentTime - cli_lasttime(cptr))));
368 /* Ok, the thing that will happen most frequently, is that someone will
369 * have sent something recently. Cover this first for speed.
371 * If it's an unregisterd client and hasn't managed to register within
372 * max_ping then it's obviously having problems (broken client) or it's
373 * just up to no good, so we won't skip it, even if its been sending
377 if ((CurrentTime-cli_lasttime(cptr) < max_ping) && IsRegistered(cptr)) {
378 expire = cli_lasttime(cptr) + max_ping;
379 if (expire < next_check)
384 /* Unregistered clients pingout after max_ping seconds, they don't
385 * get given a second chance - if they were then people could not quite
386 * finish registration and hold resources without being subject to k/g
389 if (!IsRegistered(cptr)) {
390 assert(!IsServer(cptr));
391 if ((CurrentTime-cli_firsttime(cptr) >= max_ping)) {
392 /* Display message if they have sent a NICK and a USER but no
395 if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
396 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
397 ":Your client may not be compatible with this server.");
398 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
399 ":Compatible clients are available at %s",
400 feature_str(FEAT_URL_CLIENTS));
402 exit_client_msg(cptr,cptr,&me, "Registration Timeout");
405 /* OK, they still have enough time left, so we'll just skip to the
406 * next client. Set the next check to be when their time is up, if
407 * that's before the currently scheduled next check -- hikari */
408 expire = cli_firsttime(cptr) + max_ping;
409 if (expire < next_check)
415 /* Quit the client after max_ping*2 - they should have answered by now */
416 if (CurrentTime-cli_lasttime(cptr) >= (max_ping*2) )
418 /* If it was a server, then tell ops about it. */
419 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
420 sendto_opmask_butone(0, SNO_OLDSNO,
421 "No response from %s, closing link",
423 exit_client_msg(cptr, cptr, &me, "Ping timeout");
427 if (!IsPingSent(cptr))
429 /* If we havent PINGed the connection and we havent heard from it in a
430 * while, PING it to make sure it is still alive.
434 /* If we're late in noticing don't hold it against them :) */
435 cli_lasttime(cptr) = CurrentTime - max_ping;
438 sendrawto_one(cptr, MSG_PING " :%s", cli_name(&me));
441 char *asll_ts = militime_float(NULL);
442 sendcmdto_one(&me, CMD_PING, cptr, "!%s %s %s", asll_ts,
443 cli_name(cptr), asll_ts);
447 expire = cli_lasttime(cptr) + max_ping * 2;
448 if (expire < next_check)
452 assert(next_check >= CurrentTime);
454 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
455 CurrentTime, next_check-CurrentTime));
457 timer_add(&ping_timer, check_pings, 0, TT_ABSOLUTE, next_check);
461 /*----------------------------------------------------------------------------
463 * Side Effects: changes GLOBALS me, thisServer, dpath, configfile, debuglevel
465 *--------------------------------------------------------------------------*/
466 static void parse_command_line(int argc, char** argv) {
467 const char *options = "d:f:h:ntvx:";
470 if (thisServer.euid != thisServer.uid)
471 setuid(thisServer.uid);
473 /* Do we really need to santiy check the non-NULLness of optarg? That's
474 * getopt()'s job... Removing those... -zs
476 while ((opt = getopt(argc, argv, options)) != EOF)
479 case 't': thisServer.bootopt |= BOOT_TTY; break;
480 case 'd': dpath = optarg; break;
481 case 'f': configfile = optarg; break;
482 case 'h': ircd_strncpy(cli_name(&me), optarg, HOSTLEN); break;
484 printf("ircd %s\n", version);
485 printf("Event engines: ");
490 printf("/dev/poll ");
497 printf("\nCompiled for a maximum of %d connections.\n", MAXCONNECTIONS);
504 debuglevel = atoi(optarg);
508 thisServer.bootopt |= BOOT_DEBUG;
512 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv]\n");
513 printf("\n -n -t\t Don't detach\n -v\t display version\n\n");
514 printf("Server not started.\n");
520 /*----------------------------------------------------------------------------
522 *--------------------------------------------------------------------------*/
523 static void daemon_init(int no_fork) {
524 if (!init_connection_limits())
527 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
538 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
539 ioctl(fd, TIOCNOTTY, 0);
548 /*----------------------------------------------------------------------------
549 * check_file_access: random helper function to make sure that a file is
550 * accessible in a certain way, and complain if not.
551 *--------------------------------------------------------------------------*/
552 static char check_file_access(const char *path, char which, int mode) {
553 if (!access(path, mode))
557 "Check on %cPATH (%s) failed: %s\n"
558 "Please create this file and/or rerun `configure' "
559 "using --with-%cpath and recompile to correct this.\n",
560 which, path, strerror(errno), which);
566 /*----------------------------------------------------------------------------
568 *--------------------------------------------------------------------------*/
569 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
570 static void set_core_limit(void) {
571 struct rlimit corelim;
573 if (getrlimit(RLIMIT_CORE, &corelim)) {
574 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
575 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
578 corelim.rlim_cur = corelim.rlim_max;
579 if (setrlimit(RLIMIT_CORE, &corelim))
580 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
586 /*----------------------------------------------------------------------------
587 * set_userid_if_needed()
588 *--------------------------------------------------------------------------*/
589 static int set_userid_if_needed(void) {
590 if (getuid() == 0 || geteuid() == 0 ||
591 getgid() == 0 || getegid() == 0) {
592 fprintf(stderr, "ERROR: This server will not run as superuser.\n");
600 /*----------------------------------------------------------------------------
603 * TODO: This should set the basic environment up and start the main loop.
604 * we're doing waaaaaaaaay too much server initialization here. I hate
605 * long and ugly control paths... -smd
606 *--------------------------------------------------------------------------*/
607 int main(int argc, char **argv) {
608 CurrentTime = time(NULL);
610 thisServer.argc = argc;
611 thisServer.argv = argv;
612 thisServer.uid = getuid();
613 thisServer.euid = geteuid();
616 mem_dbg_initialise();
619 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
623 umask(077); /* better safe than sorry --SRB */
624 memset(&me, 0, sizeof(me));
625 memset(&me_con, 0, sizeof(me_con));
626 cli_connect(&me) = &me_con;
629 parse_command_line(argc, argv);
632 fprintf(stderr, "Fail: Cannot chdir(%s): %s, check DPATH\n", dpath, strerror(errno));
636 if (!set_userid_if_needed())
639 /* Check paths for accessibility */
640 if (!check_file_access(SPATH, 'S', X_OK) ||
641 !check_file_access(configfile, 'C', R_OK))
644 debug_init(thisServer.bootopt & BOOT_TTY);
645 daemon_init(thisServer.bootopt & BOOT_TTY);
646 event_init(MAXCONNECTIONS);
649 feature_init(); /* initialize features... */
651 set_nomem_handler(outofmemory);
653 if (!init_string()) {
654 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to initialize string module");
668 /* we need this for now, when we're modular this
669 should be removed -- hikari */
675 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to read configuration file %s",
681 Debug((DEBUG_FATAL, "Failed to acquire PID file lock after fork"));
685 init_server_identity();
692 timer_add(timer_init(&connect_timer), try_connections, 0, TT_RELATIVE, 1);
693 timer_add(timer_init(&ping_timer), check_pings, 0, TT_RELATIVE, 1);
694 timer_add(timer_init(&destruct_event_timer), exec_expired_destruct_events, 0, TT_PERIODIC, 60);
696 CurrentTime = time(NULL);
699 cli_magic(&me) = CLIENT_MAGIC;
703 cli_serv(&me)->timestamp = TStime(); /* Abuse own link timestamp as start TS */
704 cli_serv(&me)->prot = atoi(MAJOR_PROTOCOL);
705 cli_serv(&me)->up = &me;
706 cli_serv(&me)->down = NULL;
707 cli_handler(&me) = SERVER_HANDLER;
709 SetYXXCapacity(&me, MAXCLIENTS);
711 cli_lasttime(&me) = cli_since(&me) = cli_firsttime(&me) = CurrentTime;
718 Debug((DEBUG_NOTICE, "Server ready..."));
719 log_write(LS_SYSTEM, L_NOTICE, 0, "Server Ready");