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"
48 /* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
49 static DWORD owner_processid = 0;
51 DWORD WindowsForkStart(InspIRCd * Instance)
53 /* Windows implementation of fork() :P */
55 char module[MAX_PATH];
56 if(!GetModuleFileName(NULL, module, MAX_PATH))
58 printf("GetModuleFileName() failed.\n");
62 STARTUPINFO startupinfo;
63 PROCESS_INFORMATION procinfo;
64 ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
65 ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
67 // Fill in the startup info struct
68 GetStartupInfo(&startupinfo);
70 /* Default creation flags create the processes suspended */
71 DWORD startupflags = CREATE_SUSPENDED;
73 /* On windows 2003/XP and above, we can use the value
74 * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
75 * to the process which we may require on these operating systems.
78 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
80 if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
81 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
83 // Launch our "forked" process.
84 BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
85 strdup(GetCommandLine()), // Command line (exe plus parameters from the OS)
86 // NOTE: We cannot return the direct value of the
87 // GetCommandLine function here, as the pointer is
88 // passed straight to the child process, and will be
89 // invalid once we exit as it goes out of context.
90 // strdup() seems ok, though.
91 0, // PROCESS_SECURITY_ATTRIBUTES
92 0, // THREAD_SECURITY_ATTRIBUTES
93 TRUE, // We went to inherit handles.
94 startupflags, // Allow us full access to the process and suspend it.
96 0, // CURRENT_DIRECTORY
97 &startupinfo, // startup info
98 &procinfo); // process info
102 printf("CreateProcess() error: %s\n", dlerror());
106 // Set the owner process id in the target process.
108 DWORD pid = GetCurrentProcessId();
109 if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
111 printf("WriteProcessMemory() failed: %s\n", dlerror());
115 // Resume the other thread (let it start)
116 ResumeThread(procinfo.hThread);
118 // 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.
119 WaitForSingleObject(procinfo.hProcess, INFINITE);
121 // If we hit this it means startup failed, default to 14 if this fails.
123 GetExitCodeProcess(procinfo.hProcess, &ExitCode);
124 CloseHandle(procinfo.hThread);
125 CloseHandle(procinfo.hProcess);
129 void WindowsForkKillOwner(InspIRCd * Instance)
131 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
132 if(!hProcess || !owner_processid)
134 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
139 if(!TerminateProcess(hProcess, 0))
141 printf("Could not TerminateProcess(): %s\n", dlerror());
145 CloseHandle(hProcess);
150 using irc::sockets::NonBlocking;
151 using irc::sockets::Blocking;
152 using irc::sockets::insp_ntoa;
153 using irc::sockets::insp_inaddr;
154 using irc::sockets::insp_sockaddr;
158 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
159 const char* ExitCodes[] =
162 "DIE command", /* 1 */
163 "execv() failed", /* 2 */
164 "Internal error", /* 3 */
165 "Config file error", /* 4 */
166 "Logfile error", /* 5 */
167 "POSIX fork failed", /* 6 */
168 "Bad commandline parameters", /* 7 */
169 "No ports could be bound", /* 8 */
170 "Can't write PID file", /* 9 */
171 "SocketEngine could not initialize", /* 10 */
172 "Refusing to start up as root", /* 11 */
173 "Found a <die> tag!", /* 12 */
174 "Couldn't load module on startup", /* 13 */
175 "Could not create windows forked process", /* 14 */
176 "Received SIGTERM", /* 15 */
179 void InspIRCd::AddServerName(const std::string &servername)
181 servernamelist::iterator itr = servernames.begin();
182 for(; itr != servernames.end(); ++itr)
183 if(**itr == servername)
186 string * ns = new string(servername);
187 servernames.push_back(ns);
190 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
192 servernamelist::iterator itr = servernames.begin();
193 for(; itr != servernames.end(); ++itr)
194 if(**itr == servername)
195 return (*itr)->c_str();
197 servernames.push_back(new string(servername));
198 itr = --servernames.end();
199 return (*itr)->c_str();
202 bool InspIRCd::FindServerName(const std::string &servername)
204 servernamelist::iterator itr = servernames.begin();
205 for(; itr != servernames.end(); ++itr)
206 if(**itr == servername)
211 void InspIRCd::Exit(int status)
218 SI->SendError("Exiting with status " + ConvToStr(status) + " (" + std::string(ExitCodes[status]) + ")");
224 void InspIRCd::Cleanup()
226 std::vector<std::string> mymodnames;
227 int MyModCount = this->GetModuleCount();
229 for (unsigned int i = 0; i < Config->ports.size(); i++)
231 /* This calls the constructor and closes the listening socket */
232 delete Config->ports[i];
235 Config->ports.clear();
237 /* Close all client sockets, or the new process inherits them */
238 for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
240 (*i)->SetWriteError("Server shutdown");
244 /* We do this more than once, so that any service providers get a
245 * chance to be unhooked by the modules using them, but then get
246 * a chance to be removed themsleves.
248 for (int tries = 0; tries < 3; tries++)
250 MyModCount = this->GetModuleCount();
253 /* Unload all modules, so they get a chance to clean up their listeners */
254 for (int j = 0; j <= MyModCount; j++)
255 mymodnames.push_back(Config->module_names[j]);
257 for (int k = 0; k <= MyModCount; k++)
258 this->UnloadModule(mymodnames[k].c_str());
262 this->Logger->Close();
264 /* Cleanup Server Names */
265 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
274 void InspIRCd::Restart(const std::string &reason)
276 /* SendError flushes each client's queue,
277 * regardless of writeability state
279 this->SendError(reason);
283 /* Figure out our filename (if theyve renamed it, we're boned) */
287 char module[MAX_PATH];
288 if (GetModuleFileName(NULL, module, MAX_PATH))
291 me = Config->MyDir + "/inspircd";
294 if (execv(me.c_str(), Config->argv) == -1)
296 /* Will raise a SIGABRT if not trapped */
297 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
301 void InspIRCd::Start()
303 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
304 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
305 printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey, Burlex\033[0m\n");
306 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
309 void InspIRCd::Rehash(int status)
311 SI->WriteOpers("*** Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(SI->ConfigFileName));
313 SI->OpenLog(SI->Config->argv, SI->Config->argc);
314 SI->RehashUsersAndChans();
315 FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
316 SI->Config->Read(false,NULL);
319 FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
323 void InspIRCd::ResetMaxBans()
325 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
326 i->second->ResetMaxBans();
330 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
331 * we must occasionally rehash the hash (yes really).
332 * We do this by copying the entries from the old hash to a new hash, causing all
333 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
334 * very expensive, so instead we do it when the user types /REHASH and expects a
335 * short delay anyway.
337 void InspIRCd::RehashUsersAndChans()
339 user_hash* old_users = this->clientlist;
340 chan_hash* old_chans = this->chanlist;
342 this->clientlist = new user_hash();
343 this->chanlist = new chan_hash();
345 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
346 this->clientlist->insert(*n);
350 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
351 this->chanlist->insert(*n);
356 void InspIRCd::CloseLog()
358 this->Logger->Close();
361 void InspIRCd::SetSignals()
364 signal(SIGALRM, SIG_IGN);
365 signal(SIGHUP, InspIRCd::Rehash);
366 signal(SIGPIPE, SIG_IGN);
367 signal(SIGCHLD, SIG_IGN);
369 signal(SIGTERM, InspIRCd::Exit);
372 void InspIRCd::QuickExit(int status)
377 bool InspIRCd::DaemonSeed()
380 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
383 signal(SIGTERM, InspIRCd::QuickExit);
386 if ((childpid = fork ()) < 0)
388 else if (childpid > 0)
390 /* We wait here for the child process to kill us,
391 * so that the shell prompt doesnt come back over
393 * Sending a kill with a signal of 0 just checks
394 * if the child pid is still around. If theyre not,
395 * they threw an error and we should give up.
397 while (kill(childpid, 0) != -1)
403 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
405 signal(SIGTERM, InspIRCd::Exit);
408 if (getrlimit(RLIMIT_CORE, &rl) == -1)
410 this->Log(DEFAULT,"Failed to getrlimit()!");
415 rl.rlim_cur = rl.rlim_max;
416 if (setrlimit(RLIMIT_CORE, &rl) == -1)
417 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
424 void InspIRCd::WritePID(const std::string &filename)
426 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
427 if (*(fname.begin()) != '/')
429 std::string::size_type pos;
430 std::string confpath = this->ConfigFileName;
431 if ((pos = confpath.rfind("/")) != std::string::npos)
433 /* Leaves us with just the path */
434 fname = confpath.substr(0, pos) + std::string("/") + fname;
437 std::ofstream outfile(fname.c_str());
438 if (outfile.is_open())
445 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
446 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
447 Exit(EXIT_STATUS_PID);
451 std::string InspIRCd::GetRevision()
456 InspIRCd::InspIRCd(int argc, char** argv)
457 : ModCount(-1), GlobalCulls(this)
461 int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0; /* flag variables */
466 memset(&server, 0, sizeof(server));
467 memset(&client, 0, sizeof(client));
469 this->unregistered_count = 0;
471 this->clientlist = new user_hash();
472 this->chanlist = new chan_hash();
474 this->Config = new ServerConfig(this);
476 this->Config->argv = argv;
477 this->Config->argc = argc;
479 chdir(Config->GetFullProgDir().c_str());
481 this->Config->opertypes.clear();
482 this->Config->operclass.clear();
483 this->SNO = new SnomaskManager(this);
484 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
485 this->time_delta = 0;
486 this->next_call = this->TIME + 3;
489 *this->LogFileName = 0;
490 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
492 struct option longopts[] =
494 { "nofork", no_argument, &do_nofork, 1 },
495 { "logfile", required_argument, NULL, 'f' },
496 { "config", required_argument, NULL, 'c' },
497 { "debug", no_argument, &do_debug, 1 },
498 { "nolog", no_argument, &do_nolog, 1 },
499 { "runasroot", no_argument, &do_root, 1 },
500 { "version", no_argument, &do_version, 1 },
504 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
509 /* Log filename was set */
510 strlcpy(LogFileName, optarg, MAXBUF);
513 /* Config filename was set */
514 strlcpy(ConfigFileName, optarg, MAXBUF);
517 /* getopt_long_only() set an int variable, just keep going */
520 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
521 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
522 Exit(EXIT_STATUS_ARGV);
529 printf("\n%s r%s\n", VERSION, REVISION);
530 Exit(EXIT_STATUS_NOERROR);
536 if(!do_nofork && !owner_processid)
538 DWORD ExitCode = WindowsForkStart(this);
545 WSAStartup(MAKEWORD(2,0), &wsadata);
548 if (!ServerConfig::FileExists(this->ConfigFileName))
550 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
551 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
552 Exit(EXIT_STATUS_CONFIG);
557 /* Set the finished argument values */
558 Config->nofork = do_nofork;
559 Config->forcedebug = do_debug;
560 Config->writelog = !do_nolog;
562 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
564 this->OpenLog(argv, argc);
566 this->stats = new serverstats();
567 this->Timers = new TimerManager(this);
568 this->Parser = new CommandParser(this);
569 this->XLines = new XLineManager(this);
570 Config->ClearStack();
571 Config->Read(true, NULL);
577 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
578 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
579 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
580 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
581 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
582 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
583 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
584 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
592 if (!this->DaemonSeed())
594 printf("ERROR: could not go into daemon mode. Shutting down.\n");
595 Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
596 Exit(EXIT_STATUS_FORK);
601 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
602 * initialize the socket engine.
604 SocketEngineFactory* SEF = new SocketEngineFactory();
605 SE = SEF->Create(this);
608 this->Modes = new ModeParser(this);
609 this->AddServerName(Config->ServerName);
611 int bounditems = BindPorts(true, found_ports, pl);
613 for(int t = 0; t < 255; t++)
614 Config->global_implementation[t] = 0;
616 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
620 this->Res = new DNS(this);
622 this->LoadAllModules();
623 /* Just in case no modules were loaded - fix for bug #101 */
624 this->BuildISupport();
625 InitializeDisabledCommands(Config->DisabledCommands, this);
627 if ((Config->ports.size() == 0) && (found_ports > 0))
629 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
630 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
631 Exit(EXIT_STATUS_BIND);
634 if (Config->ports.size() != (unsigned int)found_ports)
636 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
637 printf("The following port(s) failed to bind:\n");
639 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
641 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
647 if (kill(getppid(), SIGTERM) == -1)
649 printf("Error killing parent process: %s\n",strerror(errno));
650 Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
654 if (isatty(0) && isatty(1) && isatty(2))
656 /* We didn't start from a TTY, we must have started from a background process -
657 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
668 Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
675 WindowsForkKillOwner(this);
679 printf("\nInspIRCd is now running!\n");
680 Log(DEFAULT,"Startup complete.");
682 this->WritePID(Config->PID);
685 std::string InspIRCd::GetVersionString()
687 char versiondata[MAXBUF];
688 char dnsengine[] = "singlethread-object";
690 if (*Config->CustomVersion)
692 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
696 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%s,%s,%s]",VERSION,Config->ServerName,SYSTEM,REVISION,SE->GetName().c_str(),dnsengine);
701 char* InspIRCd::ModuleError()
706 void InspIRCd::EraseFactory(int j)
709 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
715 factory.push_back(NULL);
722 void InspIRCd::EraseModule(int j)
725 for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
731 modules.push_back(NULL);
737 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
741 Config->module_names.erase(v);
749 void InspIRCd::MoveTo(std::string modulename,int slot)
751 unsigned int v2 = 256;
752 for (unsigned int v = 0; v < Config->module_names.size(); v++)
754 if (Config->module_names[v] == modulename)
756 // found an instance, swap it with the item at the end
761 if ((v2 != (unsigned int)slot) && (v2 < 256))
763 // Swap the module names over
764 Config->module_names[v2] = Config->module_names[slot];
765 Config->module_names[slot] = modulename;
766 // now swap the module factories
767 ircd_module* temp = factory[v2];
768 factory[v2] = factory[slot];
769 factory[slot] = temp;
770 // now swap the module objects
771 Module* temp_module = modules[v2];
772 modules[v2] = modules[slot];
773 modules[slot] = temp_module;
774 // now swap the implement lists (we dont
775 // need to swap the global or recount it)
776 for (int n = 0; n < 255; n++)
778 char x = Config->implement_lists[v2][n];
779 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
780 Config->implement_lists[slot][n] = x;
785 void InspIRCd::MoveAfter(std::string modulename, std::string after)
787 for (unsigned int v = 0; v < Config->module_names.size(); v++)
789 if (Config->module_names[v] == after)
791 MoveTo(modulename, v);
797 void InspIRCd::MoveBefore(std::string modulename, std::string before)
799 for (unsigned int v = 0; v < Config->module_names.size(); v++)
801 if (Config->module_names[v] == before)
805 MoveTo(modulename, v-1);
809 MoveTo(modulename, v);
816 void InspIRCd::MoveToFirst(std::string modulename)
818 MoveTo(modulename,0);
821 void InspIRCd::MoveToLast(std::string modulename)
823 MoveTo(modulename,this->GetModuleCount());
826 void InspIRCd::BuildISupport()
828 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
830 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES-1 << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << Config->MaxChans << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
831 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
832 v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32 ELIST=MU";
833 Config->data005 = v.str();
834 FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
838 bool InspIRCd::UnloadModule(const char* filename)
840 std::string filename_str = filename;
841 for (unsigned int j = 0; j != Config->module_names.size(); j++)
843 if (Config->module_names[j] == filename_str)
845 if (modules[j]->GetVersion().Flags & VF_STATIC)
847 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
848 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
851 std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modules[j]);
852 if (intercount.first > 0)
854 this->Log(DEFAULT,"Failed to unload module %s, being used by %d other(s) via interface '%s'",filename, intercount.first, intercount.second.c_str());
855 snprintf(MODERR,MAXBUF,"Module not unloadable (Still in use by %d other module%s which %s using its interface '%s') -- unload dependent modules first!",
857 intercount.first > 1 ? "s" : "",
858 intercount.first > 1 ? "are" : "is",
859 intercount.second.c_str());
862 /* Give the module a chance to tidy out all its metadata */
863 for (chan_hash::iterator c = this->chanlist->begin(); c != this->chanlist->end(); c++)
865 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
867 for (user_hash::iterator u = this->clientlist->begin(); u != this->clientlist->end(); u++)
869 modules[j]->OnCleanup(TYPE_USER,u->second);
872 /* Tidy up any dangling resolvers */
873 this->Res->CleanResolvers(modules[j]);
875 FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
877 for(int t = 0; t < 255; t++)
879 Config->global_implementation[t] -= Config->implement_lists[j][t];
882 /* We have to renumber implement_lists after unload because the module numbers change!
884 for(int j2 = j; j2 < 254; j2++)
886 for(int t = 0; t < 255; t++)
888 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
893 Parser->RemoveCommands(filename);
894 this->EraseModule(j);
895 this->EraseFactory(j);
896 this->Log(DEFAULT,"Module %s unloaded",filename);
902 this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
903 snprintf(MODERR,MAXBUF,"Module not loaded");
907 bool InspIRCd::LoadModule(const char* filename)
909 /* Do we have a glob pattern in the filename?
910 * The user wants to load multiple modules which
913 if (strchr(filename,'*') || (strchr(filename,'?')))
916 DIR* library = opendir(Config->ModPath);
919 /* Try and locate and load all modules matching the pattern */
920 dirent* entry = NULL;
921 while ((entry = readdir(library)))
923 if (this->MatchText(entry->d_name, filename))
925 if (!this->LoadModule(entry->d_name))
931 /* Loadmodule will now return false if any one of the modules failed
932 * to load (but wont abort when it encounters a bad one) and when 1 or
933 * more modules were actually loaded.
935 return (n_match > 0);
938 char modfile[MAXBUF];
939 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
940 std::string filename_str = filename;
942 if (!ServerConfig::DirValid(modfile))
944 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
945 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
948 if (ServerConfig::FileExists(modfile))
951 for (unsigned int j = 0; j < Config->module_names.size(); j++)
953 if (Config->module_names[j] == filename_str)
955 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
956 snprintf(MODERR,MAXBUF,"Module already loaded");
961 ircd_module* a = NULL;
964 a = new ircd_module(this, modfile);
965 factory[this->ModCount+1] = a;
966 if (factory[this->ModCount+1]->LastError())
968 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
969 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
972 if ((long)factory[this->ModCount+1]->factory != -1)
974 m = factory[this->ModCount+1]->factory->CreateModule(this);
976 Version v = m->GetVersion();
978 if (v.API != API_VERSION)
981 this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
982 snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
987 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]"));
990 modules[this->ModCount+1] = m;
991 /* save the module and the module's classfactory, if
992 * this isnt done, random crashes can occur :/ */
993 Config->module_names.push_back(filename);
995 char* x = &Config->implement_lists[this->ModCount+1][0];
996 for(int t = 0; t < 255; t++)
999 modules[this->ModCount+1]->Implements(x);
1001 for(int t = 0; t < 255; t++)
1002 Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
1006 this->Log(DEFAULT,"Unable to load %s",modfile);
1007 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
1011 catch (CoreException& modexcept)
1013 this->Log(DEFAULT,"Unable to load %s: %s",modfile,modexcept.GetReason());
1014 snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1020 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
1021 snprintf(MODERR,MAXBUF,"Module file could not be found");
1025 FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
1026 // now work out which modules, if any, want to move to the back of the queue,
1027 // and if they do, move them there.
1028 std::vector<std::string> put_to_back;
1029 std::vector<std::string> put_to_front;
1030 std::map<std::string,std::string> put_before;
1031 std::map<std::string,std::string> put_after;
1032 for (unsigned int j = 0; j < Config->module_names.size(); j++)
1034 if (modules[j]->Prioritize() == PRIORITY_LAST)
1035 put_to_back.push_back(Config->module_names[j]);
1036 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
1037 put_to_front.push_back(Config->module_names[j]);
1038 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
1039 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
1040 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
1041 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
1043 for (unsigned int j = 0; j < put_to_back.size(); j++)
1044 MoveToLast(put_to_back[j]);
1045 for (unsigned int j = 0; j < put_to_front.size(); j++)
1046 MoveToFirst(put_to_front[j]);
1047 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
1048 MoveBefore(j->first,j->second);
1049 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
1050 MoveAfter(j->first,j->second);
1055 void InspIRCd::DoOneIteration(bool process_module_sockets)
1060 static time_t uptime;
1061 static struct tm * stime;
1062 static char window_title[100];
1065 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
1066 * Once per loop iteration is pleanty.
1071 /* Run background module timers every few seconds
1072 * (the docs say modules shouldnt rely on accurate
1073 * timing using this event, so we dont have to
1074 * time this exactly).
1076 if (TIME != OLDTIME)
1079 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
1080 if ((TIME % 3600) == 0)
1082 this->RehashUsersAndChans();
1083 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
1085 Timers->TickTimers(TIME);
1086 this->DoBackgroundUserStuff(TIME);
1088 if ((TIME % 5) == 0)
1090 XLines->expire_lines();
1091 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
1092 Timers->TickMissedTimers(TIME);
1095 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
1096 if (!getrusage(RUSAGE_SELF, &ru))
1098 gettimeofday(&this->stats->LastSampled, NULL);
1099 this->stats->LastCPU = ru.ru_utime;
1106 uptime = Time() - startup_time;
1107 stime = gmtime(&uptime);
1108 snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
1109 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
1110 SetConsoleTitle(window_title);
1115 /* Call the socket engine to wait on the active
1116 * file descriptors. The socket engine has everything's
1117 * descriptors in its list... dns, modules, users,
1118 * servers... so its nice and easy, just one call.
1119 * This will cause any read or write events to be
1120 * dispatched to their handlers.
1122 SE->DispatchEvents();
1124 /* if any users was quit, take them out */
1125 GlobalCulls.Apply();
1127 /* If any inspsockets closed, remove them */
1128 for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
1130 SE->DelFd(x->second);
1141 DoOneIteration(true);
1143 /* This is never reached -- we hope! */
1147 /**********************************************************************************/
1150 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
1153 int main(int argc, char** argv)
1155 struct timeval start, stop;
1157 std::string pattern;
1158 char *strp, *patternp;
1162 printf("not enough args: pattern string\n");
1172 printf("result of std::string.find: ");
1174 if (str.find(pattern) != string::npos)
1183 printf("result of match(): ");
1185 if (match(strp, patternp))
1195 printf("result of strstr(): ");
1197 if (strstr(strp, patternp))
1206 gettimeofday(&start, NULL);
1207 for (int i = 0; i < 30000; i++)
1211 gettimeofday(&stop, NULL);
1213 printf("std::string.find: %lds and %ldus\n", stop.tv_sec - start.tv_sec, stop.tv_usec - start.tv_usec);
1216 gettimeofday(&start, NULL);
1217 for (int i = 0; i < 30000; i++)
1219 match(strp, patternp);
1221 gettimeofday(&stop, NULL);
1223 printf("match(): %lds and %ldus\n", stop.tv_sec - start.tv_sec, stop.tv_usec - start.tv_usec);
1227 gettimeofday(&start, NULL);
1228 for (int i = 0; i < 30000; i++)
1230 strstr(strp, patternp);
1232 gettimeofday(&stop, NULL);
1234 printf("strstr(): %lds and %ldus\n", stop.tv_sec - start.tv_sec, stop.tv_usec - start.tv_usec);
1242 SI = new InspIRCd(argc, argv);
1248 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
1249 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
1250 * registration timeout maximum seconds)
1252 bool InspIRCd::AllModulesReportReady(userrec* user)
1254 if (!Config->global_implementation[I_OnCheckReady])
1257 for (int i = 0; i <= this->GetModuleCount(); i++)
1259 if (Config->implement_lists[i][I_OnCheckReady])
1261 int res = modules[i]->OnCheckReady(user);
1269 int InspIRCd::GetModuleCount()
1271 return this->ModCount;
1274 time_t InspIRCd::Time(bool delta)
1277 return TIME + time_delta;
1281 int InspIRCd::SetTimeDelta(int delta)
1283 int old = time_delta;
1285 this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
1289 void InspIRCd::AddLocalClone(userrec* user)
1291 clonemap::iterator x = local_clones.find(user->GetIPString());
1292 if (x != local_clones.end())
1295 local_clones[user->GetIPString()] = 1;
1298 void InspIRCd::AddGlobalClone(userrec* user)
1300 clonemap::iterator y = global_clones.find(user->GetIPString());
1301 if (y != global_clones.end())
1304 global_clones[user->GetIPString()] = 1;
1307 int InspIRCd::GetTimeDelta()
1312 bool FileLogger::Readable()
1317 void FileLogger::HandleEvent(EventType et, int errornum)
1319 this->WriteLogLine("");
1321 ServerInstance->SE->DelFd(this);
1324 void FileLogger::WriteLogLine(const std::string &line)
1327 buffer.append(line);
1331 int written = fprintf(log,"%s",buffer.c_str());
1335 if ((written >= 0) && (written < (int)buffer.length()))
1337 buffer.erase(0, buffer.length());
1338 ServerInstance->SE->AddFd(this);
1340 else if (written == -1)
1342 if (errno == EAGAIN)
1343 ServerInstance->SE->AddFd(this);
1347 /* Wrote the whole buffer, and no need for write callback */
1351 if (writeops++ % 20)
1358 void FileLogger::Close()
1362 /* Burlex: Windows assumes nonblocking on FILE* pointers anyway, and also "file" fd's aren't the same
1363 * as socket fd's. */
1365 int flags = fcntl(fileno(log), F_GETFL, 0);
1366 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
1369 fprintf(log,"%s",buffer.c_str());
1372 ServerInstance->SE->DelFd(this);
1382 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
1386 irc::sockets::NonBlocking(fileno(log));
1387 this->SetFd(fileno(log));
1392 FileLogger::~FileLogger()