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"
45 static DWORD owner_processid = 0;
47 DWORD WindowsForkStart(InspIRCd * Instance)
49 /* Windows implementation of fork() :P */
50 // Build the command line arguments.
52 for(int i = 0; i < Instance->Config->argc; ++i)
53 command_line += Instance->Config->argv[i];
55 char module[MAX_PATH];
56 if(!GetModuleFileName(NULL, module, MAX_PATH))
59 STARTUPINFO startupinfo;
60 PROCESS_INFORMATION procinfo;
61 ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
62 ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
64 // Fill in the startup info struct
65 GetStartupInfo(&startupinfo);
67 // Create the "startup" event
68 HANDLE fork_event = CreateEvent(0, TRUE, FALSE, "InspStartup");
72 // Launch our "forked" process.
73 BOOL bSuccess = CreateProcess ( module, module,
74 0, // PROCESS_SECURITY_ATTRIBUTES
75 0, // THREAD_SECURITY_ATTRIBUTES
76 TRUE, // We went to inherit handles.
77 CREATE_SUSPENDED | // Suspend the primary thread of the new process
78 CREATE_PRESERVE_CODE_AUTHZ_LEVEL, // Allow us full access to the process
80 0, // CURRENT_DIRECTORY
81 &startupinfo, // startup info
82 &procinfo); // process info
87 // Set the owner process id in the target process.
89 DWORD pid = GetCurrentProcessId();
90 if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
93 // Resume the other thread (let it start)
94 ResumeThread(procinfo.hThread);
96 // Wait for the new process to kill us. If there is some error, the new process will end and we will end up at the next line.
97 WaitForSingleObject(procinfo.hProcess, INFINITE);
99 // If we hit this it means startup failed, default to 14 if this fails.
101 GetExitCodeProcess(procinfo.hProcess, &ExitCode);
102 CloseHandle(procinfo.hThread);
106 void WindowsForkKillOwner(InspIRCd * Instance)
108 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
109 if(!hProcess || !owner_processid)
113 if(!TerminateProcess(hProcess, 0))
116 CloseHandle(hProcess);
121 using irc::sockets::NonBlocking;
122 using irc::sockets::Blocking;
123 using irc::sockets::insp_ntoa;
124 using irc::sockets::insp_inaddr;
125 using irc::sockets::insp_sockaddr;
129 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
130 const char* ExitCodes[] =
133 "DIE command", /* 1 */
134 "execv() failed", /* 2 */
135 "Internal error", /* 3 */
136 "Config file error", /* 4 */
137 "Logfile error", /* 5 */
138 "Fork failed", /* 6 */
139 "Bad commandline parameters", /* 7 */
140 "No ports could be bound", /* 8 */
141 "Can't write PID file", /* 9 */
142 "SocketEngine could not initialize", /* 10 */
143 "Refusing to start up as root", /* 11 */
144 "Found a <die> tag!", /* 12 */
145 "Couldn't load module on startup", /* 13 */
146 "Could not create forked process", /* 14 */
147 "Received SIGTERM", /* 15 */
150 void InspIRCd::AddServerName(const std::string &servername)
152 servernamelist::iterator itr = servernames.begin();
153 for(; itr != servernames.end(); ++itr)
154 if(**itr == servername)
157 string * ns = new string(servername);
158 servernames.push_back(ns);
161 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
163 servernamelist::iterator itr = servernames.begin();
164 for(; itr != servernames.end(); ++itr)
165 if(**itr == servername)
166 return (*itr)->c_str();
168 servernames.push_back(new string(servername));
169 itr = --servernames.end();
170 return (*itr)->c_str();
173 bool InspIRCd::FindServerName(const std::string &servername)
175 servernamelist::iterator itr = servernames.begin();
176 for(; itr != servernames.end(); ++itr)
177 if(**itr == servername)
182 void InspIRCd::Exit(int status)
189 SI->SendError("Exiting with status " + ConvToStr(status) + " (" + std::string(ExitCodes[status]) + ")");
195 void InspIRCd::Cleanup()
197 std::vector<std::string> mymodnames;
198 int MyModCount = this->GetModuleCount();
200 for (unsigned int i = 0; i < Config->ports.size(); i++)
202 /* This calls the constructor and closes the listening socket */
203 delete Config->ports[i];
206 Config->ports.clear();
208 /* Close all client sockets, or the new process inherits them */
209 for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
211 (*i)->SetWriteError("Server shutdown");
215 /* We do this more than once, so that any service providers get a
216 * chance to be unhooked by the modules using them, but then get
217 * a chance to be removed themsleves.
219 for (int tries = 0; tries < 3; tries++)
221 MyModCount = this->GetModuleCount();
224 /* Unload all modules, so they get a chance to clean up their listeners */
225 for (int j = 0; j <= MyModCount; j++)
226 mymodnames.push_back(Config->module_names[j]);
228 for (int k = 0; k <= MyModCount; k++)
229 this->UnloadModule(mymodnames[k].c_str());
233 this->Logger->Close();
235 /* Cleanup Server Names */
236 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
245 void InspIRCd::Restart(const std::string &reason)
247 /* SendError flushes each client's queue,
248 * regardless of writeability state
250 this->SendError(reason);
254 /* Figure out our filename (if theyve renamed it, we're boned) */
258 char module[MAX_PATH];
259 if (GetModuleFileName(NULL, module, MAX_PATH))
262 me = Config->MyDir + "/inspircd";
265 if (execv(me.c_str(), Config->argv) == -1)
267 /* Will raise a SIGABRT if not trapped */
268 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
272 void InspIRCd::Start()
274 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
275 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
276 printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey, Burlex\033[0m\n");
277 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
280 void InspIRCd::Rehash(int status)
282 SI->WriteOpers("*** Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(SI->ConfigFileName));
284 SI->OpenLog(SI->Config->argv, SI->Config->argc);
285 SI->RehashUsersAndChans();
286 FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
287 SI->Config->Read(false,NULL);
290 FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
294 void InspIRCd::ResetMaxBans()
296 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
297 i->second->ResetMaxBans();
301 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
302 * we must occasionally rehash the hash (yes really).
303 * We do this by copying the entries from the old hash to a new hash, causing all
304 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
305 * very expensive, so instead we do it when the user types /REHASH and expects a
306 * short delay anyway.
308 void InspIRCd::RehashUsersAndChans()
310 user_hash* old_users = this->clientlist;
311 chan_hash* old_chans = this->chanlist;
313 this->clientlist = new user_hash();
314 this->chanlist = new chan_hash();
316 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
317 this->clientlist->insert(*n);
321 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
322 this->chanlist->insert(*n);
327 void InspIRCd::CloseLog()
329 this->Logger->Close();
332 void InspIRCd::SetSignals()
335 signal(SIGALRM, SIG_IGN);
336 signal(SIGHUP, InspIRCd::Rehash);
337 signal(SIGPIPE, SIG_IGN);
338 signal(SIGCHLD, SIG_IGN);
340 signal(SIGTERM, InspIRCd::Exit);
343 void InspIRCd::QuickExit(int status)
348 bool InspIRCd::DaemonSeed()
353 signal(SIGTERM, InspIRCd::QuickExit);
356 if ((childpid = fork ()) < 0)
358 else if (childpid > 0)
360 /* We wait here for the child process to kill us,
361 * so that the shell prompt doesnt come back over
363 * Sending a kill with a signal of 0 just checks
364 * if the child pid is still around. If theyre not,
365 * they threw an error and we should give up.
367 while (kill(childpid, 0) != -1)
373 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
375 signal(SIGTERM, InspIRCd::Exit);
378 if (getrlimit(RLIMIT_CORE, &rl) == -1)
380 this->Log(DEFAULT,"Failed to getrlimit()!");
385 rl.rlim_cur = rl.rlim_max;
386 if (setrlimit(RLIMIT_CORE, &rl) == -1)
387 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
394 void InspIRCd::WritePID(const std::string &filename)
396 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
397 if (*(fname.begin()) != '/')
399 std::string::size_type pos;
400 std::string confpath = this->ConfigFileName;
401 if ((pos = confpath.rfind("/")) != std::string::npos)
403 /* Leaves us with just the path */
404 fname = confpath.substr(0, pos) + std::string("/") + fname;
407 std::ofstream outfile(fname.c_str());
408 if (outfile.is_open())
415 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
416 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
417 Exit(EXIT_STATUS_PID);
421 std::string InspIRCd::GetRevision()
426 InspIRCd::InspIRCd(int argc, char** argv)
427 : ModCount(-1), GlobalCulls(this)
431 int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0; /* flag variables */
436 memset(&server, 0, sizeof(server));
437 memset(&client, 0, sizeof(client));
439 this->unregistered_count = 0;
441 this->clientlist = new user_hash();
442 this->chanlist = new chan_hash();
444 this->Config = new ServerConfig(this);
446 this->Config->argv = argv;
447 this->Config->argc = argc;
449 chdir(Config->GetFullProgDir().c_str());
451 this->Config->opertypes.clear();
452 this->Config->operclass.clear();
453 this->SNO = new SnomaskManager(this);
454 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
455 this->time_delta = 0;
456 this->next_call = this->TIME + 3;
459 *this->LogFileName = 0;
460 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
462 struct option longopts[] =
464 { "nofork", no_argument, &do_nofork, 1 },
465 { "logfile", required_argument, NULL, 'f' },
466 { "config", required_argument, NULL, 'c' },
467 { "debug", no_argument, &do_debug, 1 },
468 { "nolog", no_argument, &do_nolog, 1 },
469 { "runasroot", no_argument, &do_root, 1 },
470 { "version", no_argument, &do_version, 1 },
474 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
479 /* Log filename was set */
480 strlcpy(LogFileName, optarg, MAXBUF);
481 printf("LOG: Setting logfile to %s\n", LogFileName);
484 /* Config filename was set */
485 strlcpy(ConfigFileName, optarg, MAXBUF);
486 printf("CONFIG: Setting config file to %s\n", ConfigFileName);
489 /* getopt_long_only() set an int variable, just keep going */
492 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
493 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
494 Exit(EXIT_STATUS_ARGV);
501 printf("\n%s r%s\n", VERSION, REVISION);
502 Exit(EXIT_STATUS_NOERROR);
508 if(!do_nofork && !owner_processid)
510 DWORD ExitCode = WindowsForkStart(this);
517 WSAStartup(MAKEWORD(2,0), &wsadata);
520 if (!ServerConfig::FileExists(this->ConfigFileName))
522 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
523 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
524 Exit(EXIT_STATUS_CONFIG);
529 /* Set the finished argument values */
530 Config->nofork = do_nofork;
531 Config->forcedebug = do_debug;
532 Config->writelog = !do_nolog;
534 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
536 this->OpenLog(argv, argc);
538 this->stats = new serverstats();
539 this->Timers = new TimerManager(this);
540 this->Parser = new CommandParser(this);
541 this->XLines = new XLineManager(this);
542 Config->ClearStack();
543 Config->Read(true, NULL);
549 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
550 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
551 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
552 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
553 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
554 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
555 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
556 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
564 if (!this->DaemonSeed())
566 printf("ERROR: could not go into daemon mode. Shutting down.\n");
567 Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
568 Exit(EXIT_STATUS_FORK);
573 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
574 * initialize the socket engine.
576 SocketEngineFactory* SEF = new SocketEngineFactory();
577 SE = SEF->Create(this);
580 this->Modes = new ModeParser(this);
581 this->AddServerName(Config->ServerName);
583 int bounditems = BindPorts(true, found_ports, pl);
585 for(int t = 0; t < 255; t++)
586 Config->global_implementation[t] = 0;
588 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
592 this->Res = new DNS(this);
594 this->LoadAllModules();
595 /* Just in case no modules were loaded - fix for bug #101 */
596 this->BuildISupport();
597 InitializeDisabledCommands(Config->DisabledCommands, this);
599 if ((Config->ports.size() == 0) && (found_ports > 0))
601 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
602 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
603 Exit(EXIT_STATUS_BIND);
606 if (Config->ports.size() != (unsigned int)found_ports)
608 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
609 printf("The following port(s) failed to bind:\n");
611 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
613 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
619 if (kill(getppid(), SIGTERM) == -1)
621 printf("Error killing parent process: %s\n",strerror(errno));
622 Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
626 if (isatty(0) && isatty(1) && isatty(2))
628 /* We didn't start from a TTY, we must have started from a background process -
629 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
640 Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
647 WindowsForkKillOwner(this);
651 printf("\nInspIRCd is now running!\n");
652 Log(DEFAULT,"Startup complete.");
654 this->WritePID(Config->PID);
657 std::string InspIRCd::GetVersionString()
659 char versiondata[MAXBUF];
660 char dnsengine[] = "singlethread-object";
662 if (*Config->CustomVersion)
664 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
668 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%s,%s,%s]",VERSION,Config->ServerName,SYSTEM,REVISION,SE->GetName().c_str(),dnsengine);
673 char* InspIRCd::ModuleError()
678 void InspIRCd::EraseFactory(int j)
681 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
687 factory.push_back(NULL);
694 void InspIRCd::EraseModule(int j)
697 for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
703 modules.push_back(NULL);
709 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
713 Config->module_names.erase(v);
721 void InspIRCd::MoveTo(std::string modulename,int slot)
723 unsigned int v2 = 256;
724 for (unsigned int v = 0; v < Config->module_names.size(); v++)
726 if (Config->module_names[v] == modulename)
728 // found an instance, swap it with the item at the end
733 if ((v2 != (unsigned int)slot) && (v2 < 256))
735 // Swap the module names over
736 Config->module_names[v2] = Config->module_names[slot];
737 Config->module_names[slot] = modulename;
738 // now swap the module factories
739 ircd_module* temp = factory[v2];
740 factory[v2] = factory[slot];
741 factory[slot] = temp;
742 // now swap the module objects
743 Module* temp_module = modules[v2];
744 modules[v2] = modules[slot];
745 modules[slot] = temp_module;
746 // now swap the implement lists (we dont
747 // need to swap the global or recount it)
748 for (int n = 0; n < 255; n++)
750 char x = Config->implement_lists[v2][n];
751 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
752 Config->implement_lists[slot][n] = x;
757 void InspIRCd::MoveAfter(std::string modulename, std::string after)
759 for (unsigned int v = 0; v < Config->module_names.size(); v++)
761 if (Config->module_names[v] == after)
763 MoveTo(modulename, v);
769 void InspIRCd::MoveBefore(std::string modulename, std::string before)
771 for (unsigned int v = 0; v < Config->module_names.size(); v++)
773 if (Config->module_names[v] == before)
777 MoveTo(modulename, v-1);
781 MoveTo(modulename, v);
788 void InspIRCd::MoveToFirst(std::string modulename)
790 MoveTo(modulename,0);
793 void InspIRCd::MoveToLast(std::string modulename)
795 MoveTo(modulename,this->GetModuleCount());
798 void InspIRCd::BuildISupport()
800 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
802 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES-1 << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << Config->MaxChans << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
803 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
804 v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32 ELIST=MU";
805 Config->data005 = v.str();
806 FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
810 bool InspIRCd::UnloadModule(const char* filename)
812 std::string filename_str = filename;
813 for (unsigned int j = 0; j != Config->module_names.size(); j++)
815 if (Config->module_names[j] == filename_str)
817 if (modules[j]->GetVersion().Flags & VF_STATIC)
819 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
820 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
823 std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modules[j]);
824 if (intercount.first > 0)
826 this->Log(DEFAULT,"Failed to unload module %s, being used by %d other(s) via interface '%s'",filename, intercount.first, intercount.second.c_str());
827 snprintf(MODERR,MAXBUF,"Module not unloadable (Still in use by %d other module%s which %s using its interface '%s') -- unload dependent modules first!",
829 intercount.first > 1 ? "s" : "",
830 intercount.first > 1 ? "are" : "is",
831 intercount.second.c_str());
834 /* Give the module a chance to tidy out all its metadata */
835 for (chan_hash::iterator c = this->chanlist->begin(); c != this->chanlist->end(); c++)
837 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
839 for (user_hash::iterator u = this->clientlist->begin(); u != this->clientlist->end(); u++)
841 modules[j]->OnCleanup(TYPE_USER,u->second);
844 /* Tidy up any dangling resolvers */
845 this->Res->CleanResolvers(modules[j]);
847 FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
849 for(int t = 0; t < 255; t++)
851 Config->global_implementation[t] -= Config->implement_lists[j][t];
854 /* We have to renumber implement_lists after unload because the module numbers change!
856 for(int j2 = j; j2 < 254; j2++)
858 for(int t = 0; t < 255; t++)
860 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
865 Parser->RemoveCommands(filename);
866 this->EraseModule(j);
867 this->EraseFactory(j);
868 this->Log(DEFAULT,"Module %s unloaded",filename);
874 this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
875 snprintf(MODERR,MAXBUF,"Module not loaded");
879 bool InspIRCd::LoadModule(const char* filename)
881 /* Do we have a glob pattern in the filename?
882 * The user wants to load multiple modules which
885 if (strchr(filename,'*') || (strchr(filename,'?')))
888 DIR* library = opendir(Config->ModPath);
891 /* Try and locate and load all modules matching the pattern */
892 dirent* entry = NULL;
893 while ((entry = readdir(library)))
895 if (this->MatchText(entry->d_name, filename))
897 if (!this->LoadModule(entry->d_name))
903 /* Loadmodule will now return false if any one of the modules failed
904 * to load (but wont abort when it encounters a bad one) and when 1 or
905 * more modules were actually loaded.
907 return (n_match > 0);
910 char modfile[MAXBUF];
911 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
912 std::string filename_str = filename;
914 if (!ServerConfig::DirValid(modfile))
916 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
917 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
920 if (ServerConfig::FileExists(modfile))
923 for (unsigned int j = 0; j < Config->module_names.size(); j++)
925 if (Config->module_names[j] == filename_str)
927 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
928 snprintf(MODERR,MAXBUF,"Module already loaded");
934 ircd_module* a = new ircd_module(this, modfile);
935 factory[this->ModCount+1] = a;
936 if (factory[this->ModCount+1]->LastError())
938 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
939 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
942 if ((long)factory[this->ModCount+1]->factory != -1)
944 Module* m = factory[this->ModCount+1]->factory->CreateModule(this);
946 Version v = m->GetVersion();
948 if (v.API != API_VERSION)
952 this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
953 snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
958 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]"));
961 modules[this->ModCount+1] = m;
962 /* save the module and the module's classfactory, if
963 * this isnt done, random crashes can occur :/ */
964 Config->module_names.push_back(filename);
966 char* x = &Config->implement_lists[this->ModCount+1][0];
967 for(int t = 0; t < 255; t++)
970 modules[this->ModCount+1]->Implements(x);
972 for(int t = 0; t < 255; t++)
973 Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
977 this->Log(DEFAULT,"Unable to load %s",modfile);
978 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
982 catch (CoreException& modexcept)
984 this->Log(DEFAULT,"Unable to load %s: %s",modfile,modexcept.GetReason());
985 snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
991 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
992 snprintf(MODERR,MAXBUF,"Module file could not be found");
996 FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
997 // now work out which modules, if any, want to move to the back of the queue,
998 // and if they do, move them there.
999 std::vector<std::string> put_to_back;
1000 std::vector<std::string> put_to_front;
1001 std::map<std::string,std::string> put_before;
1002 std::map<std::string,std::string> put_after;
1003 for (unsigned int j = 0; j < Config->module_names.size(); j++)
1005 if (modules[j]->Prioritize() == PRIORITY_LAST)
1006 put_to_back.push_back(Config->module_names[j]);
1007 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
1008 put_to_front.push_back(Config->module_names[j]);
1009 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
1010 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
1011 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
1012 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
1014 for (unsigned int j = 0; j < put_to_back.size(); j++)
1015 MoveToLast(put_to_back[j]);
1016 for (unsigned int j = 0; j < put_to_front.size(); j++)
1017 MoveToFirst(put_to_front[j]);
1018 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
1019 MoveBefore(j->first,j->second);
1020 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
1021 MoveAfter(j->first,j->second);
1026 void InspIRCd::DoOneIteration(bool process_module_sockets)
1031 static time_t uptime;
1032 static struct tm * stime;
1033 static char window_title[100];
1036 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
1037 * Once per loop iteration is pleanty.
1042 /* Run background module timers every few seconds
1043 * (the docs say modules shouldnt rely on accurate
1044 * timing using this event, so we dont have to
1045 * time this exactly).
1047 if (TIME != OLDTIME)
1050 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
1051 if ((TIME % 3600) == 0)
1053 this->RehashUsersAndChans();
1054 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
1056 Timers->TickTimers(TIME);
1057 this->DoBackgroundUserStuff(TIME);
1059 if ((TIME % 5) == 0)
1061 XLines->expire_lines();
1062 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
1063 Timers->TickMissedTimers(TIME);
1066 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
1067 if (!getrusage(RUSAGE_SELF, &ru))
1069 gettimeofday(&this->stats->LastSampled, NULL);
1070 this->stats->LastCPU = ru.ru_utime;
1077 uptime = Time() - startup_time;
1078 stime = gmtime(&uptime);
1079 snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
1080 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
1081 SetConsoleTitle(window_title);
1086 /* Call the socket engine to wait on the active
1087 * file descriptors. The socket engine has everything's
1088 * descriptors in its list... dns, modules, users,
1089 * servers... so its nice and easy, just one call.
1090 * This will cause any read or write events to be
1091 * dispatched to their handlers.
1093 SE->DispatchEvents();
1095 /* if any users was quit, take them out */
1096 GlobalCulls.Apply();
1098 /* If any inspsockets closed, remove them */
1099 for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
1101 SE->DelFd(x->second);
1112 DoOneIteration(true);
1114 /* This is never reached -- we hope! */
1118 /**********************************************************************************/
1121 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
1124 int main(int argc, char** argv)
1126 SI = new InspIRCd(argc, argv);
1132 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
1133 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
1134 * registration timeout maximum seconds)
1136 bool InspIRCd::AllModulesReportReady(userrec* user)
1138 if (!Config->global_implementation[I_OnCheckReady])
1141 for (int i = 0; i <= this->GetModuleCount(); i++)
1143 if (Config->implement_lists[i][I_OnCheckReady])
1145 int res = modules[i]->OnCheckReady(user);
1153 int InspIRCd::GetModuleCount()
1155 return this->ModCount;
1158 time_t InspIRCd::Time(bool delta)
1161 return TIME + time_delta;
1165 int InspIRCd::SetTimeDelta(int delta)
1167 int old = time_delta;
1169 this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
1173 void InspIRCd::AddLocalClone(userrec* user)
1175 clonemap::iterator x = local_clones.find(user->GetIPString());
1176 if (x != local_clones.end())
1179 local_clones[user->GetIPString()] = 1;
1182 void InspIRCd::AddGlobalClone(userrec* user)
1184 clonemap::iterator y = global_clones.find(user->GetIPString());
1185 if (y != global_clones.end())
1188 global_clones[user->GetIPString()] = 1;
1191 int InspIRCd::GetTimeDelta()
1196 bool FileLogger::Readable()
1201 void FileLogger::HandleEvent(EventType et, int errornum)
1203 this->WriteLogLine("");
1205 ServerInstance->SE->DelFd(this);
1208 void FileLogger::WriteLogLine(const std::string &line)
1211 buffer.append(line);
1215 int written = fprintf(log,"%s",buffer.c_str());
1219 if ((written >= 0) && (written < (int)buffer.length()))
1221 buffer.erase(0, buffer.length());
1222 ServerInstance->SE->AddFd(this);
1224 else if (written == -1)
1226 if (errno == EAGAIN)
1227 ServerInstance->SE->AddFd(this);
1231 /* Wrote the whole buffer, and no need for write callback */
1235 if (writeops++ % 20)
1242 void FileLogger::Close()
1246 /* Burlex: Windows assumes nonblocking on FILE* pointers anyway, and also "file" fd's aren't the same
1247 * as socket fd's. */
1249 int flags = fcntl(fileno(log), F_GETFL, 0);
1250 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
1253 fprintf(log,"%s",buffer.c_str());
1256 ServerInstance->SE->DelFd(this);
1266 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
1270 irc::sockets::NonBlocking(fileno(log));
1271 this->SetFd(fileno(log));
1276 FileLogger::~FileLogger()