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)
54 command_line += Instance->Config->argv[i];
55 if(Instance->Config->argc != i+1)
59 char module[MAX_PATH];
60 if(!GetModuleFileName(NULL, module, MAX_PATH))
62 printf("GetModuleFileName() failed.\n");
66 STARTUPINFO startupinfo;
67 PROCESS_INFORMATION procinfo;
68 ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
69 ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
71 // Fill in the startup info struct
72 GetStartupInfo(&startupinfo);
74 // Launch our "forked" process.
75 BOOL bSuccess = CreateProcess ( module, (LPTSTR)command_line.c_str(),
76 0, // PROCESS_SECURITY_ATTRIBUTES
77 0, // THREAD_SECURITY_ATTRIBUTES
78 TRUE, // We went to inherit handles.
79 CREATE_SUSPENDED | // Suspend the primary thread of the new process
80 CREATE_PRESERVE_CODE_AUTHZ_LEVEL, // Allow us full access to the process
82 0, // CURRENT_DIRECTORY
83 &startupinfo, // startup info
84 &procinfo); // process info
88 printf("CreateProcess() failed.\n");
92 // Set the owner process id in the target process.
94 DWORD pid = GetCurrentProcessId();
95 if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
97 printf("WriteProcessMemory() failed.\n");
101 // Resume the other thread (let it start)
102 ResumeThread(procinfo.hThread);
104 // 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.
105 WaitForSingleObject(procinfo.hProcess, INFINITE);
107 // If we hit this it means startup failed, default to 14 if this fails.
109 GetExitCodeProcess(procinfo.hProcess, &ExitCode);
110 printf("Startup failed, exitcode was %u.\n", ExitCode);
111 CloseHandle(procinfo.hThread);
112 CloseHandle(procinfo.hProcess);
116 void WindowsForkKillOwner(InspIRCd * Instance)
118 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
119 if(!hProcess || !owner_processid)
121 printf("Could not open process id %u.\n", owner_processid);
126 if(!TerminateProcess(hProcess, 0))
128 printf("Could not TerminateProcess().\n");
132 CloseHandle(hProcess);
137 using irc::sockets::NonBlocking;
138 using irc::sockets::Blocking;
139 using irc::sockets::insp_ntoa;
140 using irc::sockets::insp_inaddr;
141 using irc::sockets::insp_sockaddr;
145 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
146 const char* ExitCodes[] =
149 "DIE command", /* 1 */
150 "execv() failed", /* 2 */
151 "Internal error", /* 3 */
152 "Config file error", /* 4 */
153 "Logfile error", /* 5 */
154 "Fork failed", /* 6 */
155 "Bad commandline parameters", /* 7 */
156 "No ports could be bound", /* 8 */
157 "Can't write PID file", /* 9 */
158 "SocketEngine could not initialize", /* 10 */
159 "Refusing to start up as root", /* 11 */
160 "Found a <die> tag!", /* 12 */
161 "Couldn't load module on startup", /* 13 */
162 "Could not create forked process", /* 14 */
163 "Received SIGTERM", /* 15 */
166 void InspIRCd::AddServerName(const std::string &servername)
168 servernamelist::iterator itr = servernames.begin();
169 for(; itr != servernames.end(); ++itr)
170 if(**itr == servername)
173 string * ns = new string(servername);
174 servernames.push_back(ns);
177 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
179 servernamelist::iterator itr = servernames.begin();
180 for(; itr != servernames.end(); ++itr)
181 if(**itr == servername)
182 return (*itr)->c_str();
184 servernames.push_back(new string(servername));
185 itr = --servernames.end();
186 return (*itr)->c_str();
189 bool InspIRCd::FindServerName(const std::string &servername)
191 servernamelist::iterator itr = servernames.begin();
192 for(; itr != servernames.end(); ++itr)
193 if(**itr == servername)
198 void InspIRCd::Exit(int status)
205 SI->SendError("Exiting with status " + ConvToStr(status) + " (" + std::string(ExitCodes[status]) + ")");
211 void InspIRCd::Cleanup()
213 std::vector<std::string> mymodnames;
214 int MyModCount = this->GetModuleCount();
216 for (unsigned int i = 0; i < Config->ports.size(); i++)
218 /* This calls the constructor and closes the listening socket */
219 delete Config->ports[i];
222 Config->ports.clear();
224 /* Close all client sockets, or the new process inherits them */
225 for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
227 (*i)->SetWriteError("Server shutdown");
231 /* We do this more than once, so that any service providers get a
232 * chance to be unhooked by the modules using them, but then get
233 * a chance to be removed themsleves.
235 for (int tries = 0; tries < 3; tries++)
237 MyModCount = this->GetModuleCount();
240 /* Unload all modules, so they get a chance to clean up their listeners */
241 for (int j = 0; j <= MyModCount; j++)
242 mymodnames.push_back(Config->module_names[j]);
244 for (int k = 0; k <= MyModCount; k++)
245 this->UnloadModule(mymodnames[k].c_str());
249 this->Logger->Close();
251 /* Cleanup Server Names */
252 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
261 void InspIRCd::Restart(const std::string &reason)
263 /* SendError flushes each client's queue,
264 * regardless of writeability state
266 this->SendError(reason);
270 /* Figure out our filename (if theyve renamed it, we're boned) */
274 char module[MAX_PATH];
275 if (GetModuleFileName(NULL, module, MAX_PATH))
278 me = Config->MyDir + "/inspircd";
281 if (execv(me.c_str(), Config->argv) == -1)
283 /* Will raise a SIGABRT if not trapped */
284 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
288 void InspIRCd::Start()
290 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
291 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
292 printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey, Burlex\033[0m\n");
293 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
296 void InspIRCd::Rehash(int status)
298 SI->WriteOpers("*** Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(SI->ConfigFileName));
300 SI->OpenLog(SI->Config->argv, SI->Config->argc);
301 SI->RehashUsersAndChans();
302 FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
303 SI->Config->Read(false,NULL);
306 FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
310 void InspIRCd::ResetMaxBans()
312 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
313 i->second->ResetMaxBans();
317 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
318 * we must occasionally rehash the hash (yes really).
319 * We do this by copying the entries from the old hash to a new hash, causing all
320 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
321 * very expensive, so instead we do it when the user types /REHASH and expects a
322 * short delay anyway.
324 void InspIRCd::RehashUsersAndChans()
326 user_hash* old_users = this->clientlist;
327 chan_hash* old_chans = this->chanlist;
329 this->clientlist = new user_hash();
330 this->chanlist = new chan_hash();
332 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
333 this->clientlist->insert(*n);
337 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
338 this->chanlist->insert(*n);
343 void InspIRCd::CloseLog()
345 this->Logger->Close();
348 void InspIRCd::SetSignals()
351 signal(SIGALRM, SIG_IGN);
352 signal(SIGHUP, InspIRCd::Rehash);
353 signal(SIGPIPE, SIG_IGN);
354 signal(SIGCHLD, SIG_IGN);
356 signal(SIGTERM, InspIRCd::Exit);
359 void InspIRCd::QuickExit(int status)
364 bool InspIRCd::DaemonSeed()
367 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
370 signal(SIGTERM, InspIRCd::QuickExit);
373 if ((childpid = fork ()) < 0)
375 else if (childpid > 0)
377 /* We wait here for the child process to kill us,
378 * so that the shell prompt doesnt come back over
380 * Sending a kill with a signal of 0 just checks
381 * if the child pid is still around. If theyre not,
382 * they threw an error and we should give up.
384 while (kill(childpid, 0) != -1)
390 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
392 signal(SIGTERM, InspIRCd::Exit);
395 if (getrlimit(RLIMIT_CORE, &rl) == -1)
397 this->Log(DEFAULT,"Failed to getrlimit()!");
402 rl.rlim_cur = rl.rlim_max;
403 if (setrlimit(RLIMIT_CORE, &rl) == -1)
404 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
411 void InspIRCd::WritePID(const std::string &filename)
413 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
414 if (*(fname.begin()) != '/')
416 std::string::size_type pos;
417 std::string confpath = this->ConfigFileName;
418 if ((pos = confpath.rfind("/")) != std::string::npos)
420 /* Leaves us with just the path */
421 fname = confpath.substr(0, pos) + std::string("/") + fname;
424 std::ofstream outfile(fname.c_str());
425 if (outfile.is_open())
432 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
433 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
434 Exit(EXIT_STATUS_PID);
438 std::string InspIRCd::GetRevision()
443 InspIRCd::InspIRCd(int argc, char** argv)
444 : ModCount(-1), GlobalCulls(this)
448 int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0; /* flag variables */
453 memset(&server, 0, sizeof(server));
454 memset(&client, 0, sizeof(client));
456 this->unregistered_count = 0;
458 this->clientlist = new user_hash();
459 this->chanlist = new chan_hash();
461 this->Config = new ServerConfig(this);
463 this->Config->argv = argv;
464 this->Config->argc = argc;
466 chdir(Config->GetFullProgDir().c_str());
468 this->Config->opertypes.clear();
469 this->Config->operclass.clear();
470 this->SNO = new SnomaskManager(this);
471 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
472 this->time_delta = 0;
473 this->next_call = this->TIME + 3;
476 *this->LogFileName = 0;
477 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
479 struct option longopts[] =
481 { "nofork", no_argument, &do_nofork, 1 },
482 { "logfile", required_argument, NULL, 'f' },
483 { "config", required_argument, NULL, 'c' },
484 { "debug", no_argument, &do_debug, 1 },
485 { "nolog", no_argument, &do_nolog, 1 },
486 { "runasroot", no_argument, &do_root, 1 },
487 { "version", no_argument, &do_version, 1 },
491 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
496 /* Log filename was set */
497 strlcpy(LogFileName, optarg, MAXBUF);
498 printf("LOG: Setting logfile to %s\n", LogFileName);
501 /* Config filename was set */
502 strlcpy(ConfigFileName, optarg, MAXBUF);
503 printf("CONFIG: Setting config file to %s\n", ConfigFileName);
506 /* getopt_long_only() set an int variable, just keep going */
509 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
510 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
511 Exit(EXIT_STATUS_ARGV);
518 printf("\n%s r%s\n", VERSION, REVISION);
519 Exit(EXIT_STATUS_NOERROR);
525 if(!do_nofork && !owner_processid)
527 DWORD ExitCode = WindowsForkStart(this);
534 WSAStartup(MAKEWORD(2,0), &wsadata);
537 if (!ServerConfig::FileExists(this->ConfigFileName))
539 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
540 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
541 Exit(EXIT_STATUS_CONFIG);
546 /* Set the finished argument values */
547 Config->nofork = do_nofork;
548 Config->forcedebug = do_debug;
549 Config->writelog = !do_nolog;
551 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
553 this->OpenLog(argv, argc);
555 this->stats = new serverstats();
556 this->Timers = new TimerManager(this);
557 this->Parser = new CommandParser(this);
558 this->XLines = new XLineManager(this);
559 Config->ClearStack();
560 Config->Read(true, NULL);
566 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
567 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
568 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
569 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
570 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
571 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
572 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
573 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
581 if (!this->DaemonSeed())
583 printf("ERROR: could not go into daemon mode. Shutting down.\n");
584 Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
585 Exit(EXIT_STATUS_FORK);
590 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
591 * initialize the socket engine.
593 SocketEngineFactory* SEF = new SocketEngineFactory();
594 SE = SEF->Create(this);
597 this->Modes = new ModeParser(this);
598 this->AddServerName(Config->ServerName);
600 int bounditems = BindPorts(true, found_ports, pl);
602 for(int t = 0; t < 255; t++)
603 Config->global_implementation[t] = 0;
605 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
609 this->Res = new DNS(this);
611 this->LoadAllModules();
612 /* Just in case no modules were loaded - fix for bug #101 */
613 this->BuildISupport();
614 InitializeDisabledCommands(Config->DisabledCommands, this);
616 if ((Config->ports.size() == 0) && (found_ports > 0))
618 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
619 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
620 Exit(EXIT_STATUS_BIND);
623 if (Config->ports.size() != (unsigned int)found_ports)
625 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
626 printf("The following port(s) failed to bind:\n");
628 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
630 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
636 if (kill(getppid(), SIGTERM) == -1)
638 printf("Error killing parent process: %s\n",strerror(errno));
639 Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
643 if (isatty(0) && isatty(1) && isatty(2))
645 /* We didn't start from a TTY, we must have started from a background process -
646 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
657 Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
664 WindowsForkKillOwner(this);
668 printf("\nInspIRCd is now running!\n");
669 Log(DEFAULT,"Startup complete.");
671 this->WritePID(Config->PID);
674 std::string InspIRCd::GetVersionString()
676 char versiondata[MAXBUF];
677 char dnsengine[] = "singlethread-object";
679 if (*Config->CustomVersion)
681 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
685 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%s,%s,%s]",VERSION,Config->ServerName,SYSTEM,REVISION,SE->GetName().c_str(),dnsengine);
690 char* InspIRCd::ModuleError()
695 void InspIRCd::EraseFactory(int j)
698 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
704 factory.push_back(NULL);
711 void InspIRCd::EraseModule(int j)
714 for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
720 modules.push_back(NULL);
726 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
730 Config->module_names.erase(v);
738 void InspIRCd::MoveTo(std::string modulename,int slot)
740 unsigned int v2 = 256;
741 for (unsigned int v = 0; v < Config->module_names.size(); v++)
743 if (Config->module_names[v] == modulename)
745 // found an instance, swap it with the item at the end
750 if ((v2 != (unsigned int)slot) && (v2 < 256))
752 // Swap the module names over
753 Config->module_names[v2] = Config->module_names[slot];
754 Config->module_names[slot] = modulename;
755 // now swap the module factories
756 ircd_module* temp = factory[v2];
757 factory[v2] = factory[slot];
758 factory[slot] = temp;
759 // now swap the module objects
760 Module* temp_module = modules[v2];
761 modules[v2] = modules[slot];
762 modules[slot] = temp_module;
763 // now swap the implement lists (we dont
764 // need to swap the global or recount it)
765 for (int n = 0; n < 255; n++)
767 char x = Config->implement_lists[v2][n];
768 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
769 Config->implement_lists[slot][n] = x;
774 void InspIRCd::MoveAfter(std::string modulename, std::string after)
776 for (unsigned int v = 0; v < Config->module_names.size(); v++)
778 if (Config->module_names[v] == after)
780 MoveTo(modulename, v);
786 void InspIRCd::MoveBefore(std::string modulename, std::string before)
788 for (unsigned int v = 0; v < Config->module_names.size(); v++)
790 if (Config->module_names[v] == before)
794 MoveTo(modulename, v-1);
798 MoveTo(modulename, v);
805 void InspIRCd::MoveToFirst(std::string modulename)
807 MoveTo(modulename,0);
810 void InspIRCd::MoveToLast(std::string modulename)
812 MoveTo(modulename,this->GetModuleCount());
815 void InspIRCd::BuildISupport()
817 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
819 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES-1 << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << Config->MaxChans << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
820 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
821 v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32 ELIST=MU";
822 Config->data005 = v.str();
823 FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
827 bool InspIRCd::UnloadModule(const char* filename)
829 std::string filename_str = filename;
830 for (unsigned int j = 0; j != Config->module_names.size(); j++)
832 if (Config->module_names[j] == filename_str)
834 if (modules[j]->GetVersion().Flags & VF_STATIC)
836 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
837 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
840 std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modules[j]);
841 if (intercount.first > 0)
843 this->Log(DEFAULT,"Failed to unload module %s, being used by %d other(s) via interface '%s'",filename, intercount.first, intercount.second.c_str());
844 snprintf(MODERR,MAXBUF,"Module not unloadable (Still in use by %d other module%s which %s using its interface '%s') -- unload dependent modules first!",
846 intercount.first > 1 ? "s" : "",
847 intercount.first > 1 ? "are" : "is",
848 intercount.second.c_str());
851 /* Give the module a chance to tidy out all its metadata */
852 for (chan_hash::iterator c = this->chanlist->begin(); c != this->chanlist->end(); c++)
854 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
856 for (user_hash::iterator u = this->clientlist->begin(); u != this->clientlist->end(); u++)
858 modules[j]->OnCleanup(TYPE_USER,u->second);
861 /* Tidy up any dangling resolvers */
862 this->Res->CleanResolvers(modules[j]);
864 FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
866 for(int t = 0; t < 255; t++)
868 Config->global_implementation[t] -= Config->implement_lists[j][t];
871 /* We have to renumber implement_lists after unload because the module numbers change!
873 for(int j2 = j; j2 < 254; j2++)
875 for(int t = 0; t < 255; t++)
877 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
882 Parser->RemoveCommands(filename);
883 this->EraseModule(j);
884 this->EraseFactory(j);
885 this->Log(DEFAULT,"Module %s unloaded",filename);
891 this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
892 snprintf(MODERR,MAXBUF,"Module not loaded");
896 bool InspIRCd::LoadModule(const char* filename)
898 /* Do we have a glob pattern in the filename?
899 * The user wants to load multiple modules which
902 if (strchr(filename,'*') || (strchr(filename,'?')))
905 DIR* library = opendir(Config->ModPath);
908 /* Try and locate and load all modules matching the pattern */
909 dirent* entry = NULL;
910 while ((entry = readdir(library)))
912 if (this->MatchText(entry->d_name, filename))
914 if (!this->LoadModule(entry->d_name))
920 /* Loadmodule will now return false if any one of the modules failed
921 * to load (but wont abort when it encounters a bad one) and when 1 or
922 * more modules were actually loaded.
924 return (n_match > 0);
927 char modfile[MAXBUF];
928 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
929 std::string filename_str = filename;
931 if (!ServerConfig::DirValid(modfile))
933 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
934 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
937 if (ServerConfig::FileExists(modfile))
940 for (unsigned int j = 0; j < Config->module_names.size(); j++)
942 if (Config->module_names[j] == filename_str)
944 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
945 snprintf(MODERR,MAXBUF,"Module already loaded");
951 ircd_module* a = new ircd_module(this, modfile);
952 factory[this->ModCount+1] = a;
953 if (factory[this->ModCount+1]->LastError())
955 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
956 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
959 if ((long)factory[this->ModCount+1]->factory != -1)
961 Module* m = factory[this->ModCount+1]->factory->CreateModule(this);
963 Version v = m->GetVersion();
965 if (v.API != API_VERSION)
969 this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
970 snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
975 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]"));
978 modules[this->ModCount+1] = m;
979 /* save the module and the module's classfactory, if
980 * this isnt done, random crashes can occur :/ */
981 Config->module_names.push_back(filename);
983 char* x = &Config->implement_lists[this->ModCount+1][0];
984 for(int t = 0; t < 255; t++)
987 modules[this->ModCount+1]->Implements(x);
989 for(int t = 0; t < 255; t++)
990 Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
994 this->Log(DEFAULT,"Unable to load %s",modfile);
995 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
999 catch (CoreException& modexcept)
1001 this->Log(DEFAULT,"Unable to load %s: %s",modfile,modexcept.GetReason());
1002 snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1008 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
1009 snprintf(MODERR,MAXBUF,"Module file could not be found");
1013 FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
1014 // now work out which modules, if any, want to move to the back of the queue,
1015 // and if they do, move them there.
1016 std::vector<std::string> put_to_back;
1017 std::vector<std::string> put_to_front;
1018 std::map<std::string,std::string> put_before;
1019 std::map<std::string,std::string> put_after;
1020 for (unsigned int j = 0; j < Config->module_names.size(); j++)
1022 if (modules[j]->Prioritize() == PRIORITY_LAST)
1023 put_to_back.push_back(Config->module_names[j]);
1024 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
1025 put_to_front.push_back(Config->module_names[j]);
1026 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
1027 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
1028 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
1029 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
1031 for (unsigned int j = 0; j < put_to_back.size(); j++)
1032 MoveToLast(put_to_back[j]);
1033 for (unsigned int j = 0; j < put_to_front.size(); j++)
1034 MoveToFirst(put_to_front[j]);
1035 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
1036 MoveBefore(j->first,j->second);
1037 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
1038 MoveAfter(j->first,j->second);
1043 void InspIRCd::DoOneIteration(bool process_module_sockets)
1048 static time_t uptime;
1049 static struct tm * stime;
1050 static char window_title[100];
1053 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
1054 * Once per loop iteration is pleanty.
1059 /* Run background module timers every few seconds
1060 * (the docs say modules shouldnt rely on accurate
1061 * timing using this event, so we dont have to
1062 * time this exactly).
1064 if (TIME != OLDTIME)
1067 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
1068 if ((TIME % 3600) == 0)
1070 this->RehashUsersAndChans();
1071 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
1073 Timers->TickTimers(TIME);
1074 this->DoBackgroundUserStuff(TIME);
1076 if ((TIME % 5) == 0)
1078 XLines->expire_lines();
1079 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
1080 Timers->TickMissedTimers(TIME);
1083 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
1084 if (!getrusage(RUSAGE_SELF, &ru))
1086 gettimeofday(&this->stats->LastSampled, NULL);
1087 this->stats->LastCPU = ru.ru_utime;
1094 uptime = Time() - startup_time;
1095 stime = gmtime(&uptime);
1096 snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
1097 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
1098 SetConsoleTitle(window_title);
1103 /* Call the socket engine to wait on the active
1104 * file descriptors. The socket engine has everything's
1105 * descriptors in its list... dns, modules, users,
1106 * servers... so its nice and easy, just one call.
1107 * This will cause any read or write events to be
1108 * dispatched to their handlers.
1110 SE->DispatchEvents();
1112 /* if any users was quit, take them out */
1113 GlobalCulls.Apply();
1115 /* If any inspsockets closed, remove them */
1116 for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
1118 SE->DelFd(x->second);
1129 DoOneIteration(true);
1131 /* This is never reached -- we hope! */
1135 /**********************************************************************************/
1138 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
1141 int main(int argc, char** argv)
1143 SI = new InspIRCd(argc, argv);
1149 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
1150 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
1151 * registration timeout maximum seconds)
1153 bool InspIRCd::AllModulesReportReady(userrec* user)
1155 if (!Config->global_implementation[I_OnCheckReady])
1158 for (int i = 0; i <= this->GetModuleCount(); i++)
1160 if (Config->implement_lists[i][I_OnCheckReady])
1162 int res = modules[i]->OnCheckReady(user);
1170 int InspIRCd::GetModuleCount()
1172 return this->ModCount;
1175 time_t InspIRCd::Time(bool delta)
1178 return TIME + time_delta;
1182 int InspIRCd::SetTimeDelta(int delta)
1184 int old = time_delta;
1186 this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
1190 void InspIRCd::AddLocalClone(userrec* user)
1192 clonemap::iterator x = local_clones.find(user->GetIPString());
1193 if (x != local_clones.end())
1196 local_clones[user->GetIPString()] = 1;
1199 void InspIRCd::AddGlobalClone(userrec* user)
1201 clonemap::iterator y = global_clones.find(user->GetIPString());
1202 if (y != global_clones.end())
1205 global_clones[user->GetIPString()] = 1;
1208 int InspIRCd::GetTimeDelta()
1213 bool FileLogger::Readable()
1218 void FileLogger::HandleEvent(EventType et, int errornum)
1220 this->WriteLogLine("");
1222 ServerInstance->SE->DelFd(this);
1225 void FileLogger::WriteLogLine(const std::string &line)
1228 buffer.append(line);
1232 int written = fprintf(log,"%s",buffer.c_str());
1236 if ((written >= 0) && (written < (int)buffer.length()))
1238 buffer.erase(0, buffer.length());
1239 ServerInstance->SE->AddFd(this);
1241 else if (written == -1)
1243 if (errno == EAGAIN)
1244 ServerInstance->SE->AddFd(this);
1248 /* Wrote the whole buffer, and no need for write callback */
1252 if (writeops++ % 20)
1259 void FileLogger::Close()
1263 /* Burlex: Windows assumes nonblocking on FILE* pointers anyway, and also "file" fd's aren't the same
1264 * as socket fd's. */
1266 int flags = fcntl(fileno(log), F_GETFL, 0);
1267 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
1270 fprintf(log,"%s",buffer.c_str());
1273 ServerInstance->SE->DelFd(this);
1283 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
1287 irc::sockets::NonBlocking(fileno(log));
1288 this->SetFd(fileno(log));
1293 FileLogger::~FileLogger()