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_signal.h"
31 #include "ircd_string.h"
61 #include <sys/socket.h>
66 extern void init_counters(void);
73 struct Client me; /* That's me */
74 struct Client* GlobalClientList = &me; /* Pointer to beginning of Client list */
75 time_t TSoffset = 0; /* Offset of timestamps to system clock */
76 int GlobalRehashFlag = 0; /* do a rehash if set */
77 int GlobalRestartFlag = 0; /* do a restart if set */
78 time_t CurrentTime; /* Updated every time we leave select() */
80 static struct Daemon thisServer = { 0 }; /* server process info */
82 char *configfile = CPATH; /* Server configuration file */
83 int debuglevel = -1; /* Server debug level */
84 char *debugmode = ""; /* -"- -"- -"- */
85 static char *dpath = DPATH;
87 time_t nextconnect = 1; /* time for next try_connections call */
88 time_t nextping = 1; /* same as above for check_pings() */
89 time_t nextdnscheck = 0; /* next time to poll dns to force timeouts */
90 time_t nextexpire = 1; /* next expire run on the dns cache */
96 static void server_reboot(const char* message)
98 sendto_ops("Restarting server: %s", message);
99 Debug((DEBUG_NOTICE, "Restarting server..."));
100 flush_connections(0);
103 close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG)));
105 execv(SPATH, thisServer.argv);
108 * Have to reopen since it has been closed above
110 open_log(*thisServer.argv);
111 ircd_log(L_CRIT, "execv(%s,%s) failed: %m\n", SPATH, *thisServer.argv);
113 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
114 SPATH, (strerror(errno)) ? strerror(errno) : ""));
118 void server_die(const char* message)
120 ircd_log(L_CRIT, "Server terminating: %s", message);
121 sendto_ops("Server terminating: %s", message);
122 flush_connections(0);
123 close_connections(1);
124 thisServer.running = 0;
127 void server_restart(const char* message)
129 static int restarting = 0;
131 ircd_log(L_WARNING, "Restarting Server: %s", message);
132 if (restarting == 0) {
134 server_reboot(message);
138 static void outofmemory(void)
140 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
141 server_restart("Out of Memory");
144 static void write_pidfile(void)
149 if ((fd = open(PPATH, O_CREAT | O_WRONLY, 0600)) == -1) {
150 Debug((DEBUG_NOTICE, "Error opening pid file \"%s\": %s",
151 PPATH, strerror(errno)));
154 memset(buff, 0, sizeof(buff));
155 sprintf(buff, "%5d\n", getpid());
156 if (write(fd, buff, strlen(buff)) == -1)
157 Debug((DEBUG_NOTICE, "Error writing to pid file %s", PPATH));
165 * Scan through configuration and try new connections.
167 * Returns the calendar time when the next call to this
168 * function should be made latest. (No harm done if this
169 * is called earlier or later...)
171 static time_t try_connections(void)
173 struct ConfItem* aconf;
175 struct ConfItem** pconf;
179 struct ConfClass* cltmp;
180 struct ConfItem* cconf;
181 struct ConfItem* con_conf = NULL;
183 unsigned int con_class = 0;
186 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
187 for (aconf = GlobalConfList; aconf; aconf = aconf->next)
189 /* Also when already connecting! (update holdtimes) --SRB */
190 if (!(aconf->status & CONF_SERVER) || aconf->port == 0)
193 /* Also skip juped servers */
194 if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
197 cltmp = aconf->confClass;
199 * Skip this entry if the use of it is still on hold until
200 * future. Otherwise handle this entry (and set it on hold
201 * until next time). Will reset only hold times, if already
202 * made one successfull connection... [this algorithm is
203 * a bit fuzzy... -- msa >;) ]
206 if ((aconf->hold > CurrentTime))
208 if ((next > aconf->hold) || (next == 0))
213 confrq = get_con_freq(cltmp);
214 aconf->hold = CurrentTime + confrq;
216 * Found a CONNECT config with port specified, scan clients
217 * and see if this server is already connected?
219 cptr = FindServer(aconf->name);
221 if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
222 (!connecting || (ConClass(cltmp) > con_class)))
224 /* Check connect rules to see if we're allowed to try */
225 for (cconf = GlobalConfList; cconf; cconf = cconf->next)
226 if ((cconf->status & CONF_CRULE) &&
227 (match(cconf->host, aconf->name) == 0))
228 if (crule_eval(cconf->passwd))
232 con_class = ConClass(cltmp);
234 /* We connect only one at time... */
238 if ((next > aconf->hold) || (next == 0))
243 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;
251 if (connect_server(con_conf, 0, 0))
252 sendto_ops("Connection to %s activated.", con_conf->name);
254 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
258 static time_t check_pings(void)
261 /* Temp to figure out what time this connection will next need
264 int next_check = CurrentTime + PINGFREQUENCY;
266 * The current lowest expire time - ie: the time that check_pings
267 * needs to be called next.
271 * The time you've got before a ping is sent/your connection is
275 int i=0; /* loop counter */
277 /* Scan through the client table */
278 for (i=0; i <= HighestFd; i++) {
281 cptr = LocalClientArray[i];
283 /* Skip empty entries */
287 assert(&me != cptr); /* I should never be in the local client array,
288 * so if I am, dying is a good thing(tm).
291 /* Remove dead clients.
292 * We will have sent opers a message when we set the dead flag,
293 * so don't bother to send one now.
296 exit_client(cptr, cptr, &me, cptr->info);
300 /* Should we concider adding a class 0 for 'unregistered clients',
301 * where we can specify their 'ping timeout' etc?
303 max_ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
305 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
306 cptr->name, (cptr->flags & FLAGS_PINGSENT) ? "[Ping Sent]" : "[]",
307 max_ping, (int)(CurrentTime - cptr->lasttime)));
309 /* Ok, the thing that will happen most frequently, is that someone will
310 * have sent something recently. Cover this first for speed.
312 if (CurrentTime-cptr->lasttime < max_ping) {
313 expire=cptr->lasttime + max_ping;
314 if (expire<next_check)
319 /* Quit the client after max_ping*2 - they should have answered by now */
320 if (CurrentTime-cptr->lasttime >= (max_ping*2) ) {
322 /* If it was a server, then tell ops about it. */
323 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
324 sendto_ops("No response from %s, closing link", cptr->name);
326 exit_client_msg(cptr, cptr, &me, "Ping timeout");
328 } /* of testing to see if ping has been sent */
330 /* Unregistered clients pingout after max_ping seconds, they don't
331 * get given a second chance - if they were then people could not quite
332 * finish registration and hold resources without being subject to k/g
335 if (!IsRegistered(cptr)) {
336 /* Display message if they have sent a NICK and a USER but no
339 if (*cptr->name && cptr->user && *cptr->user->username) {
341 ":%s %d %s :Your client may not be compatible with this server.",
342 me.name, ERR_BADPING, cptr->name);
344 ":%s %d %s :Compatible clients are available at "
345 "ftp://ftp.undernet.org/pub/irc/clients",
346 me.name, ERR_BADPING, cptr->name);
348 exit_client_msg(cptr,cptr,&me, "Ping Timeout");
350 } /* of not registered */
352 if (0 == (cptr->flags & FLAGS_PINGSENT)) {
354 * If we havent PINGed the connection and we havent heard from it in a
355 * while, PING it to make sure it is still alive.
357 cptr->flags |= FLAGS_PINGSENT;
360 * If we're late in noticing don't hold it against them :)
362 cptr->lasttime = CurrentTime - max_ping;
365 sendto_one(cptr, MSG_PING " :%s", me.name);
367 sendto_one(cptr, "%s " TOK_PING " :%s", NumServ(&me), me.name);
368 } /* of if not ping sent... */
370 expire=cptr->lasttime+max_ping*2;
372 if (expire<next_check)
375 } /* end of loop over clients */
377 assert(next_check>=CurrentTime);
379 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",CurrentTime,next_check-CurrentTime));
385 static time_t check_pings(void)
390 time_t oldest = CurrentTime + PINGFREQUENCY;
393 /* For each client... */
394 for (i = 0; i <= HighestFd; i++) {
395 if (!(cptr = LocalClientArray[i])) /* oops! not a client... */
398 * me is never in the local client array
402 * Note: No need to notify opers here.
403 * It's already done when "FLAGS_DEADSOCKET" is set.
406 exit_client(cptr, cptr, &me, cptr->info);
410 max_ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
412 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%d ping: %d current: %d",
413 cptr->name, cptr->status, max_ping,
414 (int)(CurrentTime - cptr->lasttime)));
417 * Ok, so goto's are ugly and can be avoided here but this code
418 * is already indented enough so I think its justified. -avalon
421 * If this is a registered client that we've heard of in a reasonable
422 * time, then skip them.
424 if (IsRegistered(cptr) && (max_ping >= CurrentTime - cptr->lasttime))
427 * If the server hasnt talked to us in 2 * ping seconds
428 * and it has a ping time, then close its connection.
429 * If the client is a user and a KILL line was found
430 * to be active, close this connection too.
432 if (((CurrentTime - cptr->lasttime) >= (2 * ping) && (cptr->flags & FLAGS_PINGSENT)) ||
433 (!IsRegistered(cptr) && !IsHandshake(cptr) && (CurrentTime - cptr->firsttime) >= ping))
435 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
437 sendto_ops("No response from %s, closing link", cptr->name);
438 exit_client(cptr, cptr, &me, "Ping timeout");
442 if (!IsRegistered(cptr) && *cptr->name && *cptr->user->username) {
444 ":%s %d %s :Your client may not be compatible with this server.",
445 me.name, ERR_BADPING, cptr->name);
447 ":%s %d %s :Compatible clients are available at "
448 "ftp://ftp.undernet.org/pub/irc/clients",
449 me.name, ERR_BADPING, cptr->name);
451 exit_client_msg(cptr, cptr, &me, "Ping timeout");
455 else if (IsRegistered(cptr) && 0 == (cptr->flags & FLAGS_PINGSENT)) {
457 * If we havent PINGed the connection and we havent
458 * heard from it in a while, PING it to make sure
461 cptr->flags |= FLAGS_PINGSENT;
463 * not nice but does the job
465 cptr->lasttime = CurrentTime - ping;
467 sendto_one(cptr, "PING :%s", me.name);
469 sendto_one(cptr, "%s " TOK_PING " :%s", NumServ(&me), me.name);
472 timeout = cptr->lasttime + max_ping;
473 while (timeout <= CurrentTime)
475 if (timeout < oldest)
478 if (oldest < CurrentTime)
479 oldest = CurrentTime + PINGFREQUENCY;
481 "Next check_ping() call at: %s, %d " TIME_T_FMT " " TIME_T_FMT,
482 myctime(oldest), ping, oldest, CurrentTime));
491 * This is called when the commandline is not acceptable.
492 * Give error message and exit without starting anything.
494 static void print_usage(void)
496 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv]\n");
497 printf("\n -n -t\t Don't detach\n -v\t display version\n\n");
498 printf("Server not started\n");
504 * ZZZ this is going to need confirmation on other OS's
506 * #include <getopt.h>
507 * Solaris has getopt.h, you should too... hopefully
508 * BSD declares them in stdlib.h
509 * extern char *optarg;
511 * for FreeBSD the following are defined:
513 * extern char *optarg;
517 * extern in optreset;
520 * All command line parameters have the syntax "-f string" or "-fstring"
522 * -d filename - specify d:line file
523 * -f filename - specify config file
524 * -h hostname - specify server name
525 * -k filename - specify k:line file (hybrid)
526 * -l filename - specify log file
527 * -n - do not fork, run in foreground
528 * -t - do not fork send debugging info to tty
529 * -v - print version and exit
530 * -x - set debug level, if compiled for debug logging
532 static void parse_command_line(int argc, char** argv)
534 const char* options = "d:f:h:ntvx:";
537 if (thisServer.euid != thisServer.uid)
538 setuid(thisServer.uid);
540 while ((opt = getopt(argc, argv, options)) != EOF) {
552 ircd_strncpy(me.name, optarg, HOSTLEN);
556 thisServer.bootopt |= BOOT_TTY;
559 printf("ircd %s\n", version);
563 debuglevel = atoi(optarg);
567 thisServer.bootopt |= BOOT_DEBUG;
580 static void daemon_init(int no_fork)
582 if (!init_connection_limits())
585 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
594 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
595 ioctl(fd, TIOCNOTTY, 0);
604 static void event_loop(void)
608 while (thisServer.running) {
610 * We only want to connect if a connection is due,
611 * not every time through. Note, if there are no
612 * active C lines, this call to Tryconnections is
613 * made once only; it will return 0. - avalon
615 if (nextconnect && CurrentTime >= nextconnect)
616 nextconnect = try_connections();
618 * DNS checks. One to timeout queries, one for cache expiries.
620 nextdnscheck = timeout_resolver(CurrentTime);
622 * Take the smaller of the two 'timed' event times as
623 * the time of next event (stops us being late :) - avalon
624 * WARNING - nextconnect can return 0!
627 delay = IRCD_MIN(nextping, nextconnect);
630 delay = IRCD_MIN(nextdnscheck, delay);
631 delay -= CurrentTime;
633 * Adjust delay to something reasonable [ad hoc values]
634 * (one might think something more clever here... --msa)
635 * We don't really need to check that often and as long
636 * as we don't delay too long, everything should be ok.
637 * waiting too long can cause things to timeout...
638 * i.e. PINGS -> a disconnection :(
644 delay = IRCD_MIN(delay, TIMESEC);
647 Debug((DEBUG_DEBUG, "Got message(s)"));
650 * ...perhaps should not do these loops every time,
651 * but only if there is some chance of something
652 * happening (but, note that conf->hold times may
653 * be changed elsewhere--so precomputed next event
654 * time might be too far away... (similarly with
657 if (CurrentTime >= nextping)
658 nextping = check_pings();
661 * timeout pending queries that haven't been responded to
663 timeout_auth_queries(CurrentTime);
666 if (GlobalRehashFlag) {
668 GlobalRehashFlag = 0;
670 if (GlobalRestartFlag)
671 server_restart("caught signal: SIGINT");
675 int main(int argc, char *argv[])
677 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
678 struct rlimit corelim;
681 CurrentTime = time(NULL);
685 if (MAXCONNECTIONS < 64 || MAXCONNECTIONS > 256000) {
686 fprintf(stderr, "%s: MAXCONNECTIONS insane: %d\n", *argv, MAXCONNECTIONS);
689 thisServer.argc = argc;
690 thisServer.argv = argv;
691 thisServer.uid = getuid();
692 thisServer.euid = geteuid();
694 monstartup(0, etext);
696 signal(SIGUSR1, s_monitor);
701 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", DPATH, strerror(errno));
705 fprintf(stderr, "Fail: Cannot chroot(%s): %s\n", DPATH, strerror(errno));
709 #endif /*CHROOTDIR */
711 umask(077); /* better safe than sorry --SRB */
712 memset(&me, 0, sizeof(me));
718 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
719 if (getrlimit(RLIMIT_CORE, &corelim))
721 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
722 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
724 corelim.rlim_cur = corelim.rlim_max;
725 if (setrlimit(RLIMIT_CORE, &corelim))
726 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
728 parse_command_line(argc, argv);
731 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", dpath, strerror(errno));
736 if ((thisServer.uid != thisServer.euid) && !thisServer.euid) {
738 "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
743 #if !defined(CHROOTDIR) || (defined(IRC_UID) && defined(IRC_GID))
744 if (thisServer.euid != thisServer.uid) {
745 setuid(thisServer.uid);
746 setuid(thisServer.euid);
750 #if defined(IRC_UID) && defined(IRC_GID)
752 /* run as a specified user */
753 fprintf(stderr, "WARNING: running ircd with uid = %d\n", IRC_UID);
754 fprintf(stderr, " changing to gid %d.\n", IRC_GID);
758 /* check for setuid root as usual */
760 "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
764 #endif /*CHROOTDIR/UID/GID */
773 if (access(path, X_OK) == 0) {
776 if (access(path, R_OK) == 0) {
779 if (access(path, R_OK) == 0) {
782 if (access(path, R_OK) == 0) {
788 if (access(path, W_OK) == 0)
796 fprintf(stderr, "Check on %cPATH (%s) failed: %s\n", c, path, strerror(errno));
798 "Please create file and/or rerun `make config' and recompile to correct this.\n");
800 fprintf(stderr, "Keep in mind that all paths are relative to CHROOTDIR.\n");
813 debug_init(thisServer.bootopt & BOOT_TTY);
814 daemon_init(thisServer.bootopt & BOOT_TTY);
816 set_nomem_handler(outofmemory);
822 Debug((DEBUG_FATAL, "Failed in reading configuration file %s", configfile));
823 printf("Couldn't open configuration file %s\n", configfile);
826 if (!init_server_identity()) {
827 Debug((DEBUG_FATAL, "Failed to initialize server identity"));
832 rmotd = read_motd(RPATH);
833 motd = read_motd(MPATH);
834 CurrentTime = time(NULL);
839 * Abuse own link timestamp as start timestamp:
841 me.serv->timestamp = TStime();
842 me.serv->prot = atoi(MAJOR_PROTOCOL);
844 me.serv->down = NULL;
845 me.handler = SERVER_HANDLER;
847 SetYXXCapacity(&me, MAXCLIENTS);
849 me.lasttime = me.since = me.firsttime = CurrentTime;
857 Debug((DEBUG_NOTICE, "Server ready..."));
858 ircd_log(L_NOTICE, "Server Ready");
859 thisServer.running = 1;