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.
28 #include "ircd_alloc.h"
30 #include "ircd_reply.h"
31 #include "ircd_signal.h"
32 #include "ircd_string.h"
62 #include <sys/socket.h>
68 /*----------------------------------------------------------------------------
70 *--------------------------------------------------------------------------*/
71 extern void init_counters(void);
73 /*----------------------------------------------------------------------------
75 *--------------------------------------------------------------------------*/
82 /*----------------------------------------------------------------------------
84 *--------------------------------------------------------------------------*/
85 struct Client me; // That's me
86 struct Connection me_con; // That's me too
87 struct Client *GlobalClientList = &me; // Pointer to beginning of Client list
88 time_t TSoffset = 0; // Offset of timestamps to system clock
89 int GlobalRehashFlag = 0; // do a rehash if set
90 int GlobalRestartFlag = 0; // do a restart if set
91 time_t CurrentTime; // Updated every time we leave select()
93 char *configfile = CPATH; // Server configuration file
94 int debuglevel = -1; // Server debug level
95 char *debugmode = ""; // Server debug level
96 static char *dpath = DPATH;
98 time_t nextconnect = 1; // time for next try_connections call
99 time_t nextping = 1; // same as above for check_pings()
101 static struct Daemon thisServer = { 0 }; // server process info
105 /*----------------------------------------------------------------------------
107 *--------------------------------------------------------------------------*/
108 void server_die(const char* message) {
109 /* log_write will send out message to both log file and as server notice */
110 log_write(LS_SYSTEM, L_CRIT, 0, "Server terminating: %s", message);
111 flush_connections(0);
112 close_connections(1);
113 thisServer.running = 0;
117 /*----------------------------------------------------------------------------
118 * API: server_restart
119 *--------------------------------------------------------------------------*/
120 void server_restart(const char* message) {
121 static int restarting = 0;
123 /* inhibit sending any server notices; we may be in a loop */
124 log_write(LS_SYSTEM, L_WARNING, LOG_NOSNOTICE, "Restarting Server: %s",
126 if (restarting++) /* increment restarting to prevent looping */
129 sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
130 Debug((DEBUG_NOTICE, "Restarting server..."));
131 flush_connections(0);
135 close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG)));
137 execv(SPATH, thisServer.argv);
139 /* Have to reopen since it has been closed above */
142 log_write(LS_SYSTEM, L_CRIT, 0, "execv(%s,%s) failed: %m", SPATH,
145 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
146 SPATH, (strerror(errno)) ? strerror(errno) : ""));
151 /*----------------------------------------------------------------------------
152 * outofmemory: Handler for out of memory conditions...
153 *--------------------------------------------------------------------------*/
154 static void outofmemory(void) {
155 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
156 server_restart("Out of Memory");
160 /*----------------------------------------------------------------------------
162 *--------------------------------------------------------------------------*/
163 static void write_pidfile(void) {
166 if (!(pidf = fopen(PPATH, "w+"))) {
168 "Error opening pid file \"%s\": %s", PPATH, strerror(errno)));
172 if (fprintf(pidf, "%5d\n", getpid()) < 5)
173 Debug((DEBUG_NOTICE, "Error writing to pid file %s", PPATH));
179 /*----------------------------------------------------------------------------
182 * Scan through configuration and try new connections.
184 * Returns the calendar time when the next call to this
185 * function should be made latest. (No harm done if this
186 * is called earlier or later...)
187 *--------------------------------------------------------------------------*/
188 static time_t try_connections(void) {
189 struct ConfItem* aconf;
191 struct ConfItem** pconf;
195 struct ConnectionClass* cltmp;
196 struct ConfItem* con_conf = 0;
198 unsigned int con_class = 0;
201 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
202 for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
203 /* Also when already connecting! (update holdtimes) --SRB */
204 if (!(aconf->status & CONF_SERVER) || aconf->port == 0)
207 /* Also skip juped servers */
208 if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
211 /* Skip this entry if the use of it is still on hold until
212 * future. Otherwise handle this entry (and set it on hold until next
213 * time). Will reset only hold times, if already made one successfull
214 * connection... [this algorithm is a bit fuzzy... -- msa >;) ]
216 if (aconf->hold > CurrentTime && (next > aconf->hold || next == 0)) {
221 cltmp = aconf->conn_class;
222 confrq = get_con_freq(cltmp);
223 aconf->hold = CurrentTime + confrq;
225 /* Found a CONNECT config with port specified, scan clients and see if
226 * this server is already connected?
228 cptr = FindServer(aconf->name);
230 if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
231 (!connecting || (ConClass(cltmp) > con_class))) {
233 * Check connect rules to see if we're allowed to try
235 if (0 == conf_eval_crule(aconf->name, CRULE_MASK)) {
236 con_class = ConClass(cltmp);
238 /* We connect only one at time... */
242 if ((next > aconf->hold) || (next == 0))
246 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;
254 if (connect_server(con_conf, 0, 0))
255 sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
259 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
264 /*----------------------------------------------------------------------------
267 * TODO: This should be moved out of ircd.c. It's protocol-specific when you
268 * get right down to it. Can't really be done until the server is more
269 * modular, however...
270 *--------------------------------------------------------------------------*/
271 static time_t check_pings(void) {
273 int next_check = CurrentTime + PINGFREQUENCY;
277 /* Scan through the client table */
278 for (i=0; i <= HighestFd; i++) {
279 struct Client *cptr = LocalClientArray[i];
284 assert(&me != cptr); /* I should never be in the local client array! */
287 /* Remove dead clients. */
289 exit_client(cptr, cptr, &me, cli_info(cptr));
293 max_ping = IsRegistered(cptr) ? client_get_ping(cptr) : CONNECTTIMEOUT;
295 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
296 cli_name(cptr), (cli_flags(cptr) & FLAGS_PINGSENT) ? "[Ping Sent]" : "[]",
297 max_ping, (int)(CurrentTime - cli_lasttime(cptr))));
300 /* Ok, the thing that will happen most frequently, is that someone will
301 * have sent something recently. Cover this first for speed.
303 if (CurrentTime-cli_lasttime(cptr) < max_ping) {
304 expire = cli_lasttime(cptr) + max_ping;
305 if (expire < next_check)
310 /* Quit the client after max_ping*2 - they should have answered by now */
311 if (CurrentTime-cli_lasttime(cptr) >= (max_ping*2) ) {
312 /* If it was a server, then tell ops about it. */
313 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
314 sendto_opmask_butone(0, SNO_OLDSNO,
315 "No response from %s, closing link", cli_name(cptr));
316 exit_client_msg(cptr, cptr, &me, "Ping timeout");
320 /* Unregistered clients pingout after max_ping seconds, they don't
321 * get given a second chance - if they were then people could not quite
322 * finish registration and hold resources without being subject to k/g
325 if (!IsRegistered(cptr)) {
326 /* Display message if they have sent a NICK and a USER but no
329 if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
330 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
331 ":Your client may not be compatible with this server.");
332 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
333 ":Compatible clients are available at "
334 "ftp://ftp.undernet.org/pub/irc/clients");
336 exit_client_msg(cptr,cptr,&me, "Ping Timeout");
340 if (!(cli_flags(cptr) & FLAGS_PINGSENT)) {
341 /* If we havent PINGed the connection and we havent heard from it in a
342 * while, PING it to make sure it is still alive.
344 cli_flags(cptr) |= FLAGS_PINGSENT;
346 /* If we're late in noticing don't hold it against them :) */
347 cli_lasttime(cptr) = CurrentTime - max_ping;
350 sendrawto_one(cptr, MSG_PING " :%s", cli_name(&me));
352 sendcmdto_one(&me, CMD_PING, cptr, ":%s", cli_name(&me));
355 expire = cli_lasttime(cptr) + max_ping * 2;
356 if (expire < next_check)
360 assert(next_check >= CurrentTime);
362 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
363 CurrentTime, next_check-CurrentTime));
369 /*----------------------------------------------------------------------------
371 * Side Effects: changes GLOBALS me, thisServer, dpath, configfile, debuglevel
373 *--------------------------------------------------------------------------*/
374 static void parse_command_line(int argc, char** argv) {
375 const char *options = "d:f:h:ntvx:";
378 if (thisServer.euid != thisServer.uid)
379 setuid(thisServer.uid);
381 /* Do we really need to santiy check the non-NULLness of optarg? That's
382 * getopt()'s job... Removing those... -zs
384 while ((opt = getopt(argc, argv, options)) != EOF)
387 case 't': thisServer.bootopt |= BOOT_TTY; break;
388 case 'd': dpath = optarg; break;
389 case 'f': configfile = optarg; break;
390 case 'h': ircd_strncpy(cli_name(&me), optarg, HOSTLEN); break;
391 case 'v': printf("ircd %s\n", version); exit(0);
394 debuglevel = atoi(optarg);
398 thisServer.bootopt |= BOOT_DEBUG;
402 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv]\n");
403 printf("\n -n -t\t Don't detach\n -v\t display version\n\n");
404 printf("Server not started.\n");
410 /*----------------------------------------------------------------------------
412 *--------------------------------------------------------------------------*/
413 static void daemon_init(int no_fork) {
414 if (!init_connection_limits())
417 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
428 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
429 ioctl(fd, TIOCNOTTY, 0);
439 /*----------------------------------------------------------------------------
441 *--------------------------------------------------------------------------*/
442 static void event_loop(void) {
443 time_t nextdnscheck = 0;
446 thisServer.running = 1;
447 while (thisServer.running) {
448 /* We only want to connect if a connection is due, not every time through.
449 * Note, if there are no active C lines, this call to Tryconnections is
450 * made once only; it will return 0. - avalon
452 if (nextconnect && CurrentTime >= nextconnect)
453 nextconnect = try_connections();
455 /* DNS checks. One to timeout queries, one for cache expiries. */
456 nextdnscheck = timeout_resolver(CurrentTime);
458 /* Take the smaller of the two 'timed' event times as the time of next
459 * event (stops us being late :) - avalon
460 * WARNING - nextconnect can return 0!
463 delay = IRCD_MIN(nextping, nextconnect);
467 delay = IRCD_MIN(nextdnscheck, delay) - CurrentTime;
469 /* Adjust delay to something reasonable [ad hoc values] (one might think
470 * something more clever here... --msa) We don't really need to check that
471 * often and as long as we don't delay too long, everything should be ok.
472 * waiting too long can cause things to timeout... i.e. PINGS -> a
473 * disconnection :( - avalon
478 read_message(IRCD_MIN(delay, TIMESEC));
480 /* ...perhaps should not do these loops every time, but only if there is
481 * some chance of something happening (but, note that conf->hold times may
482 * be changed elsewhere--so precomputed next event time might be too far
483 * away... (similarly with ping times) --msa
485 if (CurrentTime >= nextping)
486 nextping = check_pings();
488 /* timeout pending queries that haven't been responded to */
489 timeout_auth_queries(CurrentTime);
493 if (GlobalRehashFlag) {
495 GlobalRehashFlag = 0;
498 if (GlobalRestartFlag)
499 server_restart("caught signal: SIGINT");
503 /*----------------------------------------------------------------------------
504 * check_file_access: random helper function to make sure that a file is
505 * accessible in a certain way, and complain if not.
506 *--------------------------------------------------------------------------*/
507 static char check_file_access(const char *path, char which, int mode) {
508 if (!access(path, mode))
512 "Check on %cPATH (%s) failed: %s\n"
513 "Please create file and/or rerun `make config' and "
514 "recompile to correct this.\n",
515 which, path, strerror(errno));
518 fprintf(stderr, "Keep in mind that paths are relative to CHROOTDIR.\n");
525 /*----------------------------------------------------------------------------
527 *--------------------------------------------------------------------------*/
528 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
529 static void set_core_limit(void) {
530 struct rlimit corelim;
532 if (getrlimit(RLIMIT_CORE, &corelim)) {
533 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
534 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
537 corelim.rlim_cur = corelim.rlim_max;
538 if (setrlimit(RLIMIT_CORE, &corelim))
539 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
545 /*----------------------------------------------------------------------------
546 * set_chroot_environment
547 *--------------------------------------------------------------------------*/
549 static char set_chroot_environment(void) {
550 /* Must be root to chroot! Silly if you ask me... */
555 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", dpath, strerror(errno));
559 fprintf(stderr, "Fail: Cannot chroot(%s): %s\n", dpath, strerror(errno));
568 /*----------------------------------------------------------------------------
569 * set_userid_if_needed()
570 *--------------------------------------------------------------------------*/
571 static int set_userid_if_needed(void) {
572 /* TODO: Drop privs correctly! */
573 #if defined(IRC_GID) && defined(IRC_UID)
580 if (getuid() == 0 || geteuid() == 0 ||
581 getgid() == 0 || getegid() == 0) {
582 fprintf(stderr, "ERROR: This server will not run as superuser.\n");
590 /*----------------------------------------------------------------------------
593 * TODO: This should set the basic environment up and start the main loop.
594 * we're doing waaaaaaaaay too much server initialization here. I hate
595 * long and ugly control paths... -smd
596 *--------------------------------------------------------------------------*/
597 int main(int argc, char **argv) {
598 CurrentTime = time(NULL);
600 thisServer.argc = argc;
601 thisServer.argv = argv;
602 thisServer.uid = getuid();
603 thisServer.euid = geteuid();
606 if (!set_chroot_environment())
610 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
614 umask(077); /* better safe than sorry --SRB */
615 memset(&me, 0, sizeof(me));
616 memset(&me_con, 0, sizeof(me_con));
617 cli_connect(&me) = &me_con;
620 parse_command_line(argc, argv);
623 fprintf(stderr, "Fail: Cannot chdir(%s): %s, check DPATH\n", dpath, strerror(errno));
627 if (!set_userid_if_needed())
630 /* Check paths for accessibility */
631 if (!check_file_access(SPATH, 'S', X_OK) ||
632 !check_file_access(configfile, 'C', R_OK) ||
633 !check_file_access(MPATH, 'M', R_OK) ||
634 !check_file_access(RPATH, 'R', R_OK))
638 if (!check_file_access(LPATH, 'L', W_OK))
642 debug_init(thisServer.bootopt & BOOT_TTY);
643 daemon_init(thisServer.bootopt & BOOT_TTY);
648 set_nomem_handler(outofmemory);
650 if (!init_string()) {
651 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to initialize string module");
668 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to read configuration file %s",
673 init_server_identity();
677 CurrentTime = time(NULL);
683 cli_serv(&me)->timestamp = TStime(); /* Abuse own link timestamp as start TS */
684 cli_serv(&me)->prot = atoi(MAJOR_PROTOCOL);
685 cli_serv(&me)->up = &me;
686 cli_serv(&me)->down = NULL;
687 cli_handler(&me) = SERVER_HANDLER;
689 SetYXXCapacity(&me, MAXCLIENTS);
691 cli_lasttime(&me) = cli_since(&me) = cli_firsttime(&me) = CurrentTime;
698 Debug((DEBUG_NOTICE, "Server ready..."));
699 log_write(LS_SYSTEM, L_NOTICE, 0, "Server Ready");