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_opmask_butone(0, SNO_OLDSNO, "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_opmask_butone(0, SNO_OLDSNO, "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_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
255 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
259 static time_t check_pings(void)
262 /* Temp to figure out what time this connection will next need
265 int next_check = CurrentTime + PINGFREQUENCY;
267 * The current lowest expire time - ie: the time that check_pings
268 * needs to be called next.
272 * The time you've got before a ping is sent/your connection is
276 int i=0; /* loop counter */
278 /* Scan through the client table */
279 for (i=0; i <= HighestFd; i++) {
282 cptr = LocalClientArray[i];
284 /* Skip empty entries */
288 assert(&me != cptr); /* I should never be in the local client array,
289 * so if I am, dying is a good thing(tm).
292 /* Remove dead clients.
293 * We will have sent opers a message when we set the dead flag,
294 * so don't bother to send one now.
297 exit_client(cptr, cptr, &me, cptr->info);
301 /* Should we concider adding a class 0 for 'unregistered clients',
302 * where we can specify their 'ping timeout' etc?
304 max_ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
306 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
307 cptr->name, (cptr->flags & FLAGS_PINGSENT) ? "[Ping Sent]" : "[]",
308 max_ping, (int)(CurrentTime - cptr->lasttime)));
310 /* Ok, the thing that will happen most frequently, is that someone will
311 * have sent something recently. Cover this first for speed.
313 if (CurrentTime-cptr->lasttime < max_ping) {
314 expire=cptr->lasttime + max_ping;
315 if (expire<next_check)
320 /* Quit the client after max_ping*2 - they should have answered by now */
321 if (CurrentTime-cptr->lasttime >= (max_ping*2) ) {
323 /* If it was a server, then tell ops about it. */
324 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
325 sendto_opmask_butone(0, SNO_OLDSNO,
326 "No response from %s, closing link", cptr->name);
328 exit_client_msg(cptr, cptr, &me, "Ping timeout");
330 } /* of testing to see if ping has been sent */
332 /* Unregistered clients pingout after max_ping seconds, they don't
333 * get given a second chance - if they were then people could not quite
334 * finish registration and hold resources without being subject to k/g
337 if (!IsRegistered(cptr)) {
338 /* Display message if they have sent a NICK and a USER but no
341 if (*cptr->name && cptr->user && *cptr->user->username) {
342 /* XXX sendto_one used to send numeric XXX */
344 ":%s %d %s :Your client may not be compatible with this server.",
345 me.name, ERR_BADPING, cptr->name);
347 ":%s %d %s :Compatible clients are available at "
348 "ftp://ftp.undernet.org/pub/irc/clients",
349 me.name, ERR_BADPING, cptr->name);
351 exit_client_msg(cptr,cptr,&me, "Ping Timeout");
353 } /* of not registered */
355 if (0 == (cptr->flags & FLAGS_PINGSENT)) {
357 * If we havent PINGed the connection and we havent heard from it in a
358 * while, PING it to make sure it is still alive.
360 cptr->flags |= FLAGS_PINGSENT;
363 * If we're late in noticing don't hold it against them :)
365 cptr->lasttime = CurrentTime - max_ping;
367 /* XXX sendto_one sending PING; must be very careful XXX */
369 sendto_one(cptr, MSG_PING " :%s", me.name);
371 sendto_one(cptr, "%s " TOK_PING " :%s", NumServ(&me), me.name);
372 } /* of if not ping sent... */
374 expire=cptr->lasttime+max_ping*2;
376 if (expire<next_check)
379 } /* end of loop over clients */
381 assert(next_check>=CurrentTime);
383 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",CurrentTime,next_check-CurrentTime));
389 static time_t check_pings(void)
394 time_t oldest = CurrentTime + PINGFREQUENCY;
397 /* For each client... */
398 for (i = 0; i <= HighestFd; i++) {
399 if (!(cptr = LocalClientArray[i])) /* oops! not a client... */
402 * me is never in the local client array
406 * Note: No need to notify opers here.
407 * It's already done when "FLAGS_DEADSOCKET" is set.
410 exit_client(cptr, cptr, &me, cptr->info);
414 max_ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
416 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%d ping: %d current: %d",
417 cptr->name, cptr->status, max_ping,
418 (int)(CurrentTime - cptr->lasttime)));
421 * Ok, so goto's are ugly and can be avoided here but this code
422 * is already indented enough so I think its justified. -avalon
425 * If this is a registered client that we've heard of in a reasonable
426 * time, then skip them.
428 if (IsRegistered(cptr) && (max_ping >= CurrentTime - cptr->lasttime))
431 * If the server hasnt talked to us in 2 * ping seconds
432 * and it has a ping time, then close its connection.
433 * If the client is a user and a KILL line was found
434 * to be active, close this connection too.
436 if (((CurrentTime - cptr->lasttime) >= (2 * ping) && (cptr->flags & FLAGS_PINGSENT)) ||
437 (!IsRegistered(cptr) && !IsHandshake(cptr) && (CurrentTime - cptr->firsttime) >= ping))
439 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
441 sendto_ops("No response from %s, closing link", cptr->name);
442 exit_client(cptr, cptr, &me, "Ping timeout");
446 if (!IsRegistered(cptr) && *cptr->name && *cptr->user->username) {
448 ":%s %d %s :Your client may not be compatible with this server.",
449 me.name, ERR_BADPING, cptr->name);
451 ":%s %d %s :Compatible clients are available at "
452 "ftp://ftp.undernet.org/pub/irc/clients",
453 me.name, ERR_BADPING, cptr->name);
455 exit_client_msg(cptr, cptr, &me, "Ping timeout");
459 else if (IsRegistered(cptr) && 0 == (cptr->flags & FLAGS_PINGSENT)) {
461 * If we havent PINGed the connection and we havent
462 * heard from it in a while, PING it to make sure
465 cptr->flags |= FLAGS_PINGSENT;
467 * not nice but does the job
469 cptr->lasttime = CurrentTime - ping;
471 sendto_one(cptr, "PING :%s", me.name);
473 sendto_one(cptr, "%s " TOK_PING " :%s", NumServ(&me), me.name);
476 timeout = cptr->lasttime + max_ping;
477 while (timeout <= CurrentTime)
479 if (timeout < oldest)
482 if (oldest < CurrentTime)
483 oldest = CurrentTime + PINGFREQUENCY;
485 "Next check_ping() call at: %s, %d " TIME_T_FMT " " TIME_T_FMT,
486 myctime(oldest), ping, oldest, CurrentTime));
495 * This is called when the commandline is not acceptable.
496 * Give error message and exit without starting anything.
498 static void print_usage(void)
500 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv]\n");
501 printf("\n -n -t\t Don't detach\n -v\t display version\n\n");
502 printf("Server not started\n");
508 * ZZZ this is going to need confirmation on other OS's
510 * #include <getopt.h>
511 * Solaris has getopt.h, you should too... hopefully
512 * BSD declares them in stdlib.h
513 * extern char *optarg;
515 * for FreeBSD the following are defined:
517 * extern char *optarg;
521 * extern in optreset;
524 * All command line parameters have the syntax "-f string" or "-fstring"
526 * -d filename - specify d:line file
527 * -f filename - specify config file
528 * -h hostname - specify server name
529 * -k filename - specify k:line file (hybrid)
530 * -l filename - specify log file
531 * -n - do not fork, run in foreground
532 * -t - do not fork send debugging info to tty
533 * -v - print version and exit
534 * -x - set debug level, if compiled for debug logging
536 static void parse_command_line(int argc, char** argv)
538 const char* options = "d:f:h:ntvx:";
541 if (thisServer.euid != thisServer.uid)
542 setuid(thisServer.uid);
544 while ((opt = getopt(argc, argv, options)) != EOF) {
556 ircd_strncpy(me.name, optarg, HOSTLEN);
560 thisServer.bootopt |= BOOT_TTY;
563 printf("ircd %s\n", version);
567 debuglevel = atoi(optarg);
571 thisServer.bootopt |= BOOT_DEBUG;
584 static void daemon_init(int no_fork)
586 if (!init_connection_limits())
589 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
598 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
599 ioctl(fd, TIOCNOTTY, 0);
608 static void event_loop(void)
612 while (thisServer.running) {
614 * We only want to connect if a connection is due,
615 * not every time through. Note, if there are no
616 * active C lines, this call to Tryconnections is
617 * made once only; it will return 0. - avalon
619 if (nextconnect && CurrentTime >= nextconnect)
620 nextconnect = try_connections();
622 * DNS checks. One to timeout queries, one for cache expiries.
624 nextdnscheck = timeout_resolver(CurrentTime);
626 * Take the smaller of the two 'timed' event times as
627 * the time of next event (stops us being late :) - avalon
628 * WARNING - nextconnect can return 0!
631 delay = IRCD_MIN(nextping, nextconnect);
634 delay = IRCD_MIN(nextdnscheck, delay);
635 delay -= CurrentTime;
637 * Adjust delay to something reasonable [ad hoc values]
638 * (one might think something more clever here... --msa)
639 * We don't really need to check that often and as long
640 * as we don't delay too long, everything should be ok.
641 * waiting too long can cause things to timeout...
642 * i.e. PINGS -> a disconnection :(
648 delay = IRCD_MIN(delay, TIMESEC);
651 Debug((DEBUG_DEBUG, "Got message(s)"));
654 * ...perhaps should not do these loops every time,
655 * but only if there is some chance of something
656 * happening (but, note that conf->hold times may
657 * be changed elsewhere--so precomputed next event
658 * time might be too far away... (similarly with
661 if (CurrentTime >= nextping)
662 nextping = check_pings();
665 * timeout pending queries that haven't been responded to
667 timeout_auth_queries(CurrentTime);
670 if (GlobalRehashFlag) {
672 GlobalRehashFlag = 0;
674 if (GlobalRestartFlag)
675 server_restart("caught signal: SIGINT");
679 int main(int argc, char *argv[])
681 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
682 struct rlimit corelim;
685 CurrentTime = time(NULL);
689 if (MAXCONNECTIONS < 64 || MAXCONNECTIONS > 256000) {
690 fprintf(stderr, "%s: MAXCONNECTIONS insane: %d\n", *argv, MAXCONNECTIONS);
693 thisServer.argc = argc;
694 thisServer.argv = argv;
695 thisServer.uid = getuid();
696 thisServer.euid = geteuid();
698 monstartup(0, etext);
700 signal(SIGUSR1, s_monitor);
705 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", DPATH, strerror(errno));
709 fprintf(stderr, "Fail: Cannot chroot(%s): %s\n", DPATH, strerror(errno));
713 #endif /*CHROOTDIR */
715 umask(077); /* better safe than sorry --SRB */
716 memset(&me, 0, sizeof(me));
722 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
723 if (getrlimit(RLIMIT_CORE, &corelim))
725 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
726 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
728 corelim.rlim_cur = corelim.rlim_max;
729 if (setrlimit(RLIMIT_CORE, &corelim))
730 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
732 parse_command_line(argc, argv);
735 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", dpath, strerror(errno));
740 if ((thisServer.uid != thisServer.euid) && !thisServer.euid) {
742 "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
747 #if !defined(CHROOTDIR) || (defined(IRC_UID) && defined(IRC_GID))
748 if (thisServer.euid != thisServer.uid) {
749 setuid(thisServer.uid);
750 setuid(thisServer.euid);
754 #if defined(IRC_UID) && defined(IRC_GID)
756 /* run as a specified user */
757 fprintf(stderr, "WARNING: running ircd with uid = %d\n", IRC_UID);
758 fprintf(stderr, " changing to gid %d.\n", IRC_GID);
762 /* check for setuid root as usual */
764 "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
768 #endif /*CHROOTDIR/UID/GID */
777 if (access(path, X_OK) == 0) {
780 if (access(path, R_OK) == 0) {
783 if (access(path, R_OK) == 0) {
786 if (access(path, R_OK) == 0) {
792 if (access(path, W_OK) == 0)
800 fprintf(stderr, "Check on %cPATH (%s) failed: %s\n", c, path, strerror(errno));
802 "Please create file and/or rerun `make config' and recompile to correct this.\n");
804 fprintf(stderr, "Keep in mind that all paths are relative to CHROOTDIR.\n");
817 debug_init(thisServer.bootopt & BOOT_TTY);
818 daemon_init(thisServer.bootopt & BOOT_TTY);
820 set_nomem_handler(outofmemory);
826 Debug((DEBUG_FATAL, "Failed in reading configuration file %s", configfile));
827 printf("Couldn't open configuration file %s\n", configfile);
830 if (!init_server_identity()) {
831 Debug((DEBUG_FATAL, "Failed to initialize server identity"));
836 rmotd = read_motd(RPATH);
837 motd = read_motd(MPATH);
838 CurrentTime = time(NULL);
843 * Abuse own link timestamp as start timestamp:
845 me.serv->timestamp = TStime();
846 me.serv->prot = atoi(MAJOR_PROTOCOL);
848 me.serv->down = NULL;
849 me.handler = SERVER_HANDLER;
851 SetYXXCapacity(&me, MAXCLIENTS);
853 me.lasttime = me.since = me.firsttime = CurrentTime;
861 Debug((DEBUG_NOTICE, "Server ready..."));
862 ircd_log(L_NOTICE, "Server Ready");
863 thisServer.running = 1;