1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 /* Now with added unF! ;) */
21 #include "inspircd_config.h"
23 #include "inspircd_io.h"
25 #include <sys/errno.h>
26 #include <sys/ioctl.h>
30 #include <ext/hash_map>
51 #include "inspstring.h"
53 #include "helperfuncs.h"
55 #include "socketengine.h"
56 #include "userprocess.h"
59 #include "command_parse.h"
61 InspIRCd* ServerInstance;
63 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
64 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
66 extern std::vector<Module*> modules;
67 extern std::vector<ircd_module*> factory;
69 std::vector<InspSocket*> module_sockets;
70 std::vector<userrec*> local_users;
73 int openSockfd[MAXSOCKS];
74 sockaddr_in client,server;
77 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
79 time_t TIME = time(NULL), OLDTIME = time(NULL);
81 // This table references users by file descriptor.
82 // its an array to make it VERY fast, as all lookups are referenced
83 // by an integer, meaning there is no need for a scan/search operation.
84 userrec* fd_ref_table[MAX_DESCRIPTORS];
86 Server* MyServer = new Server;
87 ServerConfig *Config = new ServerConfig;
92 servernamelist servernames;
95 void AddServerName(std::string servername)
97 log(DEBUG,"Adding server name: %s",servername.c_str());
98 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
100 if (*a == servername)
103 servernames.push_back(servername);
106 const char* FindServerNamePtr(std::string servername)
108 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
110 if (*a == servername)
113 AddServerName(servername);
114 return FindServerNamePtr(servername);
117 bool FindServerName(std::string servername)
119 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
121 if (*a == servername)
127 std::string InspIRCd::GetRevision()
129 /* w00t got me to replace a bunch of strtok_r
130 * with something nicer, so i did this. Its the
131 * same thing really, only in C++. It places the
132 * text into a std::stringstream which is a readable
133 * and writeable buffer stream, and then pops two
134 * words off it, space delimited. Because it reads
135 * into the same variable twice, the first word
136 * is discarded, and the second one returned.
139 /* XXX - this revision ID is NOT bumping automatically -- w00t */
140 std::stringstream Revision("$Revision$");
142 Revision >> single >> single;
146 void InspIRCd::MakeLowerMap()
148 // initialize the lowercase mapping table
149 for (unsigned int cn = 0; cn < 256; cn++)
151 // lowercase the uppercase chars
152 for (unsigned int cn = 65; cn < 91; cn++)
153 lowermap[cn] = tolower(cn);
154 // now replace the specific chars for scandanavian comparison
155 lowermap[(unsigned)'['] = '{';
156 lowermap[(unsigned)']'] = '}';
157 lowermap[(unsigned)'\\'] = '|';
160 InspIRCd::InspIRCd(int argc, char** argv)
163 module_sockets.clear();
164 this->startup_time = time(NULL);
166 log(DEBUG,"*** InspIRCd starting up!");
167 if (!FileExists(CONFIG_FILE))
169 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
170 log(DEFAULT,"main: no config");
171 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
175 for (int i = 1; i < argc; i++)
177 if (!strcmp(argv[i],"-nofork")) {
178 Config->nofork = true;
180 if (!strcmp(argv[i],"-wait")) {
183 if (!strcmp(argv[i],"-nolimit")) {
184 Config->unlimitcore = true;
189 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
191 this->MakeLowerMap();
194 Config->ClearStack();
195 Config->Read(true,NULL);
197 this->ModeGrok = new ModeParser();
198 this->Parser = new CommandParser();
199 this->stats = new serverstats();
200 AddServerName(Config->ServerName);
202 stats->BoundPortCount = BindPorts();
204 for(int t = 0; t < 255; t++)
205 Config->global_implementation[t] = 0;
207 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
213 if (DaemonSeed() == ERROR)
215 printf("ERROR: could not go into daemon mode. Shutting down.\n");
220 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
221 * initialize the socket engine.
223 SE = new SocketEngine();
225 /* We must load the modules AFTER initializing the socket engine, now */
230 std::string InspIRCd::GetVersionString()
232 char versiondata[MAXBUF];
234 char dnsengine[] = "multithread";
236 char dnsengine[] = "singlethread";
238 if (*Config->CustomVersion)
240 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s",VERSION,GetRevision().c_str(),Config->ServerName,Config->CustomVersion);
244 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s [FLAGS=%lu,%s,%s]",VERSION,GetRevision().c_str(),Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
249 char* InspIRCd::ModuleError()
254 void InspIRCd::erase_factory(int j)
257 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
262 factory.push_back(NULL);
269 void InspIRCd::erase_module(int j)
272 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
278 modules.push_back(NULL);
284 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
288 Config->module_names.erase(v);
296 void InspIRCd::MoveTo(std::string modulename,int slot)
298 unsigned int v2 = 256;
299 log(DEBUG,"Moving %s to slot %d",modulename.c_str(),slot);
300 for (unsigned int v = 0; v < Config->module_names.size(); v++)
302 if (Config->module_names[v] == modulename)
304 // found an instance, swap it with the item at MODCOUNT
309 if (v2 == (unsigned int)slot)
311 log(DEBUG,"Item %s already in slot %d!",modulename.c_str(),slot);
315 // Swap the module names over
316 Config->module_names[v2] = Config->module_names[slot];
317 Config->module_names[slot] = modulename;
318 // now swap the module factories
319 ircd_module* temp = factory[v2];
320 factory[v2] = factory[slot];
321 factory[slot] = temp;
322 // now swap the module objects
323 Module* temp_module = modules[v2];
324 modules[v2] = modules[slot];
325 modules[slot] = temp_module;
326 // now swap the implement lists (we dont
327 // need to swap the global or recount it)
328 for (int n = 0; n < 255; n++)
330 char x = Config->implement_lists[v2][n];
331 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
332 Config->implement_lists[slot][n] = x;
334 log(DEBUG,"Moved %s to slot successfully",modulename.c_str());
338 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
342 void InspIRCd::MoveAfter(std::string modulename, std::string after)
344 log(DEBUG,"Move %s after %s...",modulename.c_str(),after.c_str());
345 for (unsigned int v = 0; v < Config->module_names.size(); v++)
347 if (Config->module_names[v] == after)
349 MoveTo(modulename, v);
355 void InspIRCd::MoveBefore(std::string modulename, std::string before)
357 log(DEBUG,"Move %s before %s...",modulename.c_str(),before.c_str());
358 for (unsigned int v = 0; v < Config->module_names.size(); v++)
360 if (Config->module_names[v] == before)
364 MoveTo(modulename, v-1);
368 MoveTo(modulename, v);
375 void InspIRCd::MoveToFirst(std::string modulename)
377 MoveTo(modulename,0);
380 void InspIRCd::MoveToLast(std::string modulename)
382 MoveTo(modulename,MODCOUNT);
385 void InspIRCd::BuildISupport()
387 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
389 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
390 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
391 v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC NETWORK=" << Config->Network << " MAXPARA=32";
392 Config->data005 = v.str();
393 FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
396 bool InspIRCd::UnloadModule(const char* filename)
398 std::string filename_str = filename;
399 for (unsigned int j = 0; j != Config->module_names.size(); j++)
401 if (Config->module_names[j] == filename_str)
403 if (modules[j]->GetVersion().Flags & VF_STATIC)
405 log(DEFAULT,"Failed to unload STATIC module %s",filename);
406 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
409 /* Give the module a chance to tidy out all its metadata */
410 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
412 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
414 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
416 modules[j]->OnCleanup(TYPE_USER,u->second);
419 FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
421 for(int t = 0; t < 255; t++)
423 Config->global_implementation[t] -= Config->implement_lists[j][t];
426 /* We have to renumber implement_lists after unload because the module numbers change!
428 for(int j2 = j; j2 < 254; j2++)
430 for(int t = 0; t < 255; t++)
432 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
437 log(DEBUG,"Deleting module...");
439 log(DEBUG,"Erasing module entry...");
441 log(DEBUG,"Removing dependent commands...");
442 Parser->RemoveCommands(filename);
443 log(DEFAULT,"Module %s unloaded",filename);
449 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
450 snprintf(MODERR,MAXBUF,"Module not loaded");
454 bool InspIRCd::LoadModule(const char* filename)
456 char modfile[MAXBUF];
458 strlcpy(modfile,filename,MAXBUF);
460 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
462 std::string filename_str = filename;
465 if (!DirValid(modfile))
467 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
468 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
473 log(DEBUG,"Loading module: %s",modfile);
475 if (FileExists(modfile))
478 for (unsigned int j = 0; j < Config->module_names.size(); j++)
480 if (Config->module_names[j] == filename_str)
482 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
483 snprintf(MODERR,MAXBUF,"Module already loaded");
487 ircd_module* a = new ircd_module(modfile);
488 factory[MODCOUNT+1] = a;
489 if (factory[MODCOUNT+1]->LastError())
491 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
492 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
495 if (factory[MODCOUNT+1]->factory)
497 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
498 modules[MODCOUNT+1] = m;
499 /* save the module and the module's classfactory, if
500 * this isnt done, random crashes can occur :/ */
501 Config->module_names.push_back(filename);
503 char* x = &Config->implement_lists[MODCOUNT+1][0];
504 for(int t = 0; t < 255; t++)
507 modules[MODCOUNT+1]->Implements(x);
509 for(int t = 0; t < 255; t++)
511 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
512 if (Config->implement_lists[MODCOUNT+1][t])
514 log(DEBUG,"Add global implementation: %d %d => %d",MODCOUNT+1,t,Config->global_implementation[t]);
520 log(DEFAULT,"Unable to load %s",modfile);
521 snprintf(MODERR,MAXBUF,"Factory function failed!");
528 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
529 snprintf(MODERR,MAXBUF,"Module file could not be found");
534 FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
535 // now work out which modules, if any, want to move to the back of the queue,
536 // and if they do, move them there.
537 std::vector<std::string> put_to_back;
538 std::vector<std::string> put_to_front;
539 std::map<std::string,std::string> put_before;
540 std::map<std::string,std::string> put_after;
541 for (unsigned int j = 0; j < Config->module_names.size(); j++)
543 if (modules[j]->Prioritize() == PRIORITY_LAST)
545 put_to_back.push_back(Config->module_names[j]);
547 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
549 put_to_front.push_back(Config->module_names[j]);
551 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
553 log(DEBUG,"Module %d wants PRIORITY_BEFORE",j);
554 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
555 log(DEBUG,"Before: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
557 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
559 log(DEBUG,"Module %d wants PRIORITY_AFTER",j);
560 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
561 log(DEBUG,"After: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
564 for (unsigned int j = 0; j < put_to_back.size(); j++)
566 MoveToLast(put_to_back[j]);
568 for (unsigned int j = 0; j < put_to_front.size(); j++)
570 MoveToFirst(put_to_front[j]);
572 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
574 MoveBefore(j->first,j->second);
576 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
578 MoveAfter(j->first,j->second);
586 bool expire_run = false;
587 int activefds[MAX_DESCRIPTORS];
591 InspSocket* s = NULL;
592 InspSocket* s_del = NULL;
593 unsigned int numberactive;
594 sockaddr_in sock_us; // our port number
595 socklen_t uslen; // length of our port number
597 /* Until THIS point, ServerInstance == NULL */
599 LoadAllModules(this);
601 printf("\nInspIRCd is now running!\n");
605 freopen("/dev/null","w",stdout);
606 freopen("/dev/null","w",stderr);
609 /* Add the listening sockets used for client inbound connections
610 * to the socket engine
612 for (int count = 0; count < stats->BoundPortCount; count++)
613 SE->AddFd(openSockfd[count],true,X_LISTEN);
615 WritePID(Config->PID);
617 /* main loop, this never returns */
620 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
621 * Once per loop iteration is pleanty.
626 /* Run background module timers every few seconds
627 * (the docs say modules shouldnt rely on accurate
628 * timing using this event, so we dont have to
629 * time this exactly).
631 if (((TIME % 8) == 0) && (!expire_run))
634 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
638 else if ((TIME % 8) == 1)
643 /* Once a second, do the background processing */
647 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
648 DoBackgroundUserStuff(TIME);
651 /* Process timeouts on module sockets each time around
652 * the loop. There shouldnt be many module sockets, at
653 * most, 20 or so, so this won't be much of a performance
656 DoSocketTimeouts(TIME);
658 /* Call the socket engine to wait on the active
659 * file descriptors. The socket engine has everything's
660 * descriptors in its list... dns, modules, users,
661 * servers... so its nice and easy, just one call.
663 if (!(numberactive = SE->Wait(activefds)))
667 * Now process each of the fd's. For users, we have a fast
668 * lookup table which can find a user by file descriptor, so
669 * processing them by fd isnt expensive. If we have a lot of
670 * listening ports or module sockets though, things could get
673 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
675 int socket_type = SE->GetType(activefds[activefd]);
680 cu = fd_ref_table[activefds[activefd]];
688 /* Process module-owned sockets.
689 * Modules are encouraged to inherit their sockets from
690 * InspSocket so we can process them neatly like this.
692 s = socket_ref[activefds[activefd]];
694 if ((s) && (!s->Poll()))
696 log(DEBUG,"Socket poll returned false, close and bail");
697 SE->DelFd(s->GetFd());
698 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
700 s_del = (InspSocket*)*a;
701 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
703 module_sockets.erase(a);
715 /* When we are using single-threaded dns,
716 * the sockets for dns end up in our mainloop.
717 * When we are using multi-threaded dns,
718 * each thread has its own basic poll() loop
719 * within it, making them 'fire and forget'
720 * and independent of the mainloop.
723 dns_poll(activefds[activefd]);
729 /* It's a listener */
730 uslen = sizeof(sock_us);
731 length = sizeof(client);
732 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
734 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
736 in_port = ntohs(sock_us.sin_port);
737 log(DEBUG,"Accepted socket %d",incomingSockfd);
738 /* Years and years ago, we used to resolve here
739 * using gethostbyaddr(). That is sucky and we
740 * don't do that any more...
742 NonBlocking(incomingSockfd);
743 if (Config->GetIOHook(in_port))
745 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
747 stats->statsAccept++;
748 AddClient(incomingSockfd, in_port, false, client.sin_addr);
749 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
753 log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
754 shutdown(incomingSockfd,2);
755 close(incomingSockfd);
756 stats->statsRefused++;
761 /* Something went wrong if we're in here.
762 * In fact, so wrong, im not quite sure
763 * what we would do, so for now, its going
764 * to safely do bugger all.
771 /* This is never reached -- we hope! */
775 /**********************************************************************************/
778 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
781 int main(int argc, char** argv)
783 ServerInstance = new InspIRCd(argc, argv);
784 ServerInstance->Run();
785 delete ServerInstance;