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 "ircd_alloc.h"
31 #include "ircd_reply.h"
32 #include "ircd_signal.h"
33 #include "ircd_string.h"
62 #include <sys/socket.h>
68 /*----------------------------------------------------------------------------
70 *--------------------------------------------------------------------------*/
71 extern void init_counters(void);
73 /*----------------------------------------------------------------------------
75 *--------------------------------------------------------------------------*/
82 /*----------------------------------------------------------------------------
84 *--------------------------------------------------------------------------*/
85 struct Client me; // That's me
86 struct Client *GlobalClientList = &me; // Pointer to beginning of Client list
87 time_t TSoffset = 0; // Offset of timestamps to system clock
88 int GlobalRehashFlag = 0; // do a rehash if set
89 int GlobalRestartFlag = 0; // do a restart if set
90 time_t CurrentTime; // Updated every time we leave select()
92 char *configfile = CPATH; // Server configuration file
93 int debuglevel = -1; // Server debug level
94 char *debugmode = ""; // Server debug level
95 static char *dpath = DPATH;
97 time_t nextconnect = 1; // time for next try_connections call
98 time_t nextping = 1; // same as above for check_pings()
100 static struct Daemon thisServer = { 0 }; // server process info
104 /*----------------------------------------------------------------------------
106 *--------------------------------------------------------------------------*/
107 void server_die(const char* message) {
108 ircd_log(L_CRIT, "Server terminating: %s", message);
109 sendto_opmask_butone(0, SNO_OLDSNO, "Server terminating: %s", message);
110 flush_connections(0);
111 close_connections(1);
112 thisServer.running = 0;
116 /*----------------------------------------------------------------------------
117 * API: server_restart
118 *--------------------------------------------------------------------------*/
119 void server_restart(const char* message) {
120 static int restarting = 0;
122 ircd_log(L_WARNING, "Restarting Server: %s", message);
126 sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
127 Debug((DEBUG_NOTICE, "Restarting server..."));
128 flush_connections(0);
131 close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG)));
133 execv(SPATH, thisServer.argv);
135 /* Have to reopen since it has been closed above */
136 open_log(*thisServer.argv);
137 ircd_log(L_CRIT, "execv(%s,%s) failed: %m\n", SPATH, *thisServer.argv);
139 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
140 SPATH, (strerror(errno)) ? strerror(errno) : ""));
145 /*----------------------------------------------------------------------------
146 * outofmemory: Handler for out of memory conditions...
147 *--------------------------------------------------------------------------*/
148 static void outofmemory(void) {
149 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
150 server_restart("Out of Memory");
154 /*----------------------------------------------------------------------------
156 *--------------------------------------------------------------------------*/
157 static void write_pidfile(void) {
160 if (!(pidf = fopen(PPATH, "w+"))) {
162 "Error opening pid file \"%s\": %s", PPATH, strerror(errno)));
166 if (fprintf(pidf, "%5d\n", getpid()) < 5)
167 Debug((DEBUG_NOTICE, "Error writing to pid file %s", PPATH));
173 /*----------------------------------------------------------------------------
176 * Scan through configuration and try new connections.
178 * Returns the calendar time when the next call to this
179 * function should be made latest. (No harm done if this
180 * is called earlier or later...)
181 *--------------------------------------------------------------------------*/
182 static time_t try_connections(void) {
183 struct ConfItem *aconf;
185 struct ConfItem **pconf;
189 struct ConfClass *cltmp;
190 struct ConfItem *cconf;
191 struct ConfItem *con_conf = NULL;
193 unsigned int con_class = 0;
196 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
197 for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
198 /* Also when already connecting! (update holdtimes) --SRB */
199 if (!(aconf->status & CONF_SERVER) || aconf->port == 0)
202 /* Also skip juped servers */
203 if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
206 /* Skip this entry if the use of it is still on hold until
207 * future. Otherwise handle this entry (and set it on hold until next
208 * time). Will reset only hold times, if already made one successfull
209 * connection... [this algorithm is a bit fuzzy... -- msa >;) ]
211 if (aconf->hold > CurrentTime && (next > aconf->hold || next == 0)) {
216 cltmp = aconf->confClass;
217 confrq = get_con_freq(cltmp);
218 aconf->hold = CurrentTime + confrq;
220 /* Found a CONNECT config with port specified, scan clients and see if
221 * this server is already connected?
223 cptr = FindServer(aconf->name);
225 if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
226 (!connecting || (ConClass(cltmp) > con_class))) {
227 /* Check connect rules to see if we're allowed to try */
228 for (cconf = GlobalConfList; cconf; cconf = cconf->next) {
229 if ((cconf->status & CONF_CRULE) && !match(cconf->host, aconf->name))
230 if (crule_eval(cconf->passwd))
234 con_class = ConClass(cltmp);
236 /* We connect only one at time... */
240 if ((next > aconf->hold) || (next == 0))
244 if (con_conf->next) { /* are we already last? */
245 /* Put the current one at the end and make sure we try all connections */
246 for (pconf = &GlobalConfList; (aconf = *pconf); pconf = &(aconf->next))
247 if (aconf == con_conf)
248 *pconf = aconf->next;
249 (*pconf = con_conf)->next = 0;
252 if (connect_server(con_conf, 0, 0))
253 sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
257 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
262 /*----------------------------------------------------------------------------
265 * TODO: This should be moved out of ircd.c. It's protocol-specific when you
266 * get right down to it. Can't really be done until the server is more
267 * modular, however...
268 *--------------------------------------------------------------------------*/
269 static time_t check_pings(void) {
271 int next_check = CurrentTime + PINGFREQUENCY;
275 /* Scan through the client table */
276 for (i=0; i <= HighestFd; i++) {
277 struct Client *cptr = LocalClientArray[i];
282 assert(&me != cptr); /* I should never be in the local client array! */
285 /* Remove dead clients. */
287 exit_client(cptr, cptr, &me, cptr->info);
291 max_ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
293 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
294 cptr->name, (cptr->flags & FLAGS_PINGSENT) ? "[Ping Sent]" : "[]",
295 max_ping, (int)(CurrentTime - cptr->lasttime)));
298 /* Ok, the thing that will happen most frequently, is that someone will
299 * have sent something recently. Cover this first for speed.
301 if (CurrentTime-cptr->lasttime < max_ping) {
302 expire = cptr->lasttime + max_ping;
303 if (expire < next_check)
308 /* Quit the client after max_ping*2 - they should have answered by now */
309 if (CurrentTime-cptr->lasttime >= (max_ping*2) ) {
310 /* If it was a server, then tell ops about it. */
311 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
312 sendto_opmask_butone(0, SNO_OLDSNO,
313 "No response from %s, closing link", cptr->name);
314 exit_client_msg(cptr, cptr, &me, "Ping timeout");
318 /* Unregistered clients pingout after max_ping seconds, they don't
319 * get given a second chance - if they were then people could not quite
320 * finish registration and hold resources without being subject to k/g
323 if (!IsRegistered(cptr)) {
324 /* Display message if they have sent a NICK and a USER but no
327 if (*cptr->name && cptr->user && *cptr->user->username) {
328 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
329 ":Your client may not be compatible with this server.");
330 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
331 ":Compatible clients are available at "
332 "ftp://ftp.undernet.org/pub/irc/clients");
334 exit_client_msg(cptr,cptr,&me, "Ping Timeout");
338 if (!(cptr->flags & FLAGS_PINGSENT)) {
339 /* If we havent PINGed the connection and we havent heard from it in a
340 * while, PING it to make sure it is still alive.
342 cptr->flags |= FLAGS_PINGSENT;
344 /* If we're late in noticing don't hold it against them :) */
345 cptr->lasttime = CurrentTime - max_ping;
348 sendrawto_one(cptr, MSG_PING " :%s", me.name);
350 sendcmdto_one(&me, CMD_PING, cptr, ":%s", me.name);
353 expire = cptr->lasttime + max_ping * 2;
354 if (expire < next_check)
358 assert(next_check >= CurrentTime);
360 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
361 CurrentTime, next_check-CurrentTime));
367 /*----------------------------------------------------------------------------
369 * Side Effects: changes GLOBALS me, thisServer, dpath, configfile, debuglevel
371 *--------------------------------------------------------------------------*/
372 static void parse_command_line(int argc, char** argv) {
373 const char *options = "d:f:h:ntvx:";
376 if (thisServer.euid != thisServer.uid)
377 setuid(thisServer.uid);
379 /* Do we really need to santiy check the non-NULLness of optarg? That's
380 * getopt()'s job... Removing those... -zs
382 while ((opt = getopt(argc, argv, options)) != EOF)
385 case 't': thisServer.bootopt |= BOOT_TTY; break;
386 case 'd': dpath = optarg; break;
387 case 'f': configfile = optarg; break;
388 case 'h': ircd_strncpy(me.name, optarg, HOSTLEN); break;
389 case 'v': printf("ircd %s\n", version); exit(0);
392 debuglevel = atoi(optarg);
396 thisServer.bootopt |= BOOT_DEBUG;
400 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv]\n");
401 printf("\n -n -t\t Don't detach\n -v\t display version\n\n");
402 printf("Server not started.\n");
408 /*----------------------------------------------------------------------------
410 *--------------------------------------------------------------------------*/
411 static void daemon_init(int no_fork) {
412 if (!init_connection_limits())
415 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
426 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
427 ioctl(fd, TIOCNOTTY, 0);
437 /*----------------------------------------------------------------------------
439 *--------------------------------------------------------------------------*/
440 static void event_loop(void) {
441 time_t nextdnscheck = 0;
444 thisServer.running = 1;
445 while (thisServer.running) {
446 /* We only want to connect if a connection is due, not every time through.
447 * Note, if there are no active C lines, this call to Tryconnections is
448 * made once only; it will return 0. - avalon
450 if (nextconnect && CurrentTime >= nextconnect)
451 nextconnect = try_connections();
453 /* DNS checks. One to timeout queries, one for cache expiries. */
454 nextdnscheck = timeout_resolver(CurrentTime);
456 /* Take the smaller of the two 'timed' event times as the time of next
457 * event (stops us being late :) - avalon
458 * WARNING - nextconnect can return 0!
461 delay = IRCD_MIN(nextping, nextconnect);
465 delay = IRCD_MIN(nextdnscheck, delay) - CurrentTime;
467 /* Adjust delay to something reasonable [ad hoc values] (one might think
468 * something more clever here... --msa) We don't really need to check that
469 * often and as long as we don't delay too long, everything should be ok.
470 * waiting too long can cause things to timeout... i.e. PINGS -> a
471 * disconnection :( - avalon
476 read_message(IRCD_MIN(delay, TIMESEC));
478 /* ...perhaps should not do these loops every time, but only if there is
479 * some chance of something happening (but, note that conf->hold times may
480 * be changed elsewhere--so precomputed next event time might be too far
481 * away... (similarly with ping times) --msa
483 if (CurrentTime >= nextping)
484 nextping = check_pings();
486 /* timeout pending queries that haven't been responded to */
487 timeout_auth_queries(CurrentTime);
489 ip_registry_expire();
491 if (GlobalRehashFlag) {
493 GlobalRehashFlag = 0;
496 if (GlobalRestartFlag)
497 server_restart("caught signal: SIGINT");
502 /*----------------------------------------------------------------------------
503 * check_file_access: random helper function to make sure that a file is
504 * accessible in a certain way, and complain if not.
505 *--------------------------------------------------------------------------*/
506 static char check_file_access(const char *path, char which, int mode) {
507 if (!access(path, mode))
511 "Check on %cPATH (%s) failed: %s\n"
512 "Please create file and/or rerun `make config' and "
513 "recompile to correct this.\n",
514 which, path, strerror(errno));
517 fprintf(stderr, "Keep in mind that paths are relative to CHROOTDIR.\n");
524 /*----------------------------------------------------------------------------
526 *--------------------------------------------------------------------------*/
527 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
528 static void set_core_limit(void) {
529 struct rlimit corelim;
531 if (getrlimit(RLIMIT_CORE, &corelim)) {
532 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
533 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
536 corelim.rlim_cur = corelim.rlim_max;
537 if (setrlimit(RLIMIT_CORE, &corelim))
538 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
544 /*----------------------------------------------------------------------------
545 * set_chroot_environment
546 *--------------------------------------------------------------------------*/
548 static char set_chroot_environment(void) {
549 /* Must be root to chroot! Silly if you ask me... */
554 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", dpath, strerror(errno));
558 fprintf(stderr, "Fail: Cannot chroot(%s): %s\n", dpath, strerror(errno));
567 /*----------------------------------------------------------------------------
568 * set_userid_if_needed()
569 *--------------------------------------------------------------------------*/
570 static int set_userid_if_needed(void) {
571 /* TODO: Drop privs correctly! */
572 #if defined(IRC_GID) && defined(IRC_UID)
579 if (getuid() == 0 || geteuid() == 0 ||
580 getgid() == 0 || getegid() == 0) {
581 fprintf(stderr, "ERROR: This server will not run as superuser.\n");
589 /*----------------------------------------------------------------------------
592 * TODO: This should set the basic environment up and start the main loop.
593 * we're doing waaaaaaaaay too much server initialization here. I hate
594 * long and ugly control paths... -smd
595 *--------------------------------------------------------------------------*/
596 int main(int argc, char **argv) {
597 CurrentTime = time(NULL);
599 thisServer.argc = argc;
600 thisServer.argv = argv;
601 thisServer.uid = getuid();
602 thisServer.euid = geteuid();
605 if (!set_chroot_environment())
609 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
613 umask(077); /* better safe than sorry --SRB */
614 memset(&me, 0, sizeof(me));
617 parse_command_line(argc, argv);
620 fprintf(stderr, "Fail: Cannot chdir(%s): %s, check DPATH\n", dpath, strerror(errno));
624 if (!set_userid_if_needed())
627 /* Check paths for accessibility */
628 if (!check_file_access(SPATH, 'S', X_OK) ||
629 !check_file_access(configfile, 'C', R_OK) ||
630 !check_file_access(MPATH, 'M', R_OK) ||
631 !check_file_access(RPATH, 'R', R_OK))
635 if (!check_file_access(LPATH, 'L', W_OK))
639 debug_init(thisServer.bootopt & BOOT_TTY);
640 daemon_init(thisServer.bootopt & BOOT_TTY);
645 set_nomem_handler(outofmemory);
658 ircd_log(L_CRIT, "Failed to read configuration file %s", configfile);
662 if (!init_server_identity()) {
663 ircd_log(L_CRIT, "Failed to initialize server identity");
670 rmotd = read_motd(RPATH);
671 motd = read_motd(MPATH);
672 CurrentTime = time(NULL);
678 me.serv->timestamp = TStime(); /* Abuse own link timestamp as start TS */
679 me.serv->prot = atoi(MAJOR_PROTOCOL);
681 me.serv->down = NULL;
682 me.handler = SERVER_HANDLER;
684 SetYXXCapacity(&me, MAXCLIENTS);
686 me.lasttime = me.since = me.firsttime = CurrentTime;
694 Debug((DEBUG_NOTICE, "Server ready..."));
695 ircd_log(L_NOTICE, "Server Ready");