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"
29 #include "ircd_features.h"
31 #include "ircd_reply.h"
32 #include "ircd_signal.h"
33 #include "ircd_string.h"
63 #include <sys/socket.h>
69 /*----------------------------------------------------------------------------
71 *--------------------------------------------------------------------------*/
72 extern void init_counters(void);
74 /*----------------------------------------------------------------------------
76 *--------------------------------------------------------------------------*/
83 /*----------------------------------------------------------------------------
85 *--------------------------------------------------------------------------*/
86 struct Client me; // That's me
87 struct Connection me_con; // That's me too
88 struct Client *GlobalClientList = &me; // Pointer to beginning of Client list
89 time_t TSoffset = 0; // Offset of timestamps to system clock
90 int GlobalRehashFlag = 0; // do a rehash if set
91 int GlobalRestartFlag = 0; // do a restart if set
92 time_t CurrentTime; // Updated every time we leave select()
94 char *configfile = CPATH; // Server configuration file
95 int debuglevel = -1; // Server debug level
96 char *debugmode = ""; // Server debug level
97 static char *dpath = DPATH;
99 time_t nextconnect = 1; // time for next try_connections call
100 time_t nextping = 1; // same as above for check_pings()
102 static struct Daemon thisServer = { 0 }; // server process info
106 /*----------------------------------------------------------------------------
108 *--------------------------------------------------------------------------*/
109 void server_die(const char* message) {
110 /* log_write will send out message to both log file and as server notice */
111 log_write(LS_SYSTEM, L_CRIT, 0, "Server terminating: %s", message);
112 flush_connections(0);
113 close_connections(1);
114 thisServer.running = 0;
118 /*----------------------------------------------------------------------------
119 * API: server_restart
120 *--------------------------------------------------------------------------*/
121 void server_restart(const char* message) {
122 static int restarting = 0;
124 /* inhibit sending any server notices; we may be in a loop */
125 log_write(LS_SYSTEM, L_WARNING, LOG_NOSNOTICE, "Restarting Server: %s",
127 if (restarting++) /* increment restarting to prevent looping */
130 sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
131 Debug((DEBUG_NOTICE, "Restarting server..."));
132 flush_connections(0);
136 close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG)));
138 execv(SPATH, thisServer.argv);
140 /* Have to reopen since it has been closed above */
143 log_write(LS_SYSTEM, L_CRIT, 0, "execv(%s,%s) failed: %m", SPATH,
146 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
147 SPATH, (strerror(errno)) ? strerror(errno) : ""));
152 /*----------------------------------------------------------------------------
153 * outofmemory: Handler for out of memory conditions...
154 *--------------------------------------------------------------------------*/
155 static void outofmemory(void) {
156 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
157 server_restart("Out of Memory");
161 /*----------------------------------------------------------------------------
163 *--------------------------------------------------------------------------*/
164 static void write_pidfile(void) {
167 if (!(pidf = fopen(feature_str(FEAT_PPATH), "w+"))) {
169 "Error opening pid file \"%s\": %s", feature_str(FEAT_PPATH),
174 if (fprintf(pidf, "%5d\n", getpid()) < 5)
175 Debug((DEBUG_NOTICE, "Error writing to pid file %s",
176 feature_str(FEAT_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 ConnectionClass* cltmp;
199 struct ConfItem* con_conf = 0;
201 unsigned int con_class = 0;
204 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
205 for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
206 /* Also when already connecting! (update holdtimes) --SRB */
207 if (!(aconf->status & CONF_SERVER) || aconf->port == 0)
210 /* Also skip juped servers */
211 if ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe))
214 /* Skip this entry if the use of it is still on hold until
215 * future. Otherwise handle this entry (and set it on hold until next
216 * time). Will reset only hold times, if already made one successfull
217 * connection... [this algorithm is a bit fuzzy... -- msa >;) ]
219 if (aconf->hold > CurrentTime && (next > aconf->hold || next == 0)) {
224 cltmp = aconf->conn_class;
225 confrq = get_con_freq(cltmp);
226 aconf->hold = CurrentTime + confrq;
228 /* Found a CONNECT config with port specified, scan clients and see if
229 * this server is already connected?
231 cptr = FindServer(aconf->name);
233 if (!cptr && (Links(cltmp) < MaxLinks(cltmp)) &&
234 (!connecting || (ConClass(cltmp) > con_class))) {
236 * Check connect rules to see if we're allowed to try
238 if (0 == conf_eval_crule(aconf->name, CRULE_MASK)) {
239 con_class = ConClass(cltmp);
241 /* We connect only one at time... */
245 if ((next > aconf->hold) || (next == 0))
249 if (con_conf->next) { /* are we already last? */
250 /* Put the current one at the end and make sure we try all connections */
251 for (pconf = &GlobalConfList; (aconf = *pconf); pconf = &(aconf->next))
252 if (aconf == con_conf)
253 *pconf = aconf->next;
254 (*pconf = con_conf)->next = 0;
257 if (connect_server(con_conf, 0, 0))
258 sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
262 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
267 /*----------------------------------------------------------------------------
270 * TODO: This should be moved out of ircd.c. It's protocol-specific when you
271 * get right down to it. Can't really be done until the server is more
272 * modular, however...
273 *--------------------------------------------------------------------------*/
274 static time_t check_pings(void) {
276 int next_check = CurrentTime + PINGFREQUENCY;
280 /* Scan through the client table */
281 for (i=0; i <= HighestFd; i++) {
282 struct Client *cptr = LocalClientArray[i];
287 assert(&me != cptr); /* I should never be in the local client array! */
290 /* Remove dead clients. */
292 exit_client(cptr, cptr, &me, cli_info(cptr));
296 max_ping = IsRegistered(cptr) ? client_get_ping(cptr) : CONNECTTIMEOUT;
298 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
299 cli_name(cptr), (cli_flags(cptr) & FLAGS_PINGSENT) ? "[Ping Sent]" : "[]",
300 max_ping, (int)(CurrentTime - cli_lasttime(cptr))));
303 /* Ok, the thing that will happen most frequently, is that someone will
304 * have sent something recently. Cover this first for speed.
306 if (CurrentTime-cli_lasttime(cptr) < max_ping) {
307 expire = cli_lasttime(cptr) + max_ping;
308 if (expire < next_check)
313 /* Quit the client after max_ping*2 - they should have answered by now */
314 if (CurrentTime-cli_lasttime(cptr) >= (max_ping*2) ) {
315 /* If it was a server, then tell ops about it. */
316 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
317 sendto_opmask_butone(0, SNO_OLDSNO,
318 "No response from %s, closing link", cli_name(cptr));
319 exit_client_msg(cptr, cptr, &me, "Ping timeout");
323 /* Unregistered clients pingout after max_ping seconds, they don't
324 * get given a second chance - if they were then people could not quite
325 * finish registration and hold resources without being subject to k/g
328 if (!IsRegistered(cptr)) {
329 /* Display message if they have sent a NICK and a USER but no
332 if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
333 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
334 ":Your client may not be compatible with this server.");
335 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
336 ":Compatible clients are available at "
337 "ftp://ftp.undernet.org/pub/irc/clients");
339 exit_client_msg(cptr,cptr,&me, "Ping Timeout");
343 if (!(cli_flags(cptr) & FLAGS_PINGSENT)) {
344 /* If we havent PINGed the connection and we havent heard from it in a
345 * while, PING it to make sure it is still alive.
347 cli_flags(cptr) |= FLAGS_PINGSENT;
349 /* If we're late in noticing don't hold it against them :) */
350 cli_lasttime(cptr) = CurrentTime - max_ping;
353 sendrawto_one(cptr, MSG_PING " :%s", cli_name(&me));
355 sendcmdto_one(&me, CMD_PING, cptr, ":%s", cli_name(&me));
358 expire = cli_lasttime(cptr) + max_ping * 2;
359 if (expire < next_check)
363 assert(next_check >= CurrentTime);
365 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
366 CurrentTime, next_check-CurrentTime));
372 /*----------------------------------------------------------------------------
374 * Side Effects: changes GLOBALS me, thisServer, dpath, configfile, debuglevel
376 *--------------------------------------------------------------------------*/
377 static void parse_command_line(int argc, char** argv) {
378 const char *options = "d:f:h:ntvx:";
381 if (thisServer.euid != thisServer.uid)
382 setuid(thisServer.uid);
384 /* Do we really need to santiy check the non-NULLness of optarg? That's
385 * getopt()'s job... Removing those... -zs
387 while ((opt = getopt(argc, argv, options)) != EOF)
390 case 't': thisServer.bootopt |= BOOT_TTY; break;
391 case 'd': dpath = optarg; break;
392 case 'f': configfile = optarg; break;
393 case 'h': ircd_strncpy(cli_name(&me), optarg, HOSTLEN); break;
394 case 'v': printf("ircd %s\n", version); exit(0);
397 debuglevel = atoi(optarg);
401 thisServer.bootopt |= BOOT_DEBUG;
405 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv]\n");
406 printf("\n -n -t\t Don't detach\n -v\t display version\n\n");
407 printf("Server not started.\n");
413 /*----------------------------------------------------------------------------
415 *--------------------------------------------------------------------------*/
416 static void daemon_init(int no_fork) {
417 if (!init_connection_limits())
420 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY)));
431 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
432 ioctl(fd, TIOCNOTTY, 0);
442 /*----------------------------------------------------------------------------
444 *--------------------------------------------------------------------------*/
445 static void event_loop(void) {
446 time_t nextdnscheck = 0;
449 thisServer.running = 1;
450 while (thisServer.running) {
451 /* We only want to connect if a connection is due, not every time through.
452 * Note, if there are no active C lines, this call to Tryconnections is
453 * made once only; it will return 0. - avalon
455 if (nextconnect && CurrentTime >= nextconnect)
456 nextconnect = try_connections();
458 /* DNS checks. One to timeout queries, one for cache expiries. */
459 nextdnscheck = timeout_resolver(CurrentTime);
461 /* Take the smaller of the two 'timed' event times as the time of next
462 * event (stops us being late :) - avalon
463 * WARNING - nextconnect can return 0!
466 delay = IRCD_MIN(nextping, nextconnect);
470 delay = IRCD_MIN(nextdnscheck, delay) - CurrentTime;
472 /* Adjust delay to something reasonable [ad hoc values] (one might think
473 * something more clever here... --msa) We don't really need to check that
474 * often and as long as we don't delay too long, everything should be ok.
475 * waiting too long can cause things to timeout... i.e. PINGS -> a
476 * disconnection :( - avalon
481 read_message(IRCD_MIN(delay, TIMESEC));
483 /* ...perhaps should not do these loops every time, but only if there is
484 * some chance of something happening (but, note that conf->hold times may
485 * be changed elsewhere--so precomputed next event time might be too far
486 * away... (similarly with ping times) --msa
488 if (CurrentTime >= nextping)
489 nextping = check_pings();
491 /* timeout pending queries that haven't been responded to */
492 timeout_auth_queries(CurrentTime);
496 if (GlobalRehashFlag) {
498 GlobalRehashFlag = 0;
501 if (GlobalRestartFlag)
502 server_restart("caught signal: SIGINT");
506 /*----------------------------------------------------------------------------
507 * check_file_access: random helper function to make sure that a file is
508 * accessible in a certain way, and complain if not.
509 *--------------------------------------------------------------------------*/
510 static char check_file_access(const char *path, char which, int mode) {
511 if (!access(path, mode))
515 "Check on %cPATH (%s) failed: %s\n"
516 "Please create file and/or rerun `make config' and "
517 "recompile to correct this.\n",
518 which, path, strerror(errno));
521 fprintf(stderr, "Keep in mind that paths are relative to CHROOTDIR.\n");
528 /*----------------------------------------------------------------------------
530 *--------------------------------------------------------------------------*/
531 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
532 static void set_core_limit(void) {
533 struct rlimit corelim;
535 if (getrlimit(RLIMIT_CORE, &corelim)) {
536 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
537 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
540 corelim.rlim_cur = corelim.rlim_max;
541 if (setrlimit(RLIMIT_CORE, &corelim))
542 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
548 /*----------------------------------------------------------------------------
549 * set_chroot_environment
550 *--------------------------------------------------------------------------*/
552 static char set_chroot_environment(void) {
553 /* Must be root to chroot! Silly if you ask me... */
558 fprintf(stderr, "Fail: Cannot chdir(%s): %s\n", dpath, strerror(errno));
562 fprintf(stderr, "Fail: Cannot chroot(%s): %s\n", dpath, strerror(errno));
571 /*----------------------------------------------------------------------------
572 * set_userid_if_needed()
573 *--------------------------------------------------------------------------*/
574 static int set_userid_if_needed(void) {
575 /* TODO: Drop privs correctly! */
576 #if defined(IRC_GID) && defined(IRC_UID)
583 if (getuid() == 0 || geteuid() == 0 ||
584 getgid() == 0 || getegid() == 0) {
585 fprintf(stderr, "ERROR: This server will not run as superuser.\n");
593 /*----------------------------------------------------------------------------
596 * TODO: This should set the basic environment up and start the main loop.
597 * we're doing waaaaaaaaay too much server initialization here. I hate
598 * long and ugly control paths... -smd
599 *--------------------------------------------------------------------------*/
600 int main(int argc, char **argv) {
601 CurrentTime = time(NULL);
603 thisServer.argc = argc;
604 thisServer.argv = argv;
605 thisServer.uid = getuid();
606 thisServer.euid = geteuid();
609 if (!set_chroot_environment())
613 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
617 umask(077); /* better safe than sorry --SRB */
618 memset(&me, 0, sizeof(me));
619 memset(&me_con, 0, sizeof(me_con));
620 cli_connect(&me) = &me_con;
623 parse_command_line(argc, argv);
626 fprintf(stderr, "Fail: Cannot chdir(%s): %s, check DPATH\n", dpath, strerror(errno));
630 if (!set_userid_if_needed())
633 /* Check paths for accessibility */
634 if (!check_file_access(SPATH, 'S', X_OK) ||
635 !check_file_access(configfile, 'C', R_OK))
639 if (!check_file_access(LPATH, 'L', W_OK))
643 debug_init(thisServer.bootopt & BOOT_TTY);
644 daemon_init(thisServer.bootopt & BOOT_TTY);
647 feature_mark(); /* initialize features... */
650 set_nomem_handler(outofmemory);
652 if (!init_string()) {
653 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to initialize string module");
670 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to read configuration file %s",
675 init_server_identity();
679 CurrentTime = time(NULL);
685 cli_serv(&me)->timestamp = TStime(); /* Abuse own link timestamp as start TS */
686 cli_serv(&me)->prot = atoi(MAJOR_PROTOCOL);
687 cli_serv(&me)->up = &me;
688 cli_serv(&me)->down = NULL;
689 cli_handler(&me) = SERVER_HANDLER;
691 SetYXXCapacity(&me, MAXCLIENTS);
693 cli_lasttime(&me) = cli_since(&me) = cli_firsttime(&me) = CurrentTime;
700 Debug((DEBUG_NOTICE, "Server ready..."));
701 log_write(LS_SYSTEM, L_NOTICE, 0, "Server Ready");