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"
58 #include <sys/socket.h>
63 extern void init_counters(void);
65 struct Client me; /* That's me */
66 struct Client* GlobalClientList = &me; /* Pointer to beginning of Client list */
67 time_t TSoffset = 0; /* Offset of timestamps to system clock */
68 int GlobalRehashFlag = 0; /* do a rehash if set */
69 int GlobalRestartFlag = 0; /* do a restart if set */
70 time_t CurrentTime; /* Updated every time we leave select() */
73 char *configfile = CPATH; /* Server configuration file */
74 int debuglevel = -1; /* Server debug level */
75 unsigned int bootopt = 0; /* Server boot option flags */
76 char *debugmode = ""; /* -"- -"- -"- */
77 static char *dpath = DPATH;
79 time_t nextconnect = 1; /* time for next try_connections call */
80 time_t nextping = 1; /* same as above for check_pings() */
81 time_t nextdnscheck = 0; /* next time to poll dns to force timeouts */
82 time_t nextexpire = 1; /* next expire run on the dns cache */
88 static void server_reboot(const char* message)
92 sendto_ops("Restarting server: %s", message);
93 Debug((DEBUG_NOTICE, "Restarting server..."));
96 * fd 0 must be 'preserved' if either the -d or -i options have
97 * been passed to us before restarting.
101 for (i = 3; i < MAXCONNECTIONS; i++)
103 if (!(bootopt & (BOOT_TTY | BOOT_DEBUG)))
108 execv(SPATH, myargv);
110 /* Have to reopen since it has been closed above */
112 ircd_log(L_CRIT, "execv(%s,%s) failed: %m\n", SPATH, myargv[0]);
114 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
115 SPATH, strerror(errno)));
119 void server_die(const char* message)
121 ircd_log(L_CRIT, "Server terminating: %s", message);
122 sendto_ops("Server terminating: %s", message);
123 flush_connections(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)) >= 0) {
150 memset(buff, 0, sizeof(buff));
151 sprintf(buff, "%5d\n", (int)getpid());
152 if (write(fd, buff, strlen(buff)) == -1)
153 Debug((DEBUG_NOTICE, "Error writing to pid file %s", PPATH));
157 Debug((DEBUG_NOTICE, "Error opening pid file \"%s\": %s",
158 PPATH, strerror(errno)));
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;
176 int connecting, confrq;
178 struct ConfClass *cltmp;
179 struct ConfItem *cconf, *con_conf = NULL;
180 unsigned int con_class = 0;
183 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
184 for (aconf = GlobalConfList; aconf; aconf = aconf->next)
186 /* Also when already connecting! (update holdtimes) --SRB */
187 if (!(aconf->status & CONF_SERVER) || aconf->port == 0)
189 cltmp = aconf->confClass;
191 * Skip this entry if the use of it is still on hold until
192 * future. Otherwise handle this entry (and set it on hold
193 * until next time). Will reset only hold times, if already
194 * made one successfull connection... [this algorithm is
195 * a bit fuzzy... -- msa >;) ]
198 if ((aconf->hold > CurrentTime))
200 if ((next > aconf->hold) || (next == 0))
205 confrq = get_con_freq(cltmp);
206 aconf->hold = CurrentTime + confrq;
208 * Found a CONNECT config with port specified, scan clients
209 * and see if this server is already connected?
211 cptr = FindServer(aconf->name);
213 if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
214 (!connecting || (ConClass(cltmp) > con_class)))
216 /* Check connect rules to see if we're allowed to try */
217 for (cconf = GlobalConfList; cconf; cconf = cconf->next)
218 if ((cconf->status & CONF_CRULE) &&
219 (match(cconf->host, aconf->name) == 0))
220 if (crule_eval(cconf->passwd))
224 con_class = ConClass(cltmp);
226 /* We connect only one at time... */
230 if ((next > aconf->hold) || (next == 0))
235 if (con_conf->next) /* are we already last? */
237 /* Put the current one at the end and make sure we try all connections */
238 for (pconf = &GlobalConfList; (aconf = *pconf); pconf = &(aconf->next))
239 if (aconf == con_conf)
240 *pconf = aconf->next;
241 (*pconf = con_conf)->next = 0;
243 if (connect_server(con_conf, 0, 0))
244 sendto_ops("Connection to %s activated.", con_conf->name);
246 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
250 static time_t check_pings(void)
255 time_t oldest = CurrentTime + PINGFREQUENCY;
258 for (i = 0; i <= HighestFd; i++) {
259 if (!(cptr = LocalClientArray[i]))
262 * me is never in the local client array
266 * Note: No need to notify opers here.
267 * It's already done when "FLAGS_DEADSOCKET" is set.
270 exit_client(cptr, cptr, &me, LastDeadComment(cptr));
274 ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
275 Debug((DEBUG_DEBUG, "c(%s)=%d p %d a %d",
276 cptr->name, cptr->status, ping,
277 (int)(CurrentTime - cptr->lasttime)));
279 * Ok, so goto's are ugly and can be avoided here but this code
280 * is already indented enough so I think its justified. -avalon
282 if (IsRegistered(cptr) && (ping >= CurrentTime - cptr->lasttime))
285 * If the server hasnt talked to us in 2 * ping seconds
286 * and it has a ping time, then close its connection.
287 * If the client is a user and a KILL line was found
288 * to be active, close this connection too.
290 if (((CurrentTime - cptr->lasttime) >= (2 * ping) && (cptr->flags & FLAGS_PINGSENT)) ||
291 (!IsRegistered(cptr) && !IsHandshake(cptr) && (CurrentTime - cptr->firsttime) >= ping))
293 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
295 sendto_ops("No response from %s, closing link", cptr->name);
296 exit_client(cptr, cptr, &me, "Ping timeout");
300 if (!IsRegistered(cptr) && *cptr->name && *cptr->user->username) {
302 ":%s %d %s :Your client may not be compatible with this server.",
303 me.name, ERR_BADPING, cptr->name);
305 ":%s %d %s :Compatible clients are available at "
306 "ftp://ftp.undernet.org/pub/irc/clients",
307 me.name, ERR_BADPING, cptr->name);
309 exit_client_msg(cptr, cptr, &me, "Ping timeout for %s",
310 get_client_name(cptr, HIDE_IP));
314 else if (IsRegistered(cptr) && 0 == (cptr->flags & FLAGS_PINGSENT)) {
316 * If we havent PINGed the connection and we havent
317 * heard from it in a while, PING it to make sure
320 cptr->flags |= FLAGS_PINGSENT;
322 * not nice but does the job
324 cptr->lasttime = CurrentTime - ping;
326 sendto_one(cptr, "PING :%s", me.name);
328 sendto_one(cptr, "%s " TOK_PING " :%s", NumServ(&me), me.name);
331 timeout = cptr->lasttime + ping;
332 while (timeout <= CurrentTime)
334 if (timeout < oldest)
337 if (oldest < CurrentTime)
338 oldest = CurrentTime + PINGFREQUENCY;
340 "Next check_ping() call at: %s, %d " TIME_T_FMT " " TIME_T_FMT,
341 myctime(oldest), ping, oldest, CurrentTime));
349 * This is called when the commandline is not acceptable.
350 * Give error message and exit without starting anything.
352 static int bad_command(void)
354 printf("Usage: ircd %s[-h servername] [-x loglevel] [-t]\n",
355 #ifdef CMDLINE_CONFIG
361 printf("Server not started\n\n");
365 int main(int argc, char *argv[])
370 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
371 struct rlimit corelim;
374 CurrentTime = time(NULL);
379 if (MAXCONNECTIONS < 64 || MAXCONNECTIONS > 256000) {
380 fprintf(stderr, "%s: MAXCONNECTIONS insane: %d\n", *argv, MAXCONNECTIONS);
387 monstartup(0, etext);
389 signal(SIGUSR1, s_monitor);
395 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", DPATH, strerror(errno));
400 fprintf(stderr, "Fail: Cannot chroot(%s): %s\n", DPATH, strerror(errno));
404 #endif /*CHROOTDIR */
407 umask(077); /* better safe than sorry --SRB */
408 memset(&me, 0, sizeof(me));
413 memset(&vserv, 0, sizeof(vserv));
420 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
421 if (getrlimit(RLIMIT_CORE, &corelim))
423 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
424 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
426 corelim.rlim_cur = corelim.rlim_max;
427 if (setrlimit(RLIMIT_CORE, &corelim))
428 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
432 * All command line parameters have the syntax "-fstring"
433 * or "-f string" (e.g. the space is optional). String may
434 * be empty. Flag characters cannot be concatenated (like
435 * "-fxyz"), it would conflict with the form "-fstring".
437 while (--argc > 0 && (*++argv)[0] == '-')
439 char *p = argv[0] + 1;
442 if (flag == '\0' || *p == '\0')
444 if (argc > 1 && argv[1][0] != '-')
456 bootopt |= BOOT_QUICK;
463 #ifdef CMDLINE_CONFIG
471 ircd_strncpy(me.name, p, HOSTLEN);
479 printf("ircd %s\n", version);
486 if (!(hep = gethostbyname(p)))
488 fprintf(stderr, "%s: Error creating virtual host \"%s\": %d",
489 argv[0], p, h_errno);
492 if (hep->h_addrtype == AF_INET && hep->h_addr_list[0] &&
493 !hep->h_addr_list[1])
495 memcpy(&vserv.sin_addr, hep->h_addr_list[0], sizeof(struct in_addr));
496 vserv.sin_family = AF_INET;
500 fprintf(stderr, "%s: Error creating virtual host \"%s\": "
501 "Use -w <IP-number of interface>\n", argv[0], p);
512 debuglevel = atoi(p);
513 debugmode = *p ? p : "0";
514 bootopt |= BOOT_DEBUG;
517 fprintf(stderr, "%s: DEBUGMODE must be defined for -x y\n", myargv[0]);
528 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", dpath, strerror(errno));
533 if ((uid != euid) && !euid)
536 "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
541 #if !defined(CHROOTDIR) || (defined(IRC_UID) && defined(IRC_GID))
550 #if defined(IRC_UID) && defined(IRC_GID)
552 /* run as a specified user */
553 fprintf(stderr, "WARNING: running ircd with uid = %d\n", IRC_UID);
554 fprintf(stderr, " changing to gid %d.\n", IRC_GID);
558 /* check for setuid root as usual */
560 "ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
564 #endif /*CHROOTDIR/UID/GID */
567 return bad_command(); /* This should exit out */
576 if (access(path, X_OK) == 0) {
579 if (access(path, R_OK) == 0) {
582 if (access(path, R_OK) == 0) {
585 if (access(path, R_OK) == 0) {
591 if (access(path, W_OK) == 0)
600 fprintf(stderr, "Check on %cPATH (%s) failed: %s\n",
601 c, path, strerror(errno));
603 "Please create file and/or rerun `make config' and recompile to correct this.\n");
606 "Keep in mind that all paths are relative to CHROOTDIR.\n");
620 set_nomem_handler(outofmemory);
626 if (initconf(bootopt) == -1) {
627 Debug((DEBUG_FATAL, "Failed in reading configuration file %s", configfile));
628 printf("Couldn't open configuration file %s\n", configfile);
631 if (!init_server_identity()) {
632 Debug((DEBUG_FATAL, "Failed to initialize server identity"));
636 rmotd = read_motd(RPATH);
637 motd = read_motd(MPATH);
638 CurrentTime = time(NULL);
643 * Abuse own link timestamp as start timestamp:
645 me.serv->timestamp = TStime();
646 me.serv->prot = atoi(MAJOR_PROTOCOL);
648 me.serv->down = NULL;
649 me.handler = SERVER_HANDLER;
651 SetYXXCapacity(&me, MAXCLIENTS);
653 me.lasttime = me.since = me.firsttime = CurrentTime;
661 Debug((DEBUG_NOTICE, "Server ready..."));
662 ircd_log(L_NOTICE, "Server Ready");
667 * We only want to connect if a connection is due,
668 * not every time through. Note, if there are no
669 * active C lines, this call to Tryconnections is
670 * made once only; it will return 0. - avalon
672 if (nextconnect && CurrentTime >= nextconnect)
673 nextconnect = try_connections();
675 * DNS checks. One to timeout queries, one for cache expiries.
677 nextdnscheck = timeout_resolver(CurrentTime);
679 * Take the smaller of the two 'timed' event times as
680 * the time of next event (stops us being late :) - avalon
681 * WARNING - nextconnect can return 0!
684 delay = IRCD_MIN(nextping, nextconnect);
687 delay = IRCD_MIN(nextdnscheck, delay);
688 delay -= CurrentTime;
690 * Adjust delay to something reasonable [ad hoc values]
691 * (one might think something more clever here... --msa)
692 * We don't really need to check that often and as long
693 * as we don't delay too long, everything should be ok.
694 * waiting too long can cause things to timeout...
695 * i.e. PINGS -> a disconnection :(
701 delay = IRCD_MIN(delay, TIMESEC);
704 Debug((DEBUG_DEBUG, "Got message(s)"));
707 * ...perhaps should not do these loops every time,
708 * but only if there is some chance of something
709 * happening (but, note that conf->hold times may
710 * be changed elsewhere--so precomputed next event
711 * time might be too far away... (similarly with
714 if (CurrentTime >= nextping)
715 nextping = check_pings();
718 * timeout pending queries that haven't been responded to
720 timeout_auth_queries(CurrentTime);
722 if (GlobalRehashFlag) {
724 GlobalRehashFlag = 0;
726 if (GlobalRestartFlag)
727 server_restart("caught signal: SIGINT");