1 /* ---------------------------------------------------------------------
3 * +------------------------------------+
4 * | Inspire Internet Relay Chat Daemon |
5 * +------------------------------------+
7 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
9 * <brain@chatspike.net>
10 * <Craig@chatspike.net>
12 * Written by Craig Edwards, Craig McLure, and others.
13 * This program is free but copyrighted software; you can redistribute
14 * it and/or modify it under the terms of the GNU General Public
15 * License as published by the Free Software Foundation, version 2
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program; if not, write to the Free Software
25 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 * ---------------------------------------------------------------------
31 #include "inspircd_config.h"
33 #include "configreader.h"
35 #include <sys/errno.h>
36 #include <sys/ioctl.h>
61 #include "inspstring.h"
63 #include "helperfuncs.h"
65 #include "socketengine.h"
66 #include "userprocess.h"
69 #include "command_parse.h"
71 InspIRCd* ServerInstance;
73 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
74 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
76 extern ModuleList modules;
77 extern FactoryList factory;
79 std::vector<InspSocket*> module_sockets;
80 std::vector<userrec*> local_users;
83 extern char LOG_FILE[MAXBUF];
84 int openSockfd[MAX_DESCRIPTORS];
88 insp_sockaddr client, server;
92 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
94 time_t TIME = time(NULL), OLDTIME = time(NULL);
96 // This table references users by file descriptor.
97 // its an array to make it VERY fast, as all lookups are referenced
98 // by an integer, meaning there is no need for a scan/search operation.
99 userrec* fd_ref_table[MAX_DESCRIPTORS];
101 Server* MyServer = new Server;
102 ServerConfig *Config = new ServerConfig;
104 user_hash clientlist;
107 servernamelist servernames;
110 void AddServerName(const std::string &servername)
112 log(DEBUG,"Adding server name: %s",servername.c_str());
114 if(find(servernames.begin(), servernames.end(), servername) == servernames.end())
115 servernames.push_back(servername); /* Wasn't already there. */
118 const char* FindServerNamePtr(const std::string &servername)
120 servernamelist::iterator iter = find(servernames.begin(), servernames.end(), servername);
122 if(iter == servernames.end())
124 AddServerName(servername);
125 iter = --servernames.end();
128 return iter->c_str();
131 bool FindServerName(const std::string &servername)
133 return (find(servernames.begin(), servernames.end(), servername) != servernames.end());
136 void Exit(int status)
138 if (Config->log_file)
139 fclose(Config->log_file);
140 send_error("Server shutdown.");
146 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
147 printf("(C) ChatSpike Development team.\033[0m\n\n");
148 printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om\033[0m\n");
149 printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
150 printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
153 void Killed(int status)
155 if (Config->log_file)
156 fclose(Config->log_file);
157 send_error("Server terminated.");
161 void Rehash(int status)
163 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
164 fclose(Config->log_file);
166 Config->Read(false,NULL);
167 FOREACH_MOD(I_OnRehash,OnRehash(""));
172 signal (SIGALRM, SIG_IGN);
173 signal (SIGHUP, Rehash);
174 signal (SIGPIPE, SIG_IGN);
175 signal (SIGTERM, Exit);
176 signal (SIGSEGV, Error);
182 if ((childpid = fork ()) < 0)
184 else if (childpid > 0)
186 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
192 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
195 if (getrlimit(RLIMIT_CORE, &rl) == -1)
197 log(DEFAULT,"Failed to getrlimit()!");
202 rl.rlim_cur = rl.rlim_max;
203 if (setrlimit(RLIMIT_CORE, &rl) == -1)
204 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
210 void WritePID(const std::string &filename)
212 std::ofstream outfile(filename.c_str());
213 if (outfile.is_open())
220 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
221 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
226 std::string InspIRCd::GetRevision()
231 void InspIRCd::MakeLowerMap()
233 // initialize the lowercase mapping table
234 for (unsigned int cn = 0; cn < 256; cn++)
236 // lowercase the uppercase chars
237 for (unsigned int cn = 65; cn < 91; cn++)
238 lowermap[cn] = tolower(cn);
239 // now replace the specific chars for scandanavian comparison
240 lowermap[(unsigned)'['] = '{';
241 lowermap[(unsigned)']'] = '}';
242 lowermap[(unsigned)'\\'] = '|';
245 InspIRCd::InspIRCd(int argc, char** argv)
248 module_sockets.clear();
249 this->startup_time = time(NULL);
251 log(DEBUG,"*** InspIRCd starting up!");
252 if (!FileExists(CONFIG_FILE))
254 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
255 log(DEFAULT,"main: no config");
256 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
261 for (int i = 1; i < argc; i++)
263 if (!strcmp(argv[i],"-nofork"))
265 Config->nofork = true;
267 else if(!strcmp(argv[i],"-debug"))
269 Config->forcedebug = true;
271 else if(!strcmp(argv[i],"-nolog"))
273 Config->writelog = false;
275 else if (!strcmp(argv[i],"-wait"))
279 else if (!strcmp(argv[i],"-nolimit"))
281 printf("WARNING: The `-nolimit' option is deprecated, and now on by default. This behaviour may change in the future.\n");
283 else if (!strcmp(argv[i],"-logfile"))
287 strlcpy(LOG_FILE,argv[i+1],MAXBUF);
288 printf("LOG: Setting logfile to %s\n",LOG_FILE);
292 printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
299 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
301 this->MakeLowerMap();
304 this->stats = new serverstats();
305 Config->ClearStack();
306 Config->Read(true,NULL);
308 this->ModeGrok = new ModeParser();
309 this->Parser = new CommandParser();
310 AddServerName(Config->ServerName);
312 stats->BoundPortCount = BindPorts(true);
314 for(int t = 0; t < 255; t++)
315 Config->global_implementation[t] = 0;
317 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
325 printf("ERROR: could not go into daemon mode. Shutting down.\n");
330 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
331 * initialize the socket engine.
333 SE = new SocketEngine();
335 /* We must load the modules AFTER initializing the socket engine, now */
340 std::string InspIRCd::GetVersionString()
342 char versiondata[MAXBUF];
344 char dnsengine[] = "multithread";
346 char dnsengine[] = "singlethread";
348 if (*Config->CustomVersion)
350 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
354 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%lu,%s,%s]",VERSION,Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
359 char* InspIRCd::ModuleError()
364 void InspIRCd::erase_factory(int j)
367 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
372 factory.push_back(NULL);
379 void InspIRCd::erase_module(int j)
382 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
388 modules.push_back(NULL);
394 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
398 Config->module_names.erase(v);
406 void InspIRCd::MoveTo(std::string modulename,int slot)
408 unsigned int v2 = 256;
409 for (unsigned int v = 0; v < Config->module_names.size(); v++)
411 if (Config->module_names[v] == modulename)
413 // found an instance, swap it with the item at MODCOUNT
418 if ((v2 != (unsigned int)slot) && (v2 < 256))
420 // Swap the module names over
421 Config->module_names[v2] = Config->module_names[slot];
422 Config->module_names[slot] = modulename;
423 // now swap the module factories
424 ircd_module* temp = factory[v2];
425 factory[v2] = factory[slot];
426 factory[slot] = temp;
427 // now swap the module objects
428 Module* temp_module = modules[v2];
429 modules[v2] = modules[slot];
430 modules[slot] = temp_module;
431 // now swap the implement lists (we dont
432 // need to swap the global or recount it)
433 for (int n = 0; n < 255; n++)
435 char x = Config->implement_lists[v2][n];
436 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
437 Config->implement_lists[slot][n] = x;
442 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
446 void InspIRCd::MoveAfter(std::string modulename, std::string after)
448 for (unsigned int v = 0; v < Config->module_names.size(); v++)
450 if (Config->module_names[v] == after)
452 MoveTo(modulename, v);
458 void InspIRCd::MoveBefore(std::string modulename, std::string before)
460 for (unsigned int v = 0; v < Config->module_names.size(); v++)
462 if (Config->module_names[v] == before)
466 MoveTo(modulename, v-1);
470 MoveTo(modulename, v);
477 void InspIRCd::MoveToFirst(std::string modulename)
479 MoveTo(modulename,0);
482 void InspIRCd::MoveToLast(std::string modulename)
484 MoveTo(modulename,MODCOUNT);
487 void InspIRCd::BuildISupport()
489 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
491 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
492 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
493 v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC NETWORK=" << Config->Network << " MAXPARA=32";
494 Config->data005 = v.str();
495 FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
498 bool InspIRCd::UnloadModule(const char* filename)
500 std::string filename_str = filename;
501 for (unsigned int j = 0; j != Config->module_names.size(); j++)
503 if (Config->module_names[j] == filename_str)
505 if (modules[j]->GetVersion().Flags & VF_STATIC)
507 log(DEFAULT,"Failed to unload STATIC module %s",filename);
508 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
511 /* Give the module a chance to tidy out all its metadata */
512 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
514 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
516 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
518 modules[j]->OnCleanup(TYPE_USER,u->second);
521 FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
523 for(int t = 0; t < 255; t++)
525 Config->global_implementation[t] -= Config->implement_lists[j][t];
528 /* We have to renumber implement_lists after unload because the module numbers change!
530 for(int j2 = j; j2 < 254; j2++)
532 for(int t = 0; t < 255; t++)
534 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
539 log(DEBUG,"Deleting module...");
541 log(DEBUG,"Erasing module entry...");
543 log(DEBUG,"Removing dependent commands...");
544 Parser->RemoveCommands(filename);
545 log(DEFAULT,"Module %s unloaded",filename);
551 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
552 snprintf(MODERR,MAXBUF,"Module not loaded");
556 bool InspIRCd::LoadModule(const char* filename)
558 char modfile[MAXBUF];
560 strlcpy(modfile,filename,MAXBUF);
562 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
564 std::string filename_str = filename;
567 if (!DirValid(modfile))
569 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
570 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
575 log(DEBUG,"Loading module: %s",modfile);
577 if (FileExists(modfile))
580 for (unsigned int j = 0; j < Config->module_names.size(); j++)
582 if (Config->module_names[j] == filename_str)
584 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
585 snprintf(MODERR,MAXBUF,"Module already loaded");
589 ircd_module* a = new ircd_module(modfile);
590 factory[MODCOUNT+1] = a;
591 if (factory[MODCOUNT+1]->LastError())
593 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
594 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
599 if (factory[MODCOUNT+1]->factory)
601 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
602 modules[MODCOUNT+1] = m;
603 /* save the module and the module's classfactory, if
604 * this isnt done, random crashes can occur :/ */
605 Config->module_names.push_back(filename);
607 char* x = &Config->implement_lists[MODCOUNT+1][0];
608 for(int t = 0; t < 255; t++)
611 modules[MODCOUNT+1]->Implements(x);
613 for(int t = 0; t < 255; t++)
614 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
618 log(DEFAULT,"Unable to load %s",modfile);
619 snprintf(MODERR,MAXBUF,"Factory function failed!");
623 catch (ModuleException& modexcept)
625 log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
626 snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
633 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
634 snprintf(MODERR,MAXBUF,"Module file could not be found");
639 FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
640 // now work out which modules, if any, want to move to the back of the queue,
641 // and if they do, move them there.
642 std::vector<std::string> put_to_back;
643 std::vector<std::string> put_to_front;
644 std::map<std::string,std::string> put_before;
645 std::map<std::string,std::string> put_after;
646 for (unsigned int j = 0; j < Config->module_names.size(); j++)
648 if (modules[j]->Prioritize() == PRIORITY_LAST)
650 put_to_back.push_back(Config->module_names[j]);
652 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
654 put_to_front.push_back(Config->module_names[j]);
656 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
658 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
660 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
662 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
665 for (unsigned int j = 0; j < put_to_back.size(); j++)
667 MoveToLast(put_to_back[j]);
669 for (unsigned int j = 0; j < put_to_front.size(); j++)
671 MoveToFirst(put_to_front[j]);
673 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
675 MoveBefore(j->first,j->second);
677 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
679 MoveAfter(j->first,j->second);
685 void InspIRCd::DoOneIteration(bool process_module_sockets)
687 int activefds[MAX_DESCRIPTORS];
691 InspSocket* s = NULL;
692 InspSocket* s_del = NULL;
693 unsigned int numberactive;
694 insp_sockaddr sock_us; // our port number
695 socklen_t uslen; // length of our port number
697 if (yield_depth > 100)
702 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
703 * Once per loop iteration is pleanty.
708 /* Run background module timers every few seconds
709 * (the docs say modules shouldnt rely on accurate
710 * timing using this event, so we dont have to
711 * time this exactly).
713 if (((TIME % 5) == 0) && (!expire_run))
716 if (process_module_sockets)
718 /* Fix by brain - the addition of DoOneIteration means that this
719 * can end up getting called recursively in the following pattern:
721 * m_spanningtree DoPingChecks
722 * (server pings out and is squit)
723 * (squit causes call to DoOneIteration)
724 * DoOneIteration enters here
725 * calls DoBackground timer
726 * enters m_spanningtree DoPingChecks... see step 1.
728 * This should do the job and fix the bug.
730 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
732 TickMissedTimers(TIME);
737 else if ((TIME % 5) == 1)
742 if (iterations++ == 15)
745 DoBackgroundUserStuff(TIME);
748 /* Once a second, do the background processing */
752 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
753 if ((TIME % 3600) == 0)
755 MaintainWhoWas(TIME);
759 /* Process timeouts on module sockets each time around
760 * the loop. There shouldnt be many module sockets, at
761 * most, 20 or so, so this won't be much of a performance
764 if (process_module_sockets)
765 DoSocketTimeouts(TIME);
769 /* Call the socket engine to wait on the active
770 * file descriptors. The socket engine has everything's
771 * descriptors in its list... dns, modules, users,
772 * servers... so its nice and easy, just one call.
774 if (!(numberactive = SE->Wait(activefds)))
781 * Now process each of the fd's. For users, we have a fast
782 * lookup table which can find a user by file descriptor, so
783 * processing them by fd isnt expensive. If we have a lot of
784 * listening ports or module sockets though, things could get
787 log(DEBUG,"There are %d fd's to process.",numberactive);
789 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
791 int socket_type = SE->GetType(activefds[activefd]);
796 log(DEBUG,"Type: X_ESTAB_CLIENT: fd=%d",activefds[activefd]);
797 cu = fd_ref_table[activefds[activefd]];
805 log(DEBUG,"Type: X_ESTAB_MODULE: fd=%d",activefds[activefd]);
807 if (!process_module_sockets)
810 /* Process module-owned sockets.
811 * Modules are encouraged to inherit their sockets from
812 * InspSocket so we can process them neatly like this.
814 s = socket_ref[activefds[activefd]];
816 if ((s) && (!s->Poll()))
818 log(DEBUG,"Socket poll returned false, close and bail");
819 SE->DelFd(s->GetFd());
820 socket_ref[activefds[activefd]] = NULL;
821 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
824 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
826 module_sockets.erase(a);
835 log(DEBUG,"WTF, X_ESTAB_MODULE for nonexistent InspSocket, removed!");
836 SE->DelFd(s->GetFd());
841 /* When we are using single-threaded dns,
842 * the sockets for dns end up in our mainloop.
843 * When we are using multi-threaded dns,
844 * each thread has its own basic poll() loop
845 * within it, making them 'fire and forget'
846 * and independent of the mainloop.
849 log(DEBUG,"Type: X_ESTAB_DNS: fd=%d",activefds[activefd]);
850 dns_poll(activefds[activefd]);
856 log(DEBUG,"Type: X_LISTEN_MODULE: fd=%d",activefds[activefd]);
858 /* It's a listener */
859 uslen = sizeof(sock_us);
860 length = sizeof(client);
861 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
863 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
865 in_port = ntohs(sock_us.sin_port);
866 log(DEBUG,"Accepted socket %d",incomingSockfd);
867 /* Years and years ago, we used to resolve here
868 * using gethostbyaddr(). That is sucky and we
869 * don't do that any more...
871 NonBlocking(incomingSockfd);
872 if (Config->GetIOHook(in_port))
876 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, inet_ntoa(client.sin_addr), in_port);
878 catch (ModuleException& modexcept)
880 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
883 stats->statsAccept++;
884 AddClient(incomingSockfd, in_port, false, client.sin_addr);
885 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
889 log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
890 shutdown(incomingSockfd,2);
891 close(incomingSockfd);
892 stats->statsRefused++;
897 /* Something went wrong if we're in here.
898 * In fact, so wrong, im not quite sure
899 * what we would do, so for now, its going
900 * to safely do bugger all.
902 log(DEBUG,"Type: X_WHAT_THE_FUCK_BBQ: fd=%d",activefds[activefd]);
903 SE->DelFd(activefds[activefd]);
912 /* Until THIS point, ServerInstance == NULL */
914 LoadAllModules(this);
916 /* Just in case no modules were loaded - fix for bug #101 */
917 this->BuildISupport();
919 printf("\nInspIRCd is now running!\n");
928 /* Add the listening sockets used for client inbound connections
929 * to the socket engine
931 for (int count = 0; count < stats->BoundPortCount; count++)
932 SE->AddFd(openSockfd[count],true,X_LISTEN);
934 WritePID(Config->PID);
936 /* main loop, this never returns */
943 DoOneIteration(true);
945 /* This is never reached -- we hope! */
949 /**********************************************************************************/
952 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
955 int main(int argc, char** argv)
959 ServerInstance = new InspIRCd(argc, argv);
960 ServerInstance->Run();
961 DELETE(ServerInstance);
963 catch (std::bad_alloc)
965 log(DEFAULT,"You are out of memory! (got exception std::bad_alloc!)");
966 send_error("**** OUT OF MEMORY **** We're gonna need a bigger boat!");
967 printf("Out of memory! (got exception std::bad_alloc!");