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.
28 #include "ircd_alloc.h" /* set_nomem_handler */
30 #include "ircd_reply.h"
31 #include "ircd_signal.h"
32 #include "ircd_string.h"
62 #include <sys/socket.h>
67 extern void init_counters(void);
74 struct Client me; /* That's me */
75 struct Client* GlobalClientList = &me; /* Pointer to beginning of Client list */
76 time_t TSoffset = 0; /* Offset of timestamps to system clock */
77 int GlobalRehashFlag = 0; /* do a rehash if set */
78 int GlobalRestartFlag = 0; /* do a restart if set */
79 time_t CurrentTime; /* Updated every time we leave select() */
81 static struct Daemon thisServer = { 0 }; /* server process info */
83 char *configfile = CPATH; /* Server configuration file */
84 int debuglevel = -1; /* Server debug level */
85 char *debugmode = ""; /* -"- -"- -"- */
86 static char *dpath = DPATH;
88 time_t nextconnect = 1; /* time for next try_connections call */
89 time_t nextping = 1; /* same as above for check_pings() */
90 time_t nextdnscheck = 0; /* next time to poll dns to force timeouts */
91 time_t nextexpire = 1; /* next expire run on the dns cache */
97 static void server_reboot(const char* message)
99 sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
100 Debug((DEBUG_NOTICE, "Restarting server..."));
101 flush_connections(0);
104 close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG)));
106 execv(SPATH, thisServer.argv);
109 * Have to reopen since it has been closed above
111 open_log(*thisServer.argv);
112 ircd_log(L_CRIT, "execv(%s,%s) failed: %m\n", SPATH, *thisServer.argv);
114 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
115 SPATH, (strerror(errno)) ? strerror(errno) : ""));
119 void server_die(const char* message)
121 ircd_log(L_CRIT, "Server terminating: %s", message);
122 sendto_opmask_butone(0, SNO_OLDSNO, "Server terminating: %s", message);
123 flush_connections(0);
124 close_connections(1);
125 thisServer.running = 0;
128 void server_restart(const char* message)
130 static int restarting = 0;
132 ircd_log(L_WARNING, "Restarting Server: %s", message);
133 if (restarting == 0) {
135 server_reboot(message);
139 static void outofmemory(void)
141 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
142 server_restart("Out of Memory");
145 static void write_pidfile(void)
150 if ((fd = open(PPATH, O_CREAT | O_WRONLY, 0600)) == -1) {
151 Debug((DEBUG_NOTICE, "Error opening pid file \"%s\": %s",
152 PPATH, strerror(errno)));
155 memset(buff, 0, sizeof(buff));
156 sprintf(buff, "%5d\n", getpid());
157 if (write(fd, buff, strlen(buff)) == -1)
158 Debug((DEBUG_NOTICE, "Error writing to pid file %s", PPATH));
166 * Scan through configuration and try new connections.
168 * Returns the calendar time when the next call to this
169 * function should be made latest. (No harm done if this
170 * is called earlier or later...)
172 static time_t try_connections(void)
174 struct ConfItem* aconf;
176 struct ConfItem** pconf;
180 struct ConfClass* cltmp;
181 struct ConfItem* cconf;
182 struct ConfItem* con_conf = NULL;
184 unsigned int con_class = 0;
187 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
188 for (aconf = GlobalConfList; aconf; aconf = aconf->next)
190 /* Also when already connecting! (update holdtimes) --SRB */
191 if (!(aconf->status & CONF_SERVER) || aconf->port == 0)
194 /* Also skip juped servers */
195 if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
198 cltmp = aconf->confClass;
200 * Skip this entry if the use of it is still on hold until
201 * future. Otherwise handle this entry (and set it on hold
202 * until next time). Will reset only hold times, if already
203 * made one successfull connection... [this algorithm is
204 * a bit fuzzy... -- msa >;) ]
207 if ((aconf->hold > CurrentTime))
209 if ((next > aconf->hold) || (next == 0))
214 confrq = get_con_freq(cltmp);
215 aconf->hold = CurrentTime + confrq;
217 * Found a CONNECT config with port specified, scan clients
218 * and see if this server is already connected?
220 cptr = FindServer(aconf->name);
222 if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
223 (!connecting || (ConClass(cltmp) > con_class)))
225 /* Check connect rules to see if we're allowed to try */
226 for (cconf = GlobalConfList; cconf; cconf = cconf->next)
227 if ((cconf->status & CONF_CRULE) &&
228 (match(cconf->host, aconf->name) == 0))
229 if (crule_eval(cconf->passwd))
233 con_class = ConClass(cltmp);
235 /* We connect only one at time... */
239 if ((next > aconf->hold) || (next == 0))
244 if (con_conf->next) /* are we already last? */
246 /* Put the current one at the end and make sure we try all connections */
247 for (pconf = &GlobalConfList; (aconf = *pconf); pconf = &(aconf->next))
248 if (aconf == con_conf)
249 *pconf = aconf->next;
250 (*pconf = con_conf)->next = 0;
252 if (connect_server(con_conf, 0, 0))
253 sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
256 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
260 static time_t check_pings(void)
263 /* Temp to figure out what time this connection will next need
266 int next_check = CurrentTime + PINGFREQUENCY;
268 * The current lowest expire time - ie: the time that check_pings
269 * needs to be called next.
273 * The time you've got before a ping is sent/your connection is
277 int i=0; /* loop counter */
279 /* Scan through the client table */
280 for (i=0; i <= HighestFd; i++) {
283 cptr = LocalClientArray[i];
285 /* Skip empty entries */
289 assert(&me != cptr); /* I should never be in the local client array,
290 * so if I am, dying is a good thing(tm).
293 /* Remove dead clients.
294 * We will have sent opers a message when we set the dead flag,
295 * so don't bother to send one now.
298 exit_client(cptr, cptr, &me, cptr->info);
302 /* Should we concider adding a class 0 for 'unregistered clients',
303 * where we can specify their 'ping timeout' etc?
305 max_ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
307 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
308 cptr->name, (cptr->flags & FLAGS_PINGSENT) ? "[Ping Sent]" : "[]",
309 max_ping, (int)(CurrentTime - cptr->lasttime)));
311 /* Ok, the thing that will happen most frequently, is that someone will
312 * have sent something recently. Cover this first for speed.
314 if (CurrentTime-cptr->lasttime < max_ping) {
315 expire=cptr->lasttime + max_ping;
316 if (expire<next_check)
321 /* Quit the client after max_ping*2 - they should have answered by now */
322 if (CurrentTime-cptr->lasttime >= (max_ping*2) ) {
324 /* If it was a server, then tell ops about it. */
325 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
326 sendto_opmask_butone(0, SNO_OLDSNO,
327 "No response from %s, closing link", cptr->name);
329 exit_client_msg(cptr, cptr, &me, "Ping timeout");
331 } /* of testing to see if ping has been sent */
333 /* Unregistered clients pingout after max_ping seconds, they don't
334 * get given a second chance - if they were then people could not quite
335 * finish registration and hold resources without being subject to k/g
338 if (!IsRegistered(cptr)) {
339 /* Display message if they have sent a NICK and a USER but no
342 if (*cptr->name && cptr->user && *cptr->user->username) {
343 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
344 ":Your client may not be compatible with this server.");
345 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
346 ":Compatible clients are available at "
347 "ftp://ftp.undernet.org/pub/irc/clients");
349 exit_client_msg(cptr,cptr,&me, "Ping Timeout");
351 } /* of not registered */
353 if (0 == (cptr->flags & FLAGS_PINGSENT)) {
355 * If we havent PINGed the connection and we havent heard from it in a
356 * while, PING it to make sure it is still alive.
358 cptr->flags |= FLAGS_PINGSENT;
361 * If we're late in noticing don't hold it against them :)
363 cptr->lasttime = CurrentTime - max_ping;
366 sendrawto_one(cptr, MSG_PING " :%s", me.name);
368 sendcmdto_one(&me, CMD_PING, cptr, ":%s", me.name);
369 } /* of if not ping sent... */
371 expire=cptr->lasttime+max_ping*2;
373 if (expire<next_check)
376 } /* end of loop over clients */
378 assert(next_check>=CurrentTime);
380 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",CurrentTime,next_check-CurrentTime));
386 static time_t check_pings(void)
391 time_t oldest = CurrentTime + PINGFREQUENCY;
394 /* For each client... */
395 for (i = 0; i <= HighestFd; i++) {
396 if (!(cptr = LocalClientArray[i])) /* oops! not a client... */
399 * me is never in the local client array
403 * Note: No need to notify opers here.
404 * It's already done when "FLAGS_DEADSOCKET" is set.
407 exit_client(cptr, cptr, &me, cptr->info);
411 max_ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
413 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%d ping: %d current: %d",
414 cptr->name, cptr->status, max_ping,
415 (int)(CurrentTime - cptr->lasttime)));
418 * Ok, so goto's are ugly and can be avoided here but this code
419 * is already indented enough so I think its justified. -avalon
422 * If this is a registered client that we've heard of in a reasonable
423 * time, then skip them.
425 if (IsRegistered(cptr) && (max_ping >= CurrentTime - cptr->lasttime))
428 * If the server hasnt talked to us in 2 * ping seconds
429 * and it has a ping time, then close its connection.
430 * If the client is a user and a KILL line was found
431 * to be active, close this connection too.
433 if (((CurrentTime - cptr->lasttime) >= (2 * ping) && (cptr->flags & FLAGS_PINGSENT)) ||
434 (!IsRegistered(cptr) && !IsHandshake(cptr) && (CurrentTime - cptr->firsttime) >= ping))
436 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
438 sendto_ops("No response from %s, closing link", cptr->name); /* XXX DEAD */
439 exit_client(cptr, cptr, &me, "Ping timeout");
443 if (!IsRegistered(cptr) && *cptr->name && *cptr->user->username) {
444 sendto_one(cptr, /* XXX DEAD */
445 ":%s %d %s :Your client may not be compatible with this server.",
446 me.name, ERR_BADPING, cptr->name);
447 sendto_one(cptr, /* XXX DEAD */
448 ":%s %d %s :Compatible clients are available at "
449 "ftp://ftp.undernet.org/pub/irc/clients",
450 me.name, ERR_BADPING, cptr->name);
452 exit_client_msg(cptr, cptr, &me, "Ping timeout");
456 else if (IsRegistered(cptr) && 0 == (cptr->flags & FLAGS_PINGSENT)) {
458 * If we havent PINGed the connection and we havent
459 * heard from it in a while, PING it to make sure
462 cptr->flags |= FLAGS_PINGSENT;
464 * not nice but does the job
466 cptr->lasttime = CurrentTime - ping;
468 sendto_one(cptr, "PING :%s", me.name); /* XXX DEAD */
470 sendto_one(cptr, "%s " TOK_PING " :%s", NumServ(&me), me.name); /* XXX DEAD */
473 timeout = cptr->lasttime + max_ping;
474 while (timeout <= CurrentTime)
476 if (timeout < oldest)
479 if (oldest < CurrentTime)
480 oldest = CurrentTime + PINGFREQUENCY;
482 "Next check_ping() call at: %s, %d " TIME_T_FMT " " TIME_T_FMT,
483 myctime(oldest), ping, oldest, CurrentTime));
492 * This is called when the commandline is not acceptable.
493 * Give error message and exit without starting anything.
495 static void print_usage(void)
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 * ZZZ this is going to need confirmation on other OS's
507 * #include <getopt.h>
508 * Solaris has getopt.h, you should too... hopefully
509 * BSD declares them in stdlib.h
510 * extern char *optarg;
512 * for FreeBSD the following are defined:
514 * extern char *optarg;
518 * extern in optreset;
521 * All command line parameters have the syntax "-f string" or "-fstring"
523 * -d filename - specify d:line file
524 * -f filename - specify config file
525 * -h hostname - specify server name
526 * -k filename - specify k:line file (hybrid)
527 * -l filename - specify log file
528 * -n - do not fork, run in foreground
529 * -t - do not fork send debugging info to tty
530 * -v - print version and exit
531 * -x - set debug level, if compiled for debug logging
533 static void parse_command_line(int argc, char** argv)
535 const char* options = "d:f:h:ntvx:";
538 if (thisServer.euid != thisServer.uid)
539 setuid(thisServer.uid);
541 while ((opt = getopt(argc, argv, options)) != EOF) {
553 ircd_strncpy(me.name, optarg, HOSTLEN);
557 thisServer.bootopt |= BOOT_TTY;
560 printf("ircd %s\n", version);
564 debuglevel = atoi(optarg);
568 thisServer.bootopt |= BOOT_DEBUG;
581 static void daemon_init(int no_fork)
583 if (!init_connection_limits())
586 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
595 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
596 ioctl(fd, TIOCNOTTY, 0);
605 static void event_loop(void)
609 while (thisServer.running) {
611 * We only want to connect if a connection is due,
612 * not every time through. Note, if there are no
613 * active C lines, this call to Tryconnections is
614 * made once only; it will return 0. - avalon
616 if (nextconnect && CurrentTime >= nextconnect)
617 nextconnect = try_connections();
619 * DNS checks. One to timeout queries, one for cache expiries.
621 nextdnscheck = timeout_resolver(CurrentTime);
623 * Take the smaller of the two 'timed' event times as
624 * the time of next event (stops us being late :) - avalon
625 * WARNING - nextconnect can return 0!
628 delay = IRCD_MIN(nextping, nextconnect);
631 delay = IRCD_MIN(nextdnscheck, delay);
632 delay -= CurrentTime;
634 * Adjust delay to something reasonable [ad hoc values]
635 * (one might think something more clever here... --msa)
636 * We don't really need to check that often and as long
637 * as we don't delay too long, everything should be ok.
638 * waiting too long can cause things to timeout...
639 * i.e. PINGS -> a disconnection :(
645 delay = IRCD_MIN(delay, TIMESEC);
648 Debug((DEBUG_DEBUG, "Got message(s)"));
651 * ...perhaps should not do these loops every time,
652 * but only if there is some chance of something
653 * happening (but, note that conf->hold times may
654 * be changed elsewhere--so precomputed next event
655 * time might be too far away... (similarly with
658 if (CurrentTime >= nextping)
659 nextping = check_pings();
662 * timeout pending queries that haven't been responded to
664 timeout_auth_queries(CurrentTime);
667 if (GlobalRehashFlag) {
669 GlobalRehashFlag = 0;
671 if (GlobalRestartFlag)
672 server_restart("caught signal: SIGINT");
676 int main(int argc, char *argv[])
678 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
679 struct rlimit corelim;
682 CurrentTime = time(NULL);
686 if (MAXCONNECTIONS < 64 || MAXCONNECTIONS > 256000) {
687 fprintf(stderr, "%s: MAXCONNECTIONS insane: %d\n", *argv, MAXCONNECTIONS);
690 thisServer.argc = argc;
691 thisServer.argv = argv;
692 thisServer.uid = getuid();
693 thisServer.euid = geteuid();
695 monstartup(0, etext);
697 signal(SIGUSR1, s_monitor);
702 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", DPATH, strerror(errno));
706 fprintf(stderr, "Fail: Cannot chroot(%s): %s\n", DPATH, strerror(errno));
710 #endif /*CHROOTDIR */
712 umask(077); /* better safe than sorry --SRB */
713 memset(&me, 0, sizeof(me));
719 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
720 if (getrlimit(RLIMIT_CORE, &corelim))
722 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
723 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
725 corelim.rlim_cur = corelim.rlim_max;
726 if (setrlimit(RLIMIT_CORE, &corelim))
727 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
729 parse_command_line(argc, argv);
732 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", dpath, strerror(errno));
737 if ((thisServer.uid != thisServer.euid) && !thisServer.euid) {
739 "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
744 #if !defined(CHROOTDIR) || (defined(IRC_UID) && defined(IRC_GID))
745 if (thisServer.euid != thisServer.uid) {
746 setuid(thisServer.uid);
747 setuid(thisServer.euid);
751 #if defined(IRC_UID) && defined(IRC_GID)
753 /* run as a specified user */
754 fprintf(stderr, "WARNING: running ircd with uid = %d\n", IRC_UID);
755 fprintf(stderr, " changing to gid %d.\n", IRC_GID);
759 /* check for setuid root as usual */
761 "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
765 #endif /*CHROOTDIR/UID/GID */
774 if (access(path, X_OK) == 0) {
777 if (access(path, R_OK) == 0) {
780 if (access(path, R_OK) == 0) {
783 if (access(path, R_OK) == 0) {
789 if (access(path, W_OK) == 0)
797 fprintf(stderr, "Check on %cPATH (%s) failed: %s\n", c, path, strerror(errno));
799 "Please create file and/or rerun `make config' and recompile to correct this.\n");
801 fprintf(stderr, "Keep in mind that all paths are relative to CHROOTDIR.\n");
814 debug_init(thisServer.bootopt & BOOT_TTY);
815 daemon_init(thisServer.bootopt & BOOT_TTY);
817 set_nomem_handler(outofmemory);
823 Debug((DEBUG_FATAL, "Failed in reading configuration file %s", configfile));
824 printf("Couldn't open configuration file %s\n", configfile);
827 if (!init_server_identity()) {
828 Debug((DEBUG_FATAL, "Failed to initialize server identity"));
833 rmotd = read_motd(RPATH);
834 motd = read_motd(MPATH);
835 CurrentTime = time(NULL);
840 * Abuse own link timestamp as start timestamp:
842 me.serv->timestamp = TStime();
843 me.serv->prot = atoi(MAJOR_PROTOCOL);
845 me.serv->down = NULL;
846 me.handler = SERVER_HANDLER;
848 SetYXXCapacity(&me, MAXCLIENTS);
850 me.lasttime = me.since = me.firsttime = CurrentTime;
858 Debug((DEBUG_NOTICE, "Server ready..."));
859 ircd_log(L_NOTICE, "Server Ready");
860 thisServer.running = 1;