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"
62 InspIRCd* ServerInstance;
64 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
65 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
67 extern std::vector<Module*> modules;
68 extern std::vector<ircd_module*> factory;
70 std::vector<InspSocket*> module_sockets;
71 std::vector<userrec*> local_users;
74 int openSockfd[MAXSOCKS];
75 sockaddr_in client,server;
78 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
80 time_t TIME = time(NULL), OLDTIME = time(NULL);
82 // This table references users by file descriptor.
83 // its an array to make it VERY fast, as all lookups are referenced
84 // by an integer, meaning there is no need for a scan/search operation.
85 userrec* fd_ref_table[MAX_DESCRIPTORS];
87 Server* MyServer = new Server;
88 ServerConfig *Config = new ServerConfig;
93 servernamelist servernames;
96 void AddServerName(std::string servername)
98 log(DEBUG,"Adding server name: %s",servername.c_str());
99 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
101 if (*a == servername)
104 servernames.push_back(servername);
107 const char* FindServerNamePtr(std::string servername)
109 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
111 if (*a == servername)
114 AddServerName(servername);
115 return FindServerNamePtr(servername);
118 bool FindServerName(std::string servername)
120 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
122 if (*a == servername)
128 std::string InspIRCd::GetRevision()
130 /* w00t got me to replace a bunch of strtok_r
131 * with something nicer, so i did this. Its the
132 * same thing really, only in C++. It places the
133 * text into a std::stringstream which is a readable
134 * and writeable buffer stream, and then pops two
135 * words off it, space delimited. Because it reads
136 * into the same variable twice, the first word
137 * is discarded, and the second one returned.
140 /* XXX - this revision ID is NOT bumping automatically -- w00t */
141 std::stringstream Revision("$Revision$");
143 Revision >> single >> single;
147 void InspIRCd::MakeLowerMap()
149 // initialize the lowercase mapping table
150 for (unsigned int cn = 0; cn < 256; cn++)
152 // lowercase the uppercase chars
153 for (unsigned int cn = 65; cn < 91; cn++)
154 lowermap[cn] = tolower(cn);
155 // now replace the specific chars for scandanavian comparison
156 lowermap[(unsigned)'['] = '{';
157 lowermap[(unsigned)']'] = '}';
158 lowermap[(unsigned)'\\'] = '|';
161 InspIRCd::InspIRCd(int argc, char** argv)
164 module_sockets.clear();
165 this->startup_time = time(NULL);
167 log(DEBUG,"*** InspIRCd starting up!");
168 if (!FileExists(CONFIG_FILE))
170 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
171 log(DEFAULT,"main: no config");
172 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
176 for (int i = 1; i < argc; i++)
178 if (!strcmp(argv[i],"-nofork")) {
179 Config->nofork = true;
181 if (!strcmp(argv[i],"-wait")) {
184 if (!strcmp(argv[i],"-nolimit")) {
185 Config->unlimitcore = true;
190 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
192 this->MakeLowerMap();
195 Config->ClearStack();
196 Config->Read(true,NULL);
198 this->ModeGrok = new ModeParser();
199 this->Parser = new CommandParser();
200 this->stats = new serverstats();
201 AddServerName(Config->ServerName);
203 stats->BoundPortCount = BindPorts();
205 for(int t = 0; t < 255; t++)
206 Config->global_implementation[t] = 0;
208 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
214 if (DaemonSeed() == ERROR)
216 printf("ERROR: could not go into daemon mode. Shutting down.\n");
221 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
222 * initialize the socket engine.
224 SE = new SocketEngine();
226 /* We must load the modules AFTER initializing the socket engine, now */
231 std::string InspIRCd::GetVersionString()
233 char versiondata[MAXBUF];
235 char dnsengine[] = "multithread";
237 char dnsengine[] = "singlethread";
239 if (*Config->CustomVersion)
241 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s",VERSION,GetRevision().c_str(),Config->ServerName,Config->CustomVersion);
245 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);
250 char* InspIRCd::ModuleError()
255 void InspIRCd::erase_factory(int j)
258 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
263 factory.push_back(NULL);
270 void InspIRCd::erase_module(int j)
273 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
279 modules.push_back(NULL);
285 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
289 Config->module_names.erase(v);
297 void InspIRCd::MoveTo(std::string modulename,int slot)
299 unsigned int v2 = 256;
300 log(DEBUG,"Moving %s to slot %d",modulename.c_str(),slot);
301 for (unsigned int v = 0; v < Config->module_names.size(); v++)
303 if (Config->module_names[v] == modulename)
305 // found an instance, swap it with the item at MODCOUNT
310 if (v2 == (unsigned int)slot)
312 log(DEBUG,"Item %s already in slot %d!",modulename.c_str(),slot);
316 // Swap the module names over
317 Config->module_names[v2] = Config->module_names[slot];
318 Config->module_names[slot] = modulename;
319 // now swap the module factories
320 ircd_module* temp = factory[v2];
321 factory[v2] = factory[slot];
322 factory[slot] = temp;
323 // now swap the module objects
324 Module* temp_module = modules[v2];
325 modules[v2] = modules[slot];
326 modules[slot] = temp_module;
327 // now swap the implement lists (we dont
328 // need to swap the global or recount it)
329 for (int n = 0; n < 255; n++)
331 char x = Config->implement_lists[v2][n];
332 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
333 Config->implement_lists[slot][n] = x;
335 log(DEBUG,"Moved %s to slot successfully",modulename.c_str());
339 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
343 void InspIRCd::MoveAfter(std::string modulename, std::string after)
345 log(DEBUG,"Move %s after %s...",modulename.c_str(),after.c_str());
346 for (unsigned int v = 0; v < Config->module_names.size(); v++)
348 if (Config->module_names[v] == after)
350 MoveTo(modulename, v);
356 void InspIRCd::MoveBefore(std::string modulename, std::string before)
358 log(DEBUG,"Move %s before %s...",modulename.c_str(),before.c_str());
359 for (unsigned int v = 0; v < Config->module_names.size(); v++)
361 if (Config->module_names[v] == before)
365 MoveTo(modulename, v-1);
369 MoveTo(modulename, v);
376 void InspIRCd::MoveToFirst(std::string modulename)
378 MoveTo(modulename,0);
381 void InspIRCd::MoveToLast(std::string modulename)
383 MoveTo(modulename,MODCOUNT);
386 void InspIRCd::BuildISupport()
388 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
390 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
391 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
392 v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC NETWORK=" << Config->Network << " MAXPARA=32";
393 Config->data005 = v.str();
394 FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
397 bool InspIRCd::UnloadModule(const char* filename)
399 std::string filename_str = filename;
400 for (unsigned int j = 0; j != Config->module_names.size(); j++)
402 if (Config->module_names[j] == filename_str)
404 if (modules[j]->GetVersion().Flags & VF_STATIC)
406 log(DEFAULT,"Failed to unload STATIC module %s",filename);
407 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
410 /* Give the module a chance to tidy out all its metadata */
411 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
413 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
415 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
417 modules[j]->OnCleanup(TYPE_USER,u->second);
420 FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
422 for(int t = 0; t < 255; t++)
424 Config->global_implementation[t] -= Config->implement_lists[j][t];
427 /* We have to renumber implement_lists after unload because the module numbers change!
429 for(int j2 = j; j2 < 254; j2++)
431 for(int t = 0; t < 255; t++)
433 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
438 log(DEBUG,"Deleting module...");
440 log(DEBUG,"Erasing module entry...");
442 log(DEBUG,"Removing dependent commands...");
443 Parser->RemoveCommands(filename);
444 log(DEFAULT,"Module %s unloaded",filename);
450 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
451 snprintf(MODERR,MAXBUF,"Module not loaded");
455 bool InspIRCd::LoadModule(const char* filename)
457 char modfile[MAXBUF];
459 strlcpy(modfile,filename,MAXBUF);
461 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
463 std::string filename_str = filename;
466 if (!DirValid(modfile))
468 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
469 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
474 log(DEBUG,"Loading module: %s",modfile);
476 if (FileExists(modfile))
479 for (unsigned int j = 0; j < Config->module_names.size(); j++)
481 if (Config->module_names[j] == filename_str)
483 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
484 snprintf(MODERR,MAXBUF,"Module already loaded");
488 ircd_module* a = new ircd_module(modfile);
489 factory[MODCOUNT+1] = a;
490 if (factory[MODCOUNT+1]->LastError())
492 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
493 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
498 if (factory[MODCOUNT+1]->factory)
500 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
501 modules[MODCOUNT+1] = m;
502 /* save the module and the module's classfactory, if
503 * this isnt done, random crashes can occur :/ */
504 Config->module_names.push_back(filename);
506 char* x = &Config->implement_lists[MODCOUNT+1][0];
507 for(int t = 0; t < 255; t++)
510 modules[MODCOUNT+1]->Implements(x);
512 for(int t = 0; t < 255; t++)
514 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
515 if (Config->implement_lists[MODCOUNT+1][t])
517 log(DEBUG,"Add global implementation: %d %d => %d",MODCOUNT+1,t,Config->global_implementation[t]);
523 log(DEFAULT,"Unable to load %s",modfile);
524 snprintf(MODERR,MAXBUF,"Factory function failed!");
528 catch (ModuleException& modexcept)
530 log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
531 snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
538 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
539 snprintf(MODERR,MAXBUF,"Module file could not be found");
544 FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
545 // now work out which modules, if any, want to move to the back of the queue,
546 // and if they do, move them there.
547 std::vector<std::string> put_to_back;
548 std::vector<std::string> put_to_front;
549 std::map<std::string,std::string> put_before;
550 std::map<std::string,std::string> put_after;
551 for (unsigned int j = 0; j < Config->module_names.size(); j++)
553 if (modules[j]->Prioritize() == PRIORITY_LAST)
555 put_to_back.push_back(Config->module_names[j]);
557 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
559 put_to_front.push_back(Config->module_names[j]);
561 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
563 log(DEBUG,"Module %d wants PRIORITY_BEFORE",j);
564 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
565 log(DEBUG,"Before: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
567 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
569 log(DEBUG,"Module %d wants PRIORITY_AFTER",j);
570 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
571 log(DEBUG,"After: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
574 for (unsigned int j = 0; j < put_to_back.size(); j++)
576 MoveToLast(put_to_back[j]);
578 for (unsigned int j = 0; j < put_to_front.size(); j++)
580 MoveToFirst(put_to_front[j]);
582 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
584 MoveBefore(j->first,j->second);
586 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
588 MoveAfter(j->first,j->second);
596 bool expire_run = false;
597 int activefds[MAX_DESCRIPTORS];
601 InspSocket* s = NULL;
602 InspSocket* s_del = NULL;
603 unsigned int numberactive;
604 sockaddr_in sock_us; // our port number
605 socklen_t uslen; // length of our port number
607 /* Until THIS point, ServerInstance == NULL */
609 LoadAllModules(this);
611 printf("\nInspIRCd is now running!\n");
615 freopen("/dev/null","w",stdout);
616 freopen("/dev/null","w",stderr);
619 /* Add the listening sockets used for client inbound connections
620 * to the socket engine
622 for (int count = 0; count < stats->BoundPortCount; count++)
623 SE->AddFd(openSockfd[count],true,X_LISTEN);
625 WritePID(Config->PID);
627 /* main loop, this never returns */
630 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
631 * Once per loop iteration is pleanty.
636 /* Run background module timers every few seconds
637 * (the docs say modules shouldnt rely on accurate
638 * timing using this event, so we dont have to
639 * time this exactly).
641 if (((TIME % 5) == 0) && (!expire_run))
644 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
648 else if ((TIME % 5) == 1)
653 /* Once a second, do the background processing */
657 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
658 DoBackgroundUserStuff(TIME);
661 * Trigger all InspTimers that are pending
666 /* Process timeouts on module sockets each time around
667 * the loop. There shouldnt be many module sockets, at
668 * most, 20 or so, so this won't be much of a performance
671 DoSocketTimeouts(TIME);
673 /* Call the socket engine to wait on the active
674 * file descriptors. The socket engine has everything's
675 * descriptors in its list... dns, modules, users,
676 * servers... so its nice and easy, just one call.
678 if (!(numberactive = SE->Wait(activefds)))
682 * Now process each of the fd's. For users, we have a fast
683 * lookup table which can find a user by file descriptor, so
684 * processing them by fd isnt expensive. If we have a lot of
685 * listening ports or module sockets though, things could get
688 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
690 int socket_type = SE->GetType(activefds[activefd]);
695 cu = fd_ref_table[activefds[activefd]];
703 /* Process module-owned sockets.
704 * Modules are encouraged to inherit their sockets from
705 * InspSocket so we can process them neatly like this.
707 s = socket_ref[activefds[activefd]];
709 if ((s) && (!s->Poll()))
711 log(DEBUG,"Socket poll returned false, close and bail");
712 SE->DelFd(s->GetFd());
713 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
715 s_del = (InspSocket*)*a;
716 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
718 module_sockets.erase(a);
730 /* When we are using single-threaded dns,
731 * the sockets for dns end up in our mainloop.
732 * When we are using multi-threaded dns,
733 * each thread has its own basic poll() loop
734 * within it, making them 'fire and forget'
735 * and independent of the mainloop.
738 dns_poll(activefds[activefd]);
744 /* It's a listener */
745 uslen = sizeof(sock_us);
746 length = sizeof(client);
747 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
749 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
751 in_port = ntohs(sock_us.sin_port);
752 log(DEBUG,"Accepted socket %d",incomingSockfd);
753 /* Years and years ago, we used to resolve here
754 * using gethostbyaddr(). That is sucky and we
755 * don't do that any more...
757 NonBlocking(incomingSockfd);
758 if (Config->GetIOHook(in_port))
762 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
764 catch (ModuleException& modexcept)
766 log(DEBUG,"Module exception cought: %s",modexcept.GetReason()); \
769 stats->statsAccept++;
770 AddClient(incomingSockfd, in_port, false, client.sin_addr);
771 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
775 log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
776 shutdown(incomingSockfd,2);
777 close(incomingSockfd);
778 stats->statsRefused++;
783 /* Something went wrong if we're in here.
784 * In fact, so wrong, im not quite sure
785 * what we would do, so for now, its going
786 * to safely do bugger all.
793 /* This is never reached -- we hope! */
797 /**********************************************************************************/
800 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
803 int main(int argc, char** argv)
805 ServerInstance = new InspIRCd(argc, argv);
806 ServerInstance->Run();
807 delete ServerInstance;