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"
24 #include "socketengine.h"
25 #include "inspircd_se_config.h"
28 #include "command_parse.h"
29 #include "exitcodes.h"
34 using irc::sockets::NonBlocking;
35 using irc::sockets::Blocking;
36 using irc::sockets::insp_ntoa;
37 using irc::sockets::insp_inaddr;
38 using irc::sockets::insp_sockaddr;
42 void InspIRCd::AddServerName(const std::string &servername)
44 if(find(servernames.begin(), servernames.end(), servername) == servernames.end())
45 servernames.push_back(servername); /* Wasn't already there. */
48 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
50 servernamelist::iterator iter = find(servernames.begin(), servernames.end(), servername);
52 if(iter == servernames.end())
54 AddServerName(servername);
55 iter = --servernames.end();
61 bool InspIRCd::FindServerName(const std::string &servername)
63 return (find(servernames.begin(), servernames.end(), servername) != servernames.end());
66 void InspIRCd::Exit(int status)
70 SI->SendError("Exiting with status " + ConvToStr(status) + " (" + std::string(ExitCodes[status]) + ")");
76 void InspIRCd::Cleanup()
78 std::vector<std::string> mymodnames;
79 int MyModCount = this->GetModuleCount();
81 for (unsigned int i = 0; i < stats->BoundPortCount; i++)
83 /* This calls the constructor and closes the listening socket */
84 delete Config->openSockfd[i];
85 Config->openSockfd[i] = NULL;
87 stats->BoundPortCount = 0;
89 /* Close all client sockets, or the new process inherits them */
90 for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
92 (*i)->SetWriteError("Server shutdown");
96 /* We do this more than once, so that any service providers get a
97 * chance to be unhooked by the modules using them, but then get
98 * a chance to be removed themsleves.
100 for (int tries = 0; tries < 3; tries++)
102 MyModCount = this->GetModuleCount();
105 /* Unload all modules, so they get a chance to clean up their listeners */
106 for (int j = 0; j <= MyModCount; j++)
107 mymodnames.push_back(Config->module_names[j]);
109 for (int k = 0; k <= MyModCount; k++)
110 this->UnloadModule(mymodnames[k].c_str());
114 this->Logger->Close();
117 void InspIRCd::Restart(const std::string &reason)
119 /* SendError flushes each client's queue,
120 * regardless of writeability state
122 this->SendError(reason);
126 /* Figure out our filename (if theyve renamed it, we're boned) */
127 std::string me = Config->MyDir + "/inspircd";
129 if (execv(me.c_str(), Config->argv) == -1)
131 /* Will raise a SIGABRT if not trapped */
132 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
136 void InspIRCd::Start()
138 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
139 printf("(C) InspIRCd Development Team.\033[0m\n\n");
140 printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey\033[0m\n");
141 printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
144 void InspIRCd::Rehash(int status)
146 SI->WriteOpers("*** Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(SI->ConfigFileName));
148 SI->OpenLog(SI->Config->argv, SI->Config->argc);
149 SI->RehashUsersAndChans();
150 FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
151 SI->Config->Read(false,NULL);
155 FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
158 void InspIRCd::ResetMaxBans()
160 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
161 i->second->ResetMaxBans();
165 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
166 * we must occasionally rehash the hash (yes really).
167 * We do this by copying the entries from the old hash to a new hash, causing all
168 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
169 * very expensive, so instead we do it when the user types /REHASH and expects a
170 * short delay anyway.
172 void InspIRCd::RehashUsersAndChans()
174 user_hash* old_users = this->clientlist;
175 chan_hash* old_chans = this->chanlist;
177 this->clientlist = new user_hash();
178 this->chanlist = new chan_hash();
180 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
181 this->clientlist->insert(*n);
185 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
186 this->chanlist->insert(*n);
191 void InspIRCd::CloseLog()
193 this->Logger->Close();
196 void InspIRCd::SetSignals()
198 signal(SIGALRM, SIG_IGN);
199 signal(SIGHUP, InspIRCd::Rehash);
200 signal(SIGPIPE, SIG_IGN);
201 signal(SIGTERM, InspIRCd::Exit);
202 signal(SIGCHLD, SIG_IGN);
205 void InspIRCd::QuickExit(int status)
210 bool InspIRCd::DaemonSeed()
212 signal(SIGTERM, InspIRCd::QuickExit);
215 if ((childpid = fork ()) < 0)
217 else if (childpid > 0)
219 /* We wait here for the child process to kill us,
220 * so that the shell prompt doesnt come back over
222 * Sending a kill with a signal of 0 just checks
223 * if the child pid is still around. If theyre not,
224 * they threw an error and we should give up.
226 while (kill(childpid, 0) != -1)
232 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
234 signal(SIGTERM, InspIRCd::Exit);
237 if (getrlimit(RLIMIT_CORE, &rl) == -1)
239 this->Log(DEFAULT,"Failed to getrlimit()!");
244 rl.rlim_cur = rl.rlim_max;
245 if (setrlimit(RLIMIT_CORE, &rl) == -1)
246 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
252 void InspIRCd::WritePID(const std::string &filename)
254 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
255 if (*(fname.begin()) != '/')
257 std::string::size_type pos;
258 std::string confpath = this->ConfigFileName;
259 if ((pos = confpath.rfind("/")) != std::string::npos)
261 /* Leaves us with just the path */
262 fname = confpath.substr(0, pos) + std::string("/") + fname;
265 std::ofstream outfile(fname.c_str());
266 if (outfile.is_open())
273 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
274 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
275 Exit(EXIT_STATUS_PID);
279 std::string InspIRCd::GetRevision()
284 InspIRCd::InspIRCd(int argc, char** argv)
285 : ModCount(-1), duration_m(60), duration_h(60*60), duration_d(60*60*24), duration_w(60*60*24*7), duration_y(60*60*24*365), GlobalCulls(this)
289 int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0; /* flag variables */
295 this->unregistered_count = 0;
297 this->clientlist = new user_hash();
298 this->chanlist = new chan_hash();
300 this->Config = new ServerConfig(this);
302 this->Config->argv = argv;
303 this->Config->argc = argc;
305 this->Config->opertypes.clear();
306 this->Config->operclass.clear();
307 this->SNO = new SnomaskManager(this);
308 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
309 this->time_delta = 0;
310 this->next_call = this->TIME + 3;
313 *this->LogFileName = 0;
314 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
316 struct option longopts[] =
318 { "nofork", no_argument, &do_nofork, 1 },
319 { "logfile", required_argument, NULL, 'f' },
320 { "config", required_argument, NULL, 'c' },
321 { "debug", no_argument, &do_debug, 1 },
322 { "nolog", no_argument, &do_nolog, 1 },
323 { "runasroot", no_argument, &do_root, 1 },
324 { "version", no_argument, &do_version, 1 },
328 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
333 /* Log filename was set */
334 strlcpy(LogFileName, optarg, MAXBUF);
335 printf("LOG: Setting logfile to %s\n", LogFileName);
338 /* Config filename was set */
339 strlcpy(ConfigFileName, optarg, MAXBUF);
340 printf("CONFIG: Setting config file to %s\n", ConfigFileName);
343 /* getopt_long_only() set an int variable, just keep going */
346 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
347 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
348 Exit(EXIT_STATUS_ARGV);
355 printf("\n%s r%s\n", VERSION, REVISION);
356 Exit(EXIT_STATUS_NOERROR);
359 if (!ServerConfig::FileExists(this->ConfigFileName))
361 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
362 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
363 Exit(EXIT_STATUS_CONFIG);
368 /* Set the finished argument values */
369 Config->nofork = do_nofork;
370 Config->forcedebug = do_debug;
371 Config->writelog = !do_nolog;
373 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
375 this->OpenLog(argv, argc);
377 this->stats = new serverstats();
378 this->Timers = new TimerManager(this);
379 this->Parser = new CommandParser(this);
380 this->XLines = new XLineManager(this);
381 Config->ClearStack();
382 Config->Read(true, NULL);
388 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
389 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
390 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
391 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
392 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
393 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
394 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
395 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
399 this->Modes = new ModeParser(this);
400 this->AddServerName(Config->ServerName);
402 InitializeDisabledCommands(Config->DisabledCommands, this);
403 stats->BoundPortCount = BindPorts(true, found_ports, pl);
405 for(int t = 0; t < 255; t++)
406 Config->global_implementation[t] = 0;
408 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
415 if (!this->DaemonSeed())
417 printf("ERROR: could not go into daemon mode. Shutting down.\n");
418 Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
419 Exit(EXIT_STATUS_FORK);
423 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
424 * initialize the socket engine.
426 SocketEngineFactory* SEF = new SocketEngineFactory();
427 SE = SEF->Create(this);
430 this->Res = new DNS(this);
432 this->LoadAllModules();
433 /* Just in case no modules were loaded - fix for bug #101 */
434 this->BuildISupport();
436 if ((stats->BoundPortCount == 0) && (found_ports > 0))
438 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
439 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
440 Exit(EXIT_STATUS_BIND);
443 if (stats->BoundPortCount != (unsigned int)found_ports)
445 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %ld of %d client ports bound.\n\n", stats->BoundPortCount, found_ports);
446 printf("The following port%s failed to bind:\n", found_ports - stats->BoundPortCount != 1 ? "s" : "");
448 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
450 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
454 /* Add the listening sockets used for client inbound connections
455 * to the socket engine
457 for (unsigned long count = 0; count < stats->BoundPortCount; count++)
459 if (!SE->AddFd(Config->openSockfd[count]))
461 printf("\nEH? Could not add listener to socketengine. You screwed up, aborting.\n");
462 Log(DEFAULT,"EH? Could not add listener to socketengine. You screwed up, aborting.");
463 Exit(EXIT_STATUS_INTERNAL);
469 if (kill(getppid(), SIGTERM) == -1)
471 printf("Error killing parent process: %s\n",strerror(errno));
472 Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
476 if (isatty(0) && isatty(1) && isatty(2))
478 /* We didn't start from a TTY, we must have started from a background process -
479 * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
490 Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
494 printf("\nInspIRCd is now running!\n");
495 Log(DEFAULT,"Startup complete.");
497 this->WritePID(Config->PID);
500 std::string InspIRCd::GetVersionString()
502 char versiondata[MAXBUF];
503 char dnsengine[] = "singlethread-object";
505 if (*Config->CustomVersion)
507 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
511 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%s,%s,%s]",VERSION,Config->ServerName,SYSTEM,REVISION,SE->GetName().c_str(),dnsengine);
516 char* InspIRCd::ModuleError()
521 void InspIRCd::EraseFactory(int j)
524 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
530 factory.push_back(NULL);
537 void InspIRCd::EraseModule(int j)
540 for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
546 modules.push_back(NULL);
552 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
556 Config->module_names.erase(v);
564 void InspIRCd::MoveTo(std::string modulename,int slot)
566 unsigned int v2 = 256;
567 for (unsigned int v = 0; v < Config->module_names.size(); v++)
569 if (Config->module_names[v] == modulename)
571 // found an instance, swap it with the item at the end
576 if ((v2 != (unsigned int)slot) && (v2 < 256))
578 // Swap the module names over
579 Config->module_names[v2] = Config->module_names[slot];
580 Config->module_names[slot] = modulename;
581 // now swap the module factories
582 ircd_module* temp = factory[v2];
583 factory[v2] = factory[slot];
584 factory[slot] = temp;
585 // now swap the module objects
586 Module* temp_module = modules[v2];
587 modules[v2] = modules[slot];
588 modules[slot] = temp_module;
589 // now swap the implement lists (we dont
590 // need to swap the global or recount it)
591 for (int n = 0; n < 255; n++)
593 char x = Config->implement_lists[v2][n];
594 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
595 Config->implement_lists[slot][n] = x;
600 void InspIRCd::MoveAfter(std::string modulename, std::string after)
602 for (unsigned int v = 0; v < Config->module_names.size(); v++)
604 if (Config->module_names[v] == after)
606 MoveTo(modulename, v);
612 void InspIRCd::MoveBefore(std::string modulename, std::string before)
614 for (unsigned int v = 0; v < Config->module_names.size(); v++)
616 if (Config->module_names[v] == before)
620 MoveTo(modulename, v-1);
624 MoveTo(modulename, v);
631 void InspIRCd::MoveToFirst(std::string modulename)
633 MoveTo(modulename,0);
636 void InspIRCd::MoveToLast(std::string modulename)
638 MoveTo(modulename,this->GetModuleCount());
641 void InspIRCd::BuildISupport()
643 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
645 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES-1 << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << Config->MaxChans << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
646 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
647 v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32";
648 Config->data005 = v.str();
649 FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
653 bool InspIRCd::UnloadModule(const char* filename)
655 std::string filename_str = filename;
656 for (unsigned int j = 0; j != Config->module_names.size(); j++)
658 if (Config->module_names[j] == filename_str)
660 if (modules[j]->GetVersion().Flags & VF_STATIC)
662 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
663 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
666 std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modules[j]);
667 if (intercount.first > 0)
669 this->Log(DEFAULT,"Failed to unload module %s, being used by %d other(s) via interface '%s'",filename, intercount.first, intercount.second.c_str());
670 snprintf(MODERR,MAXBUF,"Module not unloadable (Still in use by %d other module%s which %s using its interface '%s') -- unload dependent modules first!",
672 intercount.first > 1 ? "s" : "",
673 intercount.first > 1 ? "are" : "is",
674 intercount.second.c_str());
677 /* Give the module a chance to tidy out all its metadata */
678 for (chan_hash::iterator c = this->chanlist->begin(); c != this->chanlist->end(); c++)
680 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
682 for (user_hash::iterator u = this->clientlist->begin(); u != this->clientlist->end(); u++)
684 modules[j]->OnCleanup(TYPE_USER,u->second);
687 /* Tidy up any dangling resolvers */
688 this->Res->CleanResolvers(modules[j]);
690 FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
692 for(int t = 0; t < 255; t++)
694 Config->global_implementation[t] -= Config->implement_lists[j][t];
697 /* We have to renumber implement_lists after unload because the module numbers change!
699 for(int j2 = j; j2 < 254; j2++)
701 for(int t = 0; t < 255; t++)
703 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
708 Parser->RemoveCommands(filename);
709 this->EraseModule(j);
710 this->EraseFactory(j);
711 this->Log(DEFAULT,"Module %s unloaded",filename);
717 this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
718 snprintf(MODERR,MAXBUF,"Module not loaded");
722 bool InspIRCd::LoadModule(const char* filename)
724 /* Do we have a glob pattern in the filename?
725 * The user wants to load multiple modules which
728 if (strchr(filename,'*') || (strchr(filename,'?')))
731 DIR* library = opendir(Config->ModPath);
734 /* Try and locate and load all modules matching the pattern */
735 dirent* entry = NULL;
736 while ((entry = readdir(library)))
738 if (this->MatchText(entry->d_name, filename))
740 if (!this->LoadModule(entry->d_name))
746 /* Loadmodule will now return false if any one of the modules failed
747 * to load (but wont abort when it encounters a bad one) and when 1 or
748 * more modules were actually loaded.
750 return (n_match > 0);
753 char modfile[MAXBUF];
754 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
755 std::string filename_str = filename;
757 if (!ServerConfig::DirValid(modfile))
759 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
760 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
763 if (ServerConfig::FileExists(modfile))
766 for (unsigned int j = 0; j < Config->module_names.size(); j++)
768 if (Config->module_names[j] == filename_str)
770 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
771 snprintf(MODERR,MAXBUF,"Module already loaded");
777 ircd_module* a = new ircd_module(this, modfile);
778 factory[this->ModCount+1] = a;
779 if (factory[this->ModCount+1]->LastError())
781 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
782 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
785 if ((long)factory[this->ModCount+1]->factory != -1)
787 Module* m = factory[this->ModCount+1]->factory->CreateModule(this);
789 Version v = m->GetVersion();
791 if (v.API != API_VERSION)
795 this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
796 snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
801 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]"));
804 modules[this->ModCount+1] = m;
805 /* save the module and the module's classfactory, if
806 * this isnt done, random crashes can occur :/ */
807 Config->module_names.push_back(filename);
809 char* x = &Config->implement_lists[this->ModCount+1][0];
810 for(int t = 0; t < 255; t++)
813 modules[this->ModCount+1]->Implements(x);
815 for(int t = 0; t < 255; t++)
816 Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
820 this->Log(DEFAULT,"Unable to load %s",modfile);
821 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
825 catch (CoreException& modexcept)
827 this->Log(DEFAULT,"Unable to load %s: %s",modfile,modexcept.GetReason());
828 snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
834 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
835 snprintf(MODERR,MAXBUF,"Module file could not be found");
839 FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
840 // now work out which modules, if any, want to move to the back of the queue,
841 // and if they do, move them there.
842 std::vector<std::string> put_to_back;
843 std::vector<std::string> put_to_front;
844 std::map<std::string,std::string> put_before;
845 std::map<std::string,std::string> put_after;
846 for (unsigned int j = 0; j < Config->module_names.size(); j++)
848 if (modules[j]->Prioritize() == PRIORITY_LAST)
849 put_to_back.push_back(Config->module_names[j]);
850 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
851 put_to_front.push_back(Config->module_names[j]);
852 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
853 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
854 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
855 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
857 for (unsigned int j = 0; j < put_to_back.size(); j++)
858 MoveToLast(put_to_back[j]);
859 for (unsigned int j = 0; j < put_to_front.size(); j++)
860 MoveToFirst(put_to_front[j]);
861 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
862 MoveBefore(j->first,j->second);
863 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
864 MoveAfter(j->first,j->second);
869 void InspIRCd::DoOneIteration(bool process_module_sockets)
873 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
874 * Once per loop iteration is pleanty.
879 /* Run background module timers every few seconds
880 * (the docs say modules shouldnt rely on accurate
881 * timing using this event, so we dont have to
882 * time this exactly).
887 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
888 if ((TIME % 3600) == 0)
890 this->RehashUsersAndChans();
891 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
893 Timers->TickTimers(TIME);
894 this->DoBackgroundUserStuff(TIME);
898 XLines->expire_lines();
899 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
900 Timers->TickMissedTimers(TIME);
903 if (!getrusage(0, &ru))
905 gettimeofday(&this->stats->LastSampled, NULL);
906 this->stats->LastCPU = ru.ru_utime;
910 /* Call the socket engine to wait on the active
911 * file descriptors. The socket engine has everything's
912 * descriptors in its list... dns, modules, users,
913 * servers... so its nice and easy, just one call.
914 * This will cause any read or write events to be
915 * dispatched to their handlers.
917 SE->DispatchEvents();
919 /* if any users was quit, take them out */
922 /* If any inspsockets closed, remove them */
923 for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
925 SE->DelFd(x->second);
932 bool InspIRCd::IsIdent(const char* n)
937 for (char* i = (char*)n; *i; i++)
939 if ((*i >= 'A') && (*i <= '}'))
943 if (((*i >= '0') && (*i <= '9')) || (*i == '-') || (*i == '.'))
956 DoOneIteration(true);
958 /* This is never reached -- we hope! */
962 /**********************************************************************************/
965 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
968 int main(int argc, char** argv)
970 SI = new InspIRCd(argc, argv);
976 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
977 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
978 * registration timeout maximum seconds)
980 bool InspIRCd::AllModulesReportReady(userrec* user)
982 if (!Config->global_implementation[I_OnCheckReady])
985 for (int i = 0; i <= this->GetModuleCount(); i++)
987 if (Config->implement_lists[i][I_OnCheckReady])
989 int res = modules[i]->OnCheckReady(user);
997 int InspIRCd::GetModuleCount()
999 return this->ModCount;
1002 time_t InspIRCd::Time(bool delta)
1005 return TIME + time_delta;
1009 int InspIRCd::SetTimeDelta(int delta)
1011 int old = time_delta;
1013 this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
1017 void InspIRCd::AddLocalClone(userrec* user)
1019 clonemap::iterator x = local_clones.find(user->GetIPString());
1020 if (x != local_clones.end())
1023 local_clones[user->GetIPString()] = 1;
1026 void InspIRCd::AddGlobalClone(userrec* user)
1028 clonemap::iterator y = global_clones.find(user->GetIPString());
1029 if (y != global_clones.end())
1032 global_clones[user->GetIPString()] = 1;
1035 int InspIRCd::GetTimeDelta()
1040 bool FileLogger::Readable()
1045 void FileLogger::HandleEvent(EventType et, int errornum)
1047 this->WriteLogLine("");
1049 ServerInstance->SE->DelFd(this);
1052 void FileLogger::WriteLogLine(const std::string &line)
1055 buffer.append(line);
1059 int written = fprintf(log,"%s",buffer.c_str());
1060 if ((written >= 0) && (written < (int)buffer.length()))
1062 buffer.erase(0, buffer.length());
1063 ServerInstance->SE->AddFd(this);
1065 else if (written == -1)
1067 if (errno == EAGAIN)
1068 ServerInstance->SE->AddFd(this);
1072 /* Wrote the whole buffer, and no need for write callback */
1076 if (writeops++ % 20)
1083 void FileLogger::Close()
1087 int flags = fcntl(fileno(log), F_GETFL, 0);
1088 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
1090 fprintf(log,"%s",buffer.c_str());
1092 ServerInstance->SE->DelFd(this);
1101 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
1105 irc::sockets::NonBlocking(fileno(log));
1106 this->SetFd(fileno(log));
1111 FileLogger::~FileLogger()