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.
138 std::stringstream Revision("$Revision$");
140 Revision >> single >> single;
144 void InspIRCd::MakeLowerMap()
146 // initialize the lowercase mapping table
147 for (unsigned int cn = 0; cn < 256; cn++)
149 // lowercase the uppercase chars
150 for (unsigned int cn = 65; cn < 91; cn++)
151 lowermap[cn] = tolower(cn);
152 // now replace the specific chars for scandanavian comparison
153 lowermap[(unsigned)'['] = '{';
154 lowermap[(unsigned)']'] = '}';
155 lowermap[(unsigned)'\\'] = '|';
158 InspIRCd::InspIRCd(int argc, char** argv)
161 module_sockets.clear();
162 this->startup_time = time(NULL);
164 log(DEBUG,"*** InspIRCd starting up!");
165 if (!FileExists(CONFIG_FILE))
167 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
168 log(DEFAULT,"main: no config");
169 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
173 for (int i = 1; i < argc; i++)
175 if (!strcmp(argv[i],"-nofork")) {
176 Config->nofork = true;
178 if (!strcmp(argv[i],"-wait")) {
181 if (!strcmp(argv[i],"-nolimit")) {
182 Config->unlimitcore = true;
187 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
189 this->MakeLowerMap();
192 Config->ClearStack();
193 Config->Read(true,NULL);
195 this->ModeGrok = new ModeParser();
196 this->Parser = new CommandParser();
197 this->stats = new serverstats();
198 AddServerName(Config->ServerName);
200 stats->BoundPortCount = BindPorts();
202 for(int t = 0; t < 255; t++)
203 Config->global_implementation[t] = 0;
205 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
211 if (DaemonSeed() == ERROR)
213 printf("ERROR: could not go into daemon mode. Shutting down.\n");
218 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
219 * initialize the socket engine.
221 SE = new SocketEngine();
223 /* We must load the modules AFTER initializing the socket engine, now */
228 std::string InspIRCd::GetVersionString()
230 char versiondata[MAXBUF];
232 char dnsengine[] = "multithread";
234 char dnsengine[] = "singlethread";
236 if (*Config->CustomVersion)
238 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s",VERSION,GetRevision().c_str(),Config->ServerName,Config->CustomVersion);
242 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);
247 char* InspIRCd::ModuleError()
252 void InspIRCd::erase_factory(int j)
255 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
260 factory.push_back(NULL);
267 void InspIRCd::erase_module(int j)
270 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
276 modules.push_back(NULL);
282 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
286 Config->module_names.erase(v);
294 void InspIRCd::MoveTo(std::string modulename,int slot)
296 unsigned int v2 = 256;
297 log(DEBUG,"Moving %s to slot %d",modulename.c_str(),slot);
298 for (unsigned int v = 0; v < Config->module_names.size(); v++)
300 if (Config->module_names[v] == modulename)
302 // found an instance, swap it with the item at MODCOUNT
307 if (v2 == (unsigned int)slot)
309 log(DEBUG,"Item %s already in slot %d!",modulename.c_str(),slot);
313 // Swap the module names over
314 Config->module_names[v2] = Config->module_names[slot];
315 Config->module_names[slot] = modulename;
316 // now swap the module factories
317 ircd_module* temp = factory[v2];
318 factory[v2] = factory[slot];
319 factory[slot] = temp;
320 // now swap the module objects
321 Module* temp_module = modules[v2];
322 modules[v2] = modules[slot];
323 modules[slot] = temp_module;
324 // now swap the implement lists (we dont
325 // need to swap the global or recount it)
326 for (int n = 0; n < 255; n++)
328 char x = Config->implement_lists[v2][n];
329 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
330 Config->implement_lists[slot][n] = x;
332 log(DEBUG,"Moved %s to slot successfully",modulename.c_str());
336 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
340 void InspIRCd::MoveAfter(std::string modulename, std::string after)
342 log(DEBUG,"Move %s after %s...",modulename.c_str(),after.c_str());
343 for (unsigned int v = 0; v < Config->module_names.size(); v++)
345 if (Config->module_names[v] == after)
347 MoveTo(modulename, v);
353 void InspIRCd::MoveBefore(std::string modulename, std::string before)
355 log(DEBUG,"Move %s before %s...",modulename.c_str(),before.c_str());
356 for (unsigned int v = 0; v < Config->module_names.size(); v++)
358 if (Config->module_names[v] == before)
362 MoveTo(modulename, v-1);
366 MoveTo(modulename, v);
373 void InspIRCd::MoveToFirst(std::string modulename)
375 MoveTo(modulename,0);
378 void InspIRCd::MoveToLast(std::string modulename)
380 MoveTo(modulename,MODCOUNT);
383 void InspIRCd::BuildISupport()
385 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
387 v << "WALLCHOPS MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 NICKLEN=" << NICKMAX-1;
388 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
389 v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC WALLVOICES WALLCHOPS NETWORK=" << Config->Network;
390 Config->data005 = v.str();
391 FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
394 bool InspIRCd::UnloadModule(const char* filename)
396 std::string filename_str = filename;
397 for (unsigned int j = 0; j != Config->module_names.size(); j++)
399 if (Config->module_names[j] == filename_str)
401 if (modules[j]->GetVersion().Flags & VF_STATIC)
403 log(DEFAULT,"Failed to unload STATIC module %s",filename);
404 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
407 /* Give the module a chance to tidy out all its metadata */
408 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
410 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
412 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
414 modules[j]->OnCleanup(TYPE_USER,u->second);
417 FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
419 for(int t = 0; t < 255; t++)
421 Config->global_implementation[t] -= Config->implement_lists[j][t];
424 /* We have to renumber implement_lists after unload because the module numbers change!
426 for(int j2 = j; j2 < 254; j2++)
428 for(int t = 0; t < 255; t++)
430 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
435 log(DEBUG,"Deleting module...");
437 log(DEBUG,"Erasing module entry...");
439 log(DEBUG,"Removing dependent commands...");
440 Parser->RemoveCommands(filename);
441 log(DEFAULT,"Module %s unloaded",filename);
447 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
448 snprintf(MODERR,MAXBUF,"Module not loaded");
452 bool InspIRCd::LoadModule(const char* filename)
454 char modfile[MAXBUF];
456 strlcpy(modfile,filename,MAXBUF);
458 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
460 std::string filename_str = filename;
463 if (!DirValid(modfile))
465 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
466 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
471 log(DEBUG,"Loading module: %s",modfile);
473 if (FileExists(modfile))
476 for (unsigned int j = 0; j < Config->module_names.size(); j++)
478 if (Config->module_names[j] == filename_str)
480 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
481 snprintf(MODERR,MAXBUF,"Module already loaded");
485 ircd_module* a = new ircd_module(modfile);
486 factory[MODCOUNT+1] = a;
487 if (factory[MODCOUNT+1]->LastError())
489 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
490 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
493 if (factory[MODCOUNT+1]->factory)
495 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
496 modules[MODCOUNT+1] = m;
497 /* save the module and the module's classfactory, if
498 * this isnt done, random crashes can occur :/ */
499 Config->module_names.push_back(filename);
501 char* x = &Config->implement_lists[MODCOUNT+1][0];
502 for(int t = 0; t < 255; t++)
505 modules[MODCOUNT+1]->Implements(x);
507 for(int t = 0; t < 255; t++)
509 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
510 if (Config->implement_lists[MODCOUNT+1][t])
512 log(DEBUG,"Add global implementation: %d %d => %d",MODCOUNT+1,t,Config->global_implementation[t]);
518 log(DEFAULT,"Unable to load %s",modfile);
519 snprintf(MODERR,MAXBUF,"Factory function failed!");
526 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
527 snprintf(MODERR,MAXBUF,"Module file could not be found");
532 FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
533 // now work out which modules, if any, want to move to the back of the queue,
534 // and if they do, move them there.
535 std::vector<std::string> put_to_back;
536 std::vector<std::string> put_to_front;
537 std::map<std::string,std::string> put_before;
538 std::map<std::string,std::string> put_after;
539 for (unsigned int j = 0; j < Config->module_names.size(); j++)
541 if (modules[j]->Prioritize() == PRIORITY_LAST)
543 put_to_back.push_back(Config->module_names[j]);
545 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
547 put_to_front.push_back(Config->module_names[j]);
549 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
551 log(DEBUG,"Module %d wants PRIORITY_BEFORE",j);
552 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
553 log(DEBUG,"Before: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
555 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
557 log(DEBUG,"Module %d wants PRIORITY_AFTER",j);
558 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
559 log(DEBUG,"After: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
562 for (unsigned int j = 0; j < put_to_back.size(); j++)
564 MoveToLast(put_to_back[j]);
566 for (unsigned int j = 0; j < put_to_front.size(); j++)
568 MoveToFirst(put_to_front[j]);
570 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
572 MoveBefore(j->first,j->second);
574 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
576 MoveAfter(j->first,j->second);
584 bool expire_run = false;
585 int activefds[MAX_DESCRIPTORS];
589 InspSocket* s = NULL;
590 InspSocket* s_del = NULL;
591 unsigned int numberactive;
592 sockaddr_in sock_us; // our port number
593 socklen_t uslen; // length of our port number
595 /* Until THIS point, ServerInstance == NULL */
597 LoadAllModules(this);
599 printf("\nInspIRCd is now running!\n");
603 freopen("/dev/null","w",stdout);
604 freopen("/dev/null","w",stderr);
607 /* Add the listening sockets used for client inbound connections
608 * to the socket engine
610 for (int count = 0; count < stats->BoundPortCount; count++)
611 SE->AddFd(openSockfd[count],true,X_LISTEN);
613 WritePID(Config->PID);
615 /* main loop, this never returns */
618 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
619 * Once per loop iteration is pleanty.
624 /* Run background module timers every few seconds
625 * (the docs say modules shouldnt rely on accurate
626 * timing using this event, so we dont have to
627 * time this exactly).
629 if (((TIME % 8) == 0) && (!expire_run))
632 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
636 else if ((TIME % 8) == 1)
641 /* Once a second, do the background processing */
643 DoBackgroundUserStuff(TIME);
645 /* Call the socket engine to wait on the active
646 * file descriptors. The socket engine has everything's
647 * descriptors in its list... dns, modules, users,
648 * servers... so its nice and easy, just one call.
650 if (!(numberactive = SE->Wait(activefds)))
654 * Now process each of the fd's. For users, we have a fast
655 * lookup table which can find a user by file descriptor, so
656 * processing them by fd isnt expensive. If we have a lot of
657 * listening ports or module sockets though, things could get
660 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
662 int socket_type = SE->GetType(activefds[activefd]);
667 cu = fd_ref_table[activefds[activefd]];
675 /* Process module-owned sockets.
676 * Modules are encouraged to inherit their sockets from
677 * InspSocket so we can process them neatly like this.
679 s = socket_ref[activefds[activefd]];
681 if ((s) && (!s->Poll()))
683 log(DEBUG,"Socket poll returned false, close and bail");
684 SE->DelFd(s->GetFd());
685 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
687 s_del = (InspSocket*)*a;
688 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
690 module_sockets.erase(a);
702 /* When we are using single-threaded dns,
703 * the sockets for dns end up in our mainloop.
704 * When we are using multi-threaded dns,
705 * each thread has its own basic poll() loop
706 * within it, making them 'fire and forget'
707 * and independent of the mainloop.
710 dns_poll(activefds[activefd]);
716 /* It's a listener */
717 uslen = sizeof(sock_us);
718 length = sizeof(client);
719 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
721 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
723 in_port = ntohs(sock_us.sin_port);
724 log(DEBUG,"Accepted socket %d",incomingSockfd);
725 /* Years and years ago, we used to resolve here
726 * using gethostbyaddr(). That is sucky and we
727 * don't do that any more...
729 NonBlocking(incomingSockfd);
730 if (Config->GetIOHook(in_port))
732 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
734 stats->statsAccept++;
735 AddClient(incomingSockfd, in_port, false, client.sin_addr);
736 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
740 log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
741 shutdown(incomingSockfd,2);
742 close(incomingSockfd);
743 stats->statsRefused++;
748 /* Something went wrong if we're in here.
749 * In fact, so wrong, im not quite sure
750 * what we would do, so for now, its going
751 * to safely do bugger all.
758 /* This is never reached -- we hope! */
762 /**********************************************************************************/
765 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
768 int main(int argc, char** argv)
770 ServerInstance = new InspIRCd(argc, argv);
771 ServerInstance->Run();
772 delete ServerInstance;