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);
87 /*----------------------------------------------------------------------------
89 *--------------------------------------------------------------------------*/
96 /*----------------------------------------------------------------------------
98 *--------------------------------------------------------------------------*/
99 struct Client me; // That's me
100 struct Client *GlobalClientList = &me; // Pointer to beginning of Client list
101 time_t TSoffset = 0; // Offset of timestamps to system clock
102 int GlobalRehashFlag = 0; // do a rehash if set
103 int GlobalRestartFlag = 0; // do a restart if set
104 time_t CurrentTime; // Updated every time we leave select()
106 char *configfile = CPATH; // Server configuration file
107 int debuglevel = -1; // Server debug level
108 char *debugmode = ""; // Server debug level
109 static char *dpath = DPATH;
111 time_t nextconnect = 1; // time for next try_connections call
112 time_t nextping = 1; // same as above for check_pings()
114 static struct Daemon thisServer = { 0 }; // server process info
118 /*----------------------------------------------------------------------------
120 *--------------------------------------------------------------------------*/
121 void server_die(const char* message) {
122 ircd_log(L_CRIT, "Server terminating: %s", message);
123 sendto_opmask_butone(0, SNO_OLDSNO, "Server terminating: %s", message);
124 flush_connections(0);
125 close_connections(1);
126 thisServer.running = 0;
130 /*----------------------------------------------------------------------------
131 * API: server_restart
132 *--------------------------------------------------------------------------*/
133 void server_restart(const char* message) {
134 static int restarting = 0;
136 ircd_log(L_WARNING, "Restarting Server: %s", message);
140 sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
141 Debug((DEBUG_NOTICE, "Restarting server..."));
142 flush_connections(0);
145 close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG)));
147 execv(SPATH, thisServer.argv);
149 /* Have to reopen since it has been closed above */
150 open_log(*thisServer.argv);
151 ircd_log(L_CRIT, "execv(%s,%s) failed: %m\n", SPATH, *thisServer.argv);
153 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
154 SPATH, (strerror(errno)) ? strerror(errno) : ""));
159 /*----------------------------------------------------------------------------
160 * outofmemory: Handler for out of memory conditions...
161 *--------------------------------------------------------------------------*/
162 static void outofmemory(void) {
163 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
164 server_restart("Out of Memory");
168 /*----------------------------------------------------------------------------
170 *--------------------------------------------------------------------------*/
171 static void write_pidfile(void) {
174 if (!(pidf = fopen(PPATH, "w+"))) {
176 "Error opening pid file \"%s\": %s", PPATH, strerror(errno)));
180 if (fprintf(pidf, "%5d\n", getpid()) < 5)
181 Debug((DEBUG_NOTICE, "Error writing to pid file %s", PPATH));
187 /*----------------------------------------------------------------------------
190 * Scan through configuration and try new connections.
192 * Returns the calendar time when the next call to this
193 * function should be made latest. (No harm done if this
194 * is called earlier or later...)
195 *--------------------------------------------------------------------------*/
196 static time_t try_connections(void) {
197 struct ConfItem *aconf;
199 struct ConfItem **pconf;
203 struct ConfClass *cltmp;
204 struct ConfItem *cconf;
205 struct ConfItem *con_conf = NULL;
207 unsigned int con_class = 0;
210 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
211 for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
212 /* Also when already connecting! (update holdtimes) --SRB */
213 if (!(aconf->status & CONF_SERVER) || aconf->port == 0)
216 /* Also skip juped servers */
217 if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
220 /* Skip this entry if the use of it is still on hold until
221 * future. Otherwise handle this entry (and set it on hold until next
222 * time). Will reset only hold times, if already made one successfull
223 * connection... [this algorithm is a bit fuzzy... -- msa >;) ]
225 if (aconf->hold > CurrentTime && (next > aconf->hold || next == 0)) {
230 cltmp = aconf->confClass;
231 confrq = get_con_freq(cltmp);
232 aconf->hold = CurrentTime + confrq;
234 /* Found a CONNECT config with port specified, scan clients and see if
235 * this server is already connected?
237 cptr = FindServer(aconf->name);
239 if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
240 (!connecting || (ConClass(cltmp) > con_class))) {
241 /* Check connect rules to see if we're allowed to try */
242 for (cconf = GlobalConfList; cconf; cconf = cconf->next) {
243 if ((cconf->status & CONF_CRULE) && !match(cconf->host, aconf->name))
244 if (crule_eval(cconf->passwd))
248 con_class = ConClass(cltmp);
250 /* We connect only one at time... */
254 if ((next > aconf->hold) || (next == 0))
258 if (con_conf->next) { /* are we already last? */
259 /* Put the current one at the end and make sure we try all connections */
260 for (pconf = &GlobalConfList; (aconf = *pconf); pconf = &(aconf->next))
261 if (aconf == con_conf)
262 *pconf = aconf->next;
263 (*pconf = con_conf)->next = 0;
266 if (connect_server(con_conf, 0, 0))
267 sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
271 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
276 /*----------------------------------------------------------------------------
279 * TODO: This should be moved out of ircd.c. It's protocol-specific when you
280 * get right down to it. Can't really be done until the server is more
281 * modular, however...
282 *--------------------------------------------------------------------------*/
283 static time_t check_pings(void) {
285 int next_check = CurrentTime + PINGFREQUENCY;
289 /* Scan through the client table */
290 for (i=0; i <= HighestFd; i++) {
291 struct Client *cptr = LocalClientArray[i];
296 assert(&me != cptr); /* I should never be in the local client array! */
299 /* Remove dead clients. */
301 exit_client(cptr, cptr, &me, cptr->info);
305 max_ping = IsRegistered(cptr) ? get_client_ping(cptr) : CONNECTTIMEOUT;
307 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
308 cptr->name, (cptr->flags & FLAGS_PINGSENT) ? "[Ping Sent]" : "[]",
309 max_ping, (int)(CurrentTime - cptr->lasttime)));
312 /* Ok, the thing that will happen most frequently, is that someone will
313 * have sent something recently. Cover this first for speed.
315 if (CurrentTime-cptr->lasttime < max_ping) {
316 expire = cptr->lasttime + max_ping;
317 if (expire < next_check)
322 /* Quit the client after max_ping*2 - they should have answered by now */
323 if (CurrentTime-cptr->lasttime >= (max_ping*2) ) {
324 /* If it was a server, then tell ops about it. */
325 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
326 sendto_opmask_butone(0, SNO_OLDSNO,
327 "No response from %s, closing link", cptr->name);
328 exit_client_msg(cptr, cptr, &me, "Ping timeout");
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 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
343 ":Your client may not be compatible with this server.");
344 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
345 ":Compatible clients are available at "
346 "ftp://ftp.undernet.org/pub/irc/clients");
348 exit_client_msg(cptr,cptr,&me, "Ping Timeout");
352 if (!(cptr->flags & FLAGS_PINGSENT)) {
353 /* If we havent PINGed the connection and we havent heard from it in a
354 * while, PING it to make sure it is still alive.
356 cptr->flags |= FLAGS_PINGSENT;
358 /* If we're late in noticing don't hold it against them :) */
359 cptr->lasttime = CurrentTime - max_ping;
362 sendrawto_one(cptr, MSG_PING " :%s", me.name);
364 sendcmdto_one(&me, CMD_PING, cptr, ":%s", me.name);
367 expire = cptr->lasttime + max_ping * 2;
368 if (expire < next_check)
372 assert(next_check >= CurrentTime);
374 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
375 CurrentTime, next_check-CurrentTime));
381 /*----------------------------------------------------------------------------
383 *--------------------------------------------------------------------------*/
384 static void parse_command_line(int argc, char** argv) {
385 const char *options = "d:f:h:ntvx:";
388 if (thisServer.euid != thisServer.uid)
389 setuid(thisServer.uid);
391 /* Do we really need to santiy check the non-NULLness of optarg? That's
392 * getopt()'s job... Removing those... -zs
394 while ((opt = getopt(argc, argv, options)) != EOF)
397 case 't': thisServer.bootopt |= BOOT_TTY; break;
398 case 'd': dpath = optarg; break;
399 case 'f': configfile = optarg; break;
400 case 'h': ircd_strncpy(me.name, optarg, HOSTLEN); break;
401 case 'v': printf("ircd %s\n", version); exit(0);
404 debuglevel = atoi(optarg);
408 thisServer.bootopt |= BOOT_DEBUG;
412 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv]\n");
413 printf("\n -n -t\t Don't detach\n -v\t display version\n\n");
414 printf("Server not started.\n");
420 /*----------------------------------------------------------------------------
422 *--------------------------------------------------------------------------*/
423 static void daemon_init(int no_fork) {
424 if (!init_connection_limits())
427 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
438 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
439 ioctl(fd, TIOCNOTTY, 0);
449 /*----------------------------------------------------------------------------
451 *--------------------------------------------------------------------------*/
452 static void event_loop(void) {
453 time_t nextdnscheck = 0;
456 thisServer.running = 1;
457 while (thisServer.running) {
458 /* We only want to connect if a connection is due, not every time through.
459 * Note, if there are no active C lines, this call to Tryconnections is
460 * made once only; it will return 0. - avalon
462 if (nextconnect && CurrentTime >= nextconnect)
463 nextconnect = try_connections();
465 /* DNS checks. One to timeout queries, one for cache expiries. */
466 nextdnscheck = timeout_resolver(CurrentTime);
468 /* Take the smaller of the two 'timed' event times as the time of next
469 * event (stops us being late :) - avalon
470 * WARNING - nextconnect can return 0!
473 delay = IRCD_MIN(nextping, nextconnect);
477 delay = IRCD_MIN(nextdnscheck, delay) - CurrentTime;
479 /* Adjust delay to something reasonable [ad hoc values] (one might think
480 * something more clever here... --msa) We don't really need to check that
481 * often and as long as we don't delay too long, everything should be ok.
482 * waiting too long can cause things to timeout... i.e. PINGS -> a
483 * disconnection :( - avalon
488 read_message(IRCD_MIN(delay, TIMESEC));
490 Debug((DEBUG_DEBUG, "Got message(s)"));
492 /* ...perhaps should not do these loops every time, but only if there is
493 * some chance of something happening (but, note that conf->hold times may
494 * be changed elsewhere--so precomputed next event time might be too far
495 * away... (similarly with ping times) --msa
497 if (CurrentTime >= nextping)
498 nextping = check_pings();
500 /* timeout pending queries that haven't been responded to */
501 timeout_auth_queries(CurrentTime);
505 if (GlobalRehashFlag) {
507 GlobalRehashFlag = 0;
510 if (GlobalRestartFlag)
511 server_restart("caught signal: SIGINT");
516 /*----------------------------------------------------------------------------
517 * check_file_access: random helper function to make sure that a file is
518 * accessible in a certain way, and complain if not.
519 *--------------------------------------------------------------------------*/
520 static char check_file_access(const char *path, char which, int mode) {
521 if (!access(path, mode))
525 "Check on %cPATH (%s) failed: %s\n"
526 "Please create file and/or rerun `make config' and "
527 "recompile to correct this.\n",
528 which, path, strerror(errno));
531 fprintf(stderr, "Keep in mind that paths are relative to CHROOTDIR.\n");
538 /*----------------------------------------------------------------------------
540 *--------------------------------------------------------------------------*/
541 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
542 static void set_core_limit(void) {
543 struct rlimit corelim;
545 if (getrlimit(RLIMIT_CORE, &corelim)) {
546 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
547 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
550 corelim.rlim_cur = corelim.rlim_max;
551 if (setrlimit(RLIMIT_CORE, &corelim))
552 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
558 /*----------------------------------------------------------------------------
559 * set_chroot_environment
560 *--------------------------------------------------------------------------*/
562 static char set_chroot_environment(void) {
563 /* Must be root to chroot! Silly if you ask me... */
568 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", DPATH, strerror(errno));
572 fprintf(stderr, "Fail: Cannot chroot(%s): %s\n", DPATH, strerror(errno));
581 /*----------------------------------------------------------------------------
582 * set_userid_if_needed()
583 *--------------------------------------------------------------------------*/
584 static int set_userid_if_needed(void) {
585 /* TODO: Drop privs correctly! */
586 #if defined(IRC_GID) && defined(IRC_UID)
593 if (getuid() == 0 || geteuid() == 0 ||
594 getgid() == 0 || getegid() == 0) {
595 fprintf(stderr, "ERROR: This server will not run as superuser.\n");
603 /*----------------------------------------------------------------------------
606 * TODO: This should set the basic environment up and start the main loop.
607 * we're doing waaaaaaaaay too much server initialization here. I hate
608 * long and ugly control paths... -smd
609 *--------------------------------------------------------------------------*/
610 int main(int argc, char **argv) {
612 monstartup(0, etext);
614 signal(SIGUSR1, s_monitor);
617 CurrentTime = time(NULL);
619 thisServer.argc = argc;
620 thisServer.argv = argv;
621 thisServer.uid = getuid();
622 thisServer.euid = geteuid();
625 if (!set_chroot_environment())
629 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
633 umask(077); /* better safe than sorry --SRB */
634 memset(&me, 0, sizeof(me));
640 parse_command_line(argc, argv);
643 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", dpath, strerror(errno));
647 if (!set_userid_if_needed())
650 /* Check paths for accessibility */
651 if (!check_file_access(SPATH, 'S', X_OK) ||
652 !check_file_access(CPATH, 'C', R_OK) ||
653 !check_file_access(MPATH, 'M', R_OK) ||
654 !check_file_access(RPATH, 'R', R_OK))
658 if (!check_file_access(LPATH, 'L', W_OK))
669 debug_init(thisServer.bootopt & BOOT_TTY);
670 daemon_init(thisServer.bootopt & BOOT_TTY);
672 set_nomem_handler(outofmemory);
678 Debug((DEBUG_FATAL, "Failed to read configuration file %s", configfile));
679 printf("Couldn't open configuration file %s\n", configfile);
683 if (!init_server_identity()) {
684 Debug((DEBUG_FATAL, "Failed to initialize server identity"));
691 rmotd = read_motd(RPATH);
692 motd = read_motd(MPATH);
693 CurrentTime = time(NULL);
699 me.serv->timestamp = TStime(); /* Abuse own link timestamp as start TS */
700 me.serv->prot = atoi(MAJOR_PROTOCOL);
702 me.serv->down = NULL;
703 me.handler = SERVER_HANDLER;
705 SetYXXCapacity(&me, MAXCLIENTS);
707 me.lasttime = me.since = me.firsttime = CurrentTime;
715 Debug((DEBUG_NOTICE, "Server ready..."));
716 ircd_log(L_NOTICE, "Server Ready");