1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
15 #include "configreader.h"
21 #include <sys/resource.h>
23 /* This is just to be completely certain that the change which fixed getrusage on RH7 doesn't break anything else -- Om */
34 #include "socketengine.h"
35 #include "inspircd_se_config.h"
38 #include "command_parse.h"
39 #include "exitcodes.h"
46 bool g_starting = true;
49 using irc::sockets::NonBlocking;
50 using irc::sockets::Blocking;
51 using irc::sockets::insp_ntoa;
52 using irc::sockets::insp_inaddr;
53 using irc::sockets::insp_sockaddr;
57 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
58 const char* ExitCodes[] =
61 "DIE command", /* 1 */
62 "execv() failed", /* 2 */
63 "Internal error", /* 3 */
64 "Config file error", /* 4 */
65 "Logfile error", /* 5 */
66 "Fork failed", /* 6 */
67 "Bad commandline parameters", /* 7 */
68 "No ports could be bound", /* 8 */
69 "Can't write PID file", /* 9 */
70 "SocketEngine could not initialize", /* 10 */
71 "Refusing to start up as root", /* 11 */
72 "Found a <die> tag!", /* 12 */
73 "Couldn't load module on startup", /* 13 */
75 "Received SIGTERM", /* 15 */
78 void InspIRCd::AddServerName(const std::string &servername)
80 servernamelist::iterator itr = servernames.begin();
81 for(; itr != servernames.end(); ++itr)
82 if(**itr == servername)
85 string * ns = new string(servername);
86 servernames.push_back(ns);
89 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
91 servernamelist::iterator itr = servernames.begin();
92 for(; itr != servernames.end(); ++itr)
93 if(**itr == servername)
94 return (*itr)->c_str();
96 servernames.push_back(new string(servername));
97 itr = --servernames.end();
98 return (*itr)->c_str();
101 bool InspIRCd::FindServerName(const std::string &servername)
103 servernamelist::iterator itr = servernames.begin();
104 for(; itr != servernames.end(); ++itr)
105 if(**itr == servername)
110 void InspIRCd::Exit(int status)
117 SI->SendError("Exiting with status " + ConvToStr(status) + " (" + std::string(ExitCodes[status]) + ")");
123 void InspIRCd::Cleanup()
125 std::vector<std::string> mymodnames;
126 int MyModCount = this->GetModuleCount();
128 for (unsigned int i = 0; i < Config->ports.size(); i++)
130 /* This calls the constructor and closes the listening socket */
131 delete Config->ports[i];
134 Config->ports.clear();
136 /* Close all client sockets, or the new process inherits them */
137 for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
139 (*i)->SetWriteError("Server shutdown");
143 /* We do this more than once, so that any service providers get a
144 * chance to be unhooked by the modules using them, but then get
145 * a chance to be removed themsleves.
147 for (int tries = 0; tries < 3; tries++)
149 MyModCount = this->GetModuleCount();
152 /* Unload all modules, so they get a chance to clean up their listeners */
153 for (int j = 0; j <= MyModCount; j++)
154 mymodnames.push_back(Config->module_names[j]);
156 for (int k = 0; k <= MyModCount; k++)
157 this->UnloadModule(mymodnames[k].c_str());
161 this->Logger->Close();
163 /* Cleanup Server Names */
164 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
173 void InspIRCd::Restart(const std::string &reason)
175 /* SendError flushes each client's queue,
176 * regardless of writeability state
178 this->SendError(reason);
182 /* Figure out our filename (if theyve renamed it, we're boned) */
186 char module[MAX_PATH];
187 if (GetModuleFileName(NULL, module, MAX_PATH))
190 me = Config->MyDir + "/inspircd";
193 if (execv(me.c_str(), Config->argv) == -1)
195 /* Will raise a SIGABRT if not trapped */
196 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
200 void InspIRCd::Start()
202 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
203 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
204 printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey\033[0m\n");
205 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
208 void InspIRCd::Rehash(int status)
210 SI->WriteOpers("*** Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(SI->ConfigFileName));
212 SI->OpenLog(SI->Config->argv, SI->Config->argc);
213 SI->RehashUsersAndChans();
214 FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
215 SI->Config->Read(false,NULL);
218 FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
222 void InspIRCd::ResetMaxBans()
224 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
225 i->second->ResetMaxBans();
229 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
230 * we must occasionally rehash the hash (yes really).
231 * We do this by copying the entries from the old hash to a new hash, causing all
232 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
233 * very expensive, so instead we do it when the user types /REHASH and expects a
234 * short delay anyway.
236 void InspIRCd::RehashUsersAndChans()
238 user_hash* old_users = this->clientlist;
239 chan_hash* old_chans = this->chanlist;
241 this->clientlist = new user_hash();
242 this->chanlist = new chan_hash();
244 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
245 this->clientlist->insert(*n);
249 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
250 this->chanlist->insert(*n);
255 void InspIRCd::CloseLog()
257 this->Logger->Close();
260 void InspIRCd::SetSignals()
263 signal(SIGALRM, SIG_IGN);
264 signal(SIGHUP, InspIRCd::Rehash);
265 signal(SIGPIPE, SIG_IGN);
266 signal(SIGCHLD, SIG_IGN);
268 signal(SIGTERM, InspIRCd::Exit);
271 void InspIRCd::QuickExit(int status)
276 bool InspIRCd::DaemonSeed()
281 signal(SIGTERM, InspIRCd::QuickExit);
284 if ((childpid = fork ()) < 0)
286 else if (childpid > 0)
288 /* We wait here for the child process to kill us,
289 * so that the shell prompt doesnt come back over
291 * Sending a kill with a signal of 0 just checks
292 * if the child pid is still around. If theyre not,
293 * they threw an error and we should give up.
295 while (kill(childpid, 0) != -1)
301 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
303 signal(SIGTERM, InspIRCd::Exit);
306 if (getrlimit(RLIMIT_CORE, &rl) == -1)
308 this->Log(DEFAULT,"Failed to getrlimit()!");
313 rl.rlim_cur = rl.rlim_max;
314 if (setrlimit(RLIMIT_CORE, &rl) == -1)
315 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
322 void InspIRCd::WritePID(const std::string &filename)
324 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
325 if (*(fname.begin()) != '/')
327 std::string::size_type pos;
328 std::string confpath = this->ConfigFileName;
329 if ((pos = confpath.rfind("/")) != std::string::npos)
331 /* Leaves us with just the path */
332 fname = confpath.substr(0, pos) + std::string("/") + fname;
335 std::ofstream outfile(fname.c_str());
336 if (outfile.is_open())
343 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
344 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
345 Exit(EXIT_STATUS_PID);
349 std::string InspIRCd::GetRevision()
354 InspIRCd::InspIRCd(int argc, char** argv)
355 : ModCount(-1), GlobalCulls(this)
360 WSAStartup(MAKEWORD(2,0), &wsadata);
365 int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0; /* flag variables */
370 memset(&server, 0, sizeof(server));
371 memset(&client, 0, sizeof(client));
373 this->unregistered_count = 0;
375 this->clientlist = new user_hash();
376 this->chanlist = new chan_hash();
378 this->Config = new ServerConfig(this);
380 this->Config->argv = argv;
381 this->Config->argc = argc;
383 chdir(Config->GetFullProgDir().c_str());
385 this->Config->opertypes.clear();
386 this->Config->operclass.clear();
387 this->SNO = new SnomaskManager(this);
388 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
389 this->time_delta = 0;
390 this->next_call = this->TIME + 3;
393 *this->LogFileName = 0;
394 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
396 struct option longopts[] =
398 { "nofork", no_argument, &do_nofork, 1 },
399 { "logfile", required_argument, NULL, 'f' },
400 { "config", required_argument, NULL, 'c' },
401 { "debug", no_argument, &do_debug, 1 },
402 { "nolog", no_argument, &do_nolog, 1 },
403 { "runasroot", no_argument, &do_root, 1 },
404 { "version", no_argument, &do_version, 1 },
408 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
413 /* Log filename was set */
414 strlcpy(LogFileName, optarg, MAXBUF);
415 printf("LOG: Setting logfile to %s\n", LogFileName);
418 /* Config filename was set */
419 strlcpy(ConfigFileName, optarg, MAXBUF);
420 printf("CONFIG: Setting config file to %s\n", ConfigFileName);
423 /* getopt_long_only() set an int variable, just keep going */
426 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
427 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
428 Exit(EXIT_STATUS_ARGV);
435 printf("\n%s r%s\n", VERSION, REVISION);
436 Exit(EXIT_STATUS_NOERROR);
439 if (!ServerConfig::FileExists(this->ConfigFileName))
441 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
442 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
443 Exit(EXIT_STATUS_CONFIG);
448 /* Set the finished argument values */
449 Config->nofork = do_nofork;
450 Config->forcedebug = do_debug;
451 Config->writelog = !do_nolog;
453 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
455 this->OpenLog(argv, argc);
457 this->stats = new serverstats();
458 this->Timers = new TimerManager(this);
459 this->Parser = new CommandParser(this);
460 this->XLines = new XLineManager(this);
461 Config->ClearStack();
462 Config->Read(true, NULL);
468 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
469 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
470 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
471 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
472 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
473 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
474 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
475 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
483 if (!this->DaemonSeed())
485 printf("ERROR: could not go into daemon mode. Shutting down.\n");
486 Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
487 Exit(EXIT_STATUS_FORK);
492 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
493 * initialize the socket engine.
495 SocketEngineFactory* SEF = new SocketEngineFactory();
496 SE = SEF->Create(this);
499 this->Modes = new ModeParser(this);
500 this->AddServerName(Config->ServerName);
502 int bounditems = BindPorts(true, found_ports, pl);
504 for(int t = 0; t < 255; t++)
505 Config->global_implementation[t] = 0;
507 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
511 this->Res = new DNS(this);
513 this->LoadAllModules();
514 /* Just in case no modules were loaded - fix for bug #101 */
515 this->BuildISupport();
516 InitializeDisabledCommands(Config->DisabledCommands, this);
518 if ((Config->ports.size() == 0) && (found_ports > 0))
520 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
521 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
522 Exit(EXIT_STATUS_BIND);
525 if (Config->ports.size() != (unsigned int)found_ports)
527 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
528 printf("The following port(s) failed to bind:\n");
530 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
532 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
538 if (kill(getppid(), SIGTERM) == -1)
540 printf("Error killing parent process: %s\n",strerror(errno));
541 Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
545 if (isatty(0) && isatty(1) && isatty(2))
547 /* We didn't start from a TTY, we must have started from a background process -
548 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
559 Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
563 printf("\nInspIRCd is now running!\n");
564 Log(DEFAULT,"Startup complete.");
566 this->WritePID(Config->PID);
573 // remove the console if in no-fork
580 std::string InspIRCd::GetVersionString()
582 char versiondata[MAXBUF];
583 char dnsengine[] = "singlethread-object";
585 if (*Config->CustomVersion)
587 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
591 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%s,%s,%s]",VERSION,Config->ServerName,SYSTEM,REVISION,SE->GetName().c_str(),dnsengine);
596 char* InspIRCd::ModuleError()
601 void InspIRCd::EraseFactory(int j)
604 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
610 factory.push_back(NULL);
617 void InspIRCd::EraseModule(int j)
620 for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
626 modules.push_back(NULL);
632 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
636 Config->module_names.erase(v);
644 void InspIRCd::MoveTo(std::string modulename,int slot)
646 unsigned int v2 = 256;
647 for (unsigned int v = 0; v < Config->module_names.size(); v++)
649 if (Config->module_names[v] == modulename)
651 // found an instance, swap it with the item at the end
656 if ((v2 != (unsigned int)slot) && (v2 < 256))
658 // Swap the module names over
659 Config->module_names[v2] = Config->module_names[slot];
660 Config->module_names[slot] = modulename;
661 // now swap the module factories
662 ircd_module* temp = factory[v2];
663 factory[v2] = factory[slot];
664 factory[slot] = temp;
665 // now swap the module objects
666 Module* temp_module = modules[v2];
667 modules[v2] = modules[slot];
668 modules[slot] = temp_module;
669 // now swap the implement lists (we dont
670 // need to swap the global or recount it)
671 for (int n = 0; n < 255; n++)
673 char x = Config->implement_lists[v2][n];
674 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
675 Config->implement_lists[slot][n] = x;
680 void InspIRCd::MoveAfter(std::string modulename, std::string after)
682 for (unsigned int v = 0; v < Config->module_names.size(); v++)
684 if (Config->module_names[v] == after)
686 MoveTo(modulename, v);
692 void InspIRCd::MoveBefore(std::string modulename, std::string before)
694 for (unsigned int v = 0; v < Config->module_names.size(); v++)
696 if (Config->module_names[v] == before)
700 MoveTo(modulename, v-1);
704 MoveTo(modulename, v);
711 void InspIRCd::MoveToFirst(std::string modulename)
713 MoveTo(modulename,0);
716 void InspIRCd::MoveToLast(std::string modulename)
718 MoveTo(modulename,this->GetModuleCount());
721 void InspIRCd::BuildISupport()
723 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
725 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES-1 << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << Config->MaxChans << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
726 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
727 v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32 ELIST=MU";
728 Config->data005 = v.str();
729 FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
733 bool InspIRCd::UnloadModule(const char* filename)
735 std::string filename_str = filename;
736 for (unsigned int j = 0; j != Config->module_names.size(); j++)
738 if (Config->module_names[j] == filename_str)
740 if (modules[j]->GetVersion().Flags & VF_STATIC)
742 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
743 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
746 std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modules[j]);
747 if (intercount.first > 0)
749 this->Log(DEFAULT,"Failed to unload module %s, being used by %d other(s) via interface '%s'",filename, intercount.first, intercount.second.c_str());
750 snprintf(MODERR,MAXBUF,"Module not unloadable (Still in use by %d other module%s which %s using its interface '%s') -- unload dependent modules first!",
752 intercount.first > 1 ? "s" : "",
753 intercount.first > 1 ? "are" : "is",
754 intercount.second.c_str());
757 /* Give the module a chance to tidy out all its metadata */
758 for (chan_hash::iterator c = this->chanlist->begin(); c != this->chanlist->end(); c++)
760 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
762 for (user_hash::iterator u = this->clientlist->begin(); u != this->clientlist->end(); u++)
764 modules[j]->OnCleanup(TYPE_USER,u->second);
767 /* Tidy up any dangling resolvers */
768 this->Res->CleanResolvers(modules[j]);
770 FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
772 for(int t = 0; t < 255; t++)
774 Config->global_implementation[t] -= Config->implement_lists[j][t];
777 /* We have to renumber implement_lists after unload because the module numbers change!
779 for(int j2 = j; j2 < 254; j2++)
781 for(int t = 0; t < 255; t++)
783 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
788 Parser->RemoveCommands(filename);
789 this->EraseModule(j);
790 this->EraseFactory(j);
791 this->Log(DEFAULT,"Module %s unloaded",filename);
797 this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
798 snprintf(MODERR,MAXBUF,"Module not loaded");
802 bool InspIRCd::LoadModule(const char* filename)
804 /* Do we have a glob pattern in the filename?
805 * The user wants to load multiple modules which
808 if (strchr(filename,'*') || (strchr(filename,'?')))
811 DIR* library = opendir(Config->ModPath);
814 /* Try and locate and load all modules matching the pattern */
815 dirent* entry = NULL;
816 while ((entry = readdir(library)))
818 if (this->MatchText(entry->d_name, filename))
820 if (!this->LoadModule(entry->d_name))
826 /* Loadmodule will now return false if any one of the modules failed
827 * to load (but wont abort when it encounters a bad one) and when 1 or
828 * more modules were actually loaded.
830 return (n_match > 0);
833 char modfile[MAXBUF];
834 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
835 std::string filename_str = filename;
837 if (!ServerConfig::DirValid(modfile))
839 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
840 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
843 if (ServerConfig::FileExists(modfile))
846 for (unsigned int j = 0; j < Config->module_names.size(); j++)
848 if (Config->module_names[j] == filename_str)
850 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
851 snprintf(MODERR,MAXBUF,"Module already loaded");
857 ircd_module* a = new ircd_module(this, modfile);
858 factory[this->ModCount+1] = a;
859 if (factory[this->ModCount+1]->LastError())
861 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
862 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
865 if ((long)factory[this->ModCount+1]->factory != -1)
867 Module* m = factory[this->ModCount+1]->factory->CreateModule(this);
869 Version v = m->GetVersion();
871 if (v.API != API_VERSION)
875 this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
876 snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
881 this->Log(DEFAULT,"New module introduced: %s (API version %d, Module version %d.%d.%d.%d)%s", filename, v.API, v.Major, v.Minor, v.Revision, v.Build, (!(v.Flags & VF_VENDOR) ? " [3rd Party]" : " [Vendor]"));
884 modules[this->ModCount+1] = m;
885 /* save the module and the module's classfactory, if
886 * this isnt done, random crashes can occur :/ */
887 Config->module_names.push_back(filename);
889 char* x = &Config->implement_lists[this->ModCount+1][0];
890 for(int t = 0; t < 255; t++)
893 modules[this->ModCount+1]->Implements(x);
895 for(int t = 0; t < 255; t++)
896 Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
900 this->Log(DEFAULT,"Unable to load %s",modfile);
901 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
905 catch (CoreException& modexcept)
907 this->Log(DEFAULT,"Unable to load %s: %s",modfile,modexcept.GetReason());
908 snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
914 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
915 snprintf(MODERR,MAXBUF,"Module file could not be found");
919 FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
920 // now work out which modules, if any, want to move to the back of the queue,
921 // and if they do, move them there.
922 std::vector<std::string> put_to_back;
923 std::vector<std::string> put_to_front;
924 std::map<std::string,std::string> put_before;
925 std::map<std::string,std::string> put_after;
926 for (unsigned int j = 0; j < Config->module_names.size(); j++)
928 if (modules[j]->Prioritize() == PRIORITY_LAST)
929 put_to_back.push_back(Config->module_names[j]);
930 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
931 put_to_front.push_back(Config->module_names[j]);
932 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
933 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
934 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
935 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
937 for (unsigned int j = 0; j < put_to_back.size(); j++)
938 MoveToLast(put_to_back[j]);
939 for (unsigned int j = 0; j < put_to_front.size(); j++)
940 MoveToFirst(put_to_front[j]);
941 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
942 MoveBefore(j->first,j->second);
943 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
944 MoveAfter(j->first,j->second);
949 void InspIRCd::DoOneIteration(bool process_module_sockets)
954 static time_t uptime;
955 static struct tm * stime;
956 static char window_title[100];
959 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
960 * Once per loop iteration is pleanty.
965 /* Run background module timers every few seconds
966 * (the docs say modules shouldnt rely on accurate
967 * timing using this event, so we dont have to
968 * time this exactly).
973 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
974 if ((TIME % 3600) == 0)
976 this->RehashUsersAndChans();
977 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
979 Timers->TickTimers(TIME);
980 this->DoBackgroundUserStuff(TIME);
984 XLines->expire_lines();
985 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
986 Timers->TickMissedTimers(TIME);
989 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
990 if (!getrusage(RUSAGE_SELF, &ru))
992 gettimeofday(&this->stats->LastSampled, NULL);
993 this->stats->LastCPU = ru.ru_utime;
1000 uptime = Time() - startup_time;
1001 stime = gmtime(&uptime);
1002 snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
1003 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
1004 SetConsoleTitle(window_title);
1009 /* Call the socket engine to wait on the active
1010 * file descriptors. The socket engine has everything's
1011 * descriptors in its list... dns, modules, users,
1012 * servers... so its nice and easy, just one call.
1013 * This will cause any read or write events to be
1014 * dispatched to their handlers.
1016 SE->DispatchEvents();
1018 /* if any users was quit, take them out */
1019 GlobalCulls.Apply();
1021 /* If any inspsockets closed, remove them */
1022 for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
1024 SE->DelFd(x->second);
1035 DoOneIteration(true);
1037 /* This is never reached -- we hope! */
1041 /**********************************************************************************/
1044 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
1047 int main(int argc, char** argv)
1049 SI = new InspIRCd(argc, argv);
1055 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
1056 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
1057 * registration timeout maximum seconds)
1059 bool InspIRCd::AllModulesReportReady(userrec* user)
1061 if (!Config->global_implementation[I_OnCheckReady])
1064 for (int i = 0; i <= this->GetModuleCount(); i++)
1066 if (Config->implement_lists[i][I_OnCheckReady])
1068 int res = modules[i]->OnCheckReady(user);
1076 int InspIRCd::GetModuleCount()
1078 return this->ModCount;
1081 time_t InspIRCd::Time(bool delta)
1084 return TIME + time_delta;
1088 int InspIRCd::SetTimeDelta(int delta)
1090 int old = time_delta;
1092 this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
1096 void InspIRCd::AddLocalClone(userrec* user)
1098 clonemap::iterator x = local_clones.find(user->GetIPString());
1099 if (x != local_clones.end())
1102 local_clones[user->GetIPString()] = 1;
1105 void InspIRCd::AddGlobalClone(userrec* user)
1107 clonemap::iterator y = global_clones.find(user->GetIPString());
1108 if (y != global_clones.end())
1111 global_clones[user->GetIPString()] = 1;
1114 int InspIRCd::GetTimeDelta()
1119 bool FileLogger::Readable()
1124 void FileLogger::HandleEvent(EventType et, int errornum)
1126 this->WriteLogLine("");
1128 ServerInstance->SE->DelFd(this);
1131 void FileLogger::WriteLogLine(const std::string &line)
1134 buffer.append(line);
1138 int written = fprintf(log,"%s",buffer.c_str());
1142 if ((written >= 0) && (written < (int)buffer.length()))
1144 buffer.erase(0, buffer.length());
1145 ServerInstance->SE->AddFd(this);
1147 else if (written == -1)
1149 if (errno == EAGAIN)
1150 ServerInstance->SE->AddFd(this);
1154 /* Wrote the whole buffer, and no need for write callback */
1158 if (writeops++ % 20)
1165 void FileLogger::Close()
1169 /* Burlex: Windows assumes nonblocking on FILE* pointers anyway, and also "file" fd's aren't the same
1170 * as socket fd's. */
1172 int flags = fcntl(fileno(log), F_GETFL, 0);
1173 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
1176 fprintf(log,"%s",buffer.c_str());
1179 ServerInstance->SE->DelFd(this);
1189 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
1193 irc::sockets::NonBlocking(fileno(log));
1194 this->SetFd(fileno(log));
1199 FileLogger::~FileLogger()