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.
27 #include "ircd_alloc.h" /* set_nomem_handler */
29 #include "ircd_signal.h"
30 #include "ircd_string.h"
60 #include <sys/socket.h>
65 extern void init_counters(void);
72 struct Client me; /* That's me */
73 struct Client* GlobalClientList = &me; /* Pointer to beginning of Client list */
74 time_t TSoffset = 0; /* Offset of timestamps to system clock */
75 int GlobalRehashFlag = 0; /* do a rehash if set */
76 int GlobalRestartFlag = 0; /* do a restart if set */
77 time_t CurrentTime; /* Updated every time we leave select() */
79 static struct Daemon thisServer = { 0 }; /* server process info */
81 char *configfile = CPATH; /* Server configuration file */
82 int debuglevel = -1; /* Server debug level */
83 char *debugmode = ""; /* -"- -"- -"- */
84 static char *dpath = DPATH;
86 time_t nextconnect = 1; /* time for next try_connections call */
87 time_t nextping = 1; /* same as above for check_pings() */
88 time_t nextdnscheck = 0; /* next time to poll dns to force timeouts */
89 time_t nextexpire = 1; /* next expire run on the dns cache */
95 static void server_reboot(const char* message)
97 sendto_ops("Restarting server: %s", message);
98 Debug((DEBUG_NOTICE, "Restarting server..."));
102 close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG)));
104 execv(SPATH, thisServer.argv);
107 * Have to reopen since it has been closed above
109 open_log(*thisServer.argv);
110 ircd_log(L_CRIT, "execv(%s,%s) failed: %m\n", SPATH, *thisServer.argv);
112 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
113 SPATH, (strerror(errno)) ? strerror(errno) : ""));
117 void server_die(const char* message)
119 ircd_log(L_CRIT, "Server terminating: %s", message);
120 sendto_ops("Server terminating: %s", message);
121 flush_connections(0);
122 close_connections(1);
123 thisServer.running = 0;
126 void server_restart(const char* message)
128 static int restarting = 0;
130 ircd_log(L_WARNING, "Restarting Server: %s", message);
131 if (restarting == 0) {
133 server_reboot(message);
137 static void outofmemory(void)
139 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
140 server_restart("Out of Memory");
143 static void write_pidfile(void)
148 if ((fd = open(PPATH, O_CREAT | O_WRONLY, 0600)) == -1) {
149 Debug((DEBUG_NOTICE, "Error opening pid file \"%s\": %s",
150 PPATH, strerror(errno)));
153 memset(buff, 0, sizeof(buff));
154 sprintf(buff, "%5d\n", getpid());
155 if (write(fd, buff, strlen(buff)) == -1)
156 Debug((DEBUG_NOTICE, "Error writing to pid file %s", PPATH));
164 * Scan through configuration and try new connections.
166 * Returns the calendar time when the next call to this
167 * function should be made latest. (No harm done if this
168 * is called earlier or later...)
170 static time_t try_connections(void)
172 struct ConfItem* aconf;
174 struct ConfItem** pconf;
178 struct ConfClass* cltmp;
179 struct ConfItem* cconf;
180 struct ConfItem* con_conf = NULL;
182 unsigned int con_class = 0;
185 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
186 for (aconf = GlobalConfList; aconf; aconf = aconf->next)
188 /* Also when already connecting! (update holdtimes) --SRB */
189 if (!(aconf->status & CONF_SERVER) || aconf->port == 0)
192 /* Also skip juped servers */
193 if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
196 cltmp = aconf->confClass;
198 * Skip this entry if the use of it is still on hold until
199 * future. Otherwise handle this entry (and set it on hold
200 * until next time). Will reset only hold times, if already
201 * made one successfull connection... [this algorithm is
202 * a bit fuzzy... -- msa >;) ]
205 if ((aconf->hold > CurrentTime))
207 if ((next > aconf->hold) || (next == 0))
212 confrq = get_con_freq(cltmp);
213 aconf->hold = CurrentTime + confrq;
215 * Found a CONNECT config with port specified, scan clients
216 * and see if this server is already connected?
218 cptr = FindServer(aconf->name);
220 if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
221 (!connecting || (ConClass(cltmp) > con_class)))
223 /* Check connect rules to see if we're allowed to try */
224 for (cconf = GlobalConfList; cconf; cconf = cconf->next)
225 if ((cconf->status & CONF_CRULE) &&
226 (match(cconf->host, aconf->name) == 0))
227 if (crule_eval(cconf->passwd))
231 con_class = ConClass(cltmp);
233 /* We connect only one at time... */
237 if ((next > aconf->hold) || (next == 0))
242 if (con_conf->next) /* are we already last? */
244 /* Put the current one at the end and make sure we try all connections */
245 for (pconf = &GlobalConfList; (aconf = *pconf); pconf = &(aconf->next))
246 if (aconf == con_conf)
247 *pconf = aconf->next;
248 (*pconf = con_conf)->next = 0;
250 if (connect_server(con_conf, 0, 0))
251 sendto_ops("Connection to %s activated.", con_conf->name);
253 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
257 static time_t check_pings(void)
260 /* Temp to figure out what time this connection will next need
263 int next_check = CurrentTime + PINGFREQUENCY;
265 * The current lowest expire time - ie: the time that check_pings
266 * needs to be called next.
270 * The time you've got before a ping is sent/your connection is
274 int i=0; /* loop counter */
276 /* Scan through the client table */
277 for (i=0; i <= HighestFd; i++) {
280 cptr = LocalClientArray[i];
282 /* Skip empty entries */
286 assert(&me != cptr); /* I should never be in the local client array,
287 * so if I am, dying is a good thing(tm).
290 /* Remove dead clients.
291 * We will have sent opers a message when we set the dead flag,
292 * so don't bother to send one now.
295 exit_client(cptr, cptr, &me, cptr->info);
299 /* Should we concider adding a class 0 for 'unregistered clients',
300 * where we can specify their 'ping timeout' etc?
302 max_ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
304 /* Ok, the thing that will happen most frequently, is that someone will
305 * have sent something recently. Cover this first for speed.
307 if (CurrentTime-cptr->lasttime <= max_ping) {
308 expire=cptr->lasttime + max_ping;
309 if (next_check<expire)
314 /* Quit the client after max_ping*2 - they should have answered by now */
315 if (CurrentTime-cptr->lasttime <= (max_ping*2) ) {
317 /* If it was a server, then tell ops about it. */
318 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
319 sendto_ops("No response from %s, closing link", cptr->name);
321 exit_client_msg(cptr, cptr, &me, "Ping timeout");
323 } /* of testing to see if ping has been sent */
325 /* Unregistered clients pingout after max_ping seconds, they don't
326 * get given a second chance.
328 if (!IsRegistered(cptr)) {
329 /* Display message if they have sent a NICK and a USER but no
332 if (*cptr->name && *cptr->user->username) {
334 ":%s %d %s :Your client may not be compatible with this server.",
335 me.name, ERR_BADPING, cptr->name);
337 ":%s %d %s :Compatible clients are available at "
338 "ftp://ftp.undernet.org/pub/irc/clients",
339 me.name, ERR_BADPING, cptr->name);
341 exit_client_msg(cptr,cptr,&me, "Ping Timeout");
343 } /* of not registered */
345 if (0 == (cptr->flags & FLAGS_PINGSENT)) {
347 * If we havent PINGed the connection and we havent heard from it in a
348 * while, PING it to make sure it is still alive.
350 cptr->flags |= FLAGS_PINGSENT;
353 * If we're late in noticing don't hold it against them :)
355 cptr->lasttime = CurrentTime - max_ping;
358 sendto_one(cptr, "PING :%s", me.name);
360 sendto_one(cptr, "%s " TOK_PING " :%s", NumServ(&me), me.name);
361 } /* of if not ping sent... */
363 expire=cptr->lasttime+max_ping*2;
365 if (expire<next_check)
368 } /* end of loop over clients */
370 assert(next_check>=CurrentTime);
376 static time_t check_pings(void)
381 time_t oldest = CurrentTime + PINGFREQUENCY;
384 /* For each client... */
385 for (i = 0; i <= HighestFd; i++) {
386 if (!(cptr = LocalClientArray[i])) /* oops! not a client... */
389 * me is never in the local client array
393 * Note: No need to notify opers here.
394 * It's already done when "FLAGS_DEADSOCKET" is set.
397 exit_client(cptr, cptr, &me, cptr->info);
401 max_ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
403 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%d ping: %d current: %d",
404 cptr->name, cptr->status, max_ping,
405 (int)(CurrentTime - cptr->lasttime)));
408 * Ok, so goto's are ugly and can be avoided here but this code
409 * is already indented enough so I think its justified. -avalon
412 * If this is a registered client that we've heard of in a reasonable
413 * time, then skip them.
415 if (IsRegistered(cptr) && (max_ping >= CurrentTime - cptr->lasttime))
418 * If the server hasnt talked to us in 2 * ping seconds
419 * and it has a ping time, then close its connection.
420 * If the client is a user and a KILL line was found
421 * to be active, close this connection too.
423 if (((CurrentTime - cptr->lasttime) >= (2 * ping) && (cptr->flags & FLAGS_PINGSENT)) ||
424 (!IsRegistered(cptr) && !IsHandshake(cptr) && (CurrentTime - cptr->firsttime) >= ping))
426 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
428 sendto_ops("No response from %s, closing link", cptr->name);
429 exit_client(cptr, cptr, &me, "Ping timeout");
433 if (!IsRegistered(cptr) && *cptr->name && *cptr->user->username) {
435 ":%s %d %s :Your client may not be compatible with this server.",
436 me.name, ERR_BADPING, cptr->name);
438 ":%s %d %s :Compatible clients are available at "
439 "ftp://ftp.undernet.org/pub/irc/clients",
440 me.name, ERR_BADPING, cptr->name);
442 exit_client_msg(cptr, cptr, &me, "Ping timeout");
446 else if (IsRegistered(cptr) && 0 == (cptr->flags & FLAGS_PINGSENT)) {
448 * If we havent PINGed the connection and we havent
449 * heard from it in a while, PING it to make sure
452 cptr->flags |= FLAGS_PINGSENT;
454 * not nice but does the job
456 cptr->lasttime = CurrentTime - ping;
458 sendto_one(cptr, "PING :%s", me.name);
460 sendto_one(cptr, "%s " TOK_PING " :%s", NumServ(&me), me.name);
463 timeout = cptr->lasttime + max_ping;
464 while (timeout <= CurrentTime)
466 if (timeout < oldest)
469 if (oldest < CurrentTime)
470 oldest = CurrentTime + PINGFREQUENCY;
472 "Next check_ping() call at: %s, %d " TIME_T_FMT " " TIME_T_FMT,
473 myctime(oldest), ping, oldest, CurrentTime));
482 * This is called when the commandline is not acceptable.
483 * Give error message and exit without starting anything.
485 static void print_usage(void)
487 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv]\n");
488 printf("Server not started\n");
494 * ZZZ this is going to need confirmation on other OS's
496 * #include <getopt.h>
497 * Solaris has getopt.h, you should too... hopefully
498 * BSD declares them in stdlib.h
499 * extern char *optarg;
501 * for FreeBSD the following are defined:
503 * extern char *optarg;
507 * extern in optreset;
510 * All command line parameters have the syntax "-f string" or "-fstring"
512 * -d filename - specify d:line file
513 * -f filename - specify config file
514 * -h hostname - specify server name
515 * -k filename - specify k:line file (hybrid)
516 * -l filename - specify log file
517 * -n - do not fork, run in foreground
518 * -t - do not fork send debugging info to tty
519 * -v - print version and exit
520 * -x - set debug level, if compiled for debug logging
522 static void parse_command_line(int argc, char** argv)
524 const char* options = "d:f:h:ntvx:";
527 if (thisServer.euid != thisServer.uid)
528 setuid(thisServer.uid);
530 while ((opt = getopt(argc, argv, options)) != EOF) {
542 ircd_strncpy(me.name, optarg, HOSTLEN);
546 thisServer.bootopt |= BOOT_TTY;
549 printf("ircd %s\n", version);
553 debuglevel = atoi(optarg);
557 thisServer.bootopt |= BOOT_DEBUG;
570 static void daemon_init(int no_fork)
572 if (!init_connection_limits())
575 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
584 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
585 ioctl(fd, TIOCNOTTY, 0);
594 static void event_loop(void)
598 while (thisServer.running) {
600 * We only want to connect if a connection is due,
601 * not every time through. Note, if there are no
602 * active C lines, this call to Tryconnections is
603 * made once only; it will return 0. - avalon
605 if (nextconnect && CurrentTime >= nextconnect)
606 nextconnect = try_connections();
608 * DNS checks. One to timeout queries, one for cache expiries.
610 nextdnscheck = timeout_resolver(CurrentTime);
612 * Take the smaller of the two 'timed' event times as
613 * the time of next event (stops us being late :) - avalon
614 * WARNING - nextconnect can return 0!
617 delay = IRCD_MIN(nextping, nextconnect);
620 delay = IRCD_MIN(nextdnscheck, delay);
621 delay -= CurrentTime;
623 * Adjust delay to something reasonable [ad hoc values]
624 * (one might think something more clever here... --msa)
625 * We don't really need to check that often and as long
626 * as we don't delay too long, everything should be ok.
627 * waiting too long can cause things to timeout...
628 * i.e. PINGS -> a disconnection :(
634 delay = IRCD_MIN(delay, TIMESEC);
637 Debug((DEBUG_DEBUG, "Got message(s)"));
640 * ...perhaps should not do these loops every time,
641 * but only if there is some chance of something
642 * happening (but, note that conf->hold times may
643 * be changed elsewhere--so precomputed next event
644 * time might be too far away... (similarly with
647 if (CurrentTime >= nextping)
648 nextping = check_pings();
651 * timeout pending queries that haven't been responded to
653 timeout_auth_queries(CurrentTime);
655 if (GlobalRehashFlag) {
657 GlobalRehashFlag = 0;
659 if (GlobalRestartFlag)
660 server_restart("caught signal: SIGINT");
664 int main(int argc, char *argv[])
666 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
667 struct rlimit corelim;
670 CurrentTime = time(NULL);
674 if (MAXCONNECTIONS < 64 || MAXCONNECTIONS > 256000) {
675 fprintf(stderr, "%s: MAXCONNECTIONS insane: %d\n", *argv, MAXCONNECTIONS);
678 thisServer.argc = argc;
679 thisServer.argv = argv;
680 thisServer.uid = getuid();
681 thisServer.euid = geteuid();
683 monstartup(0, etext);
685 signal(SIGUSR1, s_monitor);
690 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", DPATH, strerror(errno));
694 fprintf(stderr, "Fail: Cannot chroot(%s): %s\n", DPATH, strerror(errno));
698 #endif /*CHROOTDIR */
700 umask(077); /* better safe than sorry --SRB */
701 memset(&me, 0, sizeof(me));
707 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
708 if (getrlimit(RLIMIT_CORE, &corelim))
710 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
711 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
713 corelim.rlim_cur = corelim.rlim_max;
714 if (setrlimit(RLIMIT_CORE, &corelim))
715 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
717 parse_command_line(argc, argv);
720 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", dpath, strerror(errno));
725 if ((thisServer.uid != thisServer.euid) && !thisServer.euid) {
727 "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
732 #if !defined(CHROOTDIR) || (defined(IRC_UID) && defined(IRC_GID))
733 if (thisServer.euid != thisServer.uid) {
734 setuid(thisServer.uid);
735 setuid(thisServer.euid);
739 #if defined(IRC_UID) && defined(IRC_GID)
741 /* run as a specified user */
742 fprintf(stderr, "WARNING: running ircd with uid = %d\n", IRC_UID);
743 fprintf(stderr, " changing to gid %d.\n", IRC_GID);
747 /* check for setuid root as usual */
749 "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
753 #endif /*CHROOTDIR/UID/GID */
762 if (access(path, X_OK) == 0) {
765 if (access(path, R_OK) == 0) {
768 if (access(path, R_OK) == 0) {
771 if (access(path, R_OK) == 0) {
777 if (access(path, W_OK) == 0)
785 fprintf(stderr, "Check on %cPATH (%s) failed: %s\n", c, path, strerror(errno));
787 "Please create file and/or rerun `make config' and recompile to correct this.\n");
789 fprintf(stderr, "Keep in mind that all paths are relative to CHROOTDIR.\n");
802 debug_init(thisServer.bootopt & BOOT_TTY);
803 daemon_init(thisServer.bootopt & BOOT_TTY);
805 set_nomem_handler(outofmemory);
811 Debug((DEBUG_FATAL, "Failed in reading configuration file %s", configfile));
812 printf("Couldn't open configuration file %s\n", configfile);
815 if (!init_server_identity()) {
816 Debug((DEBUG_FATAL, "Failed to initialize server identity"));
821 rmotd = read_motd(RPATH);
822 motd = read_motd(MPATH);
823 CurrentTime = time(NULL);
828 * Abuse own link timestamp as start timestamp:
830 me.serv->timestamp = TStime();
831 me.serv->prot = atoi(MAJOR_PROTOCOL);
833 me.serv->down = NULL;
834 me.handler = SERVER_HANDLER;
836 SetYXXCapacity(&me, MAXCLIENTS);
838 me.lasttime = me.since = me.firsttime = CurrentTime;
846 Debug((DEBUG_NOTICE, "Server ready..."));
847 ircd_log(L_NOTICE, "Server Ready");
848 thisServer.running = 1;