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.
24 /*----------------------------------------------------------------------------
26 *--------------------------------------------------------------------------*/
34 #include <sys/socket.h>
40 /*----------------------------------------------------------------------------
42 *--------------------------------------------------------------------------*/
51 #include "ircd_alloc.h"
53 #include "ircd_reply.h"
54 #include "ircd_signal.h"
55 #include "ircd_string.h"
77 /*----------------------------------------------------------------------------
79 *--------------------------------------------------------------------------*/
80 extern void init_counters(void);
82 /*----------------------------------------------------------------------------
84 *--------------------------------------------------------------------------*/
91 /*----------------------------------------------------------------------------
93 *--------------------------------------------------------------------------*/
94 struct Client me; // That's me
95 struct Client *GlobalClientList = &me; // Pointer to beginning of Client list
96 time_t TSoffset = 0; // Offset of timestamps to system clock
97 int GlobalRehashFlag = 0; // do a rehash if set
98 int GlobalRestartFlag = 0; // do a restart if set
99 time_t CurrentTime; // Updated every time we leave select()
101 char *configfile = CPATH; // Server configuration file
102 int debuglevel = -1; // Server debug level
103 char *debugmode = ""; // Server debug level
104 static char *dpath = DPATH;
106 time_t nextconnect = 1; // time for next try_connections call
107 time_t nextping = 1; // same as above for check_pings()
109 static struct Daemon thisServer = { 0 }; // server process info
113 /*----------------------------------------------------------------------------
115 *--------------------------------------------------------------------------*/
116 void server_die(const char* message) {
117 ircd_log(L_CRIT, "Server terminating: %s", message);
118 sendto_opmask_butone(0, SNO_OLDSNO, "Server terminating: %s", message);
119 flush_connections(0);
120 close_connections(1);
121 thisServer.running = 0;
125 /*----------------------------------------------------------------------------
126 * API: server_restart
127 *--------------------------------------------------------------------------*/
128 void server_restart(const char* message) {
129 static int restarting = 0;
131 ircd_log(L_WARNING, "Restarting Server: %s", message);
135 sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
136 Debug((DEBUG_NOTICE, "Restarting server..."));
137 flush_connections(0);
140 close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG)));
142 execv(SPATH, thisServer.argv);
144 /* Have to reopen since it has been closed above */
145 open_log(*thisServer.argv);
146 ircd_log(L_CRIT, "execv(%s,%s) failed: %m\n", SPATH, *thisServer.argv);
148 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
149 SPATH, (strerror(errno)) ? strerror(errno) : ""));
154 /*----------------------------------------------------------------------------
155 * outofmemory: Handler for out of memory conditions...
156 *--------------------------------------------------------------------------*/
157 static void outofmemory(void) {
158 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
159 server_restart("Out of Memory");
163 /*----------------------------------------------------------------------------
165 *--------------------------------------------------------------------------*/
166 static void write_pidfile(void) {
169 if (!(pidf = fopen(PPATH, "w+"))) {
171 "Error opening pid file \"%s\": %s", PPATH, strerror(errno)));
175 if (fprintf(pidf, "%5d\n", getpid()) < 5)
176 Debug((DEBUG_NOTICE, "Error writing to pid file %s", PPATH));
182 /*----------------------------------------------------------------------------
185 * Scan through configuration and try new connections.
187 * Returns the calendar time when the next call to this
188 * function should be made latest. (No harm done if this
189 * is called earlier or later...)
190 *--------------------------------------------------------------------------*/
191 static time_t try_connections(void) {
192 struct ConfItem *aconf;
194 struct ConfItem **pconf;
198 struct ConfClass *cltmp;
199 struct ConfItem *cconf;
200 struct ConfItem *con_conf = NULL;
202 unsigned int con_class = 0;
205 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
206 for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
207 /* Also when already connecting! (update holdtimes) --SRB */
208 if (!(aconf->status & CONF_SERVER) || aconf->port == 0)
211 /* Also skip juped servers */
212 if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
215 /* Skip this entry if the use of it is still on hold until
216 * future. Otherwise handle this entry (and set it on hold until next
217 * time). Will reset only hold times, if already made one successfull
218 * connection... [this algorithm is a bit fuzzy... -- msa >;) ]
220 if (aconf->hold > CurrentTime && (next > aconf->hold || next == 0)) {
225 cltmp = aconf->confClass;
226 confrq = get_con_freq(cltmp);
227 aconf->hold = CurrentTime + confrq;
229 /* Found a CONNECT config with port specified, scan clients and see if
230 * this server is already connected?
232 cptr = FindServer(aconf->name);
234 if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
235 (!connecting || (ConClass(cltmp) > con_class))) {
236 /* Check connect rules to see if we're allowed to try */
237 for (cconf = GlobalConfList; cconf; cconf = cconf->next) {
238 if ((cconf->status & CONF_CRULE) && !match(cconf->host, aconf->name))
239 if (crule_eval(cconf->passwd))
243 con_class = ConClass(cltmp);
245 /* We connect only one at time... */
249 if ((next > aconf->hold) || (next == 0))
253 if (con_conf->next) { /* are we already last? */
254 /* Put the current one at the end and make sure we try all connections */
255 for (pconf = &GlobalConfList; (aconf = *pconf); pconf = &(aconf->next))
256 if (aconf == con_conf)
257 *pconf = aconf->next;
258 (*pconf = con_conf)->next = 0;
261 if (connect_server(con_conf, 0, 0))
262 sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
266 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
271 /*----------------------------------------------------------------------------
274 * TODO: This should be moved out of ircd.c. It's protocol-specific when you
275 * get right down to it. Can't really be done until the server is more
276 * modular, however...
277 *--------------------------------------------------------------------------*/
278 static time_t check_pings(void) {
280 int next_check = CurrentTime + PINGFREQUENCY;
284 /* Scan through the client table */
285 for (i=0; i <= HighestFd; i++) {
286 struct Client *cptr = LocalClientArray[i];
291 assert(&me != cptr); /* I should never be in the local client array! */
294 /* Remove dead clients. */
296 exit_client(cptr, cptr, &me, cptr->info);
300 max_ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
302 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
303 cptr->name, (cptr->flags & FLAGS_PINGSENT) ? "[Ping Sent]" : "[]",
304 max_ping, (int)(CurrentTime - cptr->lasttime)));
307 /* Ok, the thing that will happen most frequently, is that someone will
308 * have sent something recently. Cover this first for speed.
310 if (CurrentTime-cptr->lasttime < max_ping) {
311 expire = cptr->lasttime + max_ping;
312 if (expire < next_check)
317 /* Quit the client after max_ping*2 - they should have answered by now */
318 if (CurrentTime-cptr->lasttime >= (max_ping*2) ) {
319 /* If it was a server, then tell ops about it. */
320 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
321 sendto_opmask_butone(0, SNO_OLDSNO,
322 "No response from %s, closing link", cptr->name);
323 exit_client_msg(cptr, cptr, &me, "Ping timeout");
327 /* Unregistered clients pingout after max_ping seconds, they don't
328 * get given a second chance - if they were then people could not quite
329 * finish registration and hold resources without being subject to k/g
332 if (!IsRegistered(cptr)) {
333 /* Display message if they have sent a NICK and a USER but no
336 if (*cptr->name && cptr->user && *cptr->user->username) {
337 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
338 ":Your client may not be compatible with this server.");
339 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
340 ":Compatible clients are available at "
341 "ftp://ftp.undernet.org/pub/irc/clients");
343 exit_client_msg(cptr,cptr,&me, "Ping Timeout");
347 if (!(cptr->flags & FLAGS_PINGSENT)) {
348 /* If we havent PINGed the connection and we havent heard from it in a
349 * while, PING it to make sure it is still alive.
351 cptr->flags |= FLAGS_PINGSENT;
353 /* If we're late in noticing don't hold it against them :) */
354 cptr->lasttime = CurrentTime - max_ping;
357 sendrawto_one(cptr, MSG_PING " :%s", me.name);
359 sendcmdto_one(&me, CMD_PING, cptr, ":%s", me.name);
362 expire = cptr->lasttime + max_ping * 2;
363 if (expire < next_check)
367 assert(next_check >= CurrentTime);
369 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
370 CurrentTime, next_check-CurrentTime));
376 /*----------------------------------------------------------------------------
378 *--------------------------------------------------------------------------*/
379 static void parse_command_line(int argc, char** argv) {
380 const char *options = "d:f:h:ntvx:";
383 if (thisServer.euid != thisServer.uid)
384 setuid(thisServer.uid);
386 /* Do we really need to santiy check the non-NULLness of optarg? That's
387 * getopt()'s job... Removing those... -zs
389 while ((opt = getopt(argc, argv, options)) != EOF)
392 case 't': thisServer.bootopt |= BOOT_TTY; break;
393 case 'd': dpath = optarg; break;
394 case 'f': configfile = optarg; break;
395 case 'h': ircd_strncpy(me.name, optarg, HOSTLEN); break;
396 case 'v': printf("ircd %s\n", version); exit(0);
399 debuglevel = atoi(optarg);
403 thisServer.bootopt |= BOOT_DEBUG;
407 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv]\n");
408 printf("\n -n -t\t Don't detach\n -v\t display version\n\n");
409 printf("Server not started.\n");
415 /*----------------------------------------------------------------------------
417 *--------------------------------------------------------------------------*/
418 static void daemon_init(int no_fork) {
419 if (!init_connection_limits())
422 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
433 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
434 ioctl(fd, TIOCNOTTY, 0);
444 /*----------------------------------------------------------------------------
446 *--------------------------------------------------------------------------*/
447 static void event_loop(void) {
448 time_t nextdnscheck = 0;
451 thisServer.running = 1;
452 while (thisServer.running) {
453 /* We only want to connect if a connection is due, not every time through.
454 * Note, if there are no active C lines, this call to Tryconnections is
455 * made once only; it will return 0. - avalon
457 if (nextconnect && CurrentTime >= nextconnect)
458 nextconnect = try_connections();
460 /* DNS checks. One to timeout queries, one for cache expiries. */
461 nextdnscheck = timeout_resolver(CurrentTime);
463 /* Take the smaller of the two 'timed' event times as the time of next
464 * event (stops us being late :) - avalon
465 * WARNING - nextconnect can return 0!
468 delay = IRCD_MIN(nextping, nextconnect);
472 delay = IRCD_MIN(nextdnscheck, delay) - CurrentTime;
474 /* Adjust delay to something reasonable [ad hoc values] (one might think
475 * something more clever here... --msa) We don't really need to check that
476 * often and as long as we don't delay too long, everything should be ok.
477 * waiting too long can cause things to timeout... i.e. PINGS -> a
478 * disconnection :( - avalon
483 read_message(IRCD_MIN(delay, TIMESEC));
485 Debug((DEBUG_DEBUG, "Got message(s)"));
487 /* ...perhaps should not do these loops every time, but only if there is
488 * some chance of something happening (but, note that conf->hold times may
489 * be changed elsewhere--so precomputed next event time might be too far
490 * away... (similarly with ping times) --msa
492 if (CurrentTime >= nextping)
493 nextping = check_pings();
495 /* timeout pending queries that haven't been responded to */
496 timeout_auth_queries(CurrentTime);
498 ip_registry_expire();
500 if (GlobalRehashFlag) {
502 GlobalRehashFlag = 0;
505 if (GlobalRestartFlag)
506 server_restart("caught signal: SIGINT");
511 /*----------------------------------------------------------------------------
512 * check_file_access: random helper function to make sure that a file is
513 * accessible in a certain way, and complain if not.
514 *--------------------------------------------------------------------------*/
515 static char check_file_access(const char *path, char which, int mode) {
516 if (!access(path, mode))
520 "Check on %cPATH (%s) failed: %s\n"
521 "Please create file and/or rerun `make config' and "
522 "recompile to correct this.\n",
523 which, path, strerror(errno));
526 fprintf(stderr, "Keep in mind that paths are relative to CHROOTDIR.\n");
533 /*----------------------------------------------------------------------------
535 *--------------------------------------------------------------------------*/
536 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
537 static void set_core_limit(void) {
538 struct rlimit corelim;
540 if (getrlimit(RLIMIT_CORE, &corelim)) {
541 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
542 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
545 corelim.rlim_cur = corelim.rlim_max;
546 if (setrlimit(RLIMIT_CORE, &corelim))
547 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
553 /*----------------------------------------------------------------------------
554 * set_chroot_environment
555 *--------------------------------------------------------------------------*/
557 static char set_chroot_environment(void) {
558 /* Must be root to chroot! Silly if you ask me... */
563 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", DPATH, strerror(errno));
567 fprintf(stderr, "Fail: Cannot chroot(%s): %s\n", DPATH, strerror(errno));
576 /*----------------------------------------------------------------------------
577 * set_userid_if_needed()
578 *--------------------------------------------------------------------------*/
579 static int set_userid_if_needed(void) {
580 /* TODO: Drop privs correctly! */
581 #if defined(IRC_GID) && defined(IRC_UID)
588 if (getuid() == 0 || geteuid() == 0 ||
589 getgid() == 0 || getegid() == 0) {
590 fprintf(stderr, "ERROR: This server will not run as superuser.\n");
598 /*----------------------------------------------------------------------------
601 * TODO: This should set the basic environment up and start the main loop.
602 * we're doing waaaaaaaaay too much server initialization here. I hate
603 * long and ugly control paths... -smd
604 *--------------------------------------------------------------------------*/
605 int main(int argc, char **argv) {
606 CurrentTime = time(NULL);
608 thisServer.argc = argc;
609 thisServer.argv = argv;
610 thisServer.uid = getuid();
611 thisServer.euid = geteuid();
614 if (!set_chroot_environment())
618 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
622 umask(077); /* better safe than sorry --SRB */
623 memset(&me, 0, sizeof(me));
629 parse_command_line(argc, argv);
632 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", dpath, strerror(errno));
636 if (!set_userid_if_needed())
639 /* Check paths for accessibility */
640 if (!check_file_access(SPATH, 'S', X_OK) ||
641 !check_file_access(CPATH, 'C', R_OK) ||
642 !check_file_access(MPATH, 'M', R_OK) ||
643 !check_file_access(RPATH, 'R', R_OK))
647 if (!check_file_access(LPATH, 'L', W_OK))
658 debug_init(thisServer.bootopt & BOOT_TTY);
659 daemon_init(thisServer.bootopt & BOOT_TTY);
661 set_nomem_handler(outofmemory);
667 Debug((DEBUG_FATAL, "Failed to read configuration file %s", configfile));
668 printf("Couldn't open configuration file %s\n", configfile);
672 if (!init_server_identity()) {
673 Debug((DEBUG_FATAL, "Failed to initialize server identity"));
680 rmotd = read_motd(RPATH);
681 motd = read_motd(MPATH);
682 CurrentTime = time(NULL);
688 me.serv->timestamp = TStime(); /* Abuse own link timestamp as start TS */
689 me.serv->prot = atoi(MAJOR_PROTOCOL);
691 me.serv->down = NULL;
692 me.handler = SERVER_HANDLER;
694 SetYXXCapacity(&me, MAXCLIENTS);
696 me.lasttime = me.since = me.firsttime = CurrentTime;
704 Debug((DEBUG_NOTICE, "Server ready..."));
705 ircd_log(L_NOTICE, "Server Ready");