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)) >= 0) {
152 memset(buff, 0, sizeof(buff));
153 sprintf(buff, "%5d\n", (int)getpid());
154 if (write(fd, buff, strlen(buff)) == -1)
155 Debug((DEBUG_NOTICE, "Error writing to pid file %s", PPATH));
159 Debug((DEBUG_NOTICE, "Error opening pid file \"%s\": %s",
160 PPATH, (strerror(errno)) ? strerror(errno) : ""));
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;
178 int connecting, confrq;
180 struct ConfClass *cltmp;
181 struct ConfItem *cconf, *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)
263 time_t oldest = CurrentTime + PINGFREQUENCY;
266 for (i = 0; i <= HighestFd; i++) {
267 if (!(cptr = LocalClientArray[i]))
270 * me is never in the local client array
274 * Note: No need to notify opers here.
275 * It's already done when "FLAGS_DEADSOCKET" is set.
278 exit_client(cptr, cptr, &me, LastDeadComment(cptr));
282 ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
283 Debug((DEBUG_DEBUG, "c(%s)=%d p %d a %d",
284 cptr->name, cptr->status, ping,
285 (int)(CurrentTime - cptr->lasttime)));
287 * Ok, so goto's are ugly and can be avoided here but this code
288 * is already indented enough so I think its justified. -avalon
290 if (IsRegistered(cptr) && (ping >= CurrentTime - cptr->lasttime))
293 * If the server hasnt talked to us in 2 * ping seconds
294 * and it has a ping time, then close its connection.
295 * If the client is a user and a KILL line was found
296 * to be active, close this connection too.
298 if (((CurrentTime - cptr->lasttime) >= (2 * ping) && (cptr->flags & FLAGS_PINGSENT)) ||
299 (!IsRegistered(cptr) && !IsHandshake(cptr) && (CurrentTime - cptr->firsttime) >= ping))
301 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
303 sendto_ops("No response from %s, closing link", cptr->name);
304 exit_client(cptr, cptr, &me, "Ping timeout");
308 if (!IsRegistered(cptr) && *cptr->name && *cptr->user->username) {
310 ":%s %d %s :Your client may not be compatible with this server.",
311 me.name, ERR_BADPING, cptr->name);
313 ":%s %d %s :Compatible clients are available at "
314 "ftp://ftp.undernet.org/pub/irc/clients",
315 me.name, ERR_BADPING, cptr->name);
317 exit_client_msg(cptr, cptr, &me, "Ping timeout for %s",
318 get_client_name(cptr, HIDE_IP));
322 else if (IsRegistered(cptr) && 0 == (cptr->flags & FLAGS_PINGSENT)) {
324 * If we havent PINGed the connection and we havent
325 * heard from it in a while, PING it to make sure
328 cptr->flags |= FLAGS_PINGSENT;
330 * not nice but does the job
332 cptr->lasttime = CurrentTime - ping;
334 sendto_one(cptr, "PING :%s", me.name);
336 sendto_one(cptr, "%s " TOK_PING " :%s", NumServ(&me), me.name);
339 timeout = cptr->lasttime + ping;
340 while (timeout <= CurrentTime)
342 if (timeout < oldest)
345 if (oldest < CurrentTime)
346 oldest = CurrentTime + PINGFREQUENCY;
348 "Next check_ping() call at: %s, %d " TIME_T_FMT " " TIME_T_FMT,
349 myctime(oldest), ping, oldest, CurrentTime));
357 * This is called when the commandline is not acceptable.
358 * Give error message and exit without starting anything.
360 static int bad_command(void)
362 printf("Usage: ircd %s[-h servername] [-x loglevel] [-t]\n",
363 #ifdef CMDLINE_CONFIG
369 printf("Server not started\n\n");
373 int main(int argc, char *argv[])
378 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
379 struct rlimit corelim;
382 CurrentTime = time(NULL);
387 if (MAXCONNECTIONS < 64 || MAXCONNECTIONS > 256000) {
388 fprintf(stderr, "%s: MAXCONNECTIONS insane: %d\n", *argv, MAXCONNECTIONS);
395 monstartup(0, etext);
397 signal(SIGUSR1, s_monitor);
403 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", DPATH, (strerror(errno)) ? strerror(errno) : "");
408 fprintf(stderr, "Fail: Cannot chroot(%s): %s\n", DPATH, (strerror(errno)) ? strerror(errno) : "");
412 #endif /*CHROOTDIR */
415 umask(077); /* better safe than sorry --SRB */
416 memset(&me, 0, sizeof(me));
421 memset(&vserv, 0, sizeof(vserv));
428 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
429 if (getrlimit(RLIMIT_CORE, &corelim))
431 fprintf(stderr, "Read of rlimit core size failed: %s\n", (strerror(errno) ? strerror(errno) : "");
432 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
434 corelim.rlim_cur = corelim.rlim_max;
435 if (setrlimit(RLIMIT_CORE, &corelim))
436 fprintf(stderr, "Setting rlimit core size failed: %s\n", (strerror(errno) ? strerror(errno) : "");
440 * All command line parameters have the syntax "-fstring"
441 * or "-f string" (e.g. the space is optional). String may
442 * be empty. Flag characters cannot be concatenated (like
443 * "-fxyz"), it would conflict with the form "-fstring".
445 while (--argc > 0 && (*++argv)[0] == '-')
447 char *p = argv[0] + 1;
450 if (flag == '\0' || *p == '\0')
452 if (argc > 1 && argv[1][0] != '-')
464 bootopt |= BOOT_QUICK;
471 #ifdef CMDLINE_CONFIG
479 ircd_strncpy(me.name, p, HOSTLEN);
487 printf("ircd %s\n", version);
494 if (!(hep = gethostbyname(p)))
496 fprintf(stderr, "%s: Error creating virtual host \"%s\": %d",
497 argv[0], p, h_errno);
500 if (hep->h_addrtype == AF_INET && hep->h_addr_list[0] &&
501 !hep->h_addr_list[1])
503 memcpy(&vserv.sin_addr, hep->h_addr_list[0], sizeof(struct in_addr));
504 vserv.sin_family = AF_INET;
508 fprintf(stderr, "%s: Error creating virtual host \"%s\": "
509 "Use -w <IP-number of interface>\n", argv[0], p);
520 debuglevel = atoi(p);
521 debugmode = *p ? p : "0";
522 bootopt |= BOOT_DEBUG;
525 fprintf(stderr, "%s: DEBUGMODE must be defined for -x y\n", myargv[0]);
536 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", dpath, (strerror(errno)) ? strerror(errno) : "");
541 if ((uid != euid) && !euid)
544 "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
549 #if !defined(CHROOTDIR) || (defined(IRC_UID) && defined(IRC_GID))
558 #if defined(IRC_UID) && defined(IRC_GID)
560 /* run as a specified user */
561 fprintf(stderr, "WARNING: running ircd with uid = %d\n", IRC_UID);
562 fprintf(stderr, " changing to gid %d.\n", IRC_GID);
566 /* check for setuid root as usual */
568 "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
572 #endif /*CHROOTDIR/UID/GID */
575 return bad_command(); /* This should exit out */
584 if (access(path, X_OK) == 0) {
587 if (access(path, R_OK) == 0) {
590 if (access(path, R_OK) == 0) {
593 if (access(path, R_OK) == 0) {
599 if (access(path, W_OK) == 0)
608 fprintf(stderr, "Check on %cPATH (%s) failed: %s\n",
609 c, path, (strerror(errno)) ? strerror(errno) : "");
611 "Please create file and/or rerun `make config' and recompile to correct this.\n");
614 "Keep in mind that all paths are relative to CHROOTDIR.\n");
628 set_nomem_handler(outofmemory);
634 if (initconf(bootopt) == -1) {
635 Debug((DEBUG_FATAL, "Failed in reading configuration file %s", configfile));
636 printf("Couldn't open configuration file %s\n", configfile);
639 if (!init_server_identity()) {
640 Debug((DEBUG_FATAL, "Failed to initialize server identity"));
645 rmotd = read_motd(RPATH);
646 motd = read_motd(MPATH);
647 CurrentTime = time(NULL);
652 * Abuse own link timestamp as start timestamp:
654 me.serv->timestamp = TStime();
655 me.serv->prot = atoi(MAJOR_PROTOCOL);
657 me.serv->down = NULL;
658 me.handler = SERVER_HANDLER;
660 SetYXXCapacity(&me, MAXCLIENTS);
662 me.lasttime = me.since = me.firsttime = CurrentTime;
670 Debug((DEBUG_NOTICE, "Server ready..."));
671 ircd_log(L_NOTICE, "Server Ready");
676 * We only want to connect if a connection is due,
677 * not every time through. Note, if there are no
678 * active C lines, this call to Tryconnections is
679 * made once only; it will return 0. - avalon
681 if (nextconnect && CurrentTime >= nextconnect)
682 nextconnect = try_connections();
684 * DNS checks. One to timeout queries, one for cache expiries.
686 nextdnscheck = timeout_resolver(CurrentTime);
688 * Take the smaller of the two 'timed' event times as
689 * the time of next event (stops us being late :) - avalon
690 * WARNING - nextconnect can return 0!
693 delay = IRCD_MIN(nextping, nextconnect);
696 delay = IRCD_MIN(nextdnscheck, delay);
697 delay -= CurrentTime;
699 * Adjust delay to something reasonable [ad hoc values]
700 * (one might think something more clever here... --msa)
701 * We don't really need to check that often and as long
702 * as we don't delay too long, everything should be ok.
703 * waiting too long can cause things to timeout...
704 * i.e. PINGS -> a disconnection :(
710 delay = IRCD_MIN(delay, TIMESEC);
713 Debug((DEBUG_DEBUG, "Got message(s)"));
716 * ...perhaps should not do these loops every time,
717 * but only if there is some chance of something
718 * happening (but, note that conf->hold times may
719 * be changed elsewhere--so precomputed next event
720 * time might be too far away... (similarly with
723 if (CurrentTime >= nextping)
724 nextping = check_pings();
727 * timeout pending queries that haven't been responded to
729 timeout_auth_queries(CurrentTime);
731 if (GlobalRehashFlag) {
733 GlobalRehashFlag = 0;
735 if (GlobalRestartFlag)
736 server_restart("caught signal: SIGINT");