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>
24 /* This is just to be completely certain that the change which fixed getrusage on RH7 doesn't break anything else -- Om */
35 #include "socketengine.h"
36 #include "inspircd_se_config.h"
39 #include "command_parse.h"
40 #include "exitcodes.h"
44 /* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
45 static DWORD owner_processid = 0;
47 DWORD WindowsForkStart(InspIRCd * Instance)
49 /* Windows implementation of fork() :P */
51 char module[MAX_PATH];
52 if(!GetModuleFileName(NULL, module, MAX_PATH))
54 printf("GetModuleFileName() failed.\n");
58 STARTUPINFO startupinfo;
59 PROCESS_INFORMATION procinfo;
60 ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
61 ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
63 // Fill in the startup info struct
64 GetStartupInfo(&startupinfo);
66 /* Default creation flags create the processes suspended */
67 DWORD startupflags = CREATE_SUSPENDED;
69 /* On windows 2003/XP and above, we can use the value
70 * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
71 * to the process which we may require on these operating systems.
74 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
76 if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
77 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
79 // Launch our "forked" process.
80 BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
81 strdup(GetCommandLine()), // Command line (exe plus parameters from the OS)
82 // NOTE: We cannot return the direct value of the
83 // GetCommandLine function here, as the pointer is
84 // passed straight to the child process, and will be
85 // invalid once we exit as it goes out of context.
86 // strdup() seems ok, though.
87 0, // PROCESS_SECURITY_ATTRIBUTES
88 0, // THREAD_SECURITY_ATTRIBUTES
89 TRUE, // We went to inherit handles.
90 startupflags, // Allow us full access to the process and suspend it.
92 0, // CURRENT_DIRECTORY
93 &startupinfo, // startup info
94 &procinfo); // process info
98 printf("CreateProcess() error: %s\n", dlerror());
102 // Set the owner process id in the target process.
104 DWORD pid = GetCurrentProcessId();
105 if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
107 printf("WriteProcessMemory() failed: %s\n", dlerror());
111 // Resume the other thread (let it start)
112 ResumeThread(procinfo.hThread);
114 // 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.
115 WaitForSingleObject(procinfo.hProcess, INFINITE);
117 // If we hit this it means startup failed, default to 14 if this fails.
119 GetExitCodeProcess(procinfo.hProcess, &ExitCode);
120 CloseHandle(procinfo.hThread);
121 CloseHandle(procinfo.hProcess);
125 void WindowsForkKillOwner(InspIRCd * Instance)
127 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
128 if(!hProcess || !owner_processid)
130 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
135 if(!TerminateProcess(hProcess, 0))
137 printf("Could not TerminateProcess(): %s\n", dlerror());
141 CloseHandle(hProcess);
146 using irc::sockets::NonBlocking;
147 using irc::sockets::Blocking;
148 using irc::sockets::insp_ntoa;
149 using irc::sockets::insp_inaddr;
150 using irc::sockets::insp_sockaddr;
154 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
155 const char* ExitCodes[] =
158 "DIE command", /* 1 */
159 "execv() failed", /* 2 */
160 "Internal error", /* 3 */
161 "Config file error", /* 4 */
162 "Logfile error", /* 5 */
163 "POSIX fork failed", /* 6 */
164 "Bad commandline parameters", /* 7 */
165 "No ports could be bound", /* 8 */
166 "Can't write PID file", /* 9 */
167 "SocketEngine could not initialize", /* 10 */
168 "Refusing to start up as root", /* 11 */
169 "Found a <die> tag!", /* 12 */
170 "Couldn't load module on startup", /* 13 */
171 "Could not create windows forked process", /* 14 */
172 "Received SIGTERM", /* 15 */
175 void InspIRCd::AddServerName(const std::string &servername)
177 servernamelist::iterator itr = servernames.begin();
178 for(; itr != servernames.end(); ++itr)
179 if(**itr == servername)
182 string * ns = new string(servername);
183 servernames.push_back(ns);
186 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
188 servernamelist::iterator itr = servernames.begin();
189 for(; itr != servernames.end(); ++itr)
190 if(**itr == servername)
191 return (*itr)->c_str();
193 servernames.push_back(new string(servername));
194 itr = --servernames.end();
195 return (*itr)->c_str();
198 bool InspIRCd::FindServerName(const std::string &servername)
200 servernamelist::iterator itr = servernames.begin();
201 for(; itr != servernames.end(); ++itr)
202 if(**itr == servername)
207 void InspIRCd::Exit(int status)
214 SI->SendError("Exiting with status " + ConvToStr(status) + " (" + std::string(ExitCodes[status]) + ")");
220 void InspIRCd::Cleanup()
222 std::vector<std::string> mymodnames;
223 int MyModCount = this->GetModuleCount();
225 for (unsigned int i = 0; i < Config->ports.size(); i++)
227 /* This calls the constructor and closes the listening socket */
228 delete Config->ports[i];
231 Config->ports.clear();
233 /* Close all client sockets, or the new process inherits them */
234 for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
236 (*i)->SetWriteError("Server shutdown");
240 /* We do this more than once, so that any service providers get a
241 * chance to be unhooked by the modules using them, but then get
242 * a chance to be removed themsleves.
244 for (int tries = 0; tries < 3; tries++)
246 MyModCount = this->GetModuleCount();
249 /* Unload all modules, so they get a chance to clean up their listeners */
250 for (int j = 0; j <= MyModCount; j++)
251 mymodnames.push_back(Config->module_names[j]);
253 for (int k = 0; k <= MyModCount; k++)
254 this->UnloadModule(mymodnames[k].c_str());
258 this->Logger->Close();
260 /* Cleanup Server Names */
261 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
270 void InspIRCd::Restart(const std::string &reason)
272 /* SendError flushes each client's queue,
273 * regardless of writeability state
275 this->SendError(reason);
279 /* Figure out our filename (if theyve renamed it, we're boned) */
283 char module[MAX_PATH];
284 if (GetModuleFileName(NULL, module, MAX_PATH))
287 me = Config->MyDir + "/inspircd";
290 if (execv(me.c_str(), Config->argv) == -1)
292 /* Will raise a SIGABRT if not trapped */
293 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
297 void InspIRCd::Start()
299 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
300 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
301 printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey, Burlex\033[0m\n");
302 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
305 void InspIRCd::Rehash(int status)
307 SI->WriteOpers("*** Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(SI->ConfigFileName));
309 SI->OpenLog(SI->Config->argv, SI->Config->argc);
310 SI->RehashUsersAndChans();
311 FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
312 SI->Config->Read(false,NULL);
315 FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
319 void InspIRCd::ResetMaxBans()
321 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
322 i->second->ResetMaxBans();
326 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
327 * we must occasionally rehash the hash (yes really).
328 * We do this by copying the entries from the old hash to a new hash, causing all
329 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
330 * very expensive, so instead we do it when the user types /REHASH and expects a
331 * short delay anyway.
333 void InspIRCd::RehashUsersAndChans()
335 user_hash* old_users = this->clientlist;
336 chan_hash* old_chans = this->chanlist;
338 this->clientlist = new user_hash();
339 this->chanlist = new chan_hash();
341 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
342 this->clientlist->insert(*n);
346 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
347 this->chanlist->insert(*n);
352 void InspIRCd::CloseLog()
354 this->Logger->Close();
357 void InspIRCd::SetSignals()
360 signal(SIGALRM, SIG_IGN);
361 signal(SIGHUP, InspIRCd::Rehash);
362 signal(SIGPIPE, SIG_IGN);
363 signal(SIGCHLD, SIG_IGN);
365 signal(SIGTERM, InspIRCd::Exit);
368 void InspIRCd::QuickExit(int status)
373 bool InspIRCd::DaemonSeed()
376 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
379 signal(SIGTERM, InspIRCd::QuickExit);
382 if ((childpid = fork ()) < 0)
384 else if (childpid > 0)
386 /* We wait here for the child process to kill us,
387 * so that the shell prompt doesnt come back over
389 * Sending a kill with a signal of 0 just checks
390 * if the child pid is still around. If theyre not,
391 * they threw an error and we should give up.
393 while (kill(childpid, 0) != -1)
399 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
401 signal(SIGTERM, InspIRCd::Exit);
404 if (getrlimit(RLIMIT_CORE, &rl) == -1)
406 this->Log(DEFAULT,"Failed to getrlimit()!");
411 rl.rlim_cur = rl.rlim_max;
412 if (setrlimit(RLIMIT_CORE, &rl) == -1)
413 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
420 void InspIRCd::WritePID(const std::string &filename)
422 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
423 if (*(fname.begin()) != '/')
425 std::string::size_type pos;
426 std::string confpath = this->ConfigFileName;
427 if ((pos = confpath.rfind("/")) != std::string::npos)
429 /* Leaves us with just the path */
430 fname = confpath.substr(0, pos) + std::string("/") + fname;
433 std::ofstream outfile(fname.c_str());
434 if (outfile.is_open())
441 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
442 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
443 Exit(EXIT_STATUS_PID);
447 std::string InspIRCd::GetRevision()
452 InspIRCd::InspIRCd(int argc, char** argv)
453 : ModCount(-1), GlobalCulls(this)
457 int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0; /* flag variables */
462 memset(&server, 0, sizeof(server));
463 memset(&client, 0, sizeof(client));
465 this->unregistered_count = 0;
467 this->clientlist = new user_hash();
468 this->chanlist = new chan_hash();
470 this->Config = new ServerConfig(this);
472 this->Config->argv = argv;
473 this->Config->argc = argc;
475 chdir(Config->GetFullProgDir().c_str());
477 this->Config->opertypes.clear();
478 this->Config->operclass.clear();
479 this->SNO = new SnomaskManager(this);
480 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
481 this->time_delta = 0;
482 this->next_call = this->TIME + 3;
485 *this->LogFileName = 0;
486 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
488 struct option longopts[] =
490 { "nofork", no_argument, &do_nofork, 1 },
491 { "logfile", required_argument, NULL, 'f' },
492 { "config", required_argument, NULL, 'c' },
493 { "debug", no_argument, &do_debug, 1 },
494 { "nolog", no_argument, &do_nolog, 1 },
495 { "runasroot", no_argument, &do_root, 1 },
496 { "version", no_argument, &do_version, 1 },
500 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
505 /* Log filename was set */
506 strlcpy(LogFileName, optarg, MAXBUF);
509 /* Config filename was set */
510 strlcpy(ConfigFileName, optarg, MAXBUF);
513 /* getopt_long_only() set an int variable, just keep going */
516 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
517 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
518 Exit(EXIT_STATUS_ARGV);
525 printf("\n%s r%s\n", VERSION, REVISION);
526 Exit(EXIT_STATUS_NOERROR);
532 if(!do_nofork && !owner_processid)
534 DWORD ExitCode = WindowsForkStart(this);
541 WSAStartup(MAKEWORD(2,0), &wsadata);
544 if (!ServerConfig::FileExists(this->ConfigFileName))
546 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
547 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
548 Exit(EXIT_STATUS_CONFIG);
553 /* Set the finished argument values */
554 Config->nofork = do_nofork;
555 Config->forcedebug = do_debug;
556 Config->writelog = !do_nolog;
558 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
560 this->OpenLog(argv, argc);
562 this->stats = new serverstats();
563 this->Timers = new TimerManager(this);
564 this->Parser = new CommandParser(this);
565 this->XLines = new XLineManager(this);
566 Config->ClearStack();
567 Config->Read(true, NULL);
573 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
574 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
575 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
576 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
577 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
578 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
579 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
580 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
588 if (!this->DaemonSeed())
590 printf("ERROR: could not go into daemon mode. Shutting down.\n");
591 Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
592 Exit(EXIT_STATUS_FORK);
597 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
598 * initialize the socket engine.
600 SocketEngineFactory* SEF = new SocketEngineFactory();
601 SE = SEF->Create(this);
604 this->Modes = new ModeParser(this);
605 this->AddServerName(Config->ServerName);
607 int bounditems = BindPorts(true, found_ports, pl);
609 for(int t = 0; t < 255; t++)
610 Config->global_implementation[t] = 0;
612 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
616 this->Res = new DNS(this);
618 this->LoadAllModules();
619 /* Just in case no modules were loaded - fix for bug #101 */
620 this->BuildISupport();
621 InitializeDisabledCommands(Config->DisabledCommands, this);
623 if ((Config->ports.size() == 0) && (found_ports > 0))
625 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
626 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
627 Exit(EXIT_STATUS_BIND);
630 if (Config->ports.size() != (unsigned int)found_ports)
632 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
633 printf("The following port(s) failed to bind:\n");
635 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
637 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
643 if (kill(getppid(), SIGTERM) == -1)
645 printf("Error killing parent process: %s\n",strerror(errno));
646 Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
650 if (isatty(0) && isatty(1) && isatty(2))
652 /* We didn't start from a TTY, we must have started from a background process -
653 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
664 Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
671 WindowsForkKillOwner(this);
675 printf("\nInspIRCd is now running!\n");
676 Log(DEFAULT,"Startup complete.");
678 this->WritePID(Config->PID);
681 std::string InspIRCd::GetVersionString()
683 char versiondata[MAXBUF];
684 char dnsengine[] = "singlethread-object";
686 if (*Config->CustomVersion)
688 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
692 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%s,%s,%s]",VERSION,Config->ServerName,SYSTEM,REVISION,SE->GetName().c_str(),dnsengine);
697 char* InspIRCd::ModuleError()
702 void InspIRCd::EraseFactory(int j)
705 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
711 factory.push_back(NULL);
718 void InspIRCd::EraseModule(int j)
721 for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
727 modules.push_back(NULL);
733 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
737 Config->module_names.erase(v);
745 void InspIRCd::MoveTo(std::string modulename,int slot)
747 unsigned int v2 = 256;
748 for (unsigned int v = 0; v < Config->module_names.size(); v++)
750 if (Config->module_names[v] == modulename)
752 // found an instance, swap it with the item at the end
757 if ((v2 != (unsigned int)slot) && (v2 < 256))
759 // Swap the module names over
760 Config->module_names[v2] = Config->module_names[slot];
761 Config->module_names[slot] = modulename;
762 // now swap the module factories
763 ircd_module* temp = factory[v2];
764 factory[v2] = factory[slot];
765 factory[slot] = temp;
766 // now swap the module objects
767 Module* temp_module = modules[v2];
768 modules[v2] = modules[slot];
769 modules[slot] = temp_module;
770 // now swap the implement lists (we dont
771 // need to swap the global or recount it)
772 for (int n = 0; n < 255; n++)
774 char x = Config->implement_lists[v2][n];
775 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
776 Config->implement_lists[slot][n] = x;
781 void InspIRCd::MoveAfter(std::string modulename, std::string after)
783 for (unsigned int v = 0; v < Config->module_names.size(); v++)
785 if (Config->module_names[v] == after)
787 MoveTo(modulename, v);
793 void InspIRCd::MoveBefore(std::string modulename, std::string before)
795 for (unsigned int v = 0; v < Config->module_names.size(); v++)
797 if (Config->module_names[v] == before)
801 MoveTo(modulename, v-1);
805 MoveTo(modulename, v);
812 void InspIRCd::MoveToFirst(std::string modulename)
814 MoveTo(modulename,0);
817 void InspIRCd::MoveToLast(std::string modulename)
819 MoveTo(modulename,this->GetModuleCount());
822 void InspIRCd::BuildISupport()
824 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
826 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES-1 << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << Config->MaxChans << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
827 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
828 v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32 ELIST=MU";
829 Config->data005 = v.str();
830 FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
834 bool InspIRCd::UnloadModule(const char* filename)
836 std::string filename_str = filename;
837 for (unsigned int j = 0; j != Config->module_names.size(); j++)
839 if (Config->module_names[j] == filename_str)
841 if (modules[j]->GetVersion().Flags & VF_STATIC)
843 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
844 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
847 std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modules[j]);
848 if (intercount.first > 0)
850 this->Log(DEFAULT,"Failed to unload module %s, being used by %d other(s) via interface '%s'",filename, intercount.first, intercount.second.c_str());
851 snprintf(MODERR,MAXBUF,"Module not unloadable (Still in use by %d other module%s which %s using its interface '%s') -- unload dependent modules first!",
853 intercount.first > 1 ? "s" : "",
854 intercount.first > 1 ? "are" : "is",
855 intercount.second.c_str());
858 /* Give the module a chance to tidy out all its metadata */
859 for (chan_hash::iterator c = this->chanlist->begin(); c != this->chanlist->end(); c++)
861 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
863 for (user_hash::iterator u = this->clientlist->begin(); u != this->clientlist->end(); u++)
865 modules[j]->OnCleanup(TYPE_USER,u->second);
868 /* Tidy up any dangling resolvers */
869 this->Res->CleanResolvers(modules[j]);
871 FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
873 for(int t = 0; t < 255; t++)
875 Config->global_implementation[t] -= Config->implement_lists[j][t];
878 /* We have to renumber implement_lists after unload because the module numbers change!
880 for(int j2 = j; j2 < 254; j2++)
882 for(int t = 0; t < 255; t++)
884 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
889 Parser->RemoveCommands(filename);
890 this->EraseModule(j);
891 this->EraseFactory(j);
892 this->Log(DEFAULT,"Module %s unloaded",filename);
898 this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
899 snprintf(MODERR,MAXBUF,"Module not loaded");
903 bool InspIRCd::LoadModule(const char* filename)
905 /* Do we have a glob pattern in the filename?
906 * The user wants to load multiple modules which
909 if (strchr(filename,'*') || (strchr(filename,'?')))
912 DIR* library = opendir(Config->ModPath);
915 /* Try and locate and load all modules matching the pattern */
916 dirent* entry = NULL;
917 while ((entry = readdir(library)))
919 if (this->MatchText(entry->d_name, filename))
921 if (!this->LoadModule(entry->d_name))
927 /* Loadmodule will now return false if any one of the modules failed
928 * to load (but wont abort when it encounters a bad one) and when 1 or
929 * more modules were actually loaded.
931 return (n_match > 0);
934 char modfile[MAXBUF];
935 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
936 std::string filename_str = filename;
938 if (!ServerConfig::DirValid(modfile))
940 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
941 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
944 if (ServerConfig::FileExists(modfile))
947 for (unsigned int j = 0; j < Config->module_names.size(); j++)
949 if (Config->module_names[j] == filename_str)
951 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
952 snprintf(MODERR,MAXBUF,"Module already loaded");
958 ircd_module* a = new ircd_module(this, modfile);
959 factory[this->ModCount+1] = a;
960 if (factory[this->ModCount+1]->LastError())
962 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
963 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
966 if ((long)factory[this->ModCount+1]->factory != -1)
968 Module* m = factory[this->ModCount+1]->factory->CreateModule(this);
970 Version v = m->GetVersion();
972 if (v.API != API_VERSION)
976 this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
977 snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
982 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]"));
985 modules[this->ModCount+1] = m;
986 /* save the module and the module's classfactory, if
987 * this isnt done, random crashes can occur :/ */
988 Config->module_names.push_back(filename);
990 char* x = &Config->implement_lists[this->ModCount+1][0];
991 for(int t = 0; t < 255; t++)
994 modules[this->ModCount+1]->Implements(x);
996 for(int t = 0; t < 255; t++)
997 Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
1001 this->Log(DEFAULT,"Unable to load %s",modfile);
1002 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
1006 catch (CoreException& modexcept)
1008 this->Log(DEFAULT,"Unable to load %s: %s",modfile,modexcept.GetReason());
1009 snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1015 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
1016 snprintf(MODERR,MAXBUF,"Module file could not be found");
1020 FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
1021 // now work out which modules, if any, want to move to the back of the queue,
1022 // and if they do, move them there.
1023 std::vector<std::string> put_to_back;
1024 std::vector<std::string> put_to_front;
1025 std::map<std::string,std::string> put_before;
1026 std::map<std::string,std::string> put_after;
1027 for (unsigned int j = 0; j < Config->module_names.size(); j++)
1029 if (modules[j]->Prioritize() == PRIORITY_LAST)
1030 put_to_back.push_back(Config->module_names[j]);
1031 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
1032 put_to_front.push_back(Config->module_names[j]);
1033 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
1034 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
1035 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
1036 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
1038 for (unsigned int j = 0; j < put_to_back.size(); j++)
1039 MoveToLast(put_to_back[j]);
1040 for (unsigned int j = 0; j < put_to_front.size(); j++)
1041 MoveToFirst(put_to_front[j]);
1042 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
1043 MoveBefore(j->first,j->second);
1044 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
1045 MoveAfter(j->first,j->second);
1050 void InspIRCd::DoOneIteration(bool process_module_sockets)
1055 static time_t uptime;
1056 static struct tm * stime;
1057 static char window_title[100];
1060 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
1061 * Once per loop iteration is pleanty.
1066 /* Run background module timers every few seconds
1067 * (the docs say modules shouldnt rely on accurate
1068 * timing using this event, so we dont have to
1069 * time this exactly).
1071 if (TIME != OLDTIME)
1074 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
1075 if ((TIME % 3600) == 0)
1077 this->RehashUsersAndChans();
1078 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
1080 Timers->TickTimers(TIME);
1081 this->DoBackgroundUserStuff(TIME);
1083 if ((TIME % 5) == 0)
1085 XLines->expire_lines();
1086 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
1087 Timers->TickMissedTimers(TIME);
1090 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
1091 if (!getrusage(RUSAGE_SELF, &ru))
1093 gettimeofday(&this->stats->LastSampled, NULL);
1094 this->stats->LastCPU = ru.ru_utime;
1101 uptime = Time() - startup_time;
1102 stime = gmtime(&uptime);
1103 snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
1104 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
1105 SetConsoleTitle(window_title);
1110 /* Call the socket engine to wait on the active
1111 * file descriptors. The socket engine has everything's
1112 * descriptors in its list... dns, modules, users,
1113 * servers... so its nice and easy, just one call.
1114 * This will cause any read or write events to be
1115 * dispatched to their handlers.
1117 SE->DispatchEvents();
1119 /* if any users was quit, take them out */
1120 GlobalCulls.Apply();
1122 /* If any inspsockets closed, remove them */
1123 for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
1125 SE->DelFd(x->second);
1136 DoOneIteration(true);
1138 /* This is never reached -- we hope! */
1142 /**********************************************************************************/
1145 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
1148 int main(int argc, char** argv)
1150 SI = new InspIRCd(argc, argv);
1156 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
1157 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
1158 * registration timeout maximum seconds)
1160 bool InspIRCd::AllModulesReportReady(userrec* user)
1162 if (!Config->global_implementation[I_OnCheckReady])
1165 for (int i = 0; i <= this->GetModuleCount(); i++)
1167 if (Config->implement_lists[i][I_OnCheckReady])
1169 int res = modules[i]->OnCheckReady(user);
1177 int InspIRCd::GetModuleCount()
1179 return this->ModCount;
1182 time_t InspIRCd::Time(bool delta)
1185 return TIME + time_delta;
1189 int InspIRCd::SetTimeDelta(int delta)
1191 int old = time_delta;
1193 this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
1197 void InspIRCd::AddLocalClone(userrec* user)
1199 clonemap::iterator x = local_clones.find(user->GetIPString());
1200 if (x != local_clones.end())
1203 local_clones[user->GetIPString()] = 1;
1206 void InspIRCd::AddGlobalClone(userrec* user)
1208 clonemap::iterator y = global_clones.find(user->GetIPString());
1209 if (y != global_clones.end())
1212 global_clones[user->GetIPString()] = 1;
1215 int InspIRCd::GetTimeDelta()
1220 bool FileLogger::Readable()
1225 void FileLogger::HandleEvent(EventType et, int errornum)
1227 this->WriteLogLine("");
1229 ServerInstance->SE->DelFd(this);
1232 void FileLogger::WriteLogLine(const std::string &line)
1235 buffer.append(line);
1239 int written = fprintf(log,"%s",buffer.c_str());
1243 if ((written >= 0) && (written < (int)buffer.length()))
1245 buffer.erase(0, buffer.length());
1246 ServerInstance->SE->AddFd(this);
1248 else if (written == -1)
1250 if (errno == EAGAIN)
1251 ServerInstance->SE->AddFd(this);
1255 /* Wrote the whole buffer, and no need for write callback */
1259 if (writeops++ % 20)
1266 void FileLogger::Close()
1270 /* Burlex: Windows assumes nonblocking on FILE* pointers anyway, and also "file" fd's aren't the same
1271 * as socket fd's. */
1273 int flags = fcntl(fileno(log), F_GETFL, 0);
1274 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
1277 fprintf(log,"%s",buffer.c_str());
1280 ServerInstance->SE->DelFd(this);
1290 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
1294 irc::sockets::NonBlocking(fileno(log));
1295 this->SetFd(fileno(log));
1300 FileLogger::~FileLogger()