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.
21 * @brief Entry point and other initialization functions for the daemon.
31 #include "destruct_event.h"
33 #include "ircd_alloc.h"
34 #include "ircd_events.h"
35 #include "ircd_features.h"
37 #include "ircd_reply.h"
38 #include "ircd_signal.h"
39 #include "ircd_string.h"
40 #include "ircd_crypt.h"
64 /* #include <assert.h> -- Now using assert in ircd_log.h */
72 #include <sys/socket.h>
74 #include <sys/types.h>
79 /*----------------------------------------------------------------------------
81 *--------------------------------------------------------------------------*/
82 extern void init_counters(void);
83 extern void mem_dbg_initialise(void);
85 /*----------------------------------------------------------------------------
87 *--------------------------------------------------------------------------*/
89 BOOT_DEBUG = 1, /**< Enable debug output. */
90 BOOT_TTY = 2, /**< Stay connected to TTY. */
91 BOOT_CHKCONF = 4 /**< Exit after reading configuration file. */
95 /*----------------------------------------------------------------------------
97 *--------------------------------------------------------------------------*/
98 struct Client me; /**< That's me */
99 struct Connection me_con; /**< That's me too */
100 struct Client *GlobalClientList = &me; /**< Pointer to beginning of
102 time_t TSoffset = 0; /**< Offset of timestamps to system clock */
103 int GlobalRehashFlag = 0; /**< do a rehash if set */
104 int GlobalRestartFlag = 0; /**< do a restart if set */
105 time_t CurrentTime; /**< Updated every time we leave select() */
107 char *configfile = CPATH; /**< Server configuration file */
108 int debuglevel = -1; /**< Server debug level */
109 char *debugmode = ""; /**< Server debug level */
110 static char *dpath = DPATH; /**< Working directory for daemon */
112 static struct Timer connect_timer; /**< timer structure for try_connections() */
113 static struct Timer ping_timer; /**< timer structure for check_pings() */
114 static struct Timer destruct_event_timer; /**< timer structure for exec_expired_destruct_events() */
116 /** Daemon information. */
117 static struct Daemon thisServer = { 0, 0, 0, 0, 0, 0, -1 };
119 /** Non-zero until we want to exit. */
123 /*----------------------------------------------------------------------------
125 *--------------------------------------------------------------------------*/
126 /** Terminate the server with a message.
127 * @param[in] message Message to log and send to operators.
129 void server_die(const char *message)
131 /* log_write will send out message to both log file and as server notice */
132 log_write(LS_SYSTEM, L_CRIT, 0, "Server terminating: %s", message);
133 flush_connections(0);
134 close_connections(1);
138 /*----------------------------------------------------------------------------
140 *--------------------------------------------------------------------------*/
141 /** Immediately terminate the server with a message.
142 * @param[in] message Message to log, but not send to operators.
144 void server_panic(const char *message)
146 /* inhibit sending server notice--we may be panicing due to low memory */
147 log_write(LS_SYSTEM, L_CRIT, LOG_NOSNOTICE, "Server panic: %s", message);
148 flush_connections(0);
150 close_connections(1);
154 /*----------------------------------------------------------------------------
155 * API: server_restart
156 *--------------------------------------------------------------------------*/
157 /** Restart the server with a message.
158 * @param[in] message Message to log and send to operators.
160 void server_restart(const char *message)
162 static int restarting = 0;
164 /* inhibit sending any server notices; we may be in a loop */
165 log_write(LS_SYSTEM, L_WARNING, LOG_NOSNOTICE, "Restarting Server: %s",
167 if (restarting++) /* increment restarting to prevent looping */
170 sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
171 Debug((DEBUG_NOTICE, "Restarting server..."));
172 flush_connections(0);
176 close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG | BOOT_CHKCONF)));
178 execv(SPATH, thisServer.argv);
180 /* Have to reopen since it has been closed above */
183 log_write(LS_SYSTEM, L_CRIT, 0, "execv(%s,%s) failed: %m", SPATH,
186 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
187 SPATH, (strerror(errno)) ? strerror(errno) : ""));
192 /*----------------------------------------------------------------------------
193 * outofmemory: Handler for out of memory conditions...
194 *--------------------------------------------------------------------------*/
195 /** Handle out-of-memory condition. */
196 static void outofmemory(void) {
197 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
198 server_restart("Out of Memory");
202 /*----------------------------------------------------------------------------
204 *--------------------------------------------------------------------------*/
205 /** Write process ID to PID file. */
206 static void write_pidfile(void) {
209 if (thisServer.pid_fd >= 0) {
210 memset(buff, 0, sizeof(buff));
211 sprintf(buff, "%5d\n", (int)getpid());
212 if (write(thisServer.pid_fd, buff, strlen(buff)) == -1)
213 Debug((DEBUG_NOTICE, "Error writing to pid file %s: %m",
214 feature_str(FEAT_PPATH)));
217 Debug((DEBUG_NOTICE, "Error opening pid file %s: %m",
218 feature_str(FEAT_PPATH)));
221 /** Try to create the PID file.
222 * @return Zero on success; non-zero on any error.
224 static int check_pid(void)
228 lock.l_type = F_WRLCK;
230 lock.l_whence = SEEK_SET;
233 if ((thisServer.pid_fd = open(feature_str(FEAT_PPATH), O_CREAT | O_RDWR,
235 return fcntl(thisServer.pid_fd, F_SETLK, &lock) == -1;
241 /** Look for any connections that we should try to initiate.
242 * Reschedules itself to run again at the appropriate time.
243 * @param[in] ev Timer event (ignored).
245 static void try_connections(struct Event* ev) {
246 struct ConfItem* aconf;
247 struct ConfItem** pconf;
249 struct ConnectionClass* cltmp;
252 assert(ET_EXPIRE == ev_type(ev));
253 assert(0 != ev_timer(ev));
255 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
256 for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
257 /* Only consider server items with non-zero port and non-zero
258 * connect times that are not actively juped.
260 if (!(aconf->status & CONF_SERVER)
261 || aconf->address.port == 0
263 || ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe)))
266 /* Update next possible connection check time. */
267 if (next > aconf->hold || next == 0)
270 /* Skip this entry if its use is still on hold until future, too
271 * many links in its connection class, it is already linked, or if
272 * connect rules forbid a link now.
274 cltmp = aconf->conn_class;
275 if ((aconf->hold > CurrentTime)
276 || (Links(cltmp) >= MaxLinks(cltmp))
277 || FindServer(aconf->name)
278 || conf_eval_crule(aconf->name, CRULE_MASK))
281 /* We want to connect; update entry's hold time. */
282 aconf->hold = ConFreq(cltmp) ? CurrentTime + ConFreq(cltmp) : 0;
284 /* Ensure it is at the end of the list for future checks. */
286 /* Find aconf's location in the list and splice it out. */
287 for (pconf = &GlobalConfList; *pconf; pconf = &(*pconf)->next)
289 *pconf = aconf->next;
290 /* Reinsert it at the end of the list (where pconf is now). */
295 /* Activate the connection itself. */
296 if (connect_server(aconf, 0))
297 sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
300 /* And stop looking for further candidates. */
305 next = CurrentTime + feature_int(FEAT_CONNECTFREQUENCY);
307 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
309 timer_add(&connect_timer, try_connections, 0, TT_ABSOLUTE, next);
313 /** Check for clients that have not sent a ping response recently.
314 * Reschedules itself to run again at the appropriate time.
315 * @param[in] ev Timer event (ignored).
317 static void check_pings(struct Event* ev) {
319 int next_check = CurrentTime;
323 assert(ET_EXPIRE == ev_type(ev));
324 assert(0 != ev_timer(ev));
326 next_check += feature_int(FEAT_PINGFREQUENCY);
328 /* Scan through the client table */
329 for (i=0; i <= HighestFd; i++) {
330 struct Client *cptr = LocalClientArray[i];
335 assert(&me != cptr); /* I should never be in the local client array! */
338 /* Remove dead clients. */
340 exit_client(cptr, cptr, &me, cli_info(cptr));
344 max_ping = IsRegistered(cptr) ? client_get_ping(cptr) :
345 feature_int(FEAT_CONNECTTIMEOUT);
347 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
349 IsPingSent(cptr) ? "[Ping Sent]" : "[]",
350 max_ping, (int)(CurrentTime - cli_lasttime(cptr))));
352 /* Ok, the thing that will happen most frequently, is that someone will
353 * have sent something recently. Cover this first for speed.
355 * If it's an unregisterd client and hasn't managed to register within
356 * max_ping then it's obviously having problems (broken client) or it's
357 * just up to no good, so we won't skip it, even if its been sending
361 if ((CurrentTime-cli_lasttime(cptr) < max_ping) && IsRegistered(cptr)) {
362 expire = cli_lasttime(cptr) + max_ping;
363 if (expire < next_check)
368 /* Unregistered clients pingout after max_ping seconds, they don't
369 * get given a second chance - if they were then people could not quite
370 * finish registration and hold resources without being subject to k/g
373 if (!IsRegistered(cptr)) {
374 assert(!IsServer(cptr));
375 if ((CurrentTime-cli_firsttime(cptr) >= max_ping)) {
376 /* Display message if they have sent a NICK and a USER but no
379 if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
380 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
381 ":Your client may not be compatible with this server.");
382 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
383 ":Compatible clients are available at %s",
384 feature_str(FEAT_URL_CLIENTS));
386 exit_client_msg(cptr,cptr,&me, "Registration Timeout");
389 /* OK, they still have enough time left, so we'll just skip to the
390 * next client. Set the next check to be when their time is up, if
391 * that's before the currently scheduled next check -- hikari */
392 expire = cli_firsttime(cptr) + max_ping;
393 if (expire < next_check)
399 /* Quit the client after max_ping*2 - they should have answered by now */
400 if (CurrentTime-cli_lasttime(cptr) >= (max_ping*2) )
402 /* If it was a server, then tell ops about it. */
403 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
404 sendto_opmask_butone(0, SNO_OLDSNO,
405 "No response from %s, closing link",
407 exit_client_msg(cptr, cptr, &me, "Ping timeout");
411 if (!IsPingSent(cptr))
413 /* If we havent PINGed the connection and we havent heard from it in a
414 * while, PING it to make sure it is still alive.
418 /* If we're late in noticing don't hold it against them :) */
419 cli_lasttime(cptr) = CurrentTime - max_ping;
422 sendrawto_one(cptr, MSG_PING " :%s", cli_name(&me));
425 char *asll_ts = militime_float(NULL);
426 sendcmdto_one(&me, CMD_PING, cptr, "!%s %s %s", asll_ts,
427 cli_name(cptr), asll_ts);
431 expire = cli_lasttime(cptr) + max_ping * 2;
432 if (expire < next_check)
436 assert(next_check >= CurrentTime);
438 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
439 CurrentTime, next_check-CurrentTime));
441 timer_add(&ping_timer, check_pings, 0, TT_ABSOLUTE, next_check);
445 /** Parse command line arguments.
446 * Global variables are updated to reflect the arguments.
447 * As a side effect, makes sure the process's effective user id is the
448 * same as the real user id.
449 * @param[in] argc Number of arguments on command line.
450 * @param[in,out] argv Command-lne arguments.
452 static void parse_command_line(int argc, char** argv) {
453 const char *options = "d:f:h:nktvx:";
456 if (thisServer.euid != thisServer.uid)
457 setuid(thisServer.uid);
459 /* Do we really need to santiy check the non-NULLness of optarg? That's
460 * getopt()'s job... Removing those... -zs
462 while ((opt = getopt(argc, argv, options)) != EOF)
464 case 'k': thisServer.bootopt |= BOOT_CHKCONF; break;
466 case 't': thisServer.bootopt |= BOOT_TTY; break;
467 case 'd': dpath = optarg; break;
468 case 'f': configfile = optarg; break;
469 case 'h': ircd_strncpy(cli_name(&me), optarg, HOSTLEN); break;
471 printf("ircd %s\n", version);
472 printf("Event engines: ");
477 printf("/dev/poll ");
484 printf("\nCompiled for a maximum of %d connections.\n", MAXCONNECTIONS);
491 debuglevel = atoi(optarg);
495 thisServer.bootopt |= BOOT_DEBUG;
499 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntvk]\n");
500 printf("\n -n -t\t Don't detach\n -v\t display version\n -k\t exit after checking config\n\n");
501 printf("Server not started.\n");
508 * @param[in] no_fork If non-zero, do not fork into the background.
510 static void daemon_init(int no_fork) {
520 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
521 ioctl(fd, TIOCNOTTY, 0);
530 /** Check that we have access to a particular file.
531 * If we do not have access to the file, complain on stderr.
532 * @param[in] path File name to check for access.
533 * @param[in] which Configuration character associated with file.
534 * @param[in] mode Bitwise combination of R_OK, W_OK, X_OK and/or F_OK.
535 * @return Non-zero if we have the necessary access, zero if not.
537 static char check_file_access(const char *path, char which, int mode) {
538 if (!access(path, mode))
542 "Check on %cPATH (%s) failed: %s\n"
543 "Please create this file and/or rerun `configure' "
544 "using --with-%cpath and recompile to correct this.\n",
545 which, path, strerror(errno), which);
551 /*----------------------------------------------------------------------------
553 *--------------------------------------------------------------------------*/
554 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
555 /** Set the core size soft limit to the same as the hard limit. */
556 static void set_core_limit(void) {
557 struct rlimit corelim;
559 if (getrlimit(RLIMIT_CORE, &corelim)) {
560 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
561 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
564 corelim.rlim_cur = corelim.rlim_max;
565 if (setrlimit(RLIMIT_CORE, &corelim))
566 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
572 /** Complain to stderr if any user or group ID belongs to the superuser.
573 * @return Non-zero if all IDs are okay, zero if some are 0.
575 static int set_userid_if_needed(void) {
576 if (getuid() == 0 || geteuid() == 0 ||
577 getgid() == 0 || getegid() == 0) {
578 fprintf(stderr, "ERROR: This server will not run as superuser.\n");
586 /*----------------------------------------------------------------------------
589 * TODO: This should set the basic environment up and start the main loop.
590 * we're doing waaaaaaaaay too much server initialization here. I hate
591 * long and ugly control paths... -smd
592 *--------------------------------------------------------------------------*/
594 * @param[in] argc Number of arguments in \a argv.
595 * @param[in] argv Arguments to program execution.
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 mem_dbg_initialise();
609 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
613 umask(077); /* better safe than sorry --SRB */
614 memset(&me, 0, sizeof(me));
615 memset(&me_con, 0, sizeof(me_con));
616 cli_connect(&me) = &me_con;
619 parse_command_line(argc, argv);
622 fprintf(stderr, "Fail: Cannot chdir(%s): %s, check DPATH\n", dpath, strerror(errno));
626 if (!set_userid_if_needed())
629 /* Check paths for accessibility */
630 if (!check_file_access(SPATH, 'S', X_OK) ||
631 !check_file_access(configfile, 'C', R_OK))
634 if (!init_connection_limits())
637 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY | BOOT_CHKCONF)));
639 event_init(MAXCONNECTIONS);
642 feature_init(); /* initialize features... */
644 set_nomem_handler(outofmemory);
646 if (!init_string()) {
647 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to initialize string module");
659 /* we need this for now, when we're modular this
660 should be removed -- hikari */
666 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to read configuration file %s",
671 if (thisServer.bootopt & BOOT_CHKCONF) {
672 fprintf(stderr, "Configuration file %s checked okay.\n", configfile);
676 debug_init(thisServer.bootopt & BOOT_TTY);
677 daemon_init(thisServer.bootopt & BOOT_TTY);
679 Debug((DEBUG_FATAL, "Failed to acquire PID file lock after fork"));
683 init_server_identity();
690 timer_add(timer_init(&connect_timer), try_connections, 0, TT_RELATIVE, 1);
691 timer_add(timer_init(&ping_timer), check_pings, 0, TT_RELATIVE, 1);
692 timer_add(timer_init(&destruct_event_timer), exec_expired_destruct_events, 0, TT_PERIODIC, 60);
694 CurrentTime = time(NULL);
697 cli_magic(&me) = CLIENT_MAGIC;
701 cli_serv(&me)->timestamp = TStime(); /* Abuse own link timestamp as start TS */
702 cli_serv(&me)->prot = atoi(MAJOR_PROTOCOL);
703 cli_serv(&me)->up = &me;
704 cli_serv(&me)->down = NULL;
705 cli_handler(&me) = SERVER_HANDLER;
707 SetYXXCapacity(&me, MAXCLIENTS);
709 cli_lasttime(&me) = cli_since(&me) = cli_firsttime(&me) = CurrentTime;
716 Debug((DEBUG_NOTICE, "Server ready..."));
717 log_write(LS_SYSTEM, L_NOTICE, 0, "Server Ready");