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 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 assert(&me != cptr); /* I should never be in the local client array! */
346 /* Remove dead clients. */
348 exit_client(cptr, cptr, &me, cli_info(cptr));
352 max_ping = IsRegistered(cptr) ? client_get_ping(cptr) :
353 feature_int(FEAT_CONNECTTIMEOUT);
355 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
357 IsPingSent(cptr) ? "[Ping Sent]" : "[]",
358 max_ping, (int)(CurrentTime - cli_lasttime(cptr))));
360 /* If it's a server and we have not sent an AsLL lately, do so. */
361 if (IsServer(cptr)) {
362 if (CurrentTime - cli_serv(cptr)->asll_last >= max_ping) {
366 cli_serv(cptr)->asll_last = CurrentTime;
367 expire = cli_serv(cptr)->asll_last + max_ping;
368 asll_ts = militime_float(NULL);
369 sendcmdto_prio_one(&me, CMD_PING, cptr, "!%s %s %s", asll_ts,
370 cli_name(cptr), asll_ts);
373 expire = cli_serv(cptr)->asll_last + max_ping;
374 if (expire < next_check)
378 /* Ok, the thing that will happen most frequently, is that someone will
379 * have sent something recently. Cover this first for speed.
381 * If it's an unregistered client and hasn't managed to register within
382 * max_ping then it's obviously having problems (broken client) or it's
383 * just up to no good, so we won't skip it, even if its been sending
387 if ((CurrentTime-cli_lasttime(cptr) < max_ping) && IsRegistered(cptr)) {
388 expire = cli_lasttime(cptr) + max_ping;
389 if (expire < next_check)
394 /* Unregistered clients pingout after max_ping seconds, they don't
395 * get given a second chance - if they were then people could not quite
396 * finish registration and hold resources without being subject to k/g
399 if (!IsRegistered(cptr)) {
400 assert(!IsServer(cptr));
401 /* If client authorization time has expired, ask auth whether they
402 * should be checked again later. */
403 if ((CurrentTime-cli_firsttime(cptr) >= max_ping)
404 && auth_ping_timeout(cptr))
406 /* OK, they still have enough time left, so we'll just skip to the
407 * next client. Set the next check to be when their time is up, if
408 * that's before the currently scheduled next check -- hikari */
409 expire = cli_firsttime(cptr) + max_ping;
410 if (expire < next_check)
415 /* Quit the client after max_ping*2 - they should have answered by now */
416 if (CurrentTime-cli_lasttime(cptr) >= (max_ping*2) )
418 /* If it was a server, then tell ops about it. */
419 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
420 sendto_opmask_butone(0, SNO_OLDSNO,
421 "No response from %s, closing link",
423 exit_client_msg(cptr, cptr, &me, "Ping timeout");
427 if (!IsPingSent(cptr))
429 /* If we haven't PINGed the connection and we haven't heard from it in a
430 * while, PING it to make sure it is still alive.
434 /* If we're late in noticing don't hold it against them :) */
435 cli_lasttime(cptr) = CurrentTime - max_ping;
438 sendrawto_one(cptr, MSG_PING " :%s", cli_name(&me));
440 sendcmdto_prio_one(&me, CMD_PING, cptr, ":%s", cli_name(&me));
443 expire = cli_lasttime(cptr) + max_ping * 2;
444 if (expire < next_check)
448 assert(next_check >= CurrentTime);
450 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
451 CurrentTime, next_check-CurrentTime));
453 timer_add(&ping_timer, check_pings, 0, TT_ABSOLUTE, next_check);
457 /** Parse command line arguments.
458 * Global variables are updated to reflect the arguments.
459 * As a side effect, makes sure the process's effective user id is the
460 * same as the real user id.
461 * @param[in] argc Number of arguments on command line.
462 * @param[in,out] argv Command-lne arguments.
464 static void parse_command_line(int argc, char** argv) {
465 const char *options = "d:f:h:nktvx:c:";
468 if (thisServer.euid != thisServer.uid)
469 setuid(thisServer.uid);
471 /* Do we really need to sanity check the non-NULLness of optarg? That's
472 * getopt()'s job... Removing those... -zs
474 while ((opt = getopt(argc, argv, options)) != EOF)
476 case 'k': thisServer.bootopt |= BOOT_CHKCONF | BOOT_TTY; break;
477 case 'c': dbg_client = optarg; break;
479 case 't': thisServer.bootopt |= BOOT_TTY; break;
480 case 'd': dpath = optarg; break;
481 case 'f': configfile = optarg; break;
482 case 'h': ircd_strncpy(cli_name(&me), optarg, HOSTLEN); break;
484 printf("ircd %s\n", version);
485 printf("Event engines: ");
490 printf("/dev/poll ");
493 printf("epoll_*() ");
500 printf("\nCompiled for a maximum of %d connections.\n", MAXCONNECTIONS);
507 debuglevel = atoi(optarg);
511 thisServer.bootopt |= BOOT_DEBUG;
513 printf("WARNING: DEBUGMODE disabled; -x has no effect.\n");
518 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntv] [-k [-c clispec]]\n"
519 "\n -f config\t specify explicit configuration file"
520 "\n -x loglevel\t set debug logging verbosity"
521 "\n -n or -t\t don't detach"
522 "\n -v\t\t display version"
523 "\n -k\t\t exit after checking config"
524 "\n -c clispec\t search for client/kill blocks matching client"
525 "\n\t\t clispec is comma-separated list of user@host,"
526 "\n\t\t user@ip, $Rrealname, and port number"
527 "\n\nServer not started.\n");
534 * @param[in] no_fork If non-zero, do not fork into the background.
536 static void daemon_init(int no_fork) {
546 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
547 ioctl(fd, TIOCNOTTY, 0);
556 /** Check that we have access to a particular file.
557 * If we do not have access to the file, complain on stderr.
558 * @param[in] path File name to check for access.
559 * @param[in] which Configuration character associated with file.
560 * @param[in] mode Bitwise combination of R_OK, W_OK, X_OK and/or F_OK.
561 * @return Non-zero if we have the necessary access, zero if not.
563 static char check_file_access(const char *path, char which, int mode) {
564 if (!access(path, mode))
568 "Check on %cPATH (%s) failed: %s\n"
569 "Please create this file and/or rerun `configure' "
570 "using --with-%cpath and recompile to correct this.\n",
571 which, path, strerror(errno), which);
577 /*----------------------------------------------------------------------------
579 *--------------------------------------------------------------------------*/
580 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
581 /** Set the core size soft limit to the same as the hard limit. */
582 static void set_core_limit(void) {
583 struct rlimit corelim;
585 if (getrlimit(RLIMIT_CORE, &corelim)) {
586 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
587 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
590 corelim.rlim_cur = corelim.rlim_max;
591 if (setrlimit(RLIMIT_CORE, &corelim))
592 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
598 /** Complain to stderr if any user or group ID belongs to the superuser.
599 * @return Non-zero if all IDs are okay, zero if some are 0.
601 static int set_userid_if_needed(void) {
602 if (getuid() == 0 || geteuid() == 0 ||
603 getgid() == 0 || getegid() == 0) {
604 fprintf(stderr, "ERROR: This server will not run as superuser.\n");
612 /*----------------------------------------------------------------------------
615 * TODO: This should set the basic environment up and start the main loop.
616 * we're doing waaaaaaaaay too much server initialization here. I hate
617 * long and ugly control paths... -smd
618 *--------------------------------------------------------------------------*/
620 * @param[in] argc Number of arguments in \a argv.
621 * @param[in] argv Arguments to program execution.
623 int main(int argc, char **argv) {
624 CurrentTime = time(NULL);
625 printf("Starting IRCu 2.10.12.10 by pk910.\n");
626 printf("you are not allowed to use this version without my permission\n");
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");