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! ;) */
19 #include "inspircd_config.h"
21 #include "configreader.h"
23 #include <sys/errno.h>
24 #include <sys/ioctl.h>
48 #include "inspstring.h"
50 #include "helperfuncs.h"
52 #include "socketengine.h"
53 #include "userprocess.h"
56 #include "command_parse.h"
58 InspIRCd* ServerInstance;
60 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
61 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
63 extern std::vector<Module*> modules;
64 extern std::vector<ircd_module*> factory;
66 std::vector<InspSocket*> module_sockets;
67 std::vector<userrec*> local_users;
70 extern char LOG_FILE[MAXBUF];
71 int openSockfd[MAX_DESCRIPTORS];
75 insp_sockaddr client, server;
79 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
81 time_t TIME = time(NULL), OLDTIME = time(NULL);
83 // This table references users by file descriptor.
84 // its an array to make it VERY fast, as all lookups are referenced
85 // by an integer, meaning there is no need for a scan/search operation.
86 userrec* fd_ref_table[MAX_DESCRIPTORS];
88 Server* MyServer = new Server;
89 ServerConfig *Config = new ServerConfig;
94 servernamelist servernames;
97 void AddServerName(std::string servername)
99 log(DEBUG,"Adding server name: %s",servername.c_str());
100 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
102 if (*a == servername)
105 servernames.push_back(servername);
108 const char* FindServerNamePtr(std::string servername)
110 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
112 if (*a == servername)
115 AddServerName(servername);
116 return FindServerNamePtr(servername);
119 bool FindServerName(std::string servername)
121 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
123 if (*a == servername)
129 void Exit(int status)
131 if (Config->log_file)
132 fclose(Config->log_file);
133 send_error("Server shutdown.");
139 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
140 printf("(C) ChatSpike Development team.\033[0m\n\n");
141 printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om\033[0m\n");
142 printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
143 printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
146 void Killed(int status)
148 if (Config->log_file)
149 fclose(Config->log_file);
150 send_error("Server terminated.");
154 void Rehash(int status)
156 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
157 fclose(Config->log_file);
159 Config->Read(false,NULL);
160 FOREACH_MOD(I_OnRehash,OnRehash(""));
165 signal (SIGALRM, SIG_IGN);
166 signal (SIGHUP, Rehash);
167 signal (SIGPIPE, SIG_IGN);
168 signal (SIGTERM, Exit);
169 signal (SIGSEGV, Error);
175 if ((childpid = fork ()) < 0)
177 else if (childpid > 0)
179 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
185 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
188 if (getrlimit(RLIMIT_CORE, &rl) == -1)
190 log(DEFAULT,"Failed to getrlimit()!");
195 rl.rlim_cur = rl.rlim_max;
196 if (setrlimit(RLIMIT_CORE, &rl) == -1)
197 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
203 void WritePID(const std::string &filename)
205 std::ofstream outfile(filename.c_str());
206 if (outfile.is_open())
213 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
214 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
219 std::string InspIRCd::GetRevision()
224 void InspIRCd::MakeLowerMap()
226 // initialize the lowercase mapping table
227 for (unsigned int cn = 0; cn < 256; cn++)
229 // lowercase the uppercase chars
230 for (unsigned int cn = 65; cn < 91; cn++)
231 lowermap[cn] = tolower(cn);
232 // now replace the specific chars for scandanavian comparison
233 lowermap[(unsigned)'['] = '{';
234 lowermap[(unsigned)']'] = '}';
235 lowermap[(unsigned)'\\'] = '|';
238 InspIRCd::InspIRCd(int argc, char** argv)
241 module_sockets.clear();
242 this->startup_time = time(NULL);
244 log(DEBUG,"*** InspIRCd starting up!");
245 if (!FileExists(CONFIG_FILE))
247 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
248 log(DEFAULT,"main: no config");
249 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
254 for (int i = 1; i < argc; i++)
256 if (!strcmp(argv[i],"-nofork"))
258 Config->nofork = true;
260 else if(!strcmp(argv[i],"-debug"))
262 Config->forcedebug = true;
264 else if(!strcmp(argv[i],"-nolog"))
266 Config->writelog = false;
268 else if (!strcmp(argv[i],"-wait"))
272 else if (!strcmp(argv[i],"-nolimit"))
274 printf("WARNING: The `-nolimit' option is deprecated, and now on by default. This behaviour may change in the future.\n");
276 else if (!strcmp(argv[i],"-logfile"))
280 strlcpy(LOG_FILE,argv[i+1],MAXBUF);
281 printf("LOG: Setting logfile to %s\n",LOG_FILE);
285 printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
292 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
294 this->MakeLowerMap();
297 this->stats = new serverstats();
298 Config->ClearStack();
299 Config->Read(true,NULL);
301 this->ModeGrok = new ModeParser();
302 this->Parser = new CommandParser();
303 AddServerName(Config->ServerName);
305 stats->BoundPortCount = BindPorts(true);
307 for(int t = 0; t < 255; t++)
308 Config->global_implementation[t] = 0;
310 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
318 printf("ERROR: could not go into daemon mode. Shutting down.\n");
323 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
324 * initialize the socket engine.
326 SE = new SocketEngine();
328 /* We must load the modules AFTER initializing the socket engine, now */
333 std::string InspIRCd::GetVersionString()
335 char versiondata[MAXBUF];
337 char dnsengine[] = "multithread";
339 char dnsengine[] = "singlethread";
341 if (*Config->CustomVersion)
343 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
347 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%lu,%s,%s]",VERSION,Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
352 char* InspIRCd::ModuleError()
357 void InspIRCd::erase_factory(int j)
360 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
365 factory.push_back(NULL);
372 void InspIRCd::erase_module(int j)
375 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
381 modules.push_back(NULL);
387 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
391 Config->module_names.erase(v);
399 void InspIRCd::MoveTo(std::string modulename,int slot)
401 unsigned int v2 = 256;
402 for (unsigned int v = 0; v < Config->module_names.size(); v++)
404 if (Config->module_names[v] == modulename)
406 // found an instance, swap it with the item at MODCOUNT
411 if ((v2 != (unsigned int)slot) && (v2 < 256))
413 // Swap the module names over
414 Config->module_names[v2] = Config->module_names[slot];
415 Config->module_names[slot] = modulename;
416 // now swap the module factories
417 ircd_module* temp = factory[v2];
418 factory[v2] = factory[slot];
419 factory[slot] = temp;
420 // now swap the module objects
421 Module* temp_module = modules[v2];
422 modules[v2] = modules[slot];
423 modules[slot] = temp_module;
424 // now swap the implement lists (we dont
425 // need to swap the global or recount it)
426 for (int n = 0; n < 255; n++)
428 char x = Config->implement_lists[v2][n];
429 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
430 Config->implement_lists[slot][n] = x;
435 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
439 void InspIRCd::MoveAfter(std::string modulename, std::string after)
441 for (unsigned int v = 0; v < Config->module_names.size(); v++)
443 if (Config->module_names[v] == after)
445 MoveTo(modulename, v);
451 void InspIRCd::MoveBefore(std::string modulename, std::string before)
453 for (unsigned int v = 0; v < Config->module_names.size(); v++)
455 if (Config->module_names[v] == before)
459 MoveTo(modulename, v-1);
463 MoveTo(modulename, v);
470 void InspIRCd::MoveToFirst(std::string modulename)
472 MoveTo(modulename,0);
475 void InspIRCd::MoveToLast(std::string modulename)
477 MoveTo(modulename,MODCOUNT);
480 void InspIRCd::BuildISupport()
482 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
484 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
485 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
486 v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC NETWORK=" << Config->Network << " MAXPARA=32";
487 Config->data005 = v.str();
488 FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
491 bool InspIRCd::UnloadModule(const char* filename)
493 std::string filename_str = filename;
494 for (unsigned int j = 0; j != Config->module_names.size(); j++)
496 if (Config->module_names[j] == filename_str)
498 if (modules[j]->GetVersion().Flags & VF_STATIC)
500 log(DEFAULT,"Failed to unload STATIC module %s",filename);
501 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
504 /* Give the module a chance to tidy out all its metadata */
505 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
507 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
509 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
511 modules[j]->OnCleanup(TYPE_USER,u->second);
514 FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
516 for(int t = 0; t < 255; t++)
518 Config->global_implementation[t] -= Config->implement_lists[j][t];
521 /* We have to renumber implement_lists after unload because the module numbers change!
523 for(int j2 = j; j2 < 254; j2++)
525 for(int t = 0; t < 255; t++)
527 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
532 log(DEBUG,"Deleting module...");
534 log(DEBUG,"Erasing module entry...");
536 log(DEBUG,"Removing dependent commands...");
537 Parser->RemoveCommands(filename);
538 log(DEFAULT,"Module %s unloaded",filename);
544 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
545 snprintf(MODERR,MAXBUF,"Module not loaded");
549 bool InspIRCd::LoadModule(const char* filename)
551 char modfile[MAXBUF];
553 strlcpy(modfile,filename,MAXBUF);
555 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
557 std::string filename_str = filename;
560 if (!DirValid(modfile))
562 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
563 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
568 log(DEBUG,"Loading module: %s",modfile);
570 if (FileExists(modfile))
573 for (unsigned int j = 0; j < Config->module_names.size(); j++)
575 if (Config->module_names[j] == filename_str)
577 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
578 snprintf(MODERR,MAXBUF,"Module already loaded");
582 ircd_module* a = new ircd_module(modfile);
583 factory[MODCOUNT+1] = a;
584 if (factory[MODCOUNT+1]->LastError())
586 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
587 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
592 if (factory[MODCOUNT+1]->factory)
594 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
595 modules[MODCOUNT+1] = m;
596 /* save the module and the module's classfactory, if
597 * this isnt done, random crashes can occur :/ */
598 Config->module_names.push_back(filename);
600 char* x = &Config->implement_lists[MODCOUNT+1][0];
601 for(int t = 0; t < 255; t++)
604 modules[MODCOUNT+1]->Implements(x);
606 for(int t = 0; t < 255; t++)
607 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
611 log(DEFAULT,"Unable to load %s",modfile);
612 snprintf(MODERR,MAXBUF,"Factory function failed!");
616 catch (ModuleException& modexcept)
618 log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
619 snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
626 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
627 snprintf(MODERR,MAXBUF,"Module file could not be found");
632 FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
633 // now work out which modules, if any, want to move to the back of the queue,
634 // and if they do, move them there.
635 std::vector<std::string> put_to_back;
636 std::vector<std::string> put_to_front;
637 std::map<std::string,std::string> put_before;
638 std::map<std::string,std::string> put_after;
639 for (unsigned int j = 0; j < Config->module_names.size(); j++)
641 if (modules[j]->Prioritize() == PRIORITY_LAST)
643 put_to_back.push_back(Config->module_names[j]);
645 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
647 put_to_front.push_back(Config->module_names[j]);
649 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
651 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
653 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
655 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
658 for (unsigned int j = 0; j < put_to_back.size(); j++)
660 MoveToLast(put_to_back[j]);
662 for (unsigned int j = 0; j < put_to_front.size(); j++)
664 MoveToFirst(put_to_front[j]);
666 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
668 MoveBefore(j->first,j->second);
670 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
672 MoveAfter(j->first,j->second);
678 void InspIRCd::DoOneIteration(bool process_module_sockets)
680 int activefds[MAX_DESCRIPTORS];
684 InspSocket* s = NULL;
685 InspSocket* s_del = NULL;
686 unsigned int numberactive;
687 insp_sockaddr sock_us; // our port number
688 socklen_t uslen; // length of our port number
690 if (yield_depth > 100)
695 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
696 * Once per loop iteration is pleanty.
701 /* Run background module timers every few seconds
702 * (the docs say modules shouldnt rely on accurate
703 * timing using this event, so we dont have to
704 * time this exactly).
706 if (((TIME % 5) == 0) && (!expire_run))
709 if (process_module_sockets)
711 /* Fix by brain - the addition of DoOneIteration means that this
712 * can end up getting called recursively in the following pattern:
714 * m_spanningtree DoPingChecks
715 * (server pings out and is squit)
716 * (squit causes call to DoOneIteration)
717 * DoOneIteration enters here
718 * calls DoBackground timer
719 * enters m_spanningtree DoPingChecks... see step 1.
721 * This should do the job and fix the bug.
723 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
725 TickMissedTimers(TIME);
730 else if ((TIME % 5) == 1)
735 if (iterations++ == 15)
738 DoBackgroundUserStuff(TIME);
741 /* Once a second, do the background processing */
745 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
746 if ((TIME % 3600) == 0)
748 MaintainWhoWas(TIME);
752 /* Process timeouts on module sockets each time around
753 * the loop. There shouldnt be many module sockets, at
754 * most, 20 or so, so this won't be much of a performance
757 if (process_module_sockets)
758 DoSocketTimeouts(TIME);
762 /* Call the socket engine to wait on the active
763 * file descriptors. The socket engine has everything's
764 * descriptors in its list... dns, modules, users,
765 * servers... so its nice and easy, just one call.
767 if (!(numberactive = SE->Wait(activefds)))
774 * Now process each of the fd's. For users, we have a fast
775 * lookup table which can find a user by file descriptor, so
776 * processing them by fd isnt expensive. If we have a lot of
777 * listening ports or module sockets though, things could get
780 log(DEBUG,"There are %d fd's to process.",numberactive);
782 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
784 int socket_type = SE->GetType(activefds[activefd]);
789 log(DEBUG,"Type: X_ESTAB_CLIENT: fd=%d",activefds[activefd]);
790 cu = fd_ref_table[activefds[activefd]];
798 log(DEBUG,"Type: X_ESTAB_MODULE: fd=%d",activefds[activefd]);
800 if (!process_module_sockets)
803 /* Process module-owned sockets.
804 * Modules are encouraged to inherit their sockets from
805 * InspSocket so we can process them neatly like this.
807 s = socket_ref[activefds[activefd]];
809 if ((s) && (!s->Poll()))
811 log(DEBUG,"inspircd.cpp: Socket poll returned false, close and bail");
812 SE->DelFd(s->GetFd());
813 socket_ref[activefds[activefd]] = NULL;
814 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
816 s_del = (InspSocket*)*a;
817 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
819 module_sockets.erase(a);
828 log(DEBUG,"WTF, X_ESTAB_MODULE for nonexistent InspSocket, removed!");
829 SE->DelFd(s->GetFd());
834 /* When we are using single-threaded dns,
835 * the sockets for dns end up in our mainloop.
836 * When we are using multi-threaded dns,
837 * each thread has its own basic poll() loop
838 * within it, making them 'fire and forget'
839 * and independent of the mainloop.
842 log(DEBUG,"Type: X_ESTAB_DNS: fd=%d",activefds[activefd]);
843 dns_poll(activefds[activefd]);
849 log(DEBUG,"Type: X_LISTEN_MODULE: fd=%d",activefds[activefd]);
851 /* It's a listener */
852 uslen = sizeof(sock_us);
853 length = sizeof(client);
854 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
856 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
858 in_port = ntohs(sock_us.sin_port);
859 log(DEBUG,"Accepted socket %d",incomingSockfd);
860 /* Years and years ago, we used to resolve here
861 * using gethostbyaddr(). That is sucky and we
862 * don't do that any more...
864 NonBlocking(incomingSockfd);
865 if (Config->GetIOHook(in_port))
869 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
871 catch (ModuleException& modexcept)
873 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
876 stats->statsAccept++;
877 AddClient(incomingSockfd, in_port, false, client.sin_addr);
878 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
882 log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
883 shutdown(incomingSockfd,2);
884 close(incomingSockfd);
885 stats->statsRefused++;
890 /* Something went wrong if we're in here.
891 * In fact, so wrong, im not quite sure
892 * what we would do, so for now, its going
893 * to safely do bugger all.
895 log(DEBUG,"Type: X_WHAT_THE_FUCK_BBQ: fd=%d",activefds[activefd]);
896 SE->DelFd(activefds[activefd]);
905 /* Until THIS point, ServerInstance == NULL */
907 LoadAllModules(this);
909 /* Just in case no modules were loaded - fix for bug #101 */
910 this->BuildISupport();
912 printf("\nInspIRCd is now running!\n");
921 /* Add the listening sockets used for client inbound connections
922 * to the socket engine
924 for (int count = 0; count < stats->BoundPortCount; count++)
925 SE->AddFd(openSockfd[count],true,X_LISTEN);
927 WritePID(Config->PID);
929 /* main loop, this never returns */
936 DoOneIteration(true);
938 /* This is never reached -- we hope! */
942 /**********************************************************************************/
945 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
948 int main(int argc, char** argv)
952 ServerInstance = new InspIRCd(argc, argv);
953 ServerInstance->Run();
954 delete ServerInstance;
956 catch (std::bad_alloc)
958 log(DEFAULT,"You are out of memory! (got exception std::bad_alloc!)");
959 send_error("**** OUT OF MEMORY **** We're gonna need a bigger boat!");
960 printf("Out of memory! (got exception std::bad_alloc!");