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.
22 * @version $Id: ircd.c 1907 2009-02-09 04:11:04Z entrope $
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"
65 /* #include <assert.h> -- Now using assert in ircd_log.h */
74 #ifdef HAVE_SYS_RESOURCE_H
75 #include <sys/resource.h>
77 #include <sys/socket.h>
79 #include <sys/types.h>
84 /*----------------------------------------------------------------------------
86 *--------------------------------------------------------------------------*/
87 extern void init_counters(void);
88 extern void mem_dbg_initialise(void);
90 /*----------------------------------------------------------------------------
92 *--------------------------------------------------------------------------*/
94 BOOT_DEBUG = 1, /**< Enable debug output. */
95 BOOT_TTY = 2, /**< Stay connected to TTY. */
96 BOOT_CHKCONF = 4 /**< Exit after reading configuration file. */
100 /*----------------------------------------------------------------------------
101 * Global data (YUCK!)
102 *--------------------------------------------------------------------------*/
103 struct Client me; /**< That's me */
104 struct Connection me_con; /**< That's me too */
105 struct Client *GlobalClientList = &me; /**< Pointer to beginning of
107 time_t TSoffset = 0; /**< Offset of timestamps to system clock */
108 int GlobalRehashFlag = 0; /**< do a rehash if set */
109 int GlobalRestartFlag = 0; /**< do a restart if set */
110 time_t CurrentTime; /**< Updated every time we leave select() */
112 char *configfile = CPATH; /**< Server configuration file */
113 int debuglevel = -1; /**< Server debug level */
114 char *debugmode = ""; /**< Server debug level */
115 static char *dpath = DPATH; /**< Working directory for daemon */
116 static char *dbg_client; /**< Client specifier for chkconf */
118 static struct Timer connect_timer; /**< timer structure for try_connections() */
119 static struct Timer ping_timer; /**< timer structure for check_pings() */
120 static struct Timer destruct_event_timer; /**< timer structure for exec_expired_destruct_events() */
122 /** Daemon information. */
123 static struct Daemon thisServer = { 0, 0, 0, 0, 0, 0, -1 };
125 /** Non-zero until we want to exit. */
129 /*----------------------------------------------------------------------------
131 *--------------------------------------------------------------------------*/
132 /** Terminate the server with a message.
133 * @param[in] message Message to log and send to operators.
135 void server_die(const char *message)
137 /* log_write will send out message to both log file and as server notice */
138 log_write(LS_SYSTEM, L_CRIT, 0, "Server terminating: %s", message);
139 flush_connections(0);
140 close_connections(1);
144 /*----------------------------------------------------------------------------
146 *--------------------------------------------------------------------------*/
147 /** Immediately terminate the server with a message.
148 * @param[in] message Message to log, but not send to operators.
150 void server_panic(const char *message)
152 /* inhibit sending server notice--we may be panicking due to low memory */
153 log_write(LS_SYSTEM, L_CRIT, LOG_NOSNOTICE, "Server panic: %s", message);
154 flush_connections(0);
156 close_connections(1);
160 /*----------------------------------------------------------------------------
161 * API: server_restart
162 *--------------------------------------------------------------------------*/
163 /** Restart the server with a message.
164 * @param[in] message Message to log and send to operators.
166 void server_restart(const char *message)
168 static int restarting = 0;
170 /* inhibit sending any server notices; we may be in a loop */
171 log_write(LS_SYSTEM, L_WARNING, LOG_NOSNOTICE, "Restarting Server: %s",
173 if (restarting++) /* increment restarting to prevent looping */
176 sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
177 Debug((DEBUG_NOTICE, "Restarting server..."));
178 flush_connections(0);
182 close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG | BOOT_CHKCONF)));
186 execv(SPATH, thisServer.argv);
188 /* Have to reopen since it has been closed above */
191 log_write(LS_SYSTEM, L_CRIT, 0, "execv(%s,%s) failed: %m", SPATH,
194 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
195 SPATH, (strerror(errno)) ? strerror(errno) : ""));
200 /*----------------------------------------------------------------------------
201 * outofmemory: Handler for out of memory conditions...
202 *--------------------------------------------------------------------------*/
203 /** Handle out-of-memory condition. */
204 static void outofmemory(void) {
205 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
206 server_restart("Out of Memory");
210 /*----------------------------------------------------------------------------
212 *--------------------------------------------------------------------------*/
213 /** Write process ID to PID file. */
214 static void write_pidfile(void) {
217 if (thisServer.pid_fd >= 0) {
218 memset(buff, 0, sizeof(buff));
219 sprintf(buff, "%5d\n", (int)getpid());
220 if (write(thisServer.pid_fd, buff, strlen(buff)) == -1)
221 Debug((DEBUG_NOTICE, "Error writing to pid file %s: %m",
222 feature_str(FEAT_PPATH)));
225 Debug((DEBUG_NOTICE, "Error opening pid file %s: %m",
226 feature_str(FEAT_PPATH)));
229 /** Try to create the PID file.
230 * @return Zero on success; non-zero on any error.
232 static int check_pid(void)
236 lock.l_type = F_WRLCK;
238 lock.l_whence = SEEK_SET;
241 if ((thisServer.pid_fd = open(feature_str(FEAT_PPATH), O_CREAT | O_RDWR,
243 return fcntl(thisServer.pid_fd, F_SETLK, &lock) == -1;
249 /** Look for any connections that we should try to initiate.
250 * Reschedules itself to run again at the appropriate time.
251 * @param[in] ev Timer event (ignored).
253 static void try_connections(struct Event* ev) {
254 struct ConfItem* aconf;
255 struct ConfItem** pconf;
261 assert(ET_EXPIRE == ev_type(ev));
262 assert(0 != ev_timer(ev));
264 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
265 next = CurrentTime + feature_int(FEAT_CONNECTFREQUENCY);
268 for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
269 /* Only consider server items with non-zero port and non-zero
270 * connect times that are not actively juped.
272 if (!(aconf->status & CONF_SERVER)
273 || aconf->address.port == 0
274 || !(aconf->flags & CONF_AUTOCONNECT)
275 || ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe)))
278 /* Do we need to postpone this connection further? */
279 hold = aconf->hold > CurrentTime;
281 /* Update next possible connection check time. */
282 if (hold && next > aconf->hold)
285 /* Do not try to connect if its use is still on hold until future,
286 * we have already initiated a connection this try_connections(),
287 * too many links in its connection class, it is already linked,
288 * or if connect rules forbid a link now.
291 || (ConfLinks(aconf) > ConfMaxLinks(aconf))
292 || FindServer(aconf->name)
293 || conf_eval_crule(aconf->name, CRULE_MASK))
296 /* Ensure it is at the end of the list for future checks. */
298 /* Find aconf's location in the list and splice it out. */
299 for (pconf = &GlobalConfList; *pconf; pconf = &(*pconf)->next)
301 *pconf = aconf->next;
302 /* Reinsert it at the end of the list (where pconf is now). */
307 /* Activate the connection itself. */
308 if (connect_server(aconf, 0))
309 sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
312 /* And stop looking for further candidates. */
316 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
317 timer_add(&connect_timer, try_connections, 0, TT_ABSOLUTE, next);
321 /** Check for clients that have not sent a ping response recently.
322 * Reschedules itself to run again at the appropriate time.
323 * @param[in] ev Timer event (ignored).
325 static void check_pings(struct Event* ev) {
327 int next_check = CurrentTime;
331 assert(ET_EXPIRE == ev_type(ev));
332 assert(0 != ev_timer(ev));
334 next_check += feature_int(FEAT_PINGFREQUENCY);
336 /* Scan through the client table */
337 for (i=0; i <= HighestFd; i++) {
338 struct Client *cptr = LocalClientArray[i];
343 /* We don't need to check zombies here */
344 if (IsNotConn(cptr)) {
345 assert(IsUser(cptr));
346 /* for now: reap after fixed time (5 minutes) */
347 if ((CurrentTime - cli_user(cptr)->last) >= 300) {
348 SetFlag(cptr, FLAG_DEADSOCKET);
349 /* this will be used as exit message */
350 ircd_strncpy(cli_info(cptr), "Ping timeout", REALLEN);
355 assert(&me != cptr); /* I should never be in the local client array! */
358 /* Remove dead clients. */
360 exit_client(cptr, cptr, &me, cli_info(cptr));
364 max_ping = IsRegistered(cptr) ? client_get_ping(cptr) :
365 feature_int(FEAT_CONNECTTIMEOUT);
367 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
369 IsPingSent(cptr) ? "[Ping Sent]" : "[]",
370 max_ping, (int)(CurrentTime - cli_lasttime(cptr))));
372 /* If it's a server and we have not sent an AsLL lately, do so. */
373 if (IsServer(cptr)) {
374 if (CurrentTime - cli_serv(cptr)->asll_last >= max_ping) {
378 cli_serv(cptr)->asll_last = CurrentTime;
379 expire = cli_serv(cptr)->asll_last + max_ping;
380 asll_ts = militime_float(NULL);
381 sendcmdto_prio_one(&me, CMD_PING, cptr, "!%s %s %s", asll_ts,
382 cli_name(cptr), asll_ts);
385 expire = cli_serv(cptr)->asll_last + max_ping;
386 if (expire < next_check)
390 /* Ok, the thing that will happen most frequently, is that someone will
391 * have sent something recently. Cover this first for speed.
393 * If it's an unregistered client and hasn't managed to register within
394 * max_ping then it's obviously having problems (broken client) or it's
395 * just up to no good, so we won't skip it, even if its been sending
399 if ((CurrentTime-cli_lasttime(cptr) < max_ping) && IsRegistered(cptr)) {
400 expire = cli_lasttime(cptr) + max_ping;
401 if (expire < next_check)
406 /* Unregistered clients pingout after max_ping seconds, they don't
407 * get given a second chance - if they were then people could not quite
408 * finish registration and hold resources without being subject to k/g
411 if (!IsRegistered(cptr)) {
412 assert(!IsServer(cptr));
413 /* If client authorization time has expired, ask auth whether they
414 * should be checked again later. */
415 if ((CurrentTime-cli_firsttime(cptr) >= max_ping)
416 && auth_ping_timeout(cptr))
418 /* OK, they still have enough time left, so we'll just skip to the
419 * next client. Set the next check to be when their time is up, if
420 * that's before the currently scheduled next check -- hikari */
421 expire = cli_firsttime(cptr) + max_ping;
422 if (expire < next_check)
427 /* Quit the client after max_ping*2 - they should have answered by now */
428 if (CurrentTime-cli_lasttime(cptr) >= (max_ping*2) )
430 /* If it was a server, then tell ops about it. */
431 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
432 sendto_opmask_butone(0, SNO_OLDSNO,
433 "No response from %s, closing link",
436 * Keep client structure around when a user pings out, so that they can
437 * reconnect to it later
439 if (IsUser(cptr) && IsAccount(cptr)) {
440 zombie_client(&me, &me, cptr);
443 exit_client_msg(cptr, cptr, &me, "Ping timeout");
447 if (!IsPingSent(cptr))
449 /* If we haven't PINGed the connection and we haven't heard from it in a
450 * while, PING it to make sure it is still alive.
454 /* If we're late in noticing don't hold it against them :) */
455 cli_lasttime(cptr) = CurrentTime - max_ping;
458 sendrawto_one(cptr, MSG_PING " :%s", cli_name(&me));
460 sendcmdto_prio_one(&me, CMD_PING, cptr, ":%s", cli_name(&me));
463 expire = cli_lasttime(cptr) + max_ping * 2;
464 if (expire < next_check)
468 assert(next_check >= CurrentTime);
470 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
471 CurrentTime, next_check-CurrentTime));
473 timer_add(&ping_timer, check_pings, 0, TT_ABSOLUTE, next_check);
477 /** Parse command line arguments.
478 * Global variables are updated to reflect the arguments.
479 * As a side effect, makes sure the process's effective user id is the
480 * same as the real user id.
481 * @param[in] argc Number of arguments on command line.
482 * @param[in,out] argv Command-lne arguments.
484 static void parse_command_line(int argc, char** argv) {
485 const char *options = "d:f:h:nktvx:c:";
488 if (thisServer.euid != thisServer.uid)
489 setuid(thisServer.uid);
491 /* Do we really need to sanity check the non-NULLness of optarg? That's
492 * getopt()'s job... Removing those... -zs
494 while ((opt = getopt(argc, argv, options)) != EOF)
496 case 'k': thisServer.bootopt |= BOOT_CHKCONF | BOOT_TTY; break;
497 case 'c': dbg_client = optarg; break;
499 case 't': thisServer.bootopt |= BOOT_TTY; break;
500 case 'd': dpath = optarg; break;
501 case 'f': configfile = optarg; break;
502 case 'h': ircd_strncpy(cli_name(&me), optarg, HOSTLEN); break;
504 printf("ircd %s\n", version);
505 printf("Event engines: ");
510 printf("/dev/poll ");
513 printf("epoll_*() ");
520 printf("\nCompiled for a maximum of %d connections.\n", MAXCONNECTIONS);
527 debuglevel = atoi(optarg);
531 thisServer.bootopt |= BOOT_DEBUG;
533 printf("WARNING: DEBUGMODE disabled; -x has no effect.\n");
538 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv] [-k [-c clispec]]\n"
539 "\n -f config\t specify explicit configuration file"
540 "\n -x loglevel\t set debug logging verbosity"
541 "\n -n or -t\t don't detach"
542 "\n -v\t\t display version"
543 "\n -k\t\t exit after checking config"
544 "\n -c clispec\t search for client/kill blocks matching client"
545 "\n\t\t clispec is comma-separated list of user@host,"
546 "\n\t\t user@ip, $Rrealname, and port number"
547 "\n\nServer not started.\n");
554 * @param[in] no_fork If non-zero, do not fork into the background.
556 static void daemon_init(int no_fork) {
566 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
567 ioctl(fd, TIOCNOTTY, 0);
576 /** Check that we have access to a particular file.
577 * If we do not have access to the file, complain on stderr.
578 * @param[in] path File name to check for access.
579 * @param[in] which Configuration character associated with file.
580 * @param[in] mode Bitwise combination of R_OK, W_OK, X_OK and/or F_OK.
581 * @return Non-zero if we have the necessary access, zero if not.
583 static char check_file_access(const char *path, char which, int mode) {
584 if (!access(path, mode))
588 "Check on %cPATH (%s) failed: %s\n"
589 "Please create this file and/or rerun `configure' "
590 "using --with-%cpath and recompile to correct this.\n",
591 which, path, strerror(errno), which);
597 /*----------------------------------------------------------------------------
599 *--------------------------------------------------------------------------*/
600 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
601 /** Set the core size soft limit to the same as the hard limit. */
602 static void set_core_limit(void) {
603 struct rlimit corelim;
605 if (getrlimit(RLIMIT_CORE, &corelim)) {
606 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
607 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
610 corelim.rlim_cur = corelim.rlim_max;
611 if (setrlimit(RLIMIT_CORE, &corelim))
612 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
618 /** Complain to stderr if any user or group ID belongs to the superuser.
619 * @return Non-zero if all IDs are okay, zero if some are 0.
621 static int set_userid_if_needed(void) {
622 if (getuid() == 0 || geteuid() == 0 ||
623 getgid() == 0 || getegid() == 0) {
624 fprintf(stderr, "ERROR: This server will not run as superuser.\n");
632 /*----------------------------------------------------------------------------
635 * TODO: This should set the basic environment up and start the main loop.
636 * we're doing waaaaaaaaay too much server initialization here. I hate
637 * long and ugly control paths... -smd
638 *--------------------------------------------------------------------------*/
640 * @param[in] argc Number of arguments in \a argv.
641 * @param[in] argv Arguments to program execution.
643 int main(int argc, char **argv) {
644 CurrentTime = time(NULL);
645 printf("Starting IRCu 2.10.12.10 by pk910.\n");
646 thisServer.argc = argc;
647 thisServer.argv = argv;
648 thisServer.uid = getuid();
649 thisServer.euid = geteuid();
652 mem_dbg_initialise();
655 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
659 umask(077); /* better safe than sorry --SRB */
660 memset(&me, 0, sizeof(me));
661 memset(&me_con, 0, sizeof(me_con));
662 cli_connect(&me) = &me_con;
665 parse_command_line(argc, argv);
668 fprintf(stderr, "Fail: Cannot chdir(%s): %s, check DPATH\n", dpath, strerror(errno));
672 if (!set_userid_if_needed())
675 /* Check paths for accessibility */
676 if (!check_file_access(SPATH, 'S', X_OK) ||
677 !check_file_access(configfile, 'C', R_OK))
680 if (!init_connection_limits())
683 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY | BOOT_CHKCONF)));
685 /* daemon_init() must be before event_init() because kqueue() FDs
686 * are, perversely, not inherited across fork().
688 daemon_init(thisServer.bootopt & BOOT_TTY);
691 /* Must reserve fd 2... */
692 if (debuglevel >= 0 && !(thisServer.bootopt & BOOT_TTY)) {
694 if ((fd = open("/dev/null", O_WRONLY)) < 0) {
695 fprintf(stderr, "Unable to open /dev/null (to reserve fd 2): %s\n",
699 if (fd != 2 && dup2(fd, 2) < 0) {
700 fprintf(stderr, "Unable to reserve fd 2; dup2 said: %s\n",
707 event_init(MAXCONNECTIONS);
710 feature_init(); /* initialize features... */
712 set_nomem_handler(outofmemory);
722 /* we need this for now, when we're modular this
723 should be removed -- hikari */
729 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to read configuration file %s",
734 if (thisServer.bootopt & BOOT_CHKCONF) {
736 conf_debug_iline(dbg_client);
737 fprintf(stderr, "Configuration file %s checked okay.\n", configfile);
741 debug_init(thisServer.bootopt & BOOT_TTY);
743 Debug((DEBUG_FATAL, "Failed to acquire PID file lock after fork"));
747 init_server_identity();
754 timer_add(timer_init(&connect_timer), try_connections, 0, TT_RELATIVE, 1);
755 timer_add(timer_init(&ping_timer), check_pings, 0, TT_RELATIVE, 1);
756 timer_add(timer_init(&destruct_event_timer), exec_expired_destruct_events, 0, TT_PERIODIC, 60);
758 CurrentTime = time(NULL);
761 cli_magic(&me) = CLIENT_MAGIC;
765 cli_serv(&me)->timestamp = TStime(); /* Abuse own link timestamp as start TS */
766 cli_serv(&me)->prot = atoi(MAJOR_PROTOCOL);
767 cli_serv(&me)->up = &me;
768 cli_serv(&me)->down = NULL;
769 cli_handler(&me) = SERVER_HANDLER;
771 SetYXXCapacity(&me, MAXCLIENTS);
773 cli_lasttime(&me) = cli_since(&me) = cli_firsttime(&me) = CurrentTime;
781 Debug((DEBUG_NOTICE, "Server ready..."));
782 log_write(LS_SYSTEM, L_NOTICE, 0, "Server Ready");