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"
26 #include "socketengine.h"
27 #include "inspircd_se_config.h"
30 #include "command_parse.h"
31 #include "exitcodes.h"
38 using irc::sockets::NonBlocking;
39 using irc::sockets::Blocking;
40 using irc::sockets::insp_ntoa;
41 using irc::sockets::insp_inaddr;
42 using irc::sockets::insp_sockaddr;
46 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
47 const char* ExitCodes[] =
50 "DIE command", /* 1 */
51 "execv() failed", /* 2 */
52 "Internal error", /* 3 */
53 "Config file error", /* 4 */
54 "Logfile error", /* 5 */
55 "Fork failed", /* 6 */
56 "Bad commandline parameters", /* 7 */
57 "No ports could be bound", /* 8 */
58 "Can't write PID file", /* 9 */
59 "SocketEngine could not initialize", /* 10 */
60 "Refusing to start up as root", /* 11 */
61 "Found a <die> tag!", /* 12 */
62 "Couldn't load module on startup", /* 13 */
64 "Received SIGTERM", /* 15 */
67 void InspIRCd::AddServerName(const std::string &servername)
69 servernamelist::iterator itr = servernames.begin();
70 for(; itr != servernames.end(); ++itr)
71 if(**itr == servername)
74 string * ns = new string(servername);
75 servernames.push_back(ns);
78 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
80 servernamelist::iterator itr = servernames.begin();
81 for(; itr != servernames.end(); ++itr)
82 if(**itr == servername)
83 return (*itr)->c_str();
85 servernames.push_back(new string(servername));
86 itr = --servernames.end();
87 return (*itr)->c_str();
90 bool InspIRCd::FindServerName(const std::string &servername)
92 servernamelist::iterator itr = servernames.begin();
93 for(; itr != servernames.end(); ++itr)
94 if(**itr == servername)
99 void InspIRCd::Exit(int status)
106 SI->SendError("Exiting with status " + ConvToStr(status) + " (" + std::string(ExitCodes[status]) + ")");
112 void InspIRCd::Cleanup()
114 std::vector<std::string> mymodnames;
115 int MyModCount = this->GetModuleCount();
117 for (unsigned int i = 0; i < Config->ports.size(); i++)
119 /* This calls the constructor and closes the listening socket */
120 delete Config->ports[i];
123 Config->ports.clear();
125 /* Close all client sockets, or the new process inherits them */
126 for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
128 (*i)->SetWriteError("Server shutdown");
132 /* We do this more than once, so that any service providers get a
133 * chance to be unhooked by the modules using them, but then get
134 * a chance to be removed themsleves.
136 for (int tries = 0; tries < 3; tries++)
138 MyModCount = this->GetModuleCount();
141 /* Unload all modules, so they get a chance to clean up their listeners */
142 for (int j = 0; j <= MyModCount; j++)
143 mymodnames.push_back(Config->module_names[j]);
145 for (int k = 0; k <= MyModCount; k++)
146 this->UnloadModule(mymodnames[k].c_str());
150 this->Logger->Close();
152 /* Cleanup Server Names */
153 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
162 void InspIRCd::Restart(const std::string &reason)
164 /* SendError flushes each client's queue,
165 * regardless of writeability state
167 this->SendError(reason);
171 /* Figure out our filename (if theyve renamed it, we're boned) */
175 char module[MAX_PATH];
176 if (GetModuleFileName(NULL, module, MAX_PATH))
179 me = Config->MyDir + "/inspircd";
182 if (execv(me.c_str(), Config->argv) == -1)
184 /* Will raise a SIGABRT if not trapped */
185 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
189 void InspIRCd::Start()
191 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
192 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
193 printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey\033[0m\n");
194 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
197 void InspIRCd::Rehash(int status)
199 SI->WriteOpers("*** Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(SI->ConfigFileName));
201 SI->OpenLog(SI->Config->argv, SI->Config->argc);
202 SI->RehashUsersAndChans();
203 FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
204 SI->Config->Read(false,NULL);
207 FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
211 void InspIRCd::ResetMaxBans()
213 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
214 i->second->ResetMaxBans();
218 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
219 * we must occasionally rehash the hash (yes really).
220 * We do this by copying the entries from the old hash to a new hash, causing all
221 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
222 * very expensive, so instead we do it when the user types /REHASH and expects a
223 * short delay anyway.
225 void InspIRCd::RehashUsersAndChans()
227 user_hash* old_users = this->clientlist;
228 chan_hash* old_chans = this->chanlist;
230 this->clientlist = new user_hash();
231 this->chanlist = new chan_hash();
233 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
234 this->clientlist->insert(*n);
238 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
239 this->chanlist->insert(*n);
244 void InspIRCd::CloseLog()
246 this->Logger->Close();
249 void InspIRCd::SetSignals()
252 signal(SIGALRM, SIG_IGN);
253 signal(SIGHUP, InspIRCd::Rehash);
254 signal(SIGPIPE, SIG_IGN);
255 signal(SIGCHLD, SIG_IGN);
257 signal(SIGTERM, InspIRCd::Exit);
260 void InspIRCd::QuickExit(int status)
265 bool InspIRCd::DaemonSeed()
268 // Create process, with argument --service
270 PROCESS_INFORMATION pi;
271 memset(&si, 0, sizeof(si));
272 memset(&pi, 0, sizeof(pi));
273 SHELLEXECUTEINFO sh = {0};
274 sh.cbSize = sizeof(sh);
275 sh.fMask = SEE_MASK_NOCLOSEPROCESS;
281 sh.lpFile = "inspircd.exe";
282 sh.lpParameters = "--service";
283 if(!ShellExecuteEx(&sh))
286 CloseHandle(sh.hProcess);
290 signal(SIGTERM, InspIRCd::QuickExit);
293 if ((childpid = fork ()) < 0)
295 else if (childpid > 0)
297 /* We wait here for the child process to kill us,
298 * so that the shell prompt doesnt come back over
300 * Sending a kill with a signal of 0 just checks
301 * if the child pid is still around. If theyre not,
302 * they threw an error and we should give up.
304 while (kill(childpid, 0) != -1)
310 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
312 signal(SIGTERM, InspIRCd::Exit);
315 if (getrlimit(RLIMIT_CORE, &rl) == -1)
317 this->Log(DEFAULT,"Failed to getrlimit()!");
322 rl.rlim_cur = rl.rlim_max;
323 if (setrlimit(RLIMIT_CORE, &rl) == -1)
324 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
331 void InspIRCd::WritePID(const std::string &filename)
333 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
334 if (*(fname.begin()) != '/')
336 std::string::size_type pos;
337 std::string confpath = this->ConfigFileName;
338 if ((pos = confpath.rfind("/")) != std::string::npos)
340 /* Leaves us with just the path */
341 fname = confpath.substr(0, pos) + std::string("/") + fname;
344 std::ofstream outfile(fname.c_str());
345 if (outfile.is_open())
352 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
353 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
354 Exit(EXIT_STATUS_PID);
358 std::string InspIRCd::GetRevision()
363 InspIRCd::InspIRCd(int argc, char** argv)
364 : ModCount(-1), duration_m(60), duration_h(60*60), duration_d(60*60*24), duration_w(60*60*24*7), duration_y(60*60*24*365), GlobalCulls(this)
368 WSAStartup(MAKEWORD(2,0), &wsadata);
373 int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0, is_service = 0; /* flag variables */
378 memset(&server, 0, sizeof(server));
379 memset(&client, 0, sizeof(client));
381 this->unregistered_count = 0;
383 this->clientlist = new user_hash();
384 this->chanlist = new chan_hash();
386 this->Config = new ServerConfig(this);
388 this->Config->argv = argv;
389 this->Config->argc = argc;
391 this->Config->opertypes.clear();
392 this->Config->operclass.clear();
393 this->SNO = new SnomaskManager(this);
394 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
395 this->time_delta = 0;
396 this->next_call = this->TIME + 3;
399 *this->LogFileName = 0;
400 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
402 struct option longopts[] =
404 { "nofork", no_argument, &do_nofork, 1 },
405 { "logfile", required_argument, NULL, 'f' },
406 { "config", required_argument, NULL, 'c' },
407 { "debug", no_argument, &do_debug, 1 },
408 { "nolog", no_argument, &do_nolog, 1 },
409 { "runasroot", no_argument, &do_root, 1 },
410 { "version", no_argument, &do_version, 1 },
411 { "service", no_argument, &is_service, 1 },
415 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
420 /* Log filename was set */
421 strlcpy(LogFileName, optarg, MAXBUF);
422 printf("LOG: Setting logfile to %s\n", LogFileName);
425 /* Config filename was set */
426 strlcpy(ConfigFileName, optarg, MAXBUF);
427 printf("CONFIG: Setting config file to %s\n", ConfigFileName);
430 /* getopt_long_only() set an int variable, just keep going */
433 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
434 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
435 Exit(EXIT_STATUS_ARGV);
447 printf("\n%s r%s\n", VERSION, REVISION);
448 Exit(EXIT_STATUS_NOERROR);
451 if (!ServerConfig::FileExists(this->ConfigFileName))
453 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
454 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
455 Exit(EXIT_STATUS_CONFIG);
460 /* Set the finished argument values */
461 Config->nofork = do_nofork;
462 Config->forcedebug = do_debug;
463 Config->writelog = !do_nolog;
465 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
467 this->OpenLog(argv, argc);
469 this->stats = new serverstats();
470 this->Timers = new TimerManager(this);
471 this->Parser = new CommandParser(this);
472 this->XLines = new XLineManager(this);
473 Config->ClearStack();
474 Config->Read(true, NULL);
480 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
481 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
482 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
483 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
484 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
485 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
486 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
487 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
495 if (!is_service && !this->DaemonSeed())
497 printf("ERROR: could not go into daemon mode. Shutting down.\n");
498 Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
499 Exit(EXIT_STATUS_FORK);
504 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
505 * initialize the socket engine.
507 SocketEngineFactory* SEF = new SocketEngineFactory();
508 SE = SEF->Create(this);
511 this->Modes = new ModeParser(this);
512 this->AddServerName(Config->ServerName);
514 int bounditems = BindPorts(true, found_ports, pl);
516 for(int t = 0; t < 255; t++)
517 Config->global_implementation[t] = 0;
519 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
523 this->Res = new DNS(this);
525 this->LoadAllModules();
526 /* Just in case no modules were loaded - fix for bug #101 */
527 this->BuildISupport();
528 InitializeDisabledCommands(Config->DisabledCommands, this);
530 if ((Config->ports.size() == 0) && (found_ports > 0))
532 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
533 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
534 Exit(EXIT_STATUS_BIND);
537 if (Config->ports.size() != (unsigned int)found_ports)
539 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
540 printf("The following port(s) failed to bind:\n");
542 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
544 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
550 if (kill(getppid(), SIGTERM) == -1)
552 printf("Error killing parent process: %s\n",strerror(errno));
553 Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
557 if (isatty(0) && isatty(1) && isatty(2))
559 /* We didn't start from a TTY, we must have started from a background process -
560 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
571 Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
575 printf("\nInspIRCd is now running!\n");
576 Log(DEFAULT,"Startup complete.");
578 this->WritePID(Config->PID);
585 std::string InspIRCd::GetVersionString()
587 char versiondata[MAXBUF];
588 char dnsengine[] = "singlethread-object";
590 if (*Config->CustomVersion)
592 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
596 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%s,%s,%s]",VERSION,Config->ServerName,SYSTEM,REVISION,SE->GetName().c_str(),dnsengine);
601 char* InspIRCd::ModuleError()
606 void InspIRCd::EraseFactory(int j)
609 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
615 factory.push_back(NULL);
622 void InspIRCd::EraseModule(int j)
625 for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
631 modules.push_back(NULL);
637 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
641 Config->module_names.erase(v);
649 void InspIRCd::MoveTo(std::string modulename,int slot)
651 unsigned int v2 = 256;
652 for (unsigned int v = 0; v < Config->module_names.size(); v++)
654 if (Config->module_names[v] == modulename)
656 // found an instance, swap it with the item at the end
661 if ((v2 != (unsigned int)slot) && (v2 < 256))
663 // Swap the module names over
664 Config->module_names[v2] = Config->module_names[slot];
665 Config->module_names[slot] = modulename;
666 // now swap the module factories
667 ircd_module* temp = factory[v2];
668 factory[v2] = factory[slot];
669 factory[slot] = temp;
670 // now swap the module objects
671 Module* temp_module = modules[v2];
672 modules[v2] = modules[slot];
673 modules[slot] = temp_module;
674 // now swap the implement lists (we dont
675 // need to swap the global or recount it)
676 for (int n = 0; n < 255; n++)
678 char x = Config->implement_lists[v2][n];
679 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
680 Config->implement_lists[slot][n] = x;
685 void InspIRCd::MoveAfter(std::string modulename, std::string after)
687 for (unsigned int v = 0; v < Config->module_names.size(); v++)
689 if (Config->module_names[v] == after)
691 MoveTo(modulename, v);
697 void InspIRCd::MoveBefore(std::string modulename, std::string before)
699 for (unsigned int v = 0; v < Config->module_names.size(); v++)
701 if (Config->module_names[v] == before)
705 MoveTo(modulename, v-1);
709 MoveTo(modulename, v);
716 void InspIRCd::MoveToFirst(std::string modulename)
718 MoveTo(modulename,0);
721 void InspIRCd::MoveToLast(std::string modulename)
723 MoveTo(modulename,this->GetModuleCount());
726 void InspIRCd::BuildISupport()
728 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
730 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES-1 << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << Config->MaxChans << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
731 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
732 v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32 ELIST=MU";
733 Config->data005 = v.str();
734 FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
738 bool InspIRCd::UnloadModule(const char* filename)
740 std::string filename_str = filename;
741 for (unsigned int j = 0; j != Config->module_names.size(); j++)
743 if (Config->module_names[j] == filename_str)
745 if (modules[j]->GetVersion().Flags & VF_STATIC)
747 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
748 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
751 std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modules[j]);
752 if (intercount.first > 0)
754 this->Log(DEFAULT,"Failed to unload module %s, being used by %d other(s) via interface '%s'",filename, intercount.first, intercount.second.c_str());
755 snprintf(MODERR,MAXBUF,"Module not unloadable (Still in use by %d other module%s which %s using its interface '%s') -- unload dependent modules first!",
757 intercount.first > 1 ? "s" : "",
758 intercount.first > 1 ? "are" : "is",
759 intercount.second.c_str());
762 /* Give the module a chance to tidy out all its metadata */
763 for (chan_hash::iterator c = this->chanlist->begin(); c != this->chanlist->end(); c++)
765 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
767 for (user_hash::iterator u = this->clientlist->begin(); u != this->clientlist->end(); u++)
769 modules[j]->OnCleanup(TYPE_USER,u->second);
772 /* Tidy up any dangling resolvers */
773 this->Res->CleanResolvers(modules[j]);
775 FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
777 for(int t = 0; t < 255; t++)
779 Config->global_implementation[t] -= Config->implement_lists[j][t];
782 /* We have to renumber implement_lists after unload because the module numbers change!
784 for(int j2 = j; j2 < 254; j2++)
786 for(int t = 0; t < 255; t++)
788 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
793 Parser->RemoveCommands(filename);
794 this->EraseModule(j);
795 this->EraseFactory(j);
796 this->Log(DEFAULT,"Module %s unloaded",filename);
802 this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
803 snprintf(MODERR,MAXBUF,"Module not loaded");
807 bool InspIRCd::LoadModule(const char* filename)
809 /* Do we have a glob pattern in the filename?
810 * The user wants to load multiple modules which
813 if (strchr(filename,'*') || (strchr(filename,'?')))
816 DIR* library = opendir(Config->ModPath);
819 /* Try and locate and load all modules matching the pattern */
820 dirent* entry = NULL;
821 while ((entry = readdir(library)))
823 if (this->MatchText(entry->d_name, filename))
825 if (!this->LoadModule(entry->d_name))
831 /* Loadmodule will now return false if any one of the modules failed
832 * to load (but wont abort when it encounters a bad one) and when 1 or
833 * more modules were actually loaded.
835 return (n_match > 0);
838 char modfile[MAXBUF];
839 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
840 std::string filename_str = filename;
842 if (!ServerConfig::DirValid(modfile))
844 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
845 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
848 if (ServerConfig::FileExists(modfile))
851 for (unsigned int j = 0; j < Config->module_names.size(); j++)
853 if (Config->module_names[j] == filename_str)
855 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
856 snprintf(MODERR,MAXBUF,"Module already loaded");
862 ircd_module* a = new ircd_module(this, modfile);
863 factory[this->ModCount+1] = a;
864 if (factory[this->ModCount+1]->LastError())
866 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
867 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
870 if ((long)factory[this->ModCount+1]->factory != -1)
872 Module* m = factory[this->ModCount+1]->factory->CreateModule(this);
874 Version v = m->GetVersion();
876 if (v.API != API_VERSION)
880 this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
881 snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
886 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]"));
889 modules[this->ModCount+1] = m;
890 /* save the module and the module's classfactory, if
891 * this isnt done, random crashes can occur :/ */
892 Config->module_names.push_back(filename);
894 char* x = &Config->implement_lists[this->ModCount+1][0];
895 for(int t = 0; t < 255; t++)
898 modules[this->ModCount+1]->Implements(x);
900 for(int t = 0; t < 255; t++)
901 Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
905 this->Log(DEFAULT,"Unable to load %s",modfile);
906 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
910 catch (CoreException& modexcept)
912 this->Log(DEFAULT,"Unable to load %s: %s",modfile,modexcept.GetReason());
913 snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
919 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
920 snprintf(MODERR,MAXBUF,"Module file could not be found");
924 FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
925 // now work out which modules, if any, want to move to the back of the queue,
926 // and if they do, move them there.
927 std::vector<std::string> put_to_back;
928 std::vector<std::string> put_to_front;
929 std::map<std::string,std::string> put_before;
930 std::map<std::string,std::string> put_after;
931 for (unsigned int j = 0; j < Config->module_names.size(); j++)
933 if (modules[j]->Prioritize() == PRIORITY_LAST)
934 put_to_back.push_back(Config->module_names[j]);
935 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
936 put_to_front.push_back(Config->module_names[j]);
937 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
938 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
939 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
940 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
942 for (unsigned int j = 0; j < put_to_back.size(); j++)
943 MoveToLast(put_to_back[j]);
944 for (unsigned int j = 0; j < put_to_front.size(); j++)
945 MoveToFirst(put_to_front[j]);
946 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
947 MoveBefore(j->first,j->second);
948 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
949 MoveAfter(j->first,j->second);
954 void InspIRCd::DoOneIteration(bool process_module_sockets)
960 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
961 * Once per loop iteration is pleanty.
966 /* Run background module timers every few seconds
967 * (the docs say modules shouldnt rely on accurate
968 * timing using this event, so we dont have to
969 * time this exactly).
974 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
975 if ((TIME % 3600) == 0)
977 this->RehashUsersAndChans();
978 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
980 Timers->TickTimers(TIME);
981 this->DoBackgroundUserStuff(TIME);
985 XLines->expire_lines();
986 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
987 Timers->TickMissedTimers(TIME);
990 if (!getrusage(0, &ru))
992 gettimeofday(&this->stats->LastSampled, NULL);
993 this->stats->LastCPU = ru.ru_utime;
1000 /* Call the socket engine to wait on the active
1001 * file descriptors. The socket engine has everything's
1002 * descriptors in its list... dns, modules, users,
1003 * servers... so its nice and easy, just one call.
1004 * This will cause any read or write events to be
1005 * dispatched to their handlers.
1007 SE->DispatchEvents();
1009 /* if any users was quit, take them out */
1010 GlobalCulls.Apply();
1012 /* If any inspsockets closed, remove them */
1013 for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
1015 SE->DelFd(x->second);
1026 DoOneIteration(true);
1028 /* This is never reached -- we hope! */
1032 /**********************************************************************************/
1035 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
1038 int main(int argc, char** argv)
1040 SI = new InspIRCd(argc, argv);
1046 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
1047 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
1048 * registration timeout maximum seconds)
1050 bool InspIRCd::AllModulesReportReady(userrec* user)
1052 if (!Config->global_implementation[I_OnCheckReady])
1055 for (int i = 0; i <= this->GetModuleCount(); i++)
1057 if (Config->implement_lists[i][I_OnCheckReady])
1059 int res = modules[i]->OnCheckReady(user);
1067 int InspIRCd::GetModuleCount()
1069 return this->ModCount;
1072 time_t InspIRCd::Time(bool delta)
1075 return TIME + time_delta;
1079 int InspIRCd::SetTimeDelta(int delta)
1081 int old = time_delta;
1083 this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
1087 void InspIRCd::AddLocalClone(userrec* user)
1089 clonemap::iterator x = local_clones.find(user->GetIPString());
1090 if (x != local_clones.end())
1093 local_clones[user->GetIPString()] = 1;
1096 void InspIRCd::AddGlobalClone(userrec* user)
1098 clonemap::iterator y = global_clones.find(user->GetIPString());
1099 if (y != global_clones.end())
1102 global_clones[user->GetIPString()] = 1;
1105 int InspIRCd::GetTimeDelta()
1110 bool FileLogger::Readable()
1115 void FileLogger::HandleEvent(EventType et, int errornum)
1117 this->WriteLogLine("");
1119 ServerInstance->SE->DelFd(this);
1122 void FileLogger::WriteLogLine(const std::string &line)
1125 buffer.append(line);
1129 int written = fprintf(log,"%s",buffer.c_str());
1133 if ((written >= 0) && (written < (int)buffer.length()))
1135 buffer.erase(0, buffer.length());
1136 ServerInstance->SE->AddFd(this);
1138 else if (written == -1)
1140 if (errno == EAGAIN)
1141 ServerInstance->SE->AddFd(this);
1145 /* Wrote the whole buffer, and no need for write callback */
1149 if (writeops++ % 20)
1156 void FileLogger::Close()
1160 /* Burlex: Windows assumes nonblocking on FILE* pointers anyway, and also "file" fd's aren't the same
1161 * as socket fd's. */
1163 int flags = fcntl(fileno(log), F_GETFL, 0);
1164 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
1167 fprintf(log,"%s",buffer.c_str());
1170 ServerInstance->SE->DelFd(this);
1180 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
1184 irc::sockets::NonBlocking(fileno(log));
1185 this->SetFd(fileno(log));
1190 FileLogger::~FileLogger()