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 */
73 #ifdef HAVE_SYS_RESOURCE_H
74 #include <sys/resource.h>
76 #include <sys/socket.h>
78 #include <sys/types.h>
83 /*----------------------------------------------------------------------------
85 *--------------------------------------------------------------------------*/
86 extern void init_counters(void);
87 extern void mem_dbg_initialise(void);
89 /*----------------------------------------------------------------------------
91 *--------------------------------------------------------------------------*/
93 BOOT_DEBUG = 1, /**< Enable debug output. */
94 BOOT_TTY = 2, /**< Stay connected to TTY. */
95 BOOT_CHKCONF = 4 /**< Exit after reading configuration file. */
99 /*----------------------------------------------------------------------------
100 * Global data (YUCK!)
101 *--------------------------------------------------------------------------*/
102 struct Client me; /**< That's me */
103 struct Connection me_con; /**< That's me too */
104 struct Client *GlobalClientList = &me; /**< Pointer to beginning of
106 time_t TSoffset = 0; /**< Offset of timestamps to system clock */
107 int GlobalRehashFlag = 0; /**< do a rehash if set */
108 int GlobalRestartFlag = 0; /**< do a restart if set */
109 time_t CurrentTime; /**< Updated every time we leave select() */
111 char *configfile = CPATH; /**< Server configuration file */
112 int debuglevel = -1; /**< Server debug level */
113 char *debugmode = ""; /**< Server debug level */
114 static char *dpath = DPATH; /**< Working directory for daemon */
115 static char *dbg_client; /**< Client specifier for chkconf */
117 static struct Timer connect_timer; /**< timer structure for try_connections() */
118 static struct Timer ping_timer; /**< timer structure for check_pings() */
119 static struct Timer destruct_event_timer; /**< timer structure for exec_expired_destruct_events() */
121 /** Daemon information. */
122 static struct Daemon thisServer = { 0, 0, 0, 0, 0, 0, -1 };
124 /** Non-zero until we want to exit. */
128 /*----------------------------------------------------------------------------
130 *--------------------------------------------------------------------------*/
131 /** Terminate the server with a message.
132 * @param[in] message Message to log and send to operators.
134 void server_die(const char *message)
136 /* log_write will send out message to both log file and as server notice */
137 log_write(LS_SYSTEM, L_CRIT, 0, "Server terminating: %s", message);
138 flush_connections(0);
139 close_connections(1);
143 /*----------------------------------------------------------------------------
145 *--------------------------------------------------------------------------*/
146 /** Immediately terminate the server with a message.
147 * @param[in] message Message to log, but not send to operators.
149 void server_panic(const char *message)
151 /* inhibit sending server notice--we may be panicking due to low memory */
152 log_write(LS_SYSTEM, L_CRIT, LOG_NOSNOTICE, "Server panic: %s", message);
153 flush_connections(0);
155 close_connections(1);
159 /*----------------------------------------------------------------------------
160 * API: server_restart
161 *--------------------------------------------------------------------------*/
162 /** Restart the server with a message.
163 * @param[in] message Message to log and send to operators.
165 void server_restart(const char *message)
167 static int restarting = 0;
169 /* inhibit sending any server notices; we may be in a loop */
170 log_write(LS_SYSTEM, L_WARNING, LOG_NOSNOTICE, "Restarting Server: %s",
172 if (restarting++) /* increment restarting to prevent looping */
175 sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
176 Debug((DEBUG_NOTICE, "Restarting server..."));
177 flush_connections(0);
181 close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG | BOOT_CHKCONF)));
185 execv(SPATH, thisServer.argv);
187 /* Have to reopen since it has been closed above */
190 log_write(LS_SYSTEM, L_CRIT, 0, "execv(%s,%s) failed: %m", SPATH,
193 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
194 SPATH, (strerror(errno)) ? strerror(errno) : ""));
199 /*----------------------------------------------------------------------------
200 * outofmemory: Handler for out of memory conditions...
201 *--------------------------------------------------------------------------*/
202 /** Handle out-of-memory condition. */
203 static void outofmemory(void) {
204 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
205 server_restart("Out of Memory");
209 /*----------------------------------------------------------------------------
211 *--------------------------------------------------------------------------*/
212 /** Write process ID to PID file. */
213 static void write_pidfile(void) {
216 if (thisServer.pid_fd >= 0) {
217 memset(buff, 0, sizeof(buff));
218 sprintf(buff, "%5d\n", (int)getpid());
219 if (write(thisServer.pid_fd, buff, strlen(buff)) == -1)
220 Debug((DEBUG_NOTICE, "Error writing to pid file %s: %m",
221 feature_str(FEAT_PPATH)));
224 Debug((DEBUG_NOTICE, "Error opening pid file %s: %m",
225 feature_str(FEAT_PPATH)));
228 /** Try to create the PID file.
229 * @return Zero on success; non-zero on any error.
231 static int check_pid(void)
235 lock.l_type = F_WRLCK;
237 lock.l_whence = SEEK_SET;
240 if ((thisServer.pid_fd = open(feature_str(FEAT_PPATH), O_CREAT | O_RDWR,
242 return fcntl(thisServer.pid_fd, F_SETLK, &lock) == -1;
248 /** Look for any connections that we should try to initiate.
249 * Reschedules itself to run again at the appropriate time.
250 * @param[in] ev Timer event (ignored).
252 static void try_connections(struct Event* ev) {
253 struct ConfItem* aconf;
254 struct ConfItem** pconf;
260 assert(ET_EXPIRE == ev_type(ev));
261 assert(0 != ev_timer(ev));
263 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
264 next = CurrentTime + feature_int(FEAT_CONNECTFREQUENCY);
267 for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
268 /* Only consider server items with non-zero port and non-zero
269 * connect times that are not actively juped.
271 if (!(aconf->status & CONF_SERVER)
272 || aconf->address.port == 0
273 || !(aconf->flags & CONF_AUTOCONNECT)
274 || ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe)))
277 /* Do we need to postpone this connection further? */
278 hold = aconf->hold > CurrentTime;
280 /* Update next possible connection check time. */
281 if (hold && next > aconf->hold)
284 /* Do not try to connect if its use is still on hold until future,
285 * we have already initiated a connection this try_connections(),
286 * too many links in its connection class, it is already linked,
287 * or if connect rules forbid a link now.
290 || (ConfLinks(aconf) > ConfMaxLinks(aconf))
291 || FindServer(aconf->name)
292 || conf_eval_crule(aconf->name, CRULE_MASK))
295 /* Ensure it is at the end of the list for future checks. */
297 /* Find aconf's location in the list and splice it out. */
298 for (pconf = &GlobalConfList; *pconf; pconf = &(*pconf)->next)
300 *pconf = aconf->next;
301 /* Reinsert it at the end of the list (where pconf is now). */
306 /* Activate the connection itself. */
307 if (connect_server(aconf, 0))
308 sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
311 /* And stop looking for further candidates. */
315 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
316 timer_add(&connect_timer, try_connections, 0, TT_ABSOLUTE, next);
320 /** Check for clients that have not sent a ping response recently.
321 * Reschedules itself to run again at the appropriate time.
322 * @param[in] ev Timer event (ignored).
324 static void check_pings(struct Event* ev) {
326 int next_check = CurrentTime;
330 assert(ET_EXPIRE == ev_type(ev));
331 assert(0 != ev_timer(ev));
333 next_check += feature_int(FEAT_PINGFREQUENCY);
335 /* Scan through the client table */
336 for (i=0; i <= HighestFd; i++) {
337 struct Client *cptr = LocalClientArray[i];
342 assert(&me != cptr); /* I should never be in the local client array! */
345 /* Remove dead clients. */
347 exit_client(cptr, cptr, &me, cli_info(cptr));
351 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s current: %d",
353 IsPingSent(cptr) ? "[Ping Sent]" : "[]",
354 (int)(CurrentTime - cli_lasttime(cptr))));
356 /* Unregistered clients pingout after max_ping seconds, they don't
357 * get given a second chance - if they were then people could not quite
358 * finish registration and hold resources without being subject to k/g
361 if (!IsRegistered(cptr)) {
362 assert(!IsServer(cptr));
363 max_ping = feature_int(FEAT_CONNECTTIMEOUT);
364 /* If client authorization time has expired, ask auth whether they
365 * should be checked again later. */
366 if ((CurrentTime-cli_firsttime(cptr) >= max_ping)
367 && auth_ping_timeout(cptr))
369 if (!IsRegistered(cptr)) {
370 /* OK, they still have enough time left, so we'll just skip to the
371 * next client. Set the next check to be when their time is up, if
372 * that's before the currently scheduled next check -- hikari */
373 expire = cli_firsttime(cptr) + max_ping;
374 if (expire < next_check)
380 max_ping = client_get_ping(cptr);
382 /* If it's a server and we have not sent an AsLL lately, do so. */
383 if (IsServer(cptr)) {
384 if (CurrentTime - cli_serv(cptr)->asll_last >= max_ping) {
388 cli_serv(cptr)->asll_last = CurrentTime;
389 expire = cli_serv(cptr)->asll_last + max_ping;
390 asll_ts = militime_float(NULL);
391 sendcmdto_prio_one(&me, CMD_PING, cptr, "!%s %s %s", asll_ts,
392 cli_name(cptr), asll_ts);
395 expire = cli_serv(cptr)->asll_last + max_ping;
396 if (expire < next_check)
400 /* Ok, the thing that will happen most frequently, is that someone will
401 * have sent something recently. Cover this first for speed.
403 * If it's an unregistered client and hasn't managed to register within
404 * max_ping then it's obviously having problems (broken client) or it's
405 * just up to no good, so we won't skip it, even if its been sending
409 if ((CurrentTime-cli_lasttime(cptr) < max_ping) && IsRegistered(cptr)) {
410 expire = cli_lasttime(cptr) + max_ping;
411 if (expire < next_check)
416 /* Quit the client after max_ping*2 - they should have answered by now */
417 if (CurrentTime-cli_lasttime(cptr) >= (max_ping*2) )
419 /* If it was a server, then tell ops about it. */
420 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
421 sendto_opmask_butone(0, SNO_OLDSNO,
422 "No response from %s, closing link",
424 exit_client_msg(cptr, cptr, &me, "Ping timeout");
428 if (!IsPingSent(cptr))
430 /* If we haven't PINGed the connection and we haven't heard from it in a
431 * while, PING it to make sure it is still alive.
435 /* If we're late in noticing don't hold it against them :) */
436 cli_lasttime(cptr) = CurrentTime - max_ping;
439 sendrawto_one(cptr, MSG_PING " :%s", cli_name(&me));
441 sendcmdto_prio_one(&me, CMD_PING, cptr, ":%s", cli_name(&me));
444 expire = cli_lasttime(cptr) + max_ping * 2;
445 if (expire < next_check)
449 assert(next_check >= CurrentTime);
451 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
452 CurrentTime, next_check-CurrentTime));
454 timer_add(&ping_timer, check_pings, 0, TT_ABSOLUTE, next_check);
458 /** Parse command line arguments.
459 * Global variables are updated to reflect the arguments.
460 * As a side effect, makes sure the process's effective user id is the
461 * same as the real user id.
462 * @param[in] argc Number of arguments on command line.
463 * @param[in,out] argv Command-lne arguments.
465 static void parse_command_line(int argc, char** argv) {
466 const char *options = "d:f:h:nktvx:c:";
469 if (thisServer.euid != thisServer.uid)
470 setuid(thisServer.uid);
472 /* Do we really need to sanity check the non-NULLness of optarg? That's
473 * getopt()'s job... Removing those... -zs
475 while ((opt = getopt(argc, argv, options)) != EOF)
477 case 'k': thisServer.bootopt |= BOOT_CHKCONF | BOOT_TTY; break;
478 case 'c': dbg_client = optarg; break;
480 case 't': thisServer.bootopt |= BOOT_TTY; break;
481 case 'd': dpath = optarg; break;
482 case 'f': configfile = optarg; break;
483 case 'h': ircd_strncpy(cli_name(&me), optarg, HOSTLEN); break;
485 printf("ircd %s\n", version);
486 printf("Event engines: ");
491 printf("/dev/poll ");
494 printf("epoll_*() ");
501 printf("\nCompiled for a maximum of %d connections.\n", MAXCONNECTIONS);
508 debuglevel = atoi(optarg);
512 thisServer.bootopt |= BOOT_DEBUG;
514 printf("WARNING: DEBUGMODE disabled; -x has no effect.\n");
519 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv] [-k [-c clispec]]\n"
520 "\n -f config\t specify explicit configuration file"
521 "\n -x loglevel\t set debug logging verbosity"
522 "\n -n or -t\t don't detach"
523 "\n -v\t\t display version"
524 "\n -k\t\t exit after checking config"
525 "\n -c clispec\t search for client/kill blocks matching client"
526 "\n\t\t clispec is comma-separated list of user@host,"
527 "\n\t\t user@ip, $Rrealname, and port number"
528 "\n\nServer not started.\n");
535 * @param[in] no_fork If non-zero, do not fork into the background.
537 static void daemon_init(int no_fork) {
547 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
548 ioctl(fd, TIOCNOTTY, 0);
557 /** Check that we have access to a particular file.
558 * If we do not have access to the file, complain on stderr.
559 * @param[in] path File name to check for access.
560 * @param[in] which Configuration character associated with file.
561 * @param[in] mode Bitwise combination of R_OK, W_OK, X_OK and/or F_OK.
562 * @return Non-zero if we have the necessary access, zero if not.
564 static char check_file_access(const char *path, char which, int mode) {
565 if (!access(path, mode))
569 "Check on %cPATH (%s) failed: %s\n"
570 "Please create this file and/or rerun `configure' "
571 "using --with-%cpath and recompile to correct this.\n",
572 which, path, strerror(errno), which);
578 /*----------------------------------------------------------------------------
580 *--------------------------------------------------------------------------*/
581 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
582 /** Set the core size soft limit to the same as the hard limit. */
583 static void set_core_limit(void) {
584 struct rlimit corelim;
586 if (getrlimit(RLIMIT_CORE, &corelim)) {
587 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
588 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
591 corelim.rlim_cur = corelim.rlim_max;
592 if (setrlimit(RLIMIT_CORE, &corelim))
593 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
599 /** Complain to stderr if any user or group ID belongs to the superuser.
600 * @return Non-zero if all IDs are okay, zero if some are 0.
602 static int set_userid_if_needed(void) {
603 if (getuid() == 0 || geteuid() == 0 ||
604 getgid() == 0 || getegid() == 0) {
605 fprintf(stderr, "ERROR: This server will not run as superuser.\n");
613 /*----------------------------------------------------------------------------
616 * TODO: This should set the basic environment up and start the main loop.
617 * we're doing waaaaaaaaay too much server initialization here. I hate
618 * long and ugly control paths... -smd
619 *--------------------------------------------------------------------------*/
621 * @param[in] argc Number of arguments in \a argv.
622 * @param[in] argv Arguments to program execution.
624 int main(int argc, char **argv) {
625 CurrentTime = time(NULL);
627 thisServer.argc = argc;
628 thisServer.argv = argv;
629 thisServer.uid = getuid();
630 thisServer.euid = geteuid();
633 mem_dbg_initialise();
636 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
640 umask(077); /* better safe than sorry --SRB */
641 memset(&me, 0, sizeof(me));
642 memset(&me_con, 0, sizeof(me_con));
643 cli_connect(&me) = &me_con;
646 parse_command_line(argc, argv);
649 fprintf(stderr, "Fail: Cannot chdir(%s): %s, check DPATH\n", dpath, strerror(errno));
653 if (!set_userid_if_needed())
656 /* Check paths for accessibility */
657 if (!check_file_access(SPATH, 'S', X_OK) ||
658 !check_file_access(configfile, 'C', R_OK))
661 if (!init_connection_limits())
664 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY | BOOT_CHKCONF)));
666 /* daemon_init() must be before event_init() because kqueue() FDs
667 * are, perversely, not inherited across fork().
669 daemon_init(thisServer.bootopt & BOOT_TTY);
672 /* Must reserve fd 2... */
673 if (debuglevel >= 0 && !(thisServer.bootopt & BOOT_TTY)) {
675 if ((fd = open("/dev/null", O_WRONLY)) < 0) {
676 fprintf(stderr, "Unable to open /dev/null (to reserve fd 2): %s\n",
680 if (fd != 2 && dup2(fd, 2) < 0) {
681 fprintf(stderr, "Unable to reserve fd 2; dup2 said: %s\n",
688 event_init(MAXCONNECTIONS);
691 feature_init(); /* initialize features... */
693 set_nomem_handler(outofmemory);
703 /* we need this for now, when we're modular this
704 should be removed -- hikari */
710 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to read configuration file %s",
715 if (thisServer.bootopt & BOOT_CHKCONF) {
717 conf_debug_iline(dbg_client);
718 fprintf(stderr, "Configuration file %s checked okay.\n", configfile);
722 debug_init(thisServer.bootopt & BOOT_TTY);
724 Debug((DEBUG_FATAL, "Failed to acquire PID file lock after fork"));
728 init_server_identity();
735 timer_add(timer_init(&connect_timer), try_connections, 0, TT_RELATIVE, 1);
736 timer_add(timer_init(&ping_timer), check_pings, 0, TT_RELATIVE, 1);
737 timer_add(timer_init(&destruct_event_timer), exec_expired_destruct_events, 0, TT_PERIODIC, 60);
739 CurrentTime = time(NULL);
742 cli_magic(&me) = CLIENT_MAGIC;
746 cli_serv(&me)->timestamp = TStime(); /* Abuse own link timestamp as start TS */
747 cli_serv(&me)->prot = atoi(MAJOR_PROTOCOL);
748 cli_serv(&me)->up = &me;
749 cli_serv(&me)->down = NULL;
750 cli_handler(&me) = SERVER_HANDLER;
752 SetYXXCapacity(&me, MAXCLIENTS);
754 cli_lasttime(&me) = cli_since(&me) = cli_firsttime(&me) = CurrentTime;
762 Debug((DEBUG_NOTICE, "Server ready..."));
763 log_write(LS_SYSTEM, L_NOTICE, 0, "Server Ready");