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 #ifdef HAVE_SYS_RESOURCE_H
73 #include <sys/resource.h>
75 #include <sys/socket.h>
77 #include <sys/types.h>
82 /*----------------------------------------------------------------------------
84 *--------------------------------------------------------------------------*/
85 extern void init_counters(void);
86 extern void mem_dbg_initialise(void);
88 /*----------------------------------------------------------------------------
90 *--------------------------------------------------------------------------*/
92 BOOT_DEBUG = 1, /**< Enable debug output. */
93 BOOT_TTY = 2, /**< Stay connected to TTY. */
94 BOOT_CHKCONF = 4 /**< Exit after reading configuration file. */
98 /*----------------------------------------------------------------------------
100 *--------------------------------------------------------------------------*/
101 struct Client me; /**< That's me */
102 struct Connection me_con; /**< That's me too */
103 struct Client *GlobalClientList = &me; /**< Pointer to beginning of
105 time_t TSoffset = 0; /**< Offset of timestamps to system clock */
106 int GlobalRehashFlag = 0; /**< do a rehash if set */
107 int GlobalRestartFlag = 0; /**< do a restart if set */
108 time_t CurrentTime; /**< Updated every time we leave select() */
110 char *configfile = CPATH; /**< Server configuration file */
111 int debuglevel = -1; /**< Server debug level */
112 char *debugmode = ""; /**< Server debug level */
113 static char *dpath = DPATH; /**< Working directory for daemon */
114 static char *dbg_client; /**< Client specifier for chkconf */
116 static struct Timer connect_timer; /**< timer structure for try_connections() */
117 static struct Timer ping_timer; /**< timer structure for check_pings() */
118 static struct Timer destruct_event_timer; /**< timer structure for exec_expired_destruct_events() */
120 /** Daemon information. */
121 static struct Daemon thisServer = { 0, 0, 0, 0, 0, 0, -1 };
123 /** Non-zero until we want to exit. */
127 /*----------------------------------------------------------------------------
129 *--------------------------------------------------------------------------*/
130 /** Terminate the server with a message.
131 * @param[in] message Message to log and send to operators.
133 void server_die(const char *message)
135 /* log_write will send out message to both log file and as server notice */
136 log_write(LS_SYSTEM, L_CRIT, 0, "Server terminating: %s", message);
137 flush_connections(0);
138 close_connections(1);
142 /*----------------------------------------------------------------------------
144 *--------------------------------------------------------------------------*/
145 /** Immediately terminate the server with a message.
146 * @param[in] message Message to log, but not send to operators.
148 void server_panic(const char *message)
150 /* inhibit sending server notice--we may be panicking due to low memory */
151 log_write(LS_SYSTEM, L_CRIT, LOG_NOSNOTICE, "Server panic: %s", message);
152 flush_connections(0);
154 close_connections(1);
158 /*----------------------------------------------------------------------------
159 * API: server_restart
160 *--------------------------------------------------------------------------*/
161 /** Restart the server with a message.
162 * @param[in] message Message to log and send to operators.
164 void server_restart(const char *message)
166 static int restarting = 0;
168 /* inhibit sending any server notices; we may be in a loop */
169 log_write(LS_SYSTEM, L_WARNING, LOG_NOSNOTICE, "Restarting Server: %s",
171 if (restarting++) /* increment restarting to prevent looping */
174 sendto_opmask_butone(0, SNO_OLDSNO, "Restarting server: %s", message);
175 Debug((DEBUG_NOTICE, "Restarting server..."));
176 flush_connections(0);
180 close_connections(!(thisServer.bootopt & (BOOT_TTY | BOOT_DEBUG | BOOT_CHKCONF)));
182 execv(SPATH, thisServer.argv);
184 /* Have to reopen since it has been closed above */
187 log_write(LS_SYSTEM, L_CRIT, 0, "execv(%s,%s) failed: %m", SPATH,
190 Debug((DEBUG_FATAL, "Couldn't restart server \"%s\": %s",
191 SPATH, (strerror(errno)) ? strerror(errno) : ""));
196 /*----------------------------------------------------------------------------
197 * outofmemory: Handler for out of memory conditions...
198 *--------------------------------------------------------------------------*/
199 /** Handle out-of-memory condition. */
200 static void outofmemory(void) {
201 Debug((DEBUG_FATAL, "Out of memory: restarting server..."));
202 server_restart("Out of Memory");
206 /*----------------------------------------------------------------------------
208 *--------------------------------------------------------------------------*/
209 /** Write process ID to PID file. */
210 static void write_pidfile(void) {
213 if (thisServer.pid_fd >= 0) {
214 memset(buff, 0, sizeof(buff));
215 sprintf(buff, "%5d\n", (int)getpid());
216 if (write(thisServer.pid_fd, buff, strlen(buff)) == -1)
217 Debug((DEBUG_NOTICE, "Error writing to pid file %s: %m",
218 feature_str(FEAT_PPATH)));
221 Debug((DEBUG_NOTICE, "Error opening pid file %s: %m",
222 feature_str(FEAT_PPATH)));
225 /** Try to create the PID file.
226 * @return Zero on success; non-zero on any error.
228 static int check_pid(void)
232 lock.l_type = F_WRLCK;
234 lock.l_whence = SEEK_SET;
237 if ((thisServer.pid_fd = open(feature_str(FEAT_PPATH), O_CREAT | O_RDWR,
239 return fcntl(thisServer.pid_fd, F_SETLK, &lock) == -1;
245 /** Look for any connections that we should try to initiate.
246 * Reschedules itself to run again at the appropriate time.
247 * @param[in] ev Timer event (ignored).
249 static void try_connections(struct Event* ev) {
250 struct ConfItem* aconf;
251 struct ConfItem** pconf;
253 struct ConnectionClass* cltmp;
257 assert(ET_EXPIRE == ev_type(ev));
258 assert(0 != ev_timer(ev));
260 Debug((DEBUG_NOTICE, "Connection check at : %s", myctime(CurrentTime)));
261 for (aconf = GlobalConfList; aconf; aconf = aconf->next) {
262 /* Only consider server items with non-zero port and non-zero
263 * connect times that are not actively juped.
265 if (!(aconf->status & CONF_SERVER)
266 || aconf->address.port == 0
267 || ((ajupe = jupe_find(aconf->name)) && JupeIsActive(ajupe)))
270 /* Update next possible connection check time. */
271 if (next > aconf->hold || next == 0)
274 /* Update the next time we can consider this entry. */
275 cltmp = aconf->conn_class;
276 hold = aconf->hold > CurrentTime; /* before we update aconf->hold */
277 aconf->hold = ConFreq(cltmp) ? CurrentTime + ConFreq(cltmp) : 0;
279 /* Do not try to connect if its use is still on hold until future,
280 * too many links in its connection class, it is already linked,
281 * or if connect rules forbid a link now.
284 || (Links(cltmp) > MaxLinks(cltmp))
285 || FindServer(aconf->name)
286 || conf_eval_crule(aconf->name, CRULE_MASK))
289 /* Ensure it is at the end of the list for future checks. */
291 /* Find aconf's location in the list and splice it out. */
292 for (pconf = &GlobalConfList; *pconf; pconf = &(*pconf)->next)
294 *pconf = aconf->next;
295 /* Reinsert it at the end of the list (where pconf is now). */
300 /* Activate the connection itself. */
301 if (connect_server(aconf, 0))
302 sendto_opmask_butone(0, SNO_OLDSNO, "Connection to %s activated.",
305 /* And stop looking for further candidates. */
310 next = CurrentTime + feature_int(FEAT_CONNECTFREQUENCY);
312 Debug((DEBUG_NOTICE, "Next connection check : %s", myctime(next)));
314 timer_add(&connect_timer, try_connections, 0, TT_ABSOLUTE, next);
318 /** Check for clients that have not sent a ping response recently.
319 * Reschedules itself to run again at the appropriate time.
320 * @param[in] ev Timer event (ignored).
322 static void check_pings(struct Event* ev) {
324 int next_check = CurrentTime;
328 assert(ET_EXPIRE == ev_type(ev));
329 assert(0 != ev_timer(ev));
331 next_check += feature_int(FEAT_PINGFREQUENCY);
333 /* Scan through the client table */
334 for (i=0; i <= HighestFd; i++) {
335 struct Client *cptr = LocalClientArray[i];
340 assert(&me != cptr); /* I should never be in the local client array! */
343 /* Remove dead clients. */
345 exit_client(cptr, cptr, &me, cli_info(cptr));
349 max_ping = IsRegistered(cptr) ? client_get_ping(cptr) :
350 feature_int(FEAT_CONNECTTIMEOUT);
352 Debug((DEBUG_DEBUG, "check_pings(%s)=status:%s limit: %d current: %d",
354 IsPingSent(cptr) ? "[Ping Sent]" : "[]",
355 max_ping, (int)(CurrentTime - cli_lasttime(cptr))));
357 /* Ok, the thing that will happen most frequently, is that someone will
358 * have sent something recently. Cover this first for speed.
360 * If it's an unregistered client and hasn't managed to register within
361 * max_ping then it's obviously having problems (broken client) or it's
362 * just up to no good, so we won't skip it, even if its been sending
366 if ((CurrentTime-cli_lasttime(cptr) < max_ping) && IsRegistered(cptr)) {
367 expire = cli_lasttime(cptr) + max_ping;
368 if (expire < next_check)
373 /* Unregistered clients pingout after max_ping seconds, they don't
374 * get given a second chance - if they were then people could not quite
375 * finish registration and hold resources without being subject to k/g
378 if (!IsRegistered(cptr)) {
379 assert(!IsServer(cptr));
380 if ((CurrentTime-cli_firsttime(cptr) >= max_ping)) {
381 /* Display message if they have sent a NICK and a USER but no
384 if (*(cli_name(cptr)) && cli_user(cptr) && *(cli_user(cptr))->username) {
385 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
386 ":Your client may not be compatible with this server.");
387 send_reply(cptr, SND_EXPLICIT | ERR_BADPING,
388 ":Compatible clients are available at %s",
389 feature_str(FEAT_URL_CLIENTS));
391 exit_client_msg(cptr,cptr,&me, "Registration Timeout");
394 /* OK, they still have enough time left, so we'll just skip to the
395 * next client. Set the next check to be when their time is up, if
396 * that's before the currently scheduled next check -- hikari */
397 expire = cli_firsttime(cptr) + max_ping;
398 if (expire < next_check)
404 /* Quit the client after max_ping*2 - they should have answered by now */
405 if (CurrentTime-cli_lasttime(cptr) >= (max_ping*2) )
407 /* If it was a server, then tell ops about it. */
408 if (IsServer(cptr) || IsConnecting(cptr) || IsHandshake(cptr))
409 sendto_opmask_butone(0, SNO_OLDSNO,
410 "No response from %s, closing link",
412 exit_client_msg(cptr, cptr, &me, "Ping timeout");
416 if (!IsPingSent(cptr))
418 /* If we haven't PINGed the connection and we haven't heard from it in a
419 * while, PING it to make sure it is still alive.
423 /* If we're late in noticing don't hold it against them :) */
424 cli_lasttime(cptr) = CurrentTime - max_ping;
427 sendrawto_one(cptr, MSG_PING " :%s", cli_name(&me));
430 char *asll_ts = militime_float(NULL);
431 sendcmdto_one(&me, CMD_PING, cptr, "!%s %s %s", asll_ts,
432 cli_name(cptr), asll_ts);
436 expire = cli_lasttime(cptr) + max_ping * 2;
437 if (expire < next_check)
441 assert(next_check >= CurrentTime);
443 Debug((DEBUG_DEBUG, "[%i] check_pings() again in %is",
444 CurrentTime, next_check-CurrentTime));
446 timer_add(&ping_timer, check_pings, 0, TT_ABSOLUTE, next_check);
450 /** Parse command line arguments.
451 * Global variables are updated to reflect the arguments.
452 * As a side effect, makes sure the process's effective user id is the
453 * same as the real user id.
454 * @param[in] argc Number of arguments on command line.
455 * @param[in,out] argv Command-lne arguments.
457 static void parse_command_line(int argc, char** argv) {
458 const char *options = "d:f:h:nktvx:c:";
461 if (thisServer.euid != thisServer.uid)
462 setuid(thisServer.uid);
464 /* Do we really need to sanity check the non-NULLness of optarg? That's
465 * getopt()'s job... Removing those... -zs
467 while ((opt = getopt(argc, argv, options)) != EOF)
469 case 'k': thisServer.bootopt |= BOOT_CHKCONF | BOOT_TTY; break;
470 case 'c': dbg_client = optarg; break;
472 case 't': thisServer.bootopt |= BOOT_TTY; break;
473 case 'd': dpath = optarg; break;
474 case 'f': configfile = optarg; break;
475 case 'h': ircd_strncpy(cli_name(&me), optarg, HOSTLEN); break;
477 printf("ircd %s\n", version);
478 printf("Event engines: ");
483 printf("/dev/poll ");
490 printf("\nCompiled for a maximum of %d connections.\n", MAXCONNECTIONS);
497 debuglevel = atoi(optarg);
501 thisServer.bootopt |= BOOT_DEBUG;
505 printf("Usage: ircd [-f config] [-h servername] [-x loglevel] [-ntvk]\n");
506 printf("\n -n -t\t Don't detach\n -v\t display version\n -k\t exit after checking config\n\n");
507 printf("Server not started.\n");
514 * @param[in] no_fork If non-zero, do not fork into the background.
516 static void daemon_init(int no_fork) {
526 if ((fd = open("/dev/tty", O_RDWR)) > -1) {
527 ioctl(fd, TIOCNOTTY, 0);
536 /** Check that we have access to a particular file.
537 * If we do not have access to the file, complain on stderr.
538 * @param[in] path File name to check for access.
539 * @param[in] which Configuration character associated with file.
540 * @param[in] mode Bitwise combination of R_OK, W_OK, X_OK and/or F_OK.
541 * @return Non-zero if we have the necessary access, zero if not.
543 static char check_file_access(const char *path, char which, int mode) {
544 if (!access(path, mode))
548 "Check on %cPATH (%s) failed: %s\n"
549 "Please create this file and/or rerun `configure' "
550 "using --with-%cpath and recompile to correct this.\n",
551 which, path, strerror(errno), which);
557 /*----------------------------------------------------------------------------
559 *--------------------------------------------------------------------------*/
560 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
561 /** Set the core size soft limit to the same as the hard limit. */
562 static void set_core_limit(void) {
563 struct rlimit corelim;
565 if (getrlimit(RLIMIT_CORE, &corelim)) {
566 fprintf(stderr, "Read of rlimit core size failed: %s\n", strerror(errno));
567 corelim.rlim_max = RLIM_INFINITY; /* Try to recover */
570 corelim.rlim_cur = corelim.rlim_max;
571 if (setrlimit(RLIMIT_CORE, &corelim))
572 fprintf(stderr, "Setting rlimit core size failed: %s\n", strerror(errno));
578 /** Complain to stderr if any user or group ID belongs to the superuser.
579 * @return Non-zero if all IDs are okay, zero if some are 0.
581 static int set_userid_if_needed(void) {
582 if (getuid() == 0 || geteuid() == 0 ||
583 getgid() == 0 || getegid() == 0) {
584 fprintf(stderr, "ERROR: This server will not run as superuser.\n");
592 /*----------------------------------------------------------------------------
595 * TODO: This should set the basic environment up and start the main loop.
596 * we're doing waaaaaaaaay too much server initialization here. I hate
597 * long and ugly control paths... -smd
598 *--------------------------------------------------------------------------*/
600 * @param[in] argc Number of arguments in \a argv.
601 * @param[in] argv Arguments to program execution.
603 int main(int argc, char **argv) {
604 CurrentTime = time(NULL);
606 thisServer.argc = argc;
607 thisServer.argv = argv;
608 thisServer.uid = getuid();
609 thisServer.euid = geteuid();
612 mem_dbg_initialise();
615 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_CORE)
619 umask(077); /* better safe than sorry --SRB */
620 memset(&me, 0, sizeof(me));
621 memset(&me_con, 0, sizeof(me_con));
622 cli_connect(&me) = &me_con;
625 parse_command_line(argc, argv);
628 fprintf(stderr, "Fail: Cannot chdir(%s): %s, check DPATH\n", dpath, strerror(errno));
632 if (!set_userid_if_needed())
635 /* Check paths for accessibility */
636 if (!check_file_access(SPATH, 'S', X_OK) ||
637 !check_file_access(configfile, 'C', R_OK))
640 if (!init_connection_limits())
643 close_connections(!(thisServer.bootopt & (BOOT_DEBUG | BOOT_TTY | BOOT_CHKCONF)));
645 /* daemon_init() must be before event_init() because kqueue() FDs
646 * are, perversely, not inherited across fork().
648 daemon_init(thisServer.bootopt & BOOT_TTY);
650 event_init(MAXCONNECTIONS);
653 feature_init(); /* initialize features... */
655 set_nomem_handler(outofmemory);
657 if (!init_string()) {
658 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to initialize string module");
670 /* we need this for now, when we're modular this
671 should be removed -- hikari */
677 log_write(LS_SYSTEM, L_CRIT, 0, "Failed to read configuration file %s",
682 if (thisServer.bootopt & BOOT_CHKCONF) {
684 conf_debug_iline(dbg_client);
685 fprintf(stderr, "Configuration file %s checked okay.\n", configfile);
689 debug_init(thisServer.bootopt & BOOT_TTY);
691 Debug((DEBUG_FATAL, "Failed to acquire PID file lock after fork"));
695 init_server_identity();
702 timer_add(timer_init(&connect_timer), try_connections, 0, TT_RELATIVE, 1);
703 timer_add(timer_init(&ping_timer), check_pings, 0, TT_RELATIVE, 1);
704 timer_add(timer_init(&destruct_event_timer), exec_expired_destruct_events, 0, TT_PERIODIC, 60);
706 CurrentTime = time(NULL);
709 cli_magic(&me) = CLIENT_MAGIC;
713 cli_serv(&me)->timestamp = TStime(); /* Abuse own link timestamp as start TS */
714 cli_serv(&me)->prot = atoi(MAJOR_PROTOCOL);
715 cli_serv(&me)->up = &me;
716 cli_serv(&me)->down = NULL;
717 cli_handler(&me) = SERVER_HANDLER;
719 SetYXXCapacity(&me, MAXCLIENTS);
721 cli_lasttime(&me) = cli_since(&me) = cli_firsttime(&me) = CurrentTime;
728 Debug((DEBUG_NOTICE, "Server ready..."));
729 log_write(LS_SYSTEM, L_NOTICE, 0, "Server Ready");