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>
33 #include <ext/hash_map>
54 #include "inspstring.h"
56 #include "helperfuncs.h"
58 #include "socketengine.h"
59 #include "userprocess.h"
62 #include "command_parse.h"
64 InspIRCd* ServerInstance;
66 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
67 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
69 extern std::vector<Module*> modules;
70 extern std::vector<ircd_module*> factory;
72 std::vector<InspSocket*> module_sockets;
73 std::vector<userrec*> local_users;
76 extern char LOG_FILE[MAXBUF];
77 int openSockfd[MAX_DESCRIPTORS];
80 sockaddr_in client,server;
83 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
85 time_t TIME = time(NULL), OLDTIME = time(NULL);
87 // This table references users by file descriptor.
88 // its an array to make it VERY fast, as all lookups are referenced
89 // by an integer, meaning there is no need for a scan/search operation.
90 userrec* fd_ref_table[MAX_DESCRIPTORS];
92 Server* MyServer = new Server;
93 ServerConfig *Config = new ServerConfig;
98 servernamelist servernames;
101 void AddServerName(std::string servername)
103 log(DEBUG,"Adding server name: %s",servername.c_str());
104 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
106 if (*a == servername)
109 servernames.push_back(servername);
112 const char* FindServerNamePtr(std::string servername)
114 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
116 if (*a == servername)
119 AddServerName(servername);
120 return FindServerNamePtr(servername);
123 bool FindServerName(std::string servername)
125 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
127 if (*a == servername)
133 std::string InspIRCd::GetRevision()
138 void InspIRCd::MakeLowerMap()
140 // initialize the lowercase mapping table
141 for (unsigned int cn = 0; cn < 256; cn++)
143 // lowercase the uppercase chars
144 for (unsigned int cn = 65; cn < 91; cn++)
145 lowermap[cn] = tolower(cn);
146 // now replace the specific chars for scandanavian comparison
147 lowermap[(unsigned)'['] = '{';
148 lowermap[(unsigned)']'] = '}';
149 lowermap[(unsigned)'\\'] = '|';
152 InspIRCd::InspIRCd(int argc, char** argv)
155 module_sockets.clear();
156 this->startup_time = time(NULL);
158 log(DEBUG,"*** InspIRCd starting up!");
159 if (!FileExists(CONFIG_FILE))
161 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
162 log(DEFAULT,"main: no config");
163 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
168 for (int i = 1; i < argc; i++)
170 if (!strcmp(argv[i],"-nofork"))
172 Config->nofork = true;
174 else if(!strcmp(argv[i],"-debug"))
176 Config->forcedebug = true;
178 else if(!strcmp(argv[i],"-nolog"))
180 Config->writelog = false;
182 else if (!strcmp(argv[i],"-wait"))
186 else if (!strcmp(argv[i],"-nolimit"))
188 printf("WARNING: The `-nolimit' option is deprecated, and now on by default. This behaviour may change in the future.\n");
190 else if (!strcmp(argv[i],"-logfile"))
194 strlcpy(LOG_FILE,argv[i+1],MAXBUF);
195 printf("LOG: Setting logfile to %s\n",LOG_FILE);
199 printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
206 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
208 this->MakeLowerMap();
211 this->stats = new serverstats();
212 Config->ClearStack();
213 Config->Read(true,NULL);
215 this->ModeGrok = new ModeParser();
216 this->Parser = new CommandParser();
217 AddServerName(Config->ServerName);
219 stats->BoundPortCount = BindPorts(true);
221 for(int t = 0; t < 255; t++)
222 Config->global_implementation[t] = 0;
224 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
232 printf("ERROR: could not go into daemon mode. Shutting down.\n");
237 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
238 * initialize the socket engine.
240 SE = new SocketEngine();
242 /* We must load the modules AFTER initializing the socket engine, now */
247 std::string InspIRCd::GetVersionString()
249 char versiondata[MAXBUF];
251 char dnsengine[] = "multithread";
253 char dnsengine[] = "singlethread";
255 if (*Config->CustomVersion)
257 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
261 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%lu,%s,%s]",VERSION,Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
266 char* InspIRCd::ModuleError()
271 void InspIRCd::erase_factory(int j)
274 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
279 factory.push_back(NULL);
286 void InspIRCd::erase_module(int j)
289 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
295 modules.push_back(NULL);
301 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
305 Config->module_names.erase(v);
313 void InspIRCd::MoveTo(std::string modulename,int slot)
315 unsigned int v2 = 256;
316 for (unsigned int v = 0; v < Config->module_names.size(); v++)
318 if (Config->module_names[v] == modulename)
320 // found an instance, swap it with the item at MODCOUNT
325 if ((v2 != (unsigned int)slot) && (v2 < 256))
327 // Swap the module names over
328 Config->module_names[v2] = Config->module_names[slot];
329 Config->module_names[slot] = modulename;
330 // now swap the module factories
331 ircd_module* temp = factory[v2];
332 factory[v2] = factory[slot];
333 factory[slot] = temp;
334 // now swap the module objects
335 Module* temp_module = modules[v2];
336 modules[v2] = modules[slot];
337 modules[slot] = temp_module;
338 // now swap the implement lists (we dont
339 // need to swap the global or recount it)
340 for (int n = 0; n < 255; n++)
342 char x = Config->implement_lists[v2][n];
343 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
344 Config->implement_lists[slot][n] = x;
349 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
353 void InspIRCd::MoveAfter(std::string modulename, std::string after)
355 for (unsigned int v = 0; v < Config->module_names.size(); v++)
357 if (Config->module_names[v] == after)
359 MoveTo(modulename, v);
365 void InspIRCd::MoveBefore(std::string modulename, std::string before)
367 for (unsigned int v = 0; v < Config->module_names.size(); v++)
369 if (Config->module_names[v] == before)
373 MoveTo(modulename, v-1);
377 MoveTo(modulename, v);
384 void InspIRCd::MoveToFirst(std::string modulename)
386 MoveTo(modulename,0);
389 void InspIRCd::MoveToLast(std::string modulename)
391 MoveTo(modulename,MODCOUNT);
394 void InspIRCd::BuildISupport()
396 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
398 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
399 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
400 v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC NETWORK=" << Config->Network << " MAXPARA=32";
401 Config->data005 = v.str();
402 FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
405 bool InspIRCd::UnloadModule(const char* filename)
407 std::string filename_str = filename;
408 for (unsigned int j = 0; j != Config->module_names.size(); j++)
410 if (Config->module_names[j] == filename_str)
412 if (modules[j]->GetVersion().Flags & VF_STATIC)
414 log(DEFAULT,"Failed to unload STATIC module %s",filename);
415 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
418 /* Give the module a chance to tidy out all its metadata */
419 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
421 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
423 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
425 modules[j]->OnCleanup(TYPE_USER,u->second);
428 FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
430 for(int t = 0; t < 255; t++)
432 Config->global_implementation[t] -= Config->implement_lists[j][t];
435 /* We have to renumber implement_lists after unload because the module numbers change!
437 for(int j2 = j; j2 < 254; j2++)
439 for(int t = 0; t < 255; t++)
441 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
446 log(DEBUG,"Deleting module...");
448 log(DEBUG,"Erasing module entry...");
450 log(DEBUG,"Removing dependent commands...");
451 Parser->RemoveCommands(filename);
452 log(DEFAULT,"Module %s unloaded",filename);
458 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
459 snprintf(MODERR,MAXBUF,"Module not loaded");
463 bool InspIRCd::LoadModule(const char* filename)
465 char modfile[MAXBUF];
467 strlcpy(modfile,filename,MAXBUF);
469 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
471 std::string filename_str = filename;
474 if (!DirValid(modfile))
476 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
477 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
482 log(DEBUG,"Loading module: %s",modfile);
484 if (FileExists(modfile))
487 for (unsigned int j = 0; j < Config->module_names.size(); j++)
489 if (Config->module_names[j] == filename_str)
491 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
492 snprintf(MODERR,MAXBUF,"Module already loaded");
496 ircd_module* a = new ircd_module(modfile);
497 factory[MODCOUNT+1] = a;
498 if (factory[MODCOUNT+1]->LastError())
500 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
501 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
506 if (factory[MODCOUNT+1]->factory)
508 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
509 modules[MODCOUNT+1] = m;
510 /* save the module and the module's classfactory, if
511 * this isnt done, random crashes can occur :/ */
512 Config->module_names.push_back(filename);
514 char* x = &Config->implement_lists[MODCOUNT+1][0];
515 for(int t = 0; t < 255; t++)
518 modules[MODCOUNT+1]->Implements(x);
520 for(int t = 0; t < 255; t++)
521 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
525 log(DEFAULT,"Unable to load %s",modfile);
526 snprintf(MODERR,MAXBUF,"Factory function failed!");
530 catch (ModuleException& modexcept)
532 log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
533 snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
540 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
541 snprintf(MODERR,MAXBUF,"Module file could not be found");
546 FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
547 // now work out which modules, if any, want to move to the back of the queue,
548 // and if they do, move them there.
549 std::vector<std::string> put_to_back;
550 std::vector<std::string> put_to_front;
551 std::map<std::string,std::string> put_before;
552 std::map<std::string,std::string> put_after;
553 for (unsigned int j = 0; j < Config->module_names.size(); j++)
555 if (modules[j]->Prioritize() == PRIORITY_LAST)
557 put_to_back.push_back(Config->module_names[j]);
559 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
561 put_to_front.push_back(Config->module_names[j]);
563 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
565 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
567 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
569 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
572 for (unsigned int j = 0; j < put_to_back.size(); j++)
574 MoveToLast(put_to_back[j]);
576 for (unsigned int j = 0; j < put_to_front.size(); j++)
578 MoveToFirst(put_to_front[j]);
580 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
582 MoveBefore(j->first,j->second);
584 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
586 MoveAfter(j->first,j->second);
592 void InspIRCd::DoOneIteration(bool process_module_sockets)
594 int activefds[MAX_DESCRIPTORS];
598 InspSocket* s = NULL;
599 InspSocket* s_del = NULL;
600 unsigned int numberactive;
601 sockaddr_in sock_us; // our port number
602 socklen_t uslen; // length of our port number
604 if (yield_depth > 100)
609 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
610 * Once per loop iteration is pleanty.
615 /* Run background module timers every few seconds
616 * (the docs say modules shouldnt rely on accurate
617 * timing using this event, so we dont have to
618 * time this exactly).
620 if (((TIME % 5) == 0) && (!expire_run))
623 if (process_module_sockets)
625 /* Fix by brain - the addition of DoOneIteration means that this
626 * can end up getting called recursively in the following pattern:
628 * m_spanningtree DoPingChecks
629 * (server pings out and is squit)
630 * (squit causes call to DoOneIteration)
631 * DoOneIteration enters here
632 * calls DoBackground timer
633 * enters m_spanningtree DoPingChecks... see step 1.
635 * This should do the job and fix the bug.
637 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
639 TickMissedTimers(TIME);
644 else if ((TIME % 5) == 1)
649 if (iterations++ == 15)
652 DoBackgroundUserStuff(TIME);
655 /* Once a second, do the background processing */
659 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
660 if ((TIME % 3600) == 0)
662 MaintainWhoWas(TIME);
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 if (process_module_sockets)
672 DoSocketTimeouts(TIME);
676 /* Call the socket engine to wait on the active
677 * file descriptors. The socket engine has everything's
678 * descriptors in its list... dns, modules, users,
679 * servers... so its nice and easy, just one call.
681 if (!(numberactive = SE->Wait(activefds)))
688 * Now process each of the fd's. For users, we have a fast
689 * lookup table which can find a user by file descriptor, so
690 * processing them by fd isnt expensive. If we have a lot of
691 * listening ports or module sockets though, things could get
694 log(DEBUG,"There are %d fd's to process.",numberactive);
696 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
698 int socket_type = SE->GetType(activefds[activefd]);
703 log(DEBUG,"Type: X_ESTAB_CLIENT: fd=%d",activefds[activefd]);
704 cu = fd_ref_table[activefds[activefd]];
712 log(DEBUG,"Type: X_ESTAB_MODULE: fd=%d",activefds[activefd]);
714 if (!process_module_sockets)
717 /* Process module-owned sockets.
718 * Modules are encouraged to inherit their sockets from
719 * InspSocket so we can process them neatly like this.
721 s = socket_ref[activefds[activefd]];
723 if ((s) && (!s->Poll()))
725 log(DEBUG,"inspircd.cpp: Socket poll returned false, close and bail");
726 SE->DelFd(s->GetFd());
727 socket_ref[activefds[activefd]] = NULL;
728 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
730 s_del = (InspSocket*)*a;
731 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
733 module_sockets.erase(a);
742 log(DEBUG,"WTF, X_ESTAB_MODULE for nonexistent InspSocket, removed!");
743 SE->DelFd(s->GetFd());
748 /* When we are using single-threaded dns,
749 * the sockets for dns end up in our mainloop.
750 * When we are using multi-threaded dns,
751 * each thread has its own basic poll() loop
752 * within it, making them 'fire and forget'
753 * and independent of the mainloop.
756 log(DEBUG,"Type: X_ESTAB_DNS: fd=%d",activefds[activefd]);
757 dns_poll(activefds[activefd]);
763 log(DEBUG,"Type: X_LISTEN_MODULE: fd=%d",activefds[activefd]);
765 /* It's a listener */
766 uslen = sizeof(sock_us);
767 length = sizeof(client);
768 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
770 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
772 in_port = ntohs(sock_us.sin_port);
773 log(DEBUG,"Accepted socket %d",incomingSockfd);
774 /* Years and years ago, we used to resolve here
775 * using gethostbyaddr(). That is sucky and we
776 * don't do that any more...
778 NonBlocking(incomingSockfd);
779 if (Config->GetIOHook(in_port))
783 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
785 catch (ModuleException& modexcept)
787 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
790 stats->statsAccept++;
791 AddClient(incomingSockfd, in_port, false, client.sin_addr);
792 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
796 log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
797 shutdown(incomingSockfd,2);
798 close(incomingSockfd);
799 stats->statsRefused++;
804 /* Something went wrong if we're in here.
805 * In fact, so wrong, im not quite sure
806 * what we would do, so for now, its going
807 * to safely do bugger all.
809 log(DEBUG,"Type: X_WHAT_THE_FUCK_BBQ: fd=%d",activefds[activefd]);
810 SE->DelFd(activefds[activefd]);
819 /* Until THIS point, ServerInstance == NULL */
821 LoadAllModules(this);
823 /* Just in case no modules were loaded - fix for bug #101 */
824 this->BuildISupport();
826 printf("\nInspIRCd is now running!\n");
835 /* Add the listening sockets used for client inbound connections
836 * to the socket engine
838 for (int count = 0; count < stats->BoundPortCount; count++)
839 SE->AddFd(openSockfd[count],true,X_LISTEN);
841 WritePID(Config->PID);
843 /* main loop, this never returns */
850 DoOneIteration(true);
852 /* This is never reached -- we hope! */
856 /**********************************************************************************/
859 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
862 int main(int argc, char** argv)
866 ServerInstance = new InspIRCd(argc, argv);
867 ServerInstance->Run();
868 delete ServerInstance;
870 catch (std::bad_alloc)
872 log(DEFAULT,"You are out of memory! (got exception std::bad_alloc!)");
873 send_error("**** OUT OF MEMORY **** We're gonna need a bigger boat!");
874 printf("Out of memory! (got exception std::bad_alloc!");