1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
15 #include "configreader.h"
21 #include <sys/resource.h>
23 /* This is just to be completely certain that the change which fixed getrusage on RH7 doesn't break anything else -- Om */
34 #include "socketengine.h"
35 #include "inspircd_se_config.h"
38 #include "command_parse.h"
39 #include "exitcodes.h"
45 static DWORD owner_processid = 0;
47 DWORD WindowsForkStart(InspIRCd * Instance)
49 /* Windows implementation of fork() :P */
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 GetCommandLine(), // Command line (exe plus parameters from the OS)
82 0, // PROCESS_SECURITY_ATTRIBUTES
83 0, // THREAD_SECURITY_ATTRIBUTES
84 TRUE, // We went to inherit handles.
85 startupflags, // Allow us full access to the process and suspend it.
87 0, // CURRENT_DIRECTORY
88 &startupinfo, // startup info
89 &procinfo); // process info
93 printf("CreateProcess() error: %s\n", dlerror());
97 // Set the owner process id in the target process.
99 DWORD pid = GetCurrentProcessId();
100 if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
102 printf("WriteProcessMemory() failed: %s\n", dlerror());
106 // Resume the other thread (let it start)
107 ResumeThread(procinfo.hThread);
109 // 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.
110 WaitForSingleObject(procinfo.hProcess, INFINITE);
112 // If we hit this it means startup failed, default to 14 if this fails.
114 GetExitCodeProcess(procinfo.hProcess, &ExitCode);
115 CloseHandle(procinfo.hThread);
116 CloseHandle(procinfo.hProcess);
120 void WindowsForkKillOwner(InspIRCd * Instance)
122 HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
123 if(!hProcess || !owner_processid)
125 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
130 if(!TerminateProcess(hProcess, 0))
132 printf("Could not TerminateProcess(): %s\n", dlerror());
136 CloseHandle(hProcess);
141 using irc::sockets::NonBlocking;
142 using irc::sockets::Blocking;
143 using irc::sockets::insp_ntoa;
144 using irc::sockets::insp_inaddr;
145 using irc::sockets::insp_sockaddr;
149 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
150 const char* ExitCodes[] =
153 "DIE command", /* 1 */
154 "execv() failed", /* 2 */
155 "Internal error", /* 3 */
156 "Config file error", /* 4 */
157 "Logfile error", /* 5 */
158 "POSIX fork failed", /* 6 */
159 "Bad commandline parameters", /* 7 */
160 "No ports could be bound", /* 8 */
161 "Can't write PID file", /* 9 */
162 "SocketEngine could not initialize", /* 10 */
163 "Refusing to start up as root", /* 11 */
164 "Found a <die> tag!", /* 12 */
165 "Couldn't load module on startup", /* 13 */
166 "Could not create windows forked process", /* 14 */
167 "Received SIGTERM", /* 15 */
170 void InspIRCd::AddServerName(const std::string &servername)
172 servernamelist::iterator itr = servernames.begin();
173 for(; itr != servernames.end(); ++itr)
174 if(**itr == servername)
177 string * ns = new string(servername);
178 servernames.push_back(ns);
181 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
183 servernamelist::iterator itr = servernames.begin();
184 for(; itr != servernames.end(); ++itr)
185 if(**itr == servername)
186 return (*itr)->c_str();
188 servernames.push_back(new string(servername));
189 itr = --servernames.end();
190 return (*itr)->c_str();
193 bool InspIRCd::FindServerName(const std::string &servername)
195 servernamelist::iterator itr = servernames.begin();
196 for(; itr != servernames.end(); ++itr)
197 if(**itr == servername)
202 void InspIRCd::Exit(int status)
209 SI->SendError("Exiting with status " + ConvToStr(status) + " (" + std::string(ExitCodes[status]) + ")");
215 void InspIRCd::Cleanup()
217 std::vector<std::string> mymodnames;
218 int MyModCount = this->GetModuleCount();
220 for (unsigned int i = 0; i < Config->ports.size(); i++)
222 /* This calls the constructor and closes the listening socket */
223 delete Config->ports[i];
226 Config->ports.clear();
228 /* Close all client sockets, or the new process inherits them */
229 for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
231 (*i)->SetWriteError("Server shutdown");
235 /* We do this more than once, so that any service providers get a
236 * chance to be unhooked by the modules using them, but then get
237 * a chance to be removed themsleves.
239 for (int tries = 0; tries < 3; tries++)
241 MyModCount = this->GetModuleCount();
244 /* Unload all modules, so they get a chance to clean up their listeners */
245 for (int j = 0; j <= MyModCount; j++)
246 mymodnames.push_back(Config->module_names[j]);
248 for (int k = 0; k <= MyModCount; k++)
249 this->UnloadModule(mymodnames[k].c_str());
253 this->Logger->Close();
255 /* Cleanup Server Names */
256 for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
265 void InspIRCd::Restart(const std::string &reason)
267 /* SendError flushes each client's queue,
268 * regardless of writeability state
270 this->SendError(reason);
274 /* Figure out our filename (if theyve renamed it, we're boned) */
278 char module[MAX_PATH];
279 if (GetModuleFileName(NULL, module, MAX_PATH))
282 me = Config->MyDir + "/inspircd";
285 if (execv(me.c_str(), Config->argv) == -1)
287 /* Will raise a SIGABRT if not trapped */
288 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
292 void InspIRCd::Start()
294 printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
295 printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
296 printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey, Burlex\033[0m\n");
297 printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
300 void InspIRCd::Rehash(int status)
302 SI->WriteOpers("*** Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(SI->ConfigFileName));
304 SI->OpenLog(SI->Config->argv, SI->Config->argc);
305 SI->RehashUsersAndChans();
306 FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
307 SI->Config->Read(false,NULL);
310 FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
314 void InspIRCd::ResetMaxBans()
316 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
317 i->second->ResetMaxBans();
321 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
322 * we must occasionally rehash the hash (yes really).
323 * We do this by copying the entries from the old hash to a new hash, causing all
324 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
325 * very expensive, so instead we do it when the user types /REHASH and expects a
326 * short delay anyway.
328 void InspIRCd::RehashUsersAndChans()
330 user_hash* old_users = this->clientlist;
331 chan_hash* old_chans = this->chanlist;
333 this->clientlist = new user_hash();
334 this->chanlist = new chan_hash();
336 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
337 this->clientlist->insert(*n);
341 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
342 this->chanlist->insert(*n);
347 void InspIRCd::CloseLog()
349 this->Logger->Close();
352 void InspIRCd::SetSignals()
355 signal(SIGALRM, SIG_IGN);
356 signal(SIGHUP, InspIRCd::Rehash);
357 signal(SIGPIPE, SIG_IGN);
358 signal(SIGCHLD, SIG_IGN);
360 signal(SIGTERM, InspIRCd::Exit);
363 void InspIRCd::QuickExit(int status)
368 bool InspIRCd::DaemonSeed()
371 printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
374 signal(SIGTERM, InspIRCd::QuickExit);
377 if ((childpid = fork ()) < 0)
379 else if (childpid > 0)
381 /* We wait here for the child process to kill us,
382 * so that the shell prompt doesnt come back over
384 * Sending a kill with a signal of 0 just checks
385 * if the child pid is still around. If theyre not,
386 * they threw an error and we should give up.
388 while (kill(childpid, 0) != -1)
394 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
396 signal(SIGTERM, InspIRCd::Exit);
399 if (getrlimit(RLIMIT_CORE, &rl) == -1)
401 this->Log(DEFAULT,"Failed to getrlimit()!");
406 rl.rlim_cur = rl.rlim_max;
407 if (setrlimit(RLIMIT_CORE, &rl) == -1)
408 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
415 void InspIRCd::WritePID(const std::string &filename)
417 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
418 if (*(fname.begin()) != '/')
420 std::string::size_type pos;
421 std::string confpath = this->ConfigFileName;
422 if ((pos = confpath.rfind("/")) != std::string::npos)
424 /* Leaves us with just the path */
425 fname = confpath.substr(0, pos) + std::string("/") + fname;
428 std::ofstream outfile(fname.c_str());
429 if (outfile.is_open())
436 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
437 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
438 Exit(EXIT_STATUS_PID);
442 std::string InspIRCd::GetRevision()
447 InspIRCd::InspIRCd(int argc, char** argv)
448 : ModCount(-1), GlobalCulls(this)
452 int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0; /* flag variables */
457 memset(&server, 0, sizeof(server));
458 memset(&client, 0, sizeof(client));
460 this->unregistered_count = 0;
462 this->clientlist = new user_hash();
463 this->chanlist = new chan_hash();
465 this->Config = new ServerConfig(this);
467 this->Config->argv = argv;
468 this->Config->argc = argc;
470 chdir(Config->GetFullProgDir().c_str());
472 this->Config->opertypes.clear();
473 this->Config->operclass.clear();
474 this->SNO = new SnomaskManager(this);
475 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
476 this->time_delta = 0;
477 this->next_call = this->TIME + 3;
480 *this->LogFileName = 0;
481 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
483 struct option longopts[] =
485 { "nofork", no_argument, &do_nofork, 1 },
486 { "logfile", required_argument, NULL, 'f' },
487 { "config", required_argument, NULL, 'c' },
488 { "debug", no_argument, &do_debug, 1 },
489 { "nolog", no_argument, &do_nolog, 1 },
490 { "runasroot", no_argument, &do_root, 1 },
491 { "version", no_argument, &do_version, 1 },
495 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
500 /* Log filename was set */
501 strlcpy(LogFileName, optarg, MAXBUF);
502 printf("LOG: Setting logfile to %s\n", LogFileName);
505 /* Config filename was set */
506 strlcpy(ConfigFileName, optarg, MAXBUF);
507 printf("CONFIG: Setting config file to %s\n", ConfigFileName);
510 /* getopt_long_only() set an int variable, just keep going */
513 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
514 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
515 Exit(EXIT_STATUS_ARGV);
522 printf("\n%s r%s\n", VERSION, REVISION);
523 Exit(EXIT_STATUS_NOERROR);
529 if(!do_nofork && !owner_processid)
531 DWORD ExitCode = WindowsForkStart(this);
538 WSAStartup(MAKEWORD(2,0), &wsadata);
541 if (!ServerConfig::FileExists(this->ConfigFileName))
543 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
544 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
545 Exit(EXIT_STATUS_CONFIG);
550 /* Set the finished argument values */
551 Config->nofork = do_nofork;
552 Config->forcedebug = do_debug;
553 Config->writelog = !do_nolog;
555 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
557 this->OpenLog(argv, argc);
559 this->stats = new serverstats();
560 this->Timers = new TimerManager(this);
561 this->Parser = new CommandParser(this);
562 this->XLines = new XLineManager(this);
563 Config->ClearStack();
564 Config->Read(true, NULL);
570 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
571 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
572 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
573 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
574 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
575 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
576 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
577 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
585 if (!this->DaemonSeed())
587 printf("ERROR: could not go into daemon mode. Shutting down.\n");
588 Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
589 Exit(EXIT_STATUS_FORK);
594 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
595 * initialize the socket engine.
597 SocketEngineFactory* SEF = new SocketEngineFactory();
598 SE = SEF->Create(this);
601 this->Modes = new ModeParser(this);
602 this->AddServerName(Config->ServerName);
604 int bounditems = BindPorts(true, found_ports, pl);
606 for(int t = 0; t < 255; t++)
607 Config->global_implementation[t] = 0;
609 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
613 this->Res = new DNS(this);
615 this->LoadAllModules();
616 /* Just in case no modules were loaded - fix for bug #101 */
617 this->BuildISupport();
618 InitializeDisabledCommands(Config->DisabledCommands, this);
620 if ((Config->ports.size() == 0) && (found_ports > 0))
622 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
623 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
624 Exit(EXIT_STATUS_BIND);
627 if (Config->ports.size() != (unsigned int)found_ports)
629 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
630 printf("The following port(s) failed to bind:\n");
632 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
634 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
640 if (kill(getppid(), SIGTERM) == -1)
642 printf("Error killing parent process: %s\n",strerror(errno));
643 Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
647 if (isatty(0) && isatty(1) && isatty(2))
649 /* We didn't start from a TTY, we must have started from a background process -
650 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
661 Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
668 WindowsForkKillOwner(this);
672 printf("\nInspIRCd is now running!\n");
673 Log(DEFAULT,"Startup complete.");
675 this->WritePID(Config->PID);
678 std::string InspIRCd::GetVersionString()
680 char versiondata[MAXBUF];
681 char dnsengine[] = "singlethread-object";
683 if (*Config->CustomVersion)
685 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
689 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%s,%s,%s]",VERSION,Config->ServerName,SYSTEM,REVISION,SE->GetName().c_str(),dnsengine);
694 char* InspIRCd::ModuleError()
699 void InspIRCd::EraseFactory(int j)
702 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
708 factory.push_back(NULL);
715 void InspIRCd::EraseModule(int j)
718 for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
724 modules.push_back(NULL);
730 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
734 Config->module_names.erase(v);
742 void InspIRCd::MoveTo(std::string modulename,int slot)
744 unsigned int v2 = 256;
745 for (unsigned int v = 0; v < Config->module_names.size(); v++)
747 if (Config->module_names[v] == modulename)
749 // found an instance, swap it with the item at the end
754 if ((v2 != (unsigned int)slot) && (v2 < 256))
756 // Swap the module names over
757 Config->module_names[v2] = Config->module_names[slot];
758 Config->module_names[slot] = modulename;
759 // now swap the module factories
760 ircd_module* temp = factory[v2];
761 factory[v2] = factory[slot];
762 factory[slot] = temp;
763 // now swap the module objects
764 Module* temp_module = modules[v2];
765 modules[v2] = modules[slot];
766 modules[slot] = temp_module;
767 // now swap the implement lists (we dont
768 // need to swap the global or recount it)
769 for (int n = 0; n < 255; n++)
771 char x = Config->implement_lists[v2][n];
772 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
773 Config->implement_lists[slot][n] = x;
778 void InspIRCd::MoveAfter(std::string modulename, std::string after)
780 for (unsigned int v = 0; v < Config->module_names.size(); v++)
782 if (Config->module_names[v] == after)
784 MoveTo(modulename, v);
790 void InspIRCd::MoveBefore(std::string modulename, std::string before)
792 for (unsigned int v = 0; v < Config->module_names.size(); v++)
794 if (Config->module_names[v] == before)
798 MoveTo(modulename, v-1);
802 MoveTo(modulename, v);
809 void InspIRCd::MoveToFirst(std::string modulename)
811 MoveTo(modulename,0);
814 void InspIRCd::MoveToLast(std::string modulename)
816 MoveTo(modulename,this->GetModuleCount());
819 void InspIRCd::BuildISupport()
821 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
823 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES-1 << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << Config->MaxChans << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
824 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
825 v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32 ELIST=MU";
826 Config->data005 = v.str();
827 FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
831 bool InspIRCd::UnloadModule(const char* filename)
833 std::string filename_str = filename;
834 for (unsigned int j = 0; j != Config->module_names.size(); j++)
836 if (Config->module_names[j] == filename_str)
838 if (modules[j]->GetVersion().Flags & VF_STATIC)
840 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
841 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
844 std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modules[j]);
845 if (intercount.first > 0)
847 this->Log(DEFAULT,"Failed to unload module %s, being used by %d other(s) via interface '%s'",filename, intercount.first, intercount.second.c_str());
848 snprintf(MODERR,MAXBUF,"Module not unloadable (Still in use by %d other module%s which %s using its interface '%s') -- unload dependent modules first!",
850 intercount.first > 1 ? "s" : "",
851 intercount.first > 1 ? "are" : "is",
852 intercount.second.c_str());
855 /* Give the module a chance to tidy out all its metadata */
856 for (chan_hash::iterator c = this->chanlist->begin(); c != this->chanlist->end(); c++)
858 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
860 for (user_hash::iterator u = this->clientlist->begin(); u != this->clientlist->end(); u++)
862 modules[j]->OnCleanup(TYPE_USER,u->second);
865 /* Tidy up any dangling resolvers */
866 this->Res->CleanResolvers(modules[j]);
868 FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
870 for(int t = 0; t < 255; t++)
872 Config->global_implementation[t] -= Config->implement_lists[j][t];
875 /* We have to renumber implement_lists after unload because the module numbers change!
877 for(int j2 = j; j2 < 254; j2++)
879 for(int t = 0; t < 255; t++)
881 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
886 Parser->RemoveCommands(filename);
887 this->EraseModule(j);
888 this->EraseFactory(j);
889 this->Log(DEFAULT,"Module %s unloaded",filename);
895 this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
896 snprintf(MODERR,MAXBUF,"Module not loaded");
900 bool InspIRCd::LoadModule(const char* filename)
902 /* Do we have a glob pattern in the filename?
903 * The user wants to load multiple modules which
906 if (strchr(filename,'*') || (strchr(filename,'?')))
909 DIR* library = opendir(Config->ModPath);
912 /* Try and locate and load all modules matching the pattern */
913 dirent* entry = NULL;
914 while ((entry = readdir(library)))
916 if (this->MatchText(entry->d_name, filename))
918 if (!this->LoadModule(entry->d_name))
924 /* Loadmodule will now return false if any one of the modules failed
925 * to load (but wont abort when it encounters a bad one) and when 1 or
926 * more modules were actually loaded.
928 return (n_match > 0);
931 char modfile[MAXBUF];
932 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
933 std::string filename_str = filename;
935 if (!ServerConfig::DirValid(modfile))
937 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
938 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
941 if (ServerConfig::FileExists(modfile))
944 for (unsigned int j = 0; j < Config->module_names.size(); j++)
946 if (Config->module_names[j] == filename_str)
948 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
949 snprintf(MODERR,MAXBUF,"Module already loaded");
955 ircd_module* a = new ircd_module(this, modfile);
956 factory[this->ModCount+1] = a;
957 if (factory[this->ModCount+1]->LastError())
959 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
960 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
963 if ((long)factory[this->ModCount+1]->factory != -1)
965 Module* m = factory[this->ModCount+1]->factory->CreateModule(this);
967 Version v = m->GetVersion();
969 if (v.API != API_VERSION)
973 this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
974 snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
979 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]"));
982 modules[this->ModCount+1] = m;
983 /* save the module and the module's classfactory, if
984 * this isnt done, random crashes can occur :/ */
985 Config->module_names.push_back(filename);
987 char* x = &Config->implement_lists[this->ModCount+1][0];
988 for(int t = 0; t < 255; t++)
991 modules[this->ModCount+1]->Implements(x);
993 for(int t = 0; t < 255; t++)
994 Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
998 this->Log(DEFAULT,"Unable to load %s",modfile);
999 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
1003 catch (CoreException& modexcept)
1005 this->Log(DEFAULT,"Unable to load %s: %s",modfile,modexcept.GetReason());
1006 snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1012 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
1013 snprintf(MODERR,MAXBUF,"Module file could not be found");
1017 FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
1018 // now work out which modules, if any, want to move to the back of the queue,
1019 // and if they do, move them there.
1020 std::vector<std::string> put_to_back;
1021 std::vector<std::string> put_to_front;
1022 std::map<std::string,std::string> put_before;
1023 std::map<std::string,std::string> put_after;
1024 for (unsigned int j = 0; j < Config->module_names.size(); j++)
1026 if (modules[j]->Prioritize() == PRIORITY_LAST)
1027 put_to_back.push_back(Config->module_names[j]);
1028 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
1029 put_to_front.push_back(Config->module_names[j]);
1030 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
1031 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
1032 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
1033 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
1035 for (unsigned int j = 0; j < put_to_back.size(); j++)
1036 MoveToLast(put_to_back[j]);
1037 for (unsigned int j = 0; j < put_to_front.size(); j++)
1038 MoveToFirst(put_to_front[j]);
1039 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
1040 MoveBefore(j->first,j->second);
1041 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
1042 MoveAfter(j->first,j->second);
1047 void InspIRCd::DoOneIteration(bool process_module_sockets)
1052 static time_t uptime;
1053 static struct tm * stime;
1054 static char window_title[100];
1057 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
1058 * Once per loop iteration is pleanty.
1063 /* Run background module timers every few seconds
1064 * (the docs say modules shouldnt rely on accurate
1065 * timing using this event, so we dont have to
1066 * time this exactly).
1068 if (TIME != OLDTIME)
1071 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
1072 if ((TIME % 3600) == 0)
1074 this->RehashUsersAndChans();
1075 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
1077 Timers->TickTimers(TIME);
1078 this->DoBackgroundUserStuff(TIME);
1080 if ((TIME % 5) == 0)
1082 XLines->expire_lines();
1083 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
1084 Timers->TickMissedTimers(TIME);
1087 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
1088 if (!getrusage(RUSAGE_SELF, &ru))
1090 gettimeofday(&this->stats->LastSampled, NULL);
1091 this->stats->LastCPU = ru.ru_utime;
1098 uptime = Time() - startup_time;
1099 stime = gmtime(&uptime);
1100 snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
1101 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
1102 SetConsoleTitle(window_title);
1107 /* Call the socket engine to wait on the active
1108 * file descriptors. The socket engine has everything's
1109 * descriptors in its list... dns, modules, users,
1110 * servers... so its nice and easy, just one call.
1111 * This will cause any read or write events to be
1112 * dispatched to their handlers.
1114 SE->DispatchEvents();
1116 /* if any users was quit, take them out */
1117 GlobalCulls.Apply();
1119 /* If any inspsockets closed, remove them */
1120 for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
1122 SE->DelFd(x->second);
1133 DoOneIteration(true);
1135 /* This is never reached -- we hope! */
1139 /**********************************************************************************/
1142 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
1145 int main(int argc, char** argv)
1147 SI = new InspIRCd(argc, argv);
1153 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
1154 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
1155 * registration timeout maximum seconds)
1157 bool InspIRCd::AllModulesReportReady(userrec* user)
1159 if (!Config->global_implementation[I_OnCheckReady])
1162 for (int i = 0; i <= this->GetModuleCount(); i++)
1164 if (Config->implement_lists[i][I_OnCheckReady])
1166 int res = modules[i]->OnCheckReady(user);
1174 int InspIRCd::GetModuleCount()
1176 return this->ModCount;
1179 time_t InspIRCd::Time(bool delta)
1182 return TIME + time_delta;
1186 int InspIRCd::SetTimeDelta(int delta)
1188 int old = time_delta;
1190 this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
1194 void InspIRCd::AddLocalClone(userrec* user)
1196 clonemap::iterator x = local_clones.find(user->GetIPString());
1197 if (x != local_clones.end())
1200 local_clones[user->GetIPString()] = 1;
1203 void InspIRCd::AddGlobalClone(userrec* user)
1205 clonemap::iterator y = global_clones.find(user->GetIPString());
1206 if (y != global_clones.end())
1209 global_clones[user->GetIPString()] = 1;
1212 int InspIRCd::GetTimeDelta()
1217 bool FileLogger::Readable()
1222 void FileLogger::HandleEvent(EventType et, int errornum)
1224 this->WriteLogLine("");
1226 ServerInstance->SE->DelFd(this);
1229 void FileLogger::WriteLogLine(const std::string &line)
1232 buffer.append(line);
1236 int written = fprintf(log,"%s",buffer.c_str());
1240 if ((written >= 0) && (written < (int)buffer.length()))
1242 buffer.erase(0, buffer.length());
1243 ServerInstance->SE->AddFd(this);
1245 else if (written == -1)
1247 if (errno == EAGAIN)
1248 ServerInstance->SE->AddFd(this);
1252 /* Wrote the whole buffer, and no need for write callback */
1256 if (writeops++ % 20)
1263 void FileLogger::Close()
1267 /* Burlex: Windows assumes nonblocking on FILE* pointers anyway, and also "file" fd's aren't the same
1268 * as socket fd's. */
1270 int flags = fcntl(fileno(log), F_GETFL, 0);
1271 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
1274 fprintf(log,"%s",buffer.c_str());
1277 ServerInstance->SE->DelFd(this);
1287 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
1291 irc::sockets::NonBlocking(fileno(log));
1292 this->SetFd(fileno(log));
1297 FileLogger::~FileLogger()