1 /* ---------------------------------------------------------------------
3 * +------------------------------------+
4 * | Inspire Internet Relay Chat Daemon |
5 * +------------------------------------+
7 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
9 * <brain@chatspike.net>
10 * <Craig@chatspike.net>
12 * Written by Craig Edwards, Craig McLure, and others.
13 * This program is free but copyrighted software; you can redistribute
14 * it and/or modify it under the terms of the GNU General Public
15 * License as published by the Free Software Foundation, version 2
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program; if not, write to the Free Software
25 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 * ---------------------------------------------------------------------
31 #include "configreader.h"
46 #include "socketengine.h"
47 #include "inspircd_se_config.h"
50 #include "command_parse.h"
52 using irc::sockets::NonBlocking;
53 using irc::sockets::Blocking;
54 using irc::sockets::insp_ntoa;
55 using irc::sockets::insp_inaddr;
56 using irc::sockets::insp_sockaddr;
60 void InspIRCd::AddServerName(const std::string &servername)
62 this->Log(DEBUG,"Adding server name: %s",servername.c_str());
64 if(find(servernames.begin(), servernames.end(), servername) == servernames.end())
65 servernames.push_back(servername); /* Wasn't already there. */
68 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
70 servernamelist::iterator iter = find(servernames.begin(), servernames.end(), servername);
72 if(iter == servernames.end())
74 AddServerName(servername);
75 iter = --servernames.end();
81 bool InspIRCd::FindServerName(const std::string &servername)
83 return (find(servernames.begin(), servernames.end(), servername) != servernames.end());
86 void InspIRCd::Exit(int status)
91 void InspIRCd::Start()
93 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
94 printf("(C) ChatSpike Development team.\033[0m\n\n");
95 printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\033[0m\n");
96 printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
97 printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
100 void InspIRCd::Rehash(int status)
102 SI->WriteOpers("Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(CONFIG_FILE));
103 fclose(SI->Config->log_file);
105 SI->Config->Read(false,NULL);
106 FOREACH_MOD_I(SI,I_OnRehash,OnRehash(""));
109 void InspIRCd::SetSignals(bool SEGVHandler)
111 signal(SIGALRM, SIG_IGN);
112 signal(SIGHUP, InspIRCd::Rehash);
113 signal(SIGPIPE, SIG_IGN);
114 signal(SIGTERM, InspIRCd::Exit);
115 signal(SIGCHLD, SIG_IGN);
118 bool InspIRCd::DaemonSeed()
121 if ((childpid = fork ()) < 0)
123 else if (childpid > 0)
125 /* We wait here for the child process to kill us,
126 * so that the shell prompt doesnt come back over
128 * Sending a kill with a signal of 0 just checks
129 * if the child pid is still around. If theyre not,
130 * they threw an error and we should give up.
132 while (kill(childpid, 0) != -1)
138 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
141 if (getrlimit(RLIMIT_CORE, &rl) == -1)
143 this->Log(DEFAULT,"Failed to getrlimit()!");
148 rl.rlim_cur = rl.rlim_max;
149 if (setrlimit(RLIMIT_CORE, &rl) == -1)
150 this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
156 void InspIRCd::WritePID(const std::string &filename)
158 std::ofstream outfile(filename.c_str());
159 if (outfile.is_open())
166 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
167 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
172 std::string InspIRCd::GetRevision()
177 InspIRCd::InspIRCd(int argc, char** argv)
178 : 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)
180 bool SEGVHandler = false;
185 this->Config = new ServerConfig(this);
186 this->SNO = new SnomaskManager(this);
188 this->TIME = this->OLDTIME = this->startup_time = time(NULL);
190 this->Log(DEBUG,"*** InspIRCd starting up!");
191 if (!ServerConfig::FileExists(CONFIG_FILE))
193 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
194 this->Log(DEFAULT,"main: no config");
195 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
198 *this->LogFileName = 0;
200 for (int i = 1; i < argc; i++)
202 if (!strcmp(argv[i],"-nofork"))
204 Config->nofork = true;
206 else if(!strcmp(argv[i],"-debug"))
208 Config->forcedebug = true;
210 else if(!strcmp(argv[i],"-nolog"))
212 Config->writelog = false;
214 else if (!strcmp(argv[i],"-wait"))
218 else if (!strcmp(argv[i],"-nolimit"))
220 printf("WARNING: The `-nolimit' option is deprecated, and now on by default. This behaviour may change in the future.\n");
222 else if (!strcmp(argv[i],"-notraceback"))
226 else if (!strcmp(argv[i],"-logfile"))
230 strlcpy(LogFileName,argv[i+1],MAXBUF);
231 printf("LOG: Setting logfile to %s\n",LogFileName);
235 printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
242 printf("Usage: %s [-nofork] [-nolog] [-debug] [-wait] [-nolimit] [-notraceback] [-logfile <filename>]\n",argv[0]);
248 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
250 this->OpenLog(argv, argc);
251 this->stats = new serverstats();
252 this->Parser = new CommandParser(this);
253 this->Timers = new TimerManager();
254 this->XLines = new XLineManager(this);
255 Config->ClearStack();
256 Config->Read(true, NULL);
258 this->Modes = new ModeParser(this);
259 this->AddServerName(Config->ServerName);
261 InitializeDisabledCommands(Config->DisabledCommands, this);
262 stats->BoundPortCount = BindPorts(true);
264 for(int t = 0; t < 255; t++)
265 Config->global_implementation[t] = 0;
267 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
270 this->SetSignals(SEGVHandler);
273 if (!this->DaemonSeed())
275 printf("ERROR: could not go into daemon mode. Shutting down.\n");
280 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
281 * initialize the socket engine.
283 SocketEngineFactory* SEF = new SocketEngineFactory();
284 SE = SEF->Create(this);
287 this->Res = new DNS(this);
289 this->LoadAllModules();
290 /* Just in case no modules were loaded - fix for bug #101 */
291 this->BuildISupport();
293 if (!stats->BoundPortCount)
295 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
299 /* Add the listening sockets used for client inbound connections
300 * to the socket engine
302 this->Log(DEBUG,"%d listeners",stats->BoundPortCount);
303 for (unsigned long count = 0; count < stats->BoundPortCount; count++)
305 this->Log(DEBUG,"Add listener: %d",Config->openSockfd[count]->GetFd());
306 if (!SE->AddFd(Config->openSockfd[count]))
308 printf("\nEH? Could not add listener to socketengine. You screwed up, aborting.\n");
315 if (kill(getppid(), SIGTERM) == -1)
316 printf("Error killing parent process: %s\n",strerror(errno));
322 printf("\nInspIRCd is now running!\n");
324 this->WritePID(Config->PID);
327 std::string InspIRCd::GetVersionString()
329 char versiondata[MAXBUF];
330 char dnsengine[] = "singlethread-object";
331 if (*Config->CustomVersion)
333 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
337 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%lu,%s,%s]",VERSION,Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
342 char* InspIRCd::ModuleError()
347 void InspIRCd::EraseFactory(int j)
350 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
355 factory.push_back(NULL);
362 void InspIRCd::EraseModule(int j)
365 for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
371 modules.push_back(NULL);
377 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
381 Config->module_names.erase(v);
389 void InspIRCd::MoveTo(std::string modulename,int slot)
391 unsigned int v2 = 256;
392 for (unsigned int v = 0; v < Config->module_names.size(); v++)
394 if (Config->module_names[v] == modulename)
396 // found an instance, swap it with the item at the end
401 if ((v2 != (unsigned int)slot) && (v2 < 256))
403 // Swap the module names over
404 Config->module_names[v2] = Config->module_names[slot];
405 Config->module_names[slot] = modulename;
406 // now swap the module factories
407 ircd_module* temp = factory[v2];
408 factory[v2] = factory[slot];
409 factory[slot] = temp;
410 // now swap the module objects
411 Module* temp_module = modules[v2];
412 modules[v2] = modules[slot];
413 modules[slot] = temp_module;
414 // now swap the implement lists (we dont
415 // need to swap the global or recount it)
416 for (int n = 0; n < 255; n++)
418 char x = Config->implement_lists[v2][n];
419 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
420 Config->implement_lists[slot][n] = x;
425 this->Log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
429 void InspIRCd::MoveAfter(std::string modulename, std::string after)
431 for (unsigned int v = 0; v < Config->module_names.size(); v++)
433 if (Config->module_names[v] == after)
435 MoveTo(modulename, v);
441 void InspIRCd::MoveBefore(std::string modulename, std::string before)
443 for (unsigned int v = 0; v < Config->module_names.size(); v++)
445 if (Config->module_names[v] == before)
449 MoveTo(modulename, v-1);
453 MoveTo(modulename, v);
460 void InspIRCd::MoveToFirst(std::string modulename)
462 MoveTo(modulename,0);
465 void InspIRCd::MoveToLast(std::string modulename)
467 MoveTo(modulename,this->GetModuleCount());
470 void InspIRCd::BuildISupport()
472 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
474 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
475 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
476 v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32";
477 Config->data005 = v.str();
478 FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
481 bool InspIRCd::UnloadModule(const char* filename)
483 std::string filename_str = filename;
484 for (unsigned int j = 0; j != Config->module_names.size(); j++)
486 if (Config->module_names[j] == filename_str)
488 if (modules[j]->GetVersion().Flags & VF_STATIC)
490 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
491 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
494 /* Give the module a chance to tidy out all its metadata */
495 for (chan_hash::iterator c = this->chanlist.begin(); c != this->chanlist.end(); c++)
497 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
499 for (user_hash::iterator u = this->clientlist.begin(); u != this->clientlist.end(); u++)
501 modules[j]->OnCleanup(TYPE_USER,u->second);
504 FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
506 for(int t = 0; t < 255; t++)
508 Config->global_implementation[t] -= Config->implement_lists[j][t];
511 /* We have to renumber implement_lists after unload because the module numbers change!
513 for(int j2 = j; j2 < 254; j2++)
515 for(int t = 0; t < 255; t++)
517 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
522 this->Log(DEBUG,"Removing dependent commands...");
523 Parser->RemoveCommands(filename);
524 this->Log(DEBUG,"Deleting module...");
525 this->EraseModule(j);
526 this->Log(DEBUG,"Erasing module entry...");
527 this->EraseFactory(j);
528 this->Log(DEFAULT,"Module %s unloaded",filename);
534 this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
535 snprintf(MODERR,MAXBUF,"Module not loaded");
539 bool InspIRCd::LoadModule(const char* filename)
541 char modfile[MAXBUF];
543 strlcpy(modfile,filename,MAXBUF);
545 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
547 std::string filename_str = filename;
550 if (!ServerConfig::DirValid(modfile))
552 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
553 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
558 this->Log(DEBUG,"Loading module: %s",modfile);
560 if (ServerConfig::FileExists(modfile))
563 for (unsigned int j = 0; j < Config->module_names.size(); j++)
565 if (Config->module_names[j] == filename_str)
567 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
568 snprintf(MODERR,MAXBUF,"Module already loaded");
574 ircd_module* a = new ircd_module(this, modfile);
575 factory[this->ModCount+1] = a;
576 if (factory[this->ModCount+1]->LastError())
578 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
579 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
582 if ((long)factory[this->ModCount+1]->factory != -1)
584 Module* m = factory[this->ModCount+1]->factory->CreateModule(this);
585 modules[this->ModCount+1] = m;
586 /* save the module and the module's classfactory, if
587 * this isnt done, random crashes can occur :/ */
588 Config->module_names.push_back(filename);
590 char* x = &Config->implement_lists[this->ModCount+1][0];
591 for(int t = 0; t < 255; t++)
594 modules[this->ModCount+1]->Implements(x);
596 for(int t = 0; t < 255; t++)
597 Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
601 this->Log(DEFAULT,"Unable to load %s",modfile);
602 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
606 catch (ModuleException& modexcept)
608 this->Log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
609 snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
616 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
617 snprintf(MODERR,MAXBUF,"Module file could not be found");
622 FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
623 // now work out which modules, if any, want to move to the back of the queue,
624 // and if they do, move them there.
625 std::vector<std::string> put_to_back;
626 std::vector<std::string> put_to_front;
627 std::map<std::string,std::string> put_before;
628 std::map<std::string,std::string> put_after;
629 for (unsigned int j = 0; j < Config->module_names.size(); j++)
631 if (modules[j]->Prioritize() == PRIORITY_LAST)
632 put_to_back.push_back(Config->module_names[j]);
633 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
634 put_to_front.push_back(Config->module_names[j]);
635 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
636 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
637 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
638 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
640 for (unsigned int j = 0; j < put_to_back.size(); j++)
641 MoveToLast(put_to_back[j]);
642 for (unsigned int j = 0; j < put_to_front.size(); j++)
643 MoveToFirst(put_to_front[j]);
644 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
645 MoveBefore(j->first,j->second);
646 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
647 MoveAfter(j->first,j->second);
652 void InspIRCd::DoOneIteration(bool process_module_sockets)
654 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
655 * Once per loop iteration is pleanty.
660 /* Run background module timers every few seconds
661 * (the docs say modules shouldnt rely on accurate
662 * timing using this event, so we dont have to
663 * time this exactly).
668 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
669 if ((TIME % 3600) == 0)
671 irc::whowas::MaintainWhoWas(TIME);
673 Timers->TickTimers(TIME);
674 this->DoBackgroundUserStuff(TIME);
678 XLines->expire_lines();
679 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
680 Timers->TickMissedTimers(TIME);
684 /* Call the socket engine to wait on the active
685 * file descriptors. The socket engine has everything's
686 * descriptors in its list... dns, modules, users,
687 * servers... so its nice and easy, just one call.
688 * This will cause any read or write events to be
689 * dispatched to their handlers.
691 SE->DispatchEvents();
694 bool InspIRCd::IsIdent(const char* n)
699 for (char* i = (char*)n; *i; i++)
701 if ((*i >= 'A') && (*i <= '}'))
705 if (((*i >= '0') && (*i <= '9')) || (*i == '-') || (*i == '.'))
715 bool InspIRCd::IsNick(const char* n)
721 for (char* i = (char*)n; *i; i++, p++)
723 /* "A"-"}" can occur anywhere in a nickname */
724 if ((*i >= 'A') && (*i <= '}'))
728 /* "0"-"9", "-" can occur anywhere BUT the first char of a nickname */
729 if ((((*i >= '0') && (*i <= '9')) || (*i == '-')) && (i > n))
733 /* invalid character! abort */
736 return (p < NICKMAX - 1);
743 DoOneIteration(true);
745 /* This is never reached -- we hope! */
749 /**********************************************************************************/
752 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
755 int main(int argc, char** argv)
757 SI = new InspIRCd(argc, argv);
763 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
764 * (until this returns true, a user will block in the waiting state, waiting to connect up to the
765 * registration timeout maximum seconds)
767 bool InspIRCd::AllModulesReportReady(userrec* user)
769 if (!Config->global_implementation[I_OnCheckReady])
772 for (int i = 0; i <= this->GetModuleCount(); i++)
774 if (Config->implement_lists[i][I_OnCheckReady])
776 int res = modules[i]->OnCheckReady(user);
784 int InspIRCd::GetModuleCount()
786 return this->ModCount;
789 time_t InspIRCd::Time()
794 bool FileLogger::Readable()
799 void FileLogger::HandleEvent(EventType et)
801 this->WriteLogLine("");
802 ServerInstance->SE->DelFd(this);
805 void FileLogger::WriteLogLine(const std::string &line)
812 int written = fprintf(log,"%s",buffer.c_str());
813 if ((written >= 0) && (written < (int)buffer.length()))
815 buffer.erase(0, buffer.length());
816 ServerInstance->SE->AddFd(this);
818 else if (written == -1)
821 ServerInstance->SE->AddFd(this);
825 /* Wrote the whole buffer, and no need for write callback */
835 void FileLogger::Close()
839 int flags = fcntl(fileno(log), F_GETFL, 0);
840 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
842 fprintf(log,"%s",buffer.c_str());
847 ServerInstance->SE->DelFd(this);
850 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
852 irc::sockets::NonBlocking(fileno(log));
853 this->SetFd(fileno(log));
857 FileLogger::~FileLogger()