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>
25 /* Some systems don't define RUSAGE_SELF. This should fix them. */
37 #include "socketengine.h"
38 #include "inspircd_se_config.h"
41 #include "command_parse.h"
42 #include "exitcodes.h"
46 /* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
47 static DWORD owner_processid = 0;
49 DWORD WindowsForkStart(InspIRCd * Instance)
51 /* Windows implementation of fork() :P */
53 char module[MAX_PATH];
54 if(!GetModuleFileName(NULL, module, MAX_PATH))
56 printf("GetModuleFileName() failed.\n");
60 STARTUPINFO startupinfo;
61 PROCESS_INFORMATION procinfo;
62 ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
63 ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
65 // Fill in the startup info struct
66 GetStartupInfo(&startupinfo);
68 /* Default creation flags create the processes suspended */
69 DWORD startupflags = CREATE_SUSPENDED;
71 /* On windows 2003/XP and above, we can use the value
72 * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
73 * to the process which we may require on these operating systems.
76 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
78 if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
79 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
81 // Launch our "forked" process.
82 BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
83 strdup(GetCommandLine()), // Command line (exe plus parameters from the OS)
84 // NOTE: We cannot return the direct value of the
85 // GetCommandLine function here, as the pointer is
86 // passed straight to the child process, and will be
87 // invalid once we exit as it goes out of context.
88 // strdup() seems ok, though.
89 0, // PROCESS_SECURITY_ATTRIBUTES
90 0, // THREAD_SECURITY_ATTRIBUTES
91 TRUE, // We went to inherit handles.
92 startupflags, // Allow us full access to the process and suspend it.
94 0, // CURRENT_DIRECTORY
95 &startupinfo, // startup info
96 &procinfo); // process info
100 printf("CreateProcess() error: %s\n", dlerror());
104 // Set the owner process id in the target process.
106 DWORD pid = GetCurrentProcessId();
107 if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
109 printf("WriteProcessMemory() failed: %s\n", dlerror());
113 // Resume the other thread (let it start)
114 ResumeThread(procinfo.hThread);
116 // 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.
117 WaitForSingleObject(procinfo.hProcess, INFINITE);
119 // If we hit this it means startup failed, default to 14 if this fails.
121 GetExitCodeProcess(procinfo.hProcess, &ExitCode);
122 CloseHandle(procinfo.hThread);
123 CloseHandle(procinfo.hProcess);
127 void WindowsForkKillOwner(InspIRCd * Instance)
129 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
130 if(!hProcess || !owner_processid)
132 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
137 if(!TerminateProcess(hProcess, 0))
139 printf("Could not TerminateProcess(): %s\n", dlerror());
143 CloseHandle(hProcess);
148 using irc::sockets::NonBlocking;
149 using irc::sockets::Blocking;
150 using irc::sockets::insp_ntoa;
151 using irc::sockets::insp_inaddr;
152 using irc::sockets::insp_sockaddr;
156 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
157 const char* ExitCodes[] =
160 "DIE command", /* 1 */
161 "execv() failed", /* 2 */
162 "Internal error", /* 3 */
163 "Config file error", /* 4 */
164 "Logfile error", /* 5 */
165 "POSIX fork failed", /* 6 */
166 "Bad commandline parameters", /* 7 */
167 "No ports could be bound", /* 8 */
168 "Can't write PID file", /* 9 */
169 "SocketEngine could not initialize", /* 10 */
170 "Refusing to start up as root", /* 11 */
171 "Found a <die> tag!", /* 12 */
172 "Couldn't load module on startup", /* 13 */
173 "Could not create windows forked process", /* 14 */
174 "Received SIGTERM", /* 15 */
177 void InspIRCd::AddServerName(const std::string &servername)
179 servernamelist::iterator itr = servernames.begin();
180 for(; itr != servernames.end(); ++itr)
181 if(**itr == servername)
184 string * ns = new string(servername);
185 servernames.push_back(ns);
188 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
190 servernamelist::iterator itr = servernames.begin();
191 for(; itr != servernames.end(); ++itr)
192 if(**itr == servername)
193 return (*itr)->c_str();
195 servernames.push_back(new string(servername));
196 itr = --servernames.end();
197 return (*itr)->c_str();
200 bool InspIRCd::FindServerName(const std::string &servername)
202 servernamelist::iterator itr = servernames.begin();
203 for(; itr != servernames.end(); ++itr)
204 if(**itr == servername)
209 void InspIRCd::Exit(int status)
216 SI->SendError("Exiting with status " + ConvToStr(status) + " (" + std::string(ExitCodes[status]) + ")");
222 void InspIRCd::Cleanup()
224 std::vector<std::string> mymodnames;
225 int MyModCount = this->GetModuleCount();
227 for (unsigned int i = 0; i < Config->ports.size(); i++)
229 /* This calls the constructor and closes the listening socket */
230 delete Config->ports[i];
233 Config->ports.clear();
235 /* Close all client sockets, or the new process inherits them */
236 for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
238 (*i)->SetWriteError("Server shutdown");
242 /* We do this more than once, so that any service providers get a
243 * chance to be unhooked by the modules using them, but then get
244 * a chance to be removed themsleves.
246 for (int tries = 0; tries < 3; tries++)
248 MyModCount = this->GetModuleCount();
251 /* Unload all modules, so they get a chance to clean up their listeners */
252 for (int j = 0; j <= MyModCount; j++)
253 mymodnames.push_back(Config->module_names[j]);
255 for (int k = 0; k <= MyModCount; k++)
256 this->UnloadModule(mymodnames[k].c_str());
260 this->Logger->Close();
262 /* Cleanup Server Names */
263 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
272 void InspIRCd::Restart(const std::string &reason)
274 /* SendError flushes each client's queue,
275 * regardless of writeability state
277 this->SendError(reason);
281 /* Figure out our filename (if theyve renamed it, we're boned) */
285 char module[MAX_PATH];
286 if (GetModuleFileName(NULL, module, MAX_PATH))
289 me = Config->MyDir + "/inspircd";
292 if (execv(me.c_str(), Config->argv) == -1)
294 /* Will raise a SIGABRT if not trapped */
295 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
299 void InspIRCd::Start()
301 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
302 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
303 printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey, Burlex\033[0m\n");
304 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
307 void InspIRCd::Rehash(int status)
309 SI->WriteOpers("*** Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(SI->ConfigFileName));
311 SI->OpenLog(SI->Config->argv, SI->Config->argc);
312 SI->RehashUsersAndChans();
313 FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
314 SI->Config->Read(false,NULL);
317 FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
321 void InspIRCd::ResetMaxBans()
323 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
324 i->second->ResetMaxBans();
328 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
329 * we must occasionally rehash the hash (yes really).
330 * We do this by copying the entries from the old hash to a new hash, causing all
331 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
332 * very expensive, so instead we do it when the user types /REHASH and expects a
333 * short delay anyway.
335 void InspIRCd::RehashUsersAndChans()
337 user_hash* old_users = this->clientlist;
338 chan_hash* old_chans = this->chanlist;
340 this->clientlist = new user_hash();
341 this->chanlist = new chan_hash();
343 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
344 this->clientlist->insert(*n);
348 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
349 this->chanlist->insert(*n);
354 void InspIRCd::CloseLog()
356 this->Logger->Close();
359 void InspIRCd::SetSignals()
362 signal(SIGALRM, SIG_IGN);
363 signal(SIGHUP, InspIRCd::Rehash);
364 signal(SIGPIPE, SIG_IGN);
365 signal(SIGCHLD, SIG_IGN);
367 signal(SIGTERM, InspIRCd::Exit);
370 void InspIRCd::QuickExit(int status)
375 bool InspIRCd::DaemonSeed()
378 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
381 signal(SIGTERM, InspIRCd::QuickExit);
384 if ((childpid = fork ()) < 0)
386 else if (childpid > 0)
388 /* We wait here for the child process to kill us,
389 * so that the shell prompt doesnt come back over
391 * Sending a kill with a signal of 0 just checks
392 * if the child pid is still around. If theyre not,
393 * they threw an error and we should give up.
395 while (kill(childpid, 0) != -1)
401 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
403 signal(SIGTERM, InspIRCd::Exit);
406 if (getrlimit(RLIMIT_CORE, &rl) == -1)
408 this->Log(DEFAULT,"Failed to getrlimit()!");
413 rl.rlim_cur = rl.rlim_max;
414 if (setrlimit(RLIMIT_CORE, &rl) == -1)
415 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
422 void InspIRCd::WritePID(const std::string &filename)
424 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
425 if (*(fname.begin()) != '/')
427 std::string::size_type pos;
428 std::string confpath = this->ConfigFileName;
429 if ((pos = confpath.rfind("/")) != std::string::npos)
431 /* Leaves us with just the path */
432 fname = confpath.substr(0, pos) + std::string("/") + fname;
435 std::ofstream outfile(fname.c_str());
436 if (outfile.is_open())
443 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
444 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
445 Exit(EXIT_STATUS_PID);
449 std::string InspIRCd::GetRevision()
454 InspIRCd::InspIRCd(int argc, char** argv)
455 : ModCount(-1), GlobalCulls(this)
459 int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0; /* flag variables */
464 memset(&server, 0, sizeof(server));
465 memset(&client, 0, sizeof(client));
467 this->unregistered_count = 0;
469 this->clientlist = new user_hash();
470 this->chanlist = new chan_hash();
472 this->Config = new ServerConfig(this);
474 this->Config->argv = argv;
475 this->Config->argc = argc;
477 chdir(Config->GetFullProgDir().c_str());
479 this->Config->opertypes.clear();
480 this->Config->operclass.clear();
481 this->SNO = new SnomaskManager(this);
482 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
483 this->time_delta = 0;
484 this->next_call = this->TIME + 3;
487 *this->LogFileName = 0;
488 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
490 struct option longopts[] =
492 { "nofork", no_argument, &do_nofork, 1 },
493 { "logfile", required_argument, NULL, 'f' },
494 { "config", required_argument, NULL, 'c' },
495 { "debug", no_argument, &do_debug, 1 },
496 { "nolog", no_argument, &do_nolog, 1 },
497 { "runasroot", no_argument, &do_root, 1 },
498 { "version", no_argument, &do_version, 1 },
502 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
507 /* Log filename was set */
508 strlcpy(LogFileName, optarg, MAXBUF);
511 /* Config filename was set */
512 strlcpy(ConfigFileName, optarg, MAXBUF);
515 /* getopt_long_only() set an int variable, just keep going */
518 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
519 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
520 Exit(EXIT_STATUS_ARGV);
527 printf("\n%s r%s\n", VERSION, REVISION);
528 Exit(EXIT_STATUS_NOERROR);
534 if(!do_nofork && !owner_processid)
536 DWORD ExitCode = WindowsForkStart(this);
543 WSAStartup(MAKEWORD(2,0), &wsadata);
546 if (!ServerConfig::FileExists(this->ConfigFileName))
548 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
549 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
550 Exit(EXIT_STATUS_CONFIG);
555 /* Set the finished argument values */
556 Config->nofork = do_nofork;
557 Config->forcedebug = do_debug;
558 Config->writelog = !do_nolog;
560 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
562 this->OpenLog(argv, argc);
564 this->stats = new serverstats();
565 this->Timers = new TimerManager(this);
566 this->Parser = new CommandParser(this);
567 this->XLines = new XLineManager(this);
568 Config->ClearStack();
569 Config->Read(true, NULL);
575 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
576 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
577 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
578 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
579 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
580 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
581 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
582 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
590 if (!this->DaemonSeed())
592 printf("ERROR: could not go into daemon mode. Shutting down.\n");
593 Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
594 Exit(EXIT_STATUS_FORK);
599 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
600 * initialize the socket engine.
602 SocketEngineFactory* SEF = new SocketEngineFactory();
603 SE = SEF->Create(this);
606 this->Modes = new ModeParser(this);
607 this->AddServerName(Config->ServerName);
609 int bounditems = BindPorts(true, found_ports, pl);
611 for(int t = 0; t < 255; t++)
612 Config->global_implementation[t] = 0;
614 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
618 this->Res = new DNS(this);
620 this->LoadAllModules();
621 /* Just in case no modules were loaded - fix for bug #101 */
622 this->BuildISupport();
623 InitializeDisabledCommands(Config->DisabledCommands, this);
625 if ((Config->ports.size() == 0) && (found_ports > 0))
627 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
628 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
629 Exit(EXIT_STATUS_BIND);
632 if (Config->ports.size() != (unsigned int)found_ports)
634 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
635 printf("The following port(s) failed to bind:\n");
637 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
639 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
645 if (kill(getppid(), SIGTERM) == -1)
647 printf("Error killing parent process: %s\n",strerror(errno));
648 Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
652 if (isatty(0) && isatty(1) && isatty(2))
654 /* We didn't start from a TTY, we must have started from a background process -
655 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
666 Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
673 WindowsForkKillOwner(this);
677 printf("\nInspIRCd is now running!\n");
678 Log(DEFAULT,"Startup complete.");
680 this->WritePID(Config->PID);
683 std::string InspIRCd::GetVersionString()
685 char versiondata[MAXBUF];
686 char dnsengine[] = "singlethread-object";
688 if (*Config->CustomVersion)
690 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
694 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%s,%s,%s]",VERSION,Config->ServerName,SYSTEM,REVISION,SE->GetName().c_str(),dnsengine);
699 char* InspIRCd::ModuleError()
704 void InspIRCd::EraseFactory(int j)
707 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
713 factory.push_back(NULL);
720 void InspIRCd::EraseModule(int j)
723 for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
729 modules.push_back(NULL);
735 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
739 Config->module_names.erase(v);
747 void InspIRCd::MoveTo(std::string modulename,int slot)
749 unsigned int v2 = 256;
750 for (unsigned int v = 0; v < Config->module_names.size(); v++)
752 if (Config->module_names[v] == modulename)
754 // found an instance, swap it with the item at the end
759 if ((v2 != (unsigned int)slot) && (v2 < 256))
761 // Swap the module names over
762 Config->module_names[v2] = Config->module_names[slot];
763 Config->module_names[slot] = modulename;
764 // now swap the module factories
765 ircd_module* temp = factory[v2];
766 factory[v2] = factory[slot];
767 factory[slot] = temp;
768 // now swap the module objects
769 Module* temp_module = modules[v2];
770 modules[v2] = modules[slot];
771 modules[slot] = temp_module;
772 // now swap the implement lists (we dont
773 // need to swap the global or recount it)
774 for (int n = 0; n < 255; n++)
776 char x = Config->implement_lists[v2][n];
777 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
778 Config->implement_lists[slot][n] = x;
783 void InspIRCd::MoveAfter(std::string modulename, std::string after)
785 for (unsigned int v = 0; v < Config->module_names.size(); v++)
787 if (Config->module_names[v] == after)
789 MoveTo(modulename, v);
795 void InspIRCd::MoveBefore(std::string modulename, std::string before)
797 for (unsigned int v = 0; v < Config->module_names.size(); v++)
799 if (Config->module_names[v] == before)
803 MoveTo(modulename, v-1);
807 MoveTo(modulename, v);
814 void InspIRCd::MoveToFirst(std::string modulename)
816 MoveTo(modulename,0);
819 void InspIRCd::MoveToLast(std::string modulename)
821 MoveTo(modulename,this->GetModuleCount());
824 void InspIRCd::BuildISupport()
826 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
828 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES-1 << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << Config->MaxChans << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
829 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
830 v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32 ELIST=MU";
831 Config->data005 = v.str();
832 FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
836 bool InspIRCd::UnloadModule(const char* filename)
838 std::string filename_str = filename;
839 for (unsigned int j = 0; j != Config->module_names.size(); j++)
841 if (Config->module_names[j] == filename_str)
843 if (modules[j]->GetVersion().Flags & VF_STATIC)
845 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
846 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
849 std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modules[j]);
850 if (intercount.first > 0)
852 this->Log(DEFAULT,"Failed to unload module %s, being used by %d other(s) via interface '%s'",filename, intercount.first, intercount.second.c_str());
853 snprintf(MODERR,MAXBUF,"Module not unloadable (Still in use by %d other module%s which %s using its interface '%s') -- unload dependent modules first!",
855 intercount.first > 1 ? "s" : "",
856 intercount.first > 1 ? "are" : "is",
857 intercount.second.c_str());
860 /* Give the module a chance to tidy out all its metadata */
861 for (chan_hash::iterator c = this->chanlist->begin(); c != this->chanlist->end(); c++)
863 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
865 for (user_hash::iterator u = this->clientlist->begin(); u != this->clientlist->end(); u++)
867 modules[j]->OnCleanup(TYPE_USER,u->second);
870 /* Tidy up any dangling resolvers */
871 this->Res->CleanResolvers(modules[j]);
873 FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
875 for(int t = 0; t < 255; t++)
877 Config->global_implementation[t] -= Config->implement_lists[j][t];
880 /* We have to renumber implement_lists after unload because the module numbers change!
882 for(int j2 = j; j2 < 254; j2++)
884 for(int t = 0; t < 255; t++)
886 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
891 Parser->RemoveCommands(filename);
892 this->EraseModule(j);
893 this->EraseFactory(j);
894 this->Log(DEFAULT,"Module %s unloaded",filename);
900 this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
901 snprintf(MODERR,MAXBUF,"Module not loaded");
905 bool InspIRCd::LoadModule(const char* filename)
907 /* Do we have a glob pattern in the filename?
908 * The user wants to load multiple modules which
911 if (strchr(filename,'*') || (strchr(filename,'?')))
914 DIR* library = opendir(Config->ModPath);
917 /* Try and locate and load all modules matching the pattern */
918 dirent* entry = NULL;
919 while ((entry = readdir(library)))
921 if (this->MatchText(entry->d_name, filename))
923 if (!this->LoadModule(entry->d_name))
929 /* Loadmodule will now return false if any one of the modules failed
930 * to load (but wont abort when it encounters a bad one) and when 1 or
931 * more modules were actually loaded.
933 return (n_match > 0);
936 char modfile[MAXBUF];
937 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
938 std::string filename_str = filename;
940 if (!ServerConfig::DirValid(modfile))
942 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
943 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
946 if (ServerConfig::FileExists(modfile))
949 for (unsigned int j = 0; j < Config->module_names.size(); j++)
951 if (Config->module_names[j] == filename_str)
953 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
954 snprintf(MODERR,MAXBUF,"Module already loaded");
959 ircd_module* a = NULL;
962 a = new ircd_module(this, modfile);
963 factory[this->ModCount+1] = a;
964 if (factory[this->ModCount+1]->LastError())
966 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
967 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
970 if ((long)factory[this->ModCount+1]->factory != -1)
972 m = factory[this->ModCount+1]->factory->CreateModule(this);
974 Version v = m->GetVersion();
976 if (v.API != API_VERSION)
979 this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
980 snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
985 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]"));
988 modules[this->ModCount+1] = m;
989 /* save the module and the module's classfactory, if
990 * this isnt done, random crashes can occur :/ */
991 Config->module_names.push_back(filename);
993 char* x = &Config->implement_lists[this->ModCount+1][0];
994 for(int t = 0; t < 255; t++)
997 modules[this->ModCount+1]->Implements(x);
999 for(int t = 0; t < 255; t++)
1000 Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
1004 this->Log(DEFAULT,"Unable to load %s",modfile);
1005 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
1009 catch (CoreException& modexcept)
1011 this->Log(DEFAULT,"Unable to load %s: %s",modfile,modexcept.GetReason());
1012 snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1018 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
1019 snprintf(MODERR,MAXBUF,"Module file could not be found");
1023 FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
1024 // now work out which modules, if any, want to move to the back of the queue,
1025 // and if they do, move them there.
1026 std::vector<std::string> put_to_back;
1027 std::vector<std::string> put_to_front;
1028 std::map<std::string,std::string> put_before;
1029 std::map<std::string,std::string> put_after;
1030 for (unsigned int j = 0; j < Config->module_names.size(); j++)
1032 if (modules[j]->Prioritize() == PRIORITY_LAST)
1033 put_to_back.push_back(Config->module_names[j]);
1034 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
1035 put_to_front.push_back(Config->module_names[j]);
1036 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
1037 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
1038 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
1039 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
1041 for (unsigned int j = 0; j < put_to_back.size(); j++)
1042 MoveToLast(put_to_back[j]);
1043 for (unsigned int j = 0; j < put_to_front.size(); j++)
1044 MoveToFirst(put_to_front[j]);
1045 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
1046 MoveBefore(j->first,j->second);
1047 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
1048 MoveAfter(j->first,j->second);
1053 void InspIRCd::DoOneIteration(bool process_module_sockets)
1058 static time_t uptime;
1059 static struct tm * stime;
1060 static char window_title[100];
1063 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
1064 * Once per loop iteration is pleanty.
1069 /* Run background module timers every few seconds
1070 * (the docs say modules shouldnt rely on accurate
1071 * timing using this event, so we dont have to
1072 * time this exactly).
1074 if (TIME != OLDTIME)
1077 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
1078 if ((TIME % 3600) == 0)
1080 this->RehashUsersAndChans();
1081 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
1083 Timers->TickTimers(TIME);
1084 this->DoBackgroundUserStuff(TIME);
1086 if ((TIME % 5) == 0)
1088 XLines->expire_lines();
1089 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
1090 Timers->TickMissedTimers(TIME);
1093 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
1094 if (!getrusage(RUSAGE_SELF, &ru))
1096 gettimeofday(&this->stats->LastSampled, NULL);
1097 this->stats->LastCPU = ru.ru_utime;
1104 uptime = Time() - startup_time;
1105 stime = gmtime(&uptime);
1106 snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
1107 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
1108 SetConsoleTitle(window_title);
1113 /* Call the socket engine to wait on the active
1114 * file descriptors. The socket engine has everything's
1115 * descriptors in its list... dns, modules, users,
1116 * servers... so its nice and easy, just one call.
1117 * This will cause any read or write events to be
1118 * dispatched to their handlers.
1120 SE->DispatchEvents();
1122 /* if any users was quit, take them out */
1123 GlobalCulls.Apply();
1125 /* If any inspsockets closed, remove them */
1126 for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
1128 SE->DelFd(x->second);
1139 DoOneIteration(true);
1141 /* This is never reached -- we hope! */
1145 /**********************************************************************************/
1148 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
1151 int main(int argc, char** argv)
1153 SI = new InspIRCd(argc, argv);
1159 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
1160 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
1161 * registration timeout maximum seconds)
1163 bool InspIRCd::AllModulesReportReady(userrec* user)
1165 if (!Config->global_implementation[I_OnCheckReady])
1168 for (int i = 0; i <= this->GetModuleCount(); i++)
1170 if (Config->implement_lists[i][I_OnCheckReady])
1172 int res = modules[i]->OnCheckReady(user);
1180 int InspIRCd::GetModuleCount()
1182 return this->ModCount;
1185 time_t InspIRCd::Time(bool delta)
1188 return TIME + time_delta;
1192 int InspIRCd::SetTimeDelta(int delta)
1194 int old = time_delta;
1196 this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
1200 void InspIRCd::AddLocalClone(userrec* user)
1202 clonemap::iterator x = local_clones.find(user->GetIPString());
1203 if (x != local_clones.end())
1206 local_clones[user->GetIPString()] = 1;
1209 void InspIRCd::AddGlobalClone(userrec* user)
1211 clonemap::iterator y = global_clones.find(user->GetIPString());
1212 if (y != global_clones.end())
1215 global_clones[user->GetIPString()] = 1;
1218 int InspIRCd::GetTimeDelta()
1223 bool FileLogger::Readable()
1228 void FileLogger::HandleEvent(EventType et, int errornum)
1230 this->WriteLogLine("");
1232 ServerInstance->SE->DelFd(this);
1235 void FileLogger::WriteLogLine(const std::string &line)
1238 buffer.append(line);
1242 int written = fprintf(log,"%s",buffer.c_str());
1246 if ((written >= 0) && (written < (int)buffer.length()))
1248 buffer.erase(0, buffer.length());
1249 ServerInstance->SE->AddFd(this);
1251 else if (written == -1)
1253 if (errno == EAGAIN)
1254 ServerInstance->SE->AddFd(this);
1258 /* Wrote the whole buffer, and no need for write callback */
1262 if (writeops++ % 20)
1269 void FileLogger::Close()
1273 /* Burlex: Windows assumes nonblocking on FILE* pointers anyway, and also "file" fd's aren't the same
1274 * as socket fd's. */
1276 int flags = fcntl(fileno(log), F_GETFL, 0);
1277 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
1280 fprintf(log,"%s",buffer.c_str());
1283 ServerInstance->SE->DelFd(this);
1293 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
1297 irc::sockets::NonBlocking(fileno(log));
1298 this->SetFd(fileno(log));
1303 FileLogger::~FileLogger()