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"
69 #include <sys/socket.h>
71 #include <sys/types.h>
76 /*----------------------------------------------------------------------------
78 *--------------------------------------------------------------------------*/
79 extern void init_counters(void);
80 extern void mem_dbg_initialise(void);
82 /*----------------------------------------------------------------------------
84 *--------------------------------------------------------------------------*/
91 /*----------------------------------------------------------------------------
93 *--------------------------------------------------------------------------*/
94 struct Client me; /* That's me */
95 struct Connection me_con; /* That's me too */
96 struct Client *GlobalClientList = &me; /* Pointer to beginning of
98 time_t TSoffset = 0;/* Offset of timestamps to system clock */
99 int GlobalRehashFlag = 0; /* do a rehash if set */
100 int GlobalRestartFlag = 0; /* do a restart if set */
101 time_t CurrentTime; /* Updated every time we leave select() */
103 char *configfile = CPATH; /* Server configuration file */
104 int debuglevel = -1; /* Server debug level */
105 char *debugmode = ""; /* Server debug level */
106 static char *dpath = DPATH;
108 static struct Timer connect_timer; /* timer structure for try_connections() */
109 static struct Timer ping_timer; /* timer structure for check_pings() */
110 static struct Timer destruct_event_timer; /* timer structure for exec_expired_destruct_events() */
112 static struct Daemon thisServer = { 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0 };
117 /*----------------------------------------------------------------------------
119 *--------------------------------------------------------------------------*/
120 void server_die(const char *message)
122 /* log_write will send out message to both log file and as server notice */
123 log_write(LS_SYSTEM, L_CRIT, 0, "Server terminating: %s", message);
124 flush_connections(0);
125 close_connections(1);
129 /*----------------------------------------------------------------------------
131 *--------------------------------------------------------------------------*/
132 void server_panic(const char *message)
134 /* inhibit sending server notice--we may be panicing due to low memory */
135 log_write(LS_SYSTEM, L_CRIT, LOG_NOSNOTICE, "Server panic: %s", message);
136 flush_connections(0);
138 close_connections(1);
142 /*----------------------------------------------------------------------------
143 * API: server_restart
144 *--------------------------------------------------------------------------*/
145 void server_restart(const char *message)
147 static int restarting = 0;
149 /* inhibit sending any server notices; we may be in a loop */
150 log_write(LS_SYSTEM, L_WARNING, LOG_NOSNOTICE, "Restarting Server: %s",
152 if (restarting++) /* increment restarting to prevent looping */
155 sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
156 Debug((DEBUG_NOTICE, "Restarting server..."));
157 flush_connections(0);
161 close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG)));
163 execv(SPATH, thisServer.argv);
165 /* Have to reopen since it has been closed above */
168 log_write(LS_SYSTEM, L_CRIT, 0, "execv(%s,%s) failed: %m", SPATH,
171 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
172 SPATH, (strerror(errno)) ? strerror(errno) : ""));
177 /*----------------------------------------------------------------------------
178 * outofmemory: Handler for out of memory conditions...
179 *--------------------------------------------------------------------------*/
180 static void outofmemory(void) {
181 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
182 server_restart("Out of Memory");
186 /*----------------------------------------------------------------------------
188 *--------------------------------------------------------------------------*/
189 static void write_pidfile(void) {
192 if (thisServer.pid_fd >= 0) {
193 memset(buff, 0, sizeof(buff));
194 sprintf(buff, "%5d\n", (int)getpid());
195 if (write(thisServer.pid_fd, buff, strlen(buff)) == -1)
196 Debug((DEBUG_NOTICE, "Error writing to pid file %s: %m",
197 feature_str(FEAT_PPATH)));
200 Debug((DEBUG_NOTICE, "Error opening pid file %s: %m",
201 feature_str(FEAT_PPATH)));
209 * true - if the pid file exists (and is readable), and the pid refered
210 * to in the file is still running.
213 static int check_pid(void)
217 lock.l_type = F_WRLCK;
219 lock.l_whence = SEEK_SET;
222 if ((thisServer.pid_fd = open(feature_str(FEAT_PPATH), O_CREAT | O_RDWR,
224 return fcntl(thisServer.pid_fd, F_SETLK, &lock);
230 /*----------------------------------------------------------------------------
233 * Scan through configuration and try new connections.
235 * Returns the calendar time when the next call to this
236 * function should be made latest. (No harm done if this
237 * is called earlier or later...)
238 *--------------------------------------------------------------------------*/
239 static void try_connections(struct Event* ev) {
240 struct ConfItem* aconf;
242 struct ConfItem** pconf;
246 struct ConnectionClass* cltmp;
247 struct ConfItem* con_conf = 0;
249 const char* con_class = NULL;
251 assert(ET_EXPIRE == ev_type(ev));
252 assert(0 != ev_timer(ev));
255 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
256 for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
257 /* Also when already connecting! (update holdtimes) --SRB */
258 if (!(aconf->status & CONF_SERVER) || aconf->port == 0 || aconf->hold == 0)
261 /* Also skip juped servers */
262 if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
265 /* Skip this entry if the use of it is still on hold until
266 * future. Otherwise handle this entry (and set it on hold until next
267 * time). Will reset only hold times, if already made one successfull
268 * connection... [this algorithm is a bit fuzzy... -- msa >;) ]
270 if (aconf->hold > CurrentTime && (next > aconf->hold || next == 0)) {
275 cltmp = aconf->conn_class;
276 confrq = get_con_freq(cltmp);
278 aconf->hold = next = 0;
280 aconf->hold = CurrentTime + confrq;
282 /* Found a CONNECT config with port specified, scan clients and see if
283 * this server is already connected?
285 cptr = FindServer(aconf->name);
287 if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
288 (!connecting /*|| (ConClass(cltmp) > con_class)*/)) {
290 * Check connect rules to see if we're allowed to try
292 if (0 == conf_eval_crule(aconf->name, CRULE_MASK)) {
293 con_class = ConClass(cltmp);
295 /* We connect only one at time... */
299 if ((next > aconf->hold) || (next == 0))
303 if (con_conf->next) { /* are we already last? */
304 /* Put the current one at the end and make sure we try all connections */
305 for (pconf = &GlobalConfList; (aconf = *pconf); pconf = &(aconf->next))
306 if (aconf == con_conf)
307 *pconf = aconf->next;
308 (*pconf = con_conf)->next = 0;
311 if (connect_server(con_conf, 0))
312 sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
317 next = CurrentTime + feature_int(FEAT_CONNECTFREQUENCY);
319 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
321 timer_add(&connect_timer, try_connections, 0, TT_ABSOLUTE, next);
325 /*----------------------------------------------------------------------------
328 * TODO: This should be moved out of ircd.c. It's protocol-specific when you
329 * get right down to it. Can't really be done until the server is more
330 * modular, however...
331 *--------------------------------------------------------------------------*/
332 static void check_pings(struct Event* ev) {
334 int next_check = CurrentTime;
338 assert(ET_EXPIRE == ev_type(ev));
339 assert(0 != ev_timer(ev));
341 next_check += feature_int(FEAT_PINGFREQUENCY);
343 /* Scan through the client table */
344 for (i=0; i <= HighestFd; i++) {
345 struct Client *cptr = LocalClientArray[i];
350 assert(&me != cptr); /* I should never be in the local client array! */
353 /* Remove dead clients. */
355 exit_client(cptr, cptr, &me, cli_info(cptr));
359 max_ping = IsRegistered(cptr) ? client_get_ping(cptr) :
360 feature_int(FEAT_CONNECTTIMEOUT);
362 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
364 IsPingSent(cptr) ? "[Ping Sent]" : "[]",
365 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 (CurrentTime-cli_lasttime(cptr) < max_ping) {
372 expire = cli_lasttime(cptr) + max_ping;
373 if (expire < next_check)
378 /* Quit the client after max_ping*2 - they should have answered by now */
379 if (CurrentTime-cli_lasttime(cptr) >= (max_ping*2) )
381 /* If it was a server, then tell ops about it. */
382 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
383 sendto_opmask_butone(0, SNO_OLDSNO,
384 "No response from %s, closing link",
386 exit_client_msg(cptr, cptr, &me, "Ping timeout");
390 /* Unregistered clients pingout after max_ping seconds, they don't
391 * get given a second chance - if they were then people could not quite
392 * finish registration and hold resources without being subject to k/g
395 if (!IsRegistered(cptr))
397 /* Display message if they have sent a NICK and a USER but no
400 if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username)
402 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
403 ":Your client may not be compatible with this server.");
404 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
405 ":Compatible clients are available at %s",
406 feature_str(FEAT_URL_CLIENTS));
408 exit_client_msg(cptr,cptr,&me, "Ping Timeout");
412 if (!IsPingSent(cptr))
414 /* If we havent PINGed the connection and we havent heard from it in a
415 * while, PING it to make sure it is still alive.
419 /* If we're late in noticing don't hold it against them :) */
420 cli_lasttime(cptr) = CurrentTime - max_ping;
423 sendrawto_one(cptr, MSG_PING " :%s", cli_name(&me));
426 char *asll_ts = militime_float(NULL);
427 sendcmdto_one(&me, CMD_PING, cptr, "!%s %s %s", asll_ts,
428 cli_name(cptr), asll_ts);
432 expire = cli_lasttime(cptr) + max_ping * 2;
433 if (expire < next_check)
437 assert(next_check >= CurrentTime);
439 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
440 CurrentTime, next_check-CurrentTime));
442 timer_add(&ping_timer, check_pings, 0, TT_ABSOLUTE, next_check);
446 /*----------------------------------------------------------------------------
448 * Side Effects: changes GLOBALS me, thisServer, dpath, configfile, debuglevel
450 *--------------------------------------------------------------------------*/
451 static void parse_command_line(int argc, char** argv) {
452 const char *options = "d:f:h:ntvx:";
455 if (thisServer.euid != thisServer.uid)
456 setuid(thisServer.uid);
458 /* Do we really need to santiy check the non-NULLness of optarg? That's
459 * getopt()'s job... Removing those... -zs
461 while ((opt = getopt(argc, argv, options)) != EOF)
464 case 't': thisServer.bootopt |= BOOT_TTY; break;
465 case 'd': dpath = optarg; break;
466 case 'f': configfile = optarg; break;
467 case 'h': ircd_strncpy(cli_name(&me), optarg, HOSTLEN); break;
469 printf("ircd %s\n", version);
470 printf("Event engines: ");
475 printf("/dev/poll ");
482 printf("\nCompiled for a maximum of %d connections.\n", MAXCONNECTIONS);
489 debuglevel = atoi(optarg);
493 thisServer.bootopt |= BOOT_DEBUG;
497 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv]\n");
498 printf("\n -n -t\t Don't detach\n -v\t display version\n\n");
499 printf("Server not started.\n");
505 /*----------------------------------------------------------------------------
507 *--------------------------------------------------------------------------*/
508 static void daemon_init(int no_fork) {
509 if (!init_connection_limits())
512 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
523 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
524 ioctl(fd, TIOCNOTTY, 0);
533 /*----------------------------------------------------------------------------
534 * check_file_access: random helper function to make sure that a file is
535 * accessible in a certain way, and complain if not.
536 *--------------------------------------------------------------------------*/
537 static char check_file_access(const char *path, char which, int mode) {
538 if (!access(path, mode))
542 "Check on %cPATH (%s) failed: %s\n"
543 "Please create this file and/or rerun `configure' "
544 "using --with-%cpath and recompile to correct this.\n",
545 which, path, strerror(errno), which);
551 /*----------------------------------------------------------------------------
553 *--------------------------------------------------------------------------*/
554 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
555 static void set_core_limit(void) {
556 struct rlimit corelim;
558 if (getrlimit(RLIMIT_CORE, &corelim)) {
559 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
560 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
563 corelim.rlim_cur = corelim.rlim_max;
564 if (setrlimit(RLIMIT_CORE, &corelim))
565 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
571 /*----------------------------------------------------------------------------
572 * set_userid_if_needed()
573 *--------------------------------------------------------------------------*/
574 static int set_userid_if_needed(void) {
575 if (getuid() == 0 || geteuid() == 0 ||
576 getgid() == 0 || getegid() == 0) {
577 fprintf(stderr, "ERROR: This server will not run as superuser.\n");
585 /*----------------------------------------------------------------------------
588 * TODO: This should set the basic environment up and start the main loop.
589 * we're doing waaaaaaaaay too much server initialization here. I hate
590 * long and ugly control paths... -smd
591 *--------------------------------------------------------------------------*/
592 int main(int argc, char **argv) {
593 CurrentTime = time(NULL);
595 thisServer.argc = argc;
596 thisServer.argv = argv;
597 thisServer.uid = getuid();
598 thisServer.euid = geteuid();
601 mem_dbg_initialise();
604 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
608 umask(077); /* better safe than sorry --SRB */
609 memset(&me, 0, sizeof(me));
610 memset(&me_con, 0, sizeof(me_con));
611 cli_connect(&me) = &me_con;
614 parse_command_line(argc, argv);
617 fprintf(stderr, "Fail: Cannot chdir(%s): %s, check DPATH\n", dpath, strerror(errno));
621 if (!set_userid_if_needed())
624 /* Check paths for accessibility */
625 if (!check_file_access(SPATH, 'S', X_OK) ||
626 !check_file_access(configfile, 'C', R_OK))
629 debug_init(thisServer.bootopt & BOOT_TTY);
630 daemon_init(thisServer.bootopt & BOOT_TTY);
631 event_init(MAXCONNECTIONS);
634 feature_init(); /* initialize features... */
637 Debug((DEBUG_FATAL, "Failed to acquire PID file lock after fork"));
640 set_nomem_handler(outofmemory);
642 if (!init_string()) {
643 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to initialize string module");
660 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to read configuration file %s",
665 init_server_identity();
672 timer_add(timer_init(&connect_timer), try_connections, 0, TT_RELATIVE, 1);
673 timer_add(timer_init(&ping_timer), check_pings, 0, TT_RELATIVE, 1);
674 timer_add(timer_init(&destruct_event_timer), exec_expired_destruct_events, 0, TT_PERIODIC, 60);
676 CurrentTime = time(NULL);
679 cli_magic(&me) = CLIENT_MAGIC;
683 cli_serv(&me)->timestamp = TStime(); /* Abuse own link timestamp as start TS */
684 cli_serv(&me)->prot = atoi(MAJOR_PROTOCOL);
685 cli_serv(&me)->up = &me;
686 cli_serv(&me)->down = NULL;
687 cli_handler(&me) = SERVER_HANDLER;
689 SetYXXCapacity(&me, MAXCLIENTS);
691 cli_lasttime(&me) = cli_since(&me) = cli_firsttime(&me) = CurrentTime;
698 Debug((DEBUG_NOTICE, "Server ready..."));
699 log_write(LS_SYSTEM, L_NOTICE, 0, "Server Ready");