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";
131 argv[0] = Config->argv[0];
132 argv[1] = "--restart";
133 if (Config->forcedebug)
134 argv[endp++] = "--debug";
136 argv[endp++] = "--nofork";
137 if (!Config->writelog)
138 argv[endp++] = "--nolog";
139 if (*this->LogFileName)
141 argv[endp++] = "--logfile";
142 argv[endp++] = this->LogFileName;
147 if (execv(me.c_str(), argv) == -1)
149 /* Will raise a SIGABRT if not trapped */
150 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
154 void InspIRCd::Start()
156 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
157 printf("(C) InspIRCd Development Team.\033[0m\n\n");
158 printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey\033[0m\n");
159 printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
162 void InspIRCd::Rehash(int status)
164 SI->WriteOpers("*** Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(SI->ConfigFileName));
166 SI->OpenLog(SI->Config->argv, SI->Config->argc);
167 SI->RehashUsersAndChans();
168 FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
169 SI->Config->Read(false,NULL);
173 FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
176 void InspIRCd::ResetMaxBans()
178 for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
179 i->second->ResetMaxBans();
183 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
184 * we must occasionally rehash the hash (yes really).
185 * We do this by copying the entries from the old hash to a new hash, causing all
186 * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
187 * very expensive, so instead we do it when the user types /REHASH and expects a
188 * short delay anyway.
190 void InspIRCd::RehashUsersAndChans()
192 user_hash* old_users = this->clientlist;
193 chan_hash* old_chans = this->chanlist;
195 this->clientlist = new user_hash();
196 this->chanlist = new chan_hash();
198 for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
199 this->clientlist->insert(*n);
203 for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
204 this->chanlist->insert(*n);
209 void InspIRCd::CloseLog()
211 this->Logger->Close();
214 void InspIRCd::SetSignals()
216 signal(SIGALRM, SIG_IGN);
217 signal(SIGHUP, InspIRCd::Rehash);
218 signal(SIGPIPE, SIG_IGN);
219 signal(SIGTERM, InspIRCd::Exit);
220 signal(SIGCHLD, SIG_IGN);
223 void InspIRCd::QuickExit(int status)
228 bool InspIRCd::DaemonSeed()
231 if ((childpid = fork ()) < 0)
233 else if (childpid > 0)
235 /* We wait here for the child process to kill us,
236 * so that the shell prompt doesnt come back over
238 * Sending a kill with a signal of 0 just checks
239 * if the child pid is still around. If theyre not,
240 * they threw an error and we should give up.
242 signal(SIGTERM, InspIRCd::QuickExit);
243 while (kill(childpid, 0) != -1)
249 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
252 if (getrlimit(RLIMIT_CORE, &rl) == -1)
254 this->Log(DEFAULT,"Failed to getrlimit()!");
259 rl.rlim_cur = rl.rlim_max;
260 if (setrlimit(RLIMIT_CORE, &rl) == -1)
261 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
267 void InspIRCd::WritePID(const std::string &filename)
269 std::string fname = (filename.empty() ? "inspircd.pid" : filename);
270 if (*(fname.begin()) != '/')
272 std::string::size_type pos;
273 std::string confpath = this->ConfigFileName;
274 if ((pos = confpath.rfind("/")) != std::string::npos)
276 /* Leaves us with just the path */
277 fname = confpath.substr(0, pos) + std::string("/") + fname;
280 std::ofstream outfile(fname.c_str());
281 if (outfile.is_open())
288 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
289 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
290 Exit(EXIT_STATUS_PID);
294 std::string InspIRCd::GetRevision()
299 InspIRCd::InspIRCd(int argc, char** argv)
300 : 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)
304 int do_nofork = 0, do_debug = 0, do_nolog = 0, do_restart = 0; /* flag variables */
310 this->unregistered_count = 0;
312 this->clientlist = new user_hash();
313 this->chanlist = new chan_hash();
315 this->Config = new ServerConfig(this);
317 this->Config->argv = argv;
318 this->Config->argc = argc;
320 this->Config->opertypes.clear();
321 this->Config->operclass.clear();
322 this->SNO = new SnomaskManager(this);
324 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
325 this->time_delta = 0;
326 this->next_call = this->TIME + 3;
329 *this->LogFileName = 0;
330 strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
332 struct option longopts[] =
334 { "nofork", no_argument, &do_nofork, 1 },
335 { "logfile", required_argument, NULL, 'f' },
336 { "config", required_argument, NULL, 'c' },
337 { "debug", no_argument, &do_debug, 1 },
338 { "nolog", no_argument, &do_nolog, 1 },
339 { "restart", no_argument, &do_restart, 1 },
343 while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
348 /* Log filename was set */
349 strlcpy(LogFileName, optarg, MAXBUF);
350 printf("LOG: Setting logfile to %s\n", LogFileName);
353 /* Config filename was set */
354 strlcpy(ConfigFileName, optarg, MAXBUF);
355 printf("CONFIG: Setting config file to %s\n", ConfigFileName);
358 /* getopt_long_only() set an int variable, just keep going */
361 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
362 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--restart]\n", argv[0]);
363 Exit(EXIT_STATUS_ARGV);
368 if (!ServerConfig::FileExists(this->ConfigFileName))
370 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
371 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
372 Exit(EXIT_STATUS_CONFIG);
375 /* Set the finished argument values */
376 Config->nofork = do_nofork;
377 Config->forcedebug = do_debug;
378 Config->writelog = !do_nolog;
380 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
382 this->OpenLog(argv, argc);
383 this->stats = new serverstats();
384 this->Timers = new TimerManager(this);
385 this->Parser = new CommandParser(this);
386 this->XLines = new XLineManager(this);
387 Config->ClearStack();
388 Config->Read(true, NULL);
390 this->Modes = new ModeParser(this);
391 this->AddServerName(Config->ServerName);
393 InitializeDisabledCommands(Config->DisabledCommands, this);
394 stats->BoundPortCount = BindPorts(true, found_ports, pl);
396 for(int t = 0; t < 255; t++)
397 Config->global_implementation[t] = 0;
399 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
406 if (!this->DaemonSeed())
408 printf("ERROR: could not go into daemon mode. Shutting down.\n");
409 Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
410 Exit(EXIT_STATUS_FORK);
414 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
415 * initialize the socket engine.
417 SocketEngineFactory* SEF = new SocketEngineFactory();
418 SE = SEF->Create(this);
421 this->Res = new DNS(this);
423 this->LoadAllModules();
424 /* Just in case no modules were loaded - fix for bug #101 */
425 this->BuildISupport();
427 if ((stats->BoundPortCount == 0) && (found_ports > 0))
429 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
430 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
431 Exit(EXIT_STATUS_BIND);
434 if (stats->BoundPortCount != (unsigned int)found_ports)
436 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);
437 printf("The following port%s failed to bind:\n", found_ports - stats->BoundPortCount != 1 ? "s" : "");
439 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
441 printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
445 /* Add the listening sockets used for client inbound connections
446 * to the socket engine
448 for (unsigned long count = 0; count < stats->BoundPortCount; count++)
450 if (!SE->AddFd(Config->openSockfd[count]))
452 printf("\nEH? Could not add listener to socketengine. You screwed up, aborting.\n");
453 Log(DEFAULT,"EH? Could not add listener to socketengine. You screwed up, aborting.");
454 Exit(EXIT_STATUS_INTERNAL);
458 if (!Config->nofork && !do_restart)
460 if (kill(getppid(), SIGTERM) == -1)
462 printf("Error killing parent process: %s\n",strerror(errno));
463 Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
471 printf("\nInspIRCd is now running!\n");
472 Log(DEFAULT,"Startup complete.");
474 this->WritePID(Config->PID);
477 std::string InspIRCd::GetVersionString()
479 char versiondata[MAXBUF];
480 char dnsengine[] = "singlethread-object";
481 if (*Config->CustomVersion)
483 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
487 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%s,%s,%s]",VERSION,Config->ServerName,SYSTEM,REVISION,SE->GetName().c_str(),dnsengine);
492 char* InspIRCd::ModuleError()
497 void InspIRCd::EraseFactory(int j)
500 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
506 factory.push_back(NULL);
513 void InspIRCd::EraseModule(int j)
516 for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
522 modules.push_back(NULL);
528 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
532 Config->module_names.erase(v);
540 void InspIRCd::MoveTo(std::string modulename,int slot)
542 unsigned int v2 = 256;
543 for (unsigned int v = 0; v < Config->module_names.size(); v++)
545 if (Config->module_names[v] == modulename)
547 // found an instance, swap it with the item at the end
552 if ((v2 != (unsigned int)slot) && (v2 < 256))
554 // Swap the module names over
555 Config->module_names[v2] = Config->module_names[slot];
556 Config->module_names[slot] = modulename;
557 // now swap the module factories
558 ircd_module* temp = factory[v2];
559 factory[v2] = factory[slot];
560 factory[slot] = temp;
561 // now swap the module objects
562 Module* temp_module = modules[v2];
563 modules[v2] = modules[slot];
564 modules[slot] = temp_module;
565 // now swap the implement lists (we dont
566 // need to swap the global or recount it)
567 for (int n = 0; n < 255; n++)
569 char x = Config->implement_lists[v2][n];
570 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
571 Config->implement_lists[slot][n] = x;
576 void InspIRCd::MoveAfter(std::string modulename, std::string after)
578 for (unsigned int v = 0; v < Config->module_names.size(); v++)
580 if (Config->module_names[v] == after)
582 MoveTo(modulename, v);
588 void InspIRCd::MoveBefore(std::string modulename, std::string before)
590 for (unsigned int v = 0; v < Config->module_names.size(); v++)
592 if (Config->module_names[v] == before)
596 MoveTo(modulename, v-1);
600 MoveTo(modulename, v);
607 void InspIRCd::MoveToFirst(std::string modulename)
609 MoveTo(modulename,0);
612 void InspIRCd::MoveToLast(std::string modulename)
614 MoveTo(modulename,this->GetModuleCount());
617 void InspIRCd::BuildISupport()
619 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
621 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << Config->MaxChans << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
622 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
623 v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32";
624 Config->data005 = v.str();
625 FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
629 bool InspIRCd::UnloadModule(const char* filename)
631 std::string filename_str = filename;
632 for (unsigned int j = 0; j != Config->module_names.size(); j++)
634 if (Config->module_names[j] == filename_str)
636 if (modules[j]->GetVersion().Flags & VF_STATIC)
638 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
639 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
642 std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modules[j]);
643 if (intercount.first > 0)
645 this->Log(DEFAULT,"Failed to unload module %s, being used by %d other(s) via interface '%s'",filename, intercount.first, intercount.second.c_str());
646 snprintf(MODERR,MAXBUF,"Module not unloadable (Still in use by %d other module%s which %s using its interface '%s') -- unload dependent modules first!",
648 intercount.first > 1 ? "s" : "",
649 intercount.first > 1 ? "are" : "is",
650 intercount.second.c_str());
653 /* Give the module a chance to tidy out all its metadata */
654 for (chan_hash::iterator c = this->chanlist->begin(); c != this->chanlist->end(); c++)
656 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
658 for (user_hash::iterator u = this->clientlist->begin(); u != this->clientlist->end(); u++)
660 modules[j]->OnCleanup(TYPE_USER,u->second);
663 /* Tidy up any dangling resolvers */
664 this->Res->CleanResolvers(modules[j]);
666 FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
668 for(int t = 0; t < 255; t++)
670 Config->global_implementation[t] -= Config->implement_lists[j][t];
673 /* We have to renumber implement_lists after unload because the module numbers change!
675 for(int j2 = j; j2 < 254; j2++)
677 for(int t = 0; t < 255; t++)
679 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
684 Parser->RemoveCommands(filename);
685 this->EraseModule(j);
686 this->EraseFactory(j);
687 this->Log(DEFAULT,"Module %s unloaded",filename);
693 this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
694 snprintf(MODERR,MAXBUF,"Module not loaded");
698 bool InspIRCd::LoadModule(const char* filename)
700 /* Do we have a glob pattern in the filename?
701 * The user wants to load multiple modules which
704 if (strchr(filename,'*') || (strchr(filename,'?')))
707 DIR* library = opendir(Config->ModPath);
710 /* Try and locate and load all modules matching the pattern */
711 dirent* entry = NULL;
712 while ((entry = readdir(library)))
714 if (this->MatchText(entry->d_name, filename))
716 if (!this->LoadModule(entry->d_name))
722 /* Loadmodule will now return false if any one of the modules failed
723 * to load (but wont abort when it encounters a bad one) and when 1 or
724 * more modules were actually loaded.
726 return (n_match > 0);
729 char modfile[MAXBUF];
730 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
731 std::string filename_str = filename;
733 if (!ServerConfig::DirValid(modfile))
735 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
736 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
739 if (ServerConfig::FileExists(modfile))
742 for (unsigned int j = 0; j < Config->module_names.size(); j++)
744 if (Config->module_names[j] == filename_str)
746 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
747 snprintf(MODERR,MAXBUF,"Module already loaded");
753 ircd_module* a = new ircd_module(this, modfile);
754 factory[this->ModCount+1] = a;
755 if (factory[this->ModCount+1]->LastError())
757 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
758 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
761 if ((long)factory[this->ModCount+1]->factory != -1)
763 Module* m = factory[this->ModCount+1]->factory->CreateModule(this);
765 Version v = m->GetVersion();
767 if (v.API != API_VERSION)
771 this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
772 snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
777 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]"));
780 modules[this->ModCount+1] = m;
781 /* save the module and the module's classfactory, if
782 * this isnt done, random crashes can occur :/ */
783 Config->module_names.push_back(filename);
785 char* x = &Config->implement_lists[this->ModCount+1][0];
786 for(int t = 0; t < 255; t++)
789 modules[this->ModCount+1]->Implements(x);
791 for(int t = 0; t < 255; t++)
792 Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
796 this->Log(DEFAULT,"Unable to load %s",modfile);
797 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
801 catch (CoreException& modexcept)
803 this->Log(DEFAULT,"Unable to load %s: %s",modfile,modexcept.GetReason());
804 snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
810 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
811 snprintf(MODERR,MAXBUF,"Module file could not be found");
815 FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
816 // now work out which modules, if any, want to move to the back of the queue,
817 // and if they do, move them there.
818 std::vector<std::string> put_to_back;
819 std::vector<std::string> put_to_front;
820 std::map<std::string,std::string> put_before;
821 std::map<std::string,std::string> put_after;
822 for (unsigned int j = 0; j < Config->module_names.size(); j++)
824 if (modules[j]->Prioritize() == PRIORITY_LAST)
825 put_to_back.push_back(Config->module_names[j]);
826 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
827 put_to_front.push_back(Config->module_names[j]);
828 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
829 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
830 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
831 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
833 for (unsigned int j = 0; j < put_to_back.size(); j++)
834 MoveToLast(put_to_back[j]);
835 for (unsigned int j = 0; j < put_to_front.size(); j++)
836 MoveToFirst(put_to_front[j]);
837 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
838 MoveBefore(j->first,j->second);
839 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
840 MoveAfter(j->first,j->second);
845 void InspIRCd::DoOneIteration(bool process_module_sockets)
849 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
850 * Once per loop iteration is pleanty.
855 /* Run background module timers every few seconds
856 * (the docs say modules shouldnt rely on accurate
857 * timing using this event, so we dont have to
858 * time this exactly).
863 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
864 if ((TIME % 3600) == 0)
866 this->RehashUsersAndChans();
867 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
869 Timers->TickTimers(TIME);
870 this->DoBackgroundUserStuff(TIME);
874 XLines->expire_lines();
875 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
876 Timers->TickMissedTimers(TIME);
879 if (!getrusage(0, &ru))
881 gettimeofday(&this->stats->LastSampled, NULL);
882 this->stats->LastCPU = ru.ru_utime;
886 /* Call the socket engine to wait on the active
887 * file descriptors. The socket engine has everything's
888 * descriptors in its list... dns, modules, users,
889 * servers... so its nice and easy, just one call.
890 * This will cause any read or write events to be
891 * dispatched to their handlers.
893 SE->DispatchEvents();
895 /* if any users was quit, take them out */
900 bool InspIRCd::IsIdent(const char* n)
905 for (char* i = (char*)n; *i; i++)
907 if ((*i >= 'A') && (*i <= '}'))
911 if (((*i >= '0') && (*i <= '9')) || (*i == '-') || (*i == '.'))
925 DoOneIteration(true);
927 /* This is never reached -- we hope! */
931 /**********************************************************************************/
934 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
937 int main(int argc, char** argv)
939 SI = new InspIRCd(argc, argv);
945 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
946 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
947 * registration timeout maximum seconds)
949 bool InspIRCd::AllModulesReportReady(userrec* user)
951 if (!Config->global_implementation[I_OnCheckReady])
954 for (int i = 0; i <= this->GetModuleCount(); i++)
956 if (Config->implement_lists[i][I_OnCheckReady])
958 int res = modules[i]->OnCheckReady(user);
966 int InspIRCd::GetModuleCount()
968 return this->ModCount;
971 time_t InspIRCd::Time(bool delta)
974 return TIME + time_delta;
978 int InspIRCd::SetTimeDelta(int delta)
980 int old = time_delta;
982 this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
986 void InspIRCd::AddLocalClone(userrec* user)
988 clonemap::iterator x = local_clones.find(user->GetIPString());
989 if (x != local_clones.end())
992 local_clones[user->GetIPString()] = 1;
995 void InspIRCd::AddGlobalClone(userrec* user)
997 clonemap::iterator y = global_clones.find(user->GetIPString());
998 if (y != global_clones.end())
1001 global_clones[user->GetIPString()] = 1;
1004 int InspIRCd::GetTimeDelta()
1009 bool FileLogger::Readable()
1014 void FileLogger::HandleEvent(EventType et, int errornum)
1016 this->WriteLogLine("");
1018 ServerInstance->SE->DelFd(this);
1021 void FileLogger::WriteLogLine(const std::string &line)
1024 buffer.append(line);
1028 int written = fprintf(log,"%s",buffer.c_str());
1029 if ((written >= 0) && (written < (int)buffer.length()))
1031 buffer.erase(0, buffer.length());
1032 ServerInstance->SE->AddFd(this);
1034 else if (written == -1)
1036 if (errno == EAGAIN)
1037 ServerInstance->SE->AddFd(this);
1041 /* Wrote the whole buffer, and no need for write callback */
1045 if (writeops++ % 20)
1052 void FileLogger::Close()
1056 int flags = fcntl(fileno(log), F_GETFL, 0);
1057 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
1059 fprintf(log,"%s",buffer.c_str());
1061 ServerInstance->SE->DelFd(this);
1070 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
1074 irc::sockets::NonBlocking(fileno(log));
1075 this->SetFd(fileno(log));
1080 FileLogger::~FileLogger()