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 extern char LOG_FILE[MAXBUF];
74 int openSockfd[MAXSOCKS];
77 sockaddr_in client,server;
80 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
82 time_t TIME = time(NULL), OLDTIME = time(NULL);
84 // This table references users by file descriptor.
85 // its an array to make it VERY fast, as all lookups are referenced
86 // by an integer, meaning there is no need for a scan/search operation.
87 userrec* fd_ref_table[MAX_DESCRIPTORS];
89 Server* MyServer = new Server;
90 ServerConfig *Config = new ServerConfig;
95 servernamelist servernames;
98 void AddServerName(std::string servername)
100 log(DEBUG,"Adding server name: %s",servername.c_str());
101 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
103 if (*a == servername)
106 servernames.push_back(servername);
109 const char* FindServerNamePtr(std::string servername)
111 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
113 if (*a == servername)
116 AddServerName(servername);
117 return FindServerNamePtr(servername);
120 bool FindServerName(std::string servername)
122 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
124 if (*a == servername)
130 std::string InspIRCd::GetRevision()
135 void InspIRCd::MakeLowerMap()
137 // initialize the lowercase mapping table
138 for (unsigned int cn = 0; cn < 256; cn++)
140 // lowercase the uppercase chars
141 for (unsigned int cn = 65; cn < 91; cn++)
142 lowermap[cn] = tolower(cn);
143 // now replace the specific chars for scandanavian comparison
144 lowermap[(unsigned)'['] = '{';
145 lowermap[(unsigned)']'] = '}';
146 lowermap[(unsigned)'\\'] = '|';
149 InspIRCd::InspIRCd(int argc, char** argv)
152 module_sockets.clear();
153 this->startup_time = time(NULL);
155 log(DEBUG,"*** InspIRCd starting up!");
156 if (!FileExists(CONFIG_FILE))
158 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
159 log(DEFAULT,"main: no config");
160 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
165 for (int i = 1; i < argc; i++)
167 if (!strcmp(argv[i],"-nofork")) {
168 Config->nofork = true;
170 if (!strcmp(argv[i],"-wait")) {
173 if (!strcmp(argv[i],"-nolimit")) {
174 Config->unlimitcore = true;
176 if (!strcmp(argv[i],"-logfile")) {
179 strlcpy(LOG_FILE,argv[i+1],MAXBUF);
180 printf("LOG: Setting logfile to %s\n",LOG_FILE);
184 printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
191 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
193 this->MakeLowerMap();
196 Config->ClearStack();
197 Config->Read(true,NULL);
199 this->ModeGrok = new ModeParser();
200 this->Parser = new CommandParser();
201 this->stats = new serverstats();
202 AddServerName(Config->ServerName);
204 stats->BoundPortCount = BindPorts();
206 for(int t = 0; t < 255; t++)
207 Config->global_implementation[t] = 0;
209 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
215 if (DaemonSeed() == ERROR)
217 printf("ERROR: could not go into daemon mode. Shutting down.\n");
222 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
223 * initialize the socket engine.
225 SE = new SocketEngine();
227 /* We must load the modules AFTER initializing the socket engine, now */
232 std::string InspIRCd::GetVersionString()
234 char versiondata[MAXBUF];
236 char dnsengine[] = "multithread";
238 char dnsengine[] = "singlethread";
240 if (*Config->CustomVersion)
242 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
246 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%lu,%s,%s]",VERSION,Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
251 char* InspIRCd::ModuleError()
256 void InspIRCd::erase_factory(int j)
259 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
264 factory.push_back(NULL);
271 void InspIRCd::erase_module(int j)
274 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
280 modules.push_back(NULL);
286 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
290 Config->module_names.erase(v);
298 void InspIRCd::MoveTo(std::string modulename,int slot)
300 unsigned int v2 = 256;
301 log(DEBUG,"Moving %s to slot %d",modulename.c_str(),slot);
302 for (unsigned int v = 0; v < Config->module_names.size(); v++)
304 if (Config->module_names[v] == modulename)
306 // found an instance, swap it with the item at MODCOUNT
311 if (v2 == (unsigned int)slot)
313 log(DEBUG,"Item %s already in slot %d!",modulename.c_str(),slot);
317 // Swap the module names over
318 Config->module_names[v2] = Config->module_names[slot];
319 Config->module_names[slot] = modulename;
320 // now swap the module factories
321 ircd_module* temp = factory[v2];
322 factory[v2] = factory[slot];
323 factory[slot] = temp;
324 // now swap the module objects
325 Module* temp_module = modules[v2];
326 modules[v2] = modules[slot];
327 modules[slot] = temp_module;
328 // now swap the implement lists (we dont
329 // need to swap the global or recount it)
330 for (int n = 0; n < 255; n++)
332 char x = Config->implement_lists[v2][n];
333 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
334 Config->implement_lists[slot][n] = x;
336 log(DEBUG,"Moved %s to slot successfully",modulename.c_str());
340 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
344 void InspIRCd::MoveAfter(std::string modulename, std::string after)
346 log(DEBUG,"Move %s after %s...",modulename.c_str(),after.c_str());
347 for (unsigned int v = 0; v < Config->module_names.size(); v++)
349 if (Config->module_names[v] == after)
351 MoveTo(modulename, v);
357 void InspIRCd::MoveBefore(std::string modulename, std::string before)
359 log(DEBUG,"Move %s before %s...",modulename.c_str(),before.c_str());
360 for (unsigned int v = 0; v < Config->module_names.size(); v++)
362 if (Config->module_names[v] == before)
366 MoveTo(modulename, v-1);
370 MoveTo(modulename, v);
377 void InspIRCd::MoveToFirst(std::string modulename)
379 MoveTo(modulename,0);
382 void InspIRCd::MoveToLast(std::string modulename)
384 MoveTo(modulename,MODCOUNT);
387 void InspIRCd::BuildISupport()
389 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
391 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
392 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
393 v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC NETWORK=" << Config->Network << " MAXPARA=32";
394 Config->data005 = v.str();
395 FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
398 bool InspIRCd::UnloadModule(const char* filename)
400 std::string filename_str = filename;
401 for (unsigned int j = 0; j != Config->module_names.size(); j++)
403 if (Config->module_names[j] == filename_str)
405 if (modules[j]->GetVersion().Flags & VF_STATIC)
407 log(DEFAULT,"Failed to unload STATIC module %s",filename);
408 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
411 /* Give the module a chance to tidy out all its metadata */
412 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
414 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
416 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
418 modules[j]->OnCleanup(TYPE_USER,u->second);
421 FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
423 for(int t = 0; t < 255; t++)
425 Config->global_implementation[t] -= Config->implement_lists[j][t];
428 /* We have to renumber implement_lists after unload because the module numbers change!
430 for(int j2 = j; j2 < 254; j2++)
432 for(int t = 0; t < 255; t++)
434 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
439 log(DEBUG,"Deleting module...");
441 log(DEBUG,"Erasing module entry...");
443 log(DEBUG,"Removing dependent commands...");
444 Parser->RemoveCommands(filename);
445 log(DEFAULT,"Module %s unloaded",filename);
451 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
452 snprintf(MODERR,MAXBUF,"Module not loaded");
456 bool InspIRCd::LoadModule(const char* filename)
458 char modfile[MAXBUF];
460 strlcpy(modfile,filename,MAXBUF);
462 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
464 std::string filename_str = filename;
467 if (!DirValid(modfile))
469 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
470 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
475 log(DEBUG,"Loading module: %s",modfile);
477 if (FileExists(modfile))
480 for (unsigned int j = 0; j < Config->module_names.size(); j++)
482 if (Config->module_names[j] == filename_str)
484 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
485 snprintf(MODERR,MAXBUF,"Module already loaded");
489 ircd_module* a = new ircd_module(modfile);
490 factory[MODCOUNT+1] = a;
491 if (factory[MODCOUNT+1]->LastError())
493 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
494 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
499 if (factory[MODCOUNT+1]->factory)
501 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
502 modules[MODCOUNT+1] = m;
503 /* save the module and the module's classfactory, if
504 * this isnt done, random crashes can occur :/ */
505 Config->module_names.push_back(filename);
507 char* x = &Config->implement_lists[MODCOUNT+1][0];
508 for(int t = 0; t < 255; t++)
511 modules[MODCOUNT+1]->Implements(x);
513 for(int t = 0; t < 255; t++)
515 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
516 if (Config->implement_lists[MODCOUNT+1][t])
518 log(DEBUG,"Add global implementation: %d %d => %d",MODCOUNT+1,t,Config->global_implementation[t]);
524 log(DEFAULT,"Unable to load %s",modfile);
525 snprintf(MODERR,MAXBUF,"Factory function failed!");
529 catch (ModuleException& modexcept)
531 log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
532 snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
539 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
540 snprintf(MODERR,MAXBUF,"Module file could not be found");
545 FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
546 // now work out which modules, if any, want to move to the back of the queue,
547 // and if they do, move them there.
548 std::vector<std::string> put_to_back;
549 std::vector<std::string> put_to_front;
550 std::map<std::string,std::string> put_before;
551 std::map<std::string,std::string> put_after;
552 for (unsigned int j = 0; j < Config->module_names.size(); j++)
554 if (modules[j]->Prioritize() == PRIORITY_LAST)
556 put_to_back.push_back(Config->module_names[j]);
558 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
560 put_to_front.push_back(Config->module_names[j]);
562 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
564 log(DEBUG,"Module %d wants PRIORITY_BEFORE",j);
565 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
566 log(DEBUG,"Before: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
568 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
570 log(DEBUG,"Module %d wants PRIORITY_AFTER",j);
571 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
572 log(DEBUG,"After: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
575 for (unsigned int j = 0; j < put_to_back.size(); j++)
577 MoveToLast(put_to_back[j]);
579 for (unsigned int j = 0; j < put_to_front.size(); j++)
581 MoveToFirst(put_to_front[j]);
583 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
585 MoveBefore(j->first,j->second);
587 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
589 MoveAfter(j->first,j->second);
595 void InspIRCd::DoOneIteration(bool process_module_sockets)
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
612 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
613 * Once per loop iteration is pleanty.
618 /* Run background module timers every few seconds
619 * (the docs say modules shouldnt rely on accurate
620 * timing using this event, so we dont have to
621 * time this exactly).
623 if (((TIME % 5) == 0) && (!expire_run))
626 if (process_module_sockets)
628 /* Fix by brain - the addition of DoOneIteration means that this
629 * can end up getting called recursively in the following pattern:
631 * m_spanningtree DoPingChecks
632 * (server pings out and is squit)
633 * (squit causes call to DoOneIteration)
634 * DoOneIteration enters here
635 * calls DoBackground timer
636 * enters m_spanningtree DoPingChecks... see step 1.
638 * This should do the job and fix the bug.
640 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
642 TickMissedTimers(TIME);
647 else if ((TIME % 5) == 1)
652 if (iterations++ == 15)
655 DoBackgroundUserStuff(TIME);
658 /* Once a second, do the background processing */
662 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
663 if ((TIME % 3600) == 0)
665 MaintainWhoWas(TIME);
669 /* Process timeouts on module sockets each time around
670 * the loop. There shouldnt be many module sockets, at
671 * most, 20 or so, so this won't be much of a performance
674 if (process_module_sockets)
675 DoSocketTimeouts(TIME);
679 /* Call the socket engine to wait on the active
680 * file descriptors. The socket engine has everything's
681 * descriptors in its list... dns, modules, users,
682 * servers... so its nice and easy, just one call.
684 if (!(numberactive = SE->Wait(activefds)))
691 * Now process each of the fd's. For users, we have a fast
692 * lookup table which can find a user by file descriptor, so
693 * processing them by fd isnt expensive. If we have a lot of
694 * listening ports or module sockets though, things could get
697 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
699 int socket_type = SE->GetType(activefds[activefd]);
704 cu = fd_ref_table[activefds[activefd]];
712 if (!process_module_sockets)
715 /* Process module-owned sockets.
716 * Modules are encouraged to inherit their sockets from
717 * InspSocket so we can process them neatly like this.
719 s = socket_ref[activefds[activefd]];
721 if ((s) && (!s->Poll()))
723 log(DEBUG,"Socket poll returned false, close and bail");
724 SE->DelFd(s->GetFd());
725 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
727 s_del = (InspSocket*)*a;
728 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
730 module_sockets.erase(a);
740 /* When we are using single-threaded dns,
741 * the sockets for dns end up in our mainloop.
742 * When we are using multi-threaded dns,
743 * each thread has its own basic poll() loop
744 * within it, making them 'fire and forget'
745 * and independent of the mainloop.
748 dns_poll(activefds[activefd]);
754 /* It's a listener */
755 uslen = sizeof(sock_us);
756 length = sizeof(client);
757 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
759 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
761 in_port = ntohs(sock_us.sin_port);
762 log(DEBUG,"Accepted socket %d",incomingSockfd);
763 /* Years and years ago, we used to resolve here
764 * using gethostbyaddr(). That is sucky and we
765 * don't do that any more...
767 NonBlocking(incomingSockfd);
768 if (Config->GetIOHook(in_port))
772 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
774 catch (ModuleException& modexcept)
776 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
779 stats->statsAccept++;
780 AddClient(incomingSockfd, in_port, false, client.sin_addr);
781 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
785 log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
786 shutdown(incomingSockfd,2);
787 close(incomingSockfd);
788 stats->statsRefused++;
793 /* Something went wrong if we're in here.
794 * In fact, so wrong, im not quite sure
795 * what we would do, so for now, its going
796 * to safely do bugger all.
798 SE->DelFd(activefds[activefd]);
807 /* Until THIS point, ServerInstance == NULL */
809 LoadAllModules(this);
811 printf("\nInspIRCd is now running!\n");
820 /* Add the listening sockets used for client inbound connections
821 * to the socket engine
823 for (int count = 0; count < stats->BoundPortCount; count++)
824 SE->AddFd(openSockfd[count],true,X_LISTEN);
826 WritePID(Config->PID);
828 /* main loop, this never returns */
835 DoOneIteration(true);
837 /* This is never reached -- we hope! */
841 /**********************************************************************************/
844 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
847 int main(int argc, char** argv)
849 ServerInstance = new InspIRCd(argc, argv);
850 ServerInstance->Run();
851 delete ServerInstance;