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);
67 struct Client me; /* That's me */
68 struct Client* GlobalClientList = &me; /* Pointer to beginning of Client list */
69 time_t TSoffset = 0; /* Offset of timestamps to system clock */
70 int GlobalRehashFlag = 0; /* do a rehash if set */
71 int GlobalRestartFlag = 0; /* do a restart if set */
72 time_t CurrentTime; /* Updated every time we leave select() */
75 char *configfile = CPATH; /* Server configuration file */
76 int debuglevel = -1; /* Server debug level */
77 unsigned int bootopt = 0; /* Server boot option flags */
78 char *debugmode = ""; /* -"- -"- -"- */
79 static char *dpath = DPATH;
81 time_t nextconnect = 1; /* time for next try_connections call */
82 time_t nextping = 1; /* same as above for check_pings() */
83 time_t nextdnscheck = 0; /* next time to poll dns to force timeouts */
84 time_t nextexpire = 1; /* next expire run on the dns cache */
90 static void server_reboot(const char* message)
94 sendto_ops("Restarting server: %s", message);
95 Debug((DEBUG_NOTICE, "Restarting server..."));
98 * fd 0 must be 'preserved' if either the -d or -i options have
99 * been passed to us before restarting.
103 for (i = 3; i < MAXCONNECTIONS; i++)
105 if (!(bootopt & (BOOT_TTY | BOOT_DEBUG)))
110 execv(SPATH, myargv);
112 /* Have to reopen since it has been closed above */
114 ircd_log(L_CRIT, "execv(%s,%s) failed: %m\n", SPATH, myargv[0]);
116 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
117 SPATH, (strerror(errno)) ? strerror(errno) : ""));
121 void server_die(const char* message)
123 ircd_log(L_CRIT, "Server terminating: %s", message);
124 sendto_ops("Server terminating: %s", message);
125 flush_connections(0);
129 void server_restart(const char* message)
131 static int restarting = 0;
133 ircd_log(L_WARNING, "Restarting Server: %s", message);
134 if (restarting == 0) {
136 server_reboot(message);
140 static void outofmemory(void)
142 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
143 server_restart("Out of Memory");
146 static void write_pidfile(void)
151 if ((fd = open(PPATH, O_CREAT | O_WRONLY, 0600)) == -1) {
152 Debug((DEBUG_NOTICE, "Error opening pid file \"%s\": %s",
153 PPATH, strerror(errno)));
156 memset(buff, 0, sizeof(buff));
157 sprintf(buff, "%5d\n", getpid());
158 if (write(fd, buff, strlen(buff)) == -1)
159 Debug((DEBUG_NOTICE, "Error writing to pid file %s", PPATH));
167 * Scan through configuration and try new connections.
169 * Returns the calendar time when the next call to this
170 * function should be made latest. (No harm done if this
171 * is called earlier or later...)
173 static time_t try_connections(void)
175 struct ConfItem* aconf;
177 struct ConfItem** pconf;
181 struct ConfClass* cltmp;
182 struct ConfItem* cconf;
183 strcut ConfItem* con_conf = NULL;
185 unsigned int con_class = 0;
188 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
189 for (aconf = GlobalConfList; aconf; aconf = aconf->next)
191 /* Also when already connecting! (update holdtimes) --SRB */
192 if (!(aconf->status & CONF_SERVER) || aconf->port == 0)
195 /* Also skip juped servers */
196 if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
199 cltmp = aconf->confClass;
201 * Skip this entry if the use of it is still on hold until
202 * future. Otherwise handle this entry (and set it on hold
203 * until next time). Will reset only hold times, if already
204 * made one successfull connection... [this algorithm is
205 * a bit fuzzy... -- msa >;) ]
208 if ((aconf->hold > CurrentTime))
210 if ((next > aconf->hold) || (next == 0))
215 confrq = get_con_freq(cltmp);
216 aconf->hold = CurrentTime + confrq;
218 * Found a CONNECT config with port specified, scan clients
219 * and see if this server is already connected?
221 cptr = FindServer(aconf->name);
223 if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
224 (!connecting || (ConClass(cltmp) > con_class)))
226 /* Check connect rules to see if we're allowed to try */
227 for (cconf = GlobalConfList; cconf; cconf = cconf->next)
228 if ((cconf->status & CONF_CRULE) &&
229 (match(cconf->host, aconf->name) == 0))
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))
245 if (con_conf->next) /* are we already last? */
247 /* Put the current one at the end and make sure we try all connections */
248 for (pconf = &GlobalConfList; (aconf = *pconf); pconf = &(aconf->next))
249 if (aconf == con_conf)
250 *pconf = aconf->next;
251 (*pconf = con_conf)->next = 0;
253 if (connect_server(con_conf, 0, 0))
254 sendto_ops("Connection to %s activated.", con_conf->name);
256 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
260 static time_t check_pings(void)
265 time_t oldest = CurrentTime + PINGFREQUENCY;
268 for (i = 0; i <= HighestFd; i++) {
269 if (!(cptr = LocalClientArray[i]))
272 * me is never in the local client array
276 * Note: No need to notify opers here.
277 * It's already done when "FLAGS_DEADSOCKET" is set.
280 exit_client(cptr, cptr, &me, cptr->info);
284 ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
285 Debug((DEBUG_DEBUG, "c(%s)=%d p %d a %d",
286 cptr->name, cptr->status, ping,
287 (int)(CurrentTime - cptr->lasttime)));
289 * Ok, so goto's are ugly and can be avoided here but this code
290 * is already indented enough so I think its justified. -avalon
292 if (IsRegistered(cptr) && (ping >= CurrentTime - cptr->lasttime))
295 * If the server hasnt talked to us in 2 * ping seconds
296 * and it has a ping time, then close its connection.
297 * If the client is a user and a KILL line was found
298 * to be active, close this connection too.
300 if (((CurrentTime - cptr->lasttime) >= (2 * ping) && (cptr->flags & FLAGS_PINGSENT)) ||
301 (!IsRegistered(cptr) && !IsHandshake(cptr) && (CurrentTime - cptr->firsttime) >= ping))
303 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
305 sendto_ops("No response from %s, closing link", cptr->name);
306 exit_client(cptr, cptr, &me, "Ping timeout");
310 if (!IsRegistered(cptr) && *cptr->name && *cptr->user->username) {
312 ":%s %d %s :Your client may not be compatible with this server.",
313 me.name, ERR_BADPING, cptr->name);
315 ":%s %d %s :Compatible clients are available at "
316 "ftp://ftp.undernet.org/pub/irc/clients",
317 me.name, ERR_BADPING, cptr->name);
319 exit_client_msg(cptr, cptr, &me, "Ping timeout for %s",
320 get_client_name(cptr, HIDE_IP));
324 else if (IsRegistered(cptr) && 0 == (cptr->flags & FLAGS_PINGSENT)) {
326 * If we havent PINGed the connection and we havent
327 * heard from it in a while, PING it to make sure
330 cptr->flags |= FLAGS_PINGSENT;
332 * not nice but does the job
334 cptr->lasttime = CurrentTime - ping;
336 sendto_one(cptr, "PING :%s", me.name);
338 sendto_one(cptr, "%s " TOK_PING " :%s", NumServ(&me), me.name);
341 timeout = cptr->lasttime + ping;
342 while (timeout <= CurrentTime)
344 if (timeout < oldest)
347 if (oldest < CurrentTime)
348 oldest = CurrentTime + PINGFREQUENCY;
350 "Next check_ping() call at: %s, %d " TIME_T_FMT " " TIME_T_FMT,
351 myctime(oldest), ping, oldest, CurrentTime));
359 * This is called when the commandline is not acceptable.
360 * Give error message and exit without starting anything.
362 static int bad_command(void)
364 printf("Usage: ircd %s[-h servername] [-x loglevel] [-t]\n",
365 #ifdef CMDLINE_CONFIG
371 printf("Server not started\n\n");
375 int main(int argc, char *argv[])
380 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
381 struct rlimit corelim;
384 CurrentTime = time(NULL);
389 if (MAXCONNECTIONS < 64 || MAXCONNECTIONS > 256000) {
390 fprintf(stderr, "%s: MAXCONNECTIONS insane: %d\n", *argv, MAXCONNECTIONS);
397 monstartup(0, etext);
399 signal(SIGUSR1, s_monitor);
405 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", DPATH, (strerror(errno)) ? strerror(errno) : "");
410 fprintf(stderr, "Fail: Cannot chroot(%s): %s\n", DPATH, (strerror(errno)) ? strerror(errno) : "");
414 #endif /*CHROOTDIR */
417 umask(077); /* better safe than sorry --SRB */
418 memset(&me, 0, sizeof(me));
423 memset(&vserv, 0, sizeof(vserv));
430 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
431 if (getrlimit(RLIMIT_CORE, &corelim))
433 fprintf(stderr, "Read of rlimit core size failed: %s\n", (strerror(errno) ? strerror(errno) : "");
434 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
436 corelim.rlim_cur = corelim.rlim_max;
437 if (setrlimit(RLIMIT_CORE, &corelim))
438 fprintf(stderr, "Setting rlimit core size failed: %s\n", (strerror(errno) ? strerror(errno) : "");
442 * All command line parameters have the syntax "-fstring"
443 * or "-f string" (e.g. the space is optional). String may
444 * be empty. Flag characters cannot be concatenated (like
445 * "-fxyz"), it would conflict with the form "-fstring".
447 while (--argc > 0 && (*++argv)[0] == '-')
449 char *p = argv[0] + 1;
452 if (flag == '\0' || *p == '\0')
454 if (argc > 1 && argv[1][0] != '-')
466 bootopt |= BOOT_QUICK;
473 #ifdef CMDLINE_CONFIG
481 ircd_strncpy(me.name, p, HOSTLEN);
489 printf("ircd %s\n", version);
496 if (!(hep = gethostbyname(p)))
498 fprintf(stderr, "%s: Error creating virtual host \"%s\": %d",
499 argv[0], p, h_errno);
502 if (hep->h_addrtype == AF_INET && hep->h_addr_list[0] &&
503 !hep->h_addr_list[1])
505 memcpy(&vserv.sin_addr, hep->h_addr_list[0], sizeof(struct in_addr));
506 vserv.sin_family = AF_INET;
510 fprintf(stderr, "%s: Error creating virtual host \"%s\": "
511 "Use -w <IP-number of interface>\n", argv[0], p);
522 debuglevel = atoi(p);
523 debugmode = *p ? p : "0";
524 bootopt |= BOOT_DEBUG;
527 fprintf(stderr, "%s: DEBUGMODE must be defined for -x y\n", myargv[0]);
538 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", dpath, (strerror(errno)) ? strerror(errno) : "");
543 if ((uid != euid) && !euid)
546 "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
551 #if !defined(CHROOTDIR) || (defined(IRC_UID) && defined(IRC_GID))
560 #if defined(IRC_UID) && defined(IRC_GID)
562 /* run as a specified user */
563 fprintf(stderr, "WARNING: running ircd with uid = %d\n", IRC_UID);
564 fprintf(stderr, " changing to gid %d.\n", IRC_GID);
568 /* check for setuid root as usual */
570 "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
574 #endif /*CHROOTDIR/UID/GID */
577 return bad_command(); /* This should exit out */
586 if (access(path, X_OK) == 0) {
589 if (access(path, R_OK) == 0) {
592 if (access(path, R_OK) == 0) {
595 if (access(path, R_OK) == 0) {
601 if (access(path, W_OK) == 0)
610 fprintf(stderr, "Check on %cPATH (%s) failed: %s\n",
611 c, path, (strerror(errno)) ? strerror(errno) : "");
613 "Please create file and/or rerun `make config' and recompile to correct this.\n");
616 "Keep in mind that all paths are relative to CHROOTDIR.\n");
630 set_nomem_handler(outofmemory);
636 if (initconf(bootopt) == -1) {
637 Debug((DEBUG_FATAL, "Failed in reading configuration file %s", configfile));
638 printf("Couldn't open configuration file %s\n", configfile);
641 if (!init_server_identity()) {
642 Debug((DEBUG_FATAL, "Failed to initialize server identity"));
647 rmotd = read_motd(RPATH);
648 motd = read_motd(MPATH);
649 CurrentTime = time(NULL);
654 * Abuse own link timestamp as start timestamp:
656 me.serv->timestamp = TStime();
657 me.serv->prot = atoi(MAJOR_PROTOCOL);
659 me.serv->down = NULL;
660 me.handler = SERVER_HANDLER;
662 SetYXXCapacity(&me, MAXCLIENTS);
664 me.lasttime = me.since = me.firsttime = CurrentTime;
672 Debug((DEBUG_NOTICE, "Server ready..."));
673 ircd_log(L_NOTICE, "Server Ready");
678 * We only want to connect if a connection is due,
679 * not every time through. Note, if there are no
680 * active C lines, this call to Tryconnections is
681 * made once only; it will return 0. - avalon
683 if (nextconnect && CurrentTime >= nextconnect)
684 nextconnect = try_connections();
686 * DNS checks. One to timeout queries, one for cache expiries.
688 nextdnscheck = timeout_resolver(CurrentTime);
690 * Take the smaller of the two 'timed' event times as
691 * the time of next event (stops us being late :) - avalon
692 * WARNING - nextconnect can return 0!
695 delay = IRCD_MIN(nextping, nextconnect);
698 delay = IRCD_MIN(nextdnscheck, delay);
699 delay -= CurrentTime;
701 * Adjust delay to something reasonable [ad hoc values]
702 * (one might think something more clever here... --msa)
703 * We don't really need to check that often and as long
704 * as we don't delay too long, everything should be ok.
705 * waiting too long can cause things to timeout...
706 * i.e. PINGS -> a disconnection :(
712 delay = IRCD_MIN(delay, TIMESEC);
715 Debug((DEBUG_DEBUG, "Got message(s)"));
718 * ...perhaps should not do these loops every time,
719 * but only if there is some chance of something
720 * happening (but, note that conf->hold times may
721 * be changed elsewhere--so precomputed next event
722 * time might be too far away... (similarly with
725 if (CurrentTime >= nextping)
726 nextping = check_pings();
729 * timeout pending queries that haven't been responded to
731 timeout_auth_queries(CurrentTime);
733 if (GlobalRehashFlag) {
735 GlobalRehashFlag = 0;
737 if (GlobalRestartFlag)
738 server_restart("caught signal: SIGINT");