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! ;) */
20 #include "inspircd_config.h"
22 #include "configreader.h"
24 #include <sys/errno.h>
25 #include <sys/ioctl.h>
50 #include "inspstring.h"
52 #include "helperfuncs.h"
54 #include "socketengine.h"
55 #include "userprocess.h"
58 #include "command_parse.h"
60 InspIRCd* ServerInstance;
62 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
63 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
65 extern ModuleList modules;
66 extern FactoryList factory;
68 std::vector<InspSocket*> module_sockets;
69 std::vector<userrec*> local_users;
72 extern char LOG_FILE[MAXBUF];
73 int openSockfd[MAX_DESCRIPTORS];
77 insp_sockaddr client, server;
81 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
83 time_t TIME = time(NULL), OLDTIME = time(NULL);
85 // This table references users by file descriptor.
86 // its an array to make it VERY fast, as all lookups are referenced
87 // by an integer, meaning there is no need for a scan/search operation.
88 userrec* fd_ref_table[MAX_DESCRIPTORS];
90 Server* MyServer = new Server;
91 ServerConfig *Config = new ServerConfig;
96 servernamelist servernames;
99 void AddServerName(const std::string &servername)
101 log(DEBUG,"Adding server name: %s",servername.c_str());
103 if(find(servernames.begin(), servernames.end(), servername) == servernames.end())
104 servernames.push_back(servername); /* Wasn't already there. */
107 const char* FindServerNamePtr(const std::string &servername)
109 servernamelist::iterator iter = find(servernames.begin(), servernames.end(), servername);
111 if(iter == servernames.end())
113 AddServerName(servername);
114 iter = --servernames.end();
117 return iter->c_str();
120 bool FindServerName(const std::string &servername)
122 return (find(servernames.begin(), servernames.end(), servername) != servernames.end());
125 void Exit(int status)
127 if (Config->log_file)
128 fclose(Config->log_file);
129 send_error("Server shutdown.");
135 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
136 printf("(C) ChatSpike Development team.\033[0m\n\n");
137 printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om\033[0m\n");
138 printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
139 printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
142 void Killed(int status)
144 if (Config->log_file)
145 fclose(Config->log_file);
146 send_error("Server terminated.");
150 void Rehash(int status)
152 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
153 fclose(Config->log_file);
155 Config->Read(false,NULL);
156 FOREACH_MOD(I_OnRehash,OnRehash(""));
161 signal (SIGALRM, SIG_IGN);
162 signal (SIGHUP, Rehash);
163 signal (SIGPIPE, SIG_IGN);
164 signal (SIGTERM, Exit);
165 signal (SIGSEGV, Error);
171 if ((childpid = fork ()) < 0)
173 else if (childpid > 0)
175 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
181 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
184 if (getrlimit(RLIMIT_CORE, &rl) == -1)
186 log(DEFAULT,"Failed to getrlimit()!");
191 rl.rlim_cur = rl.rlim_max;
192 if (setrlimit(RLIMIT_CORE, &rl) == -1)
193 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
199 void WritePID(const std::string &filename)
201 std::ofstream outfile(filename.c_str());
202 if (outfile.is_open())
209 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
210 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
215 std::string InspIRCd::GetRevision()
220 void InspIRCd::MakeLowerMap()
222 // initialize the lowercase mapping table
223 for (unsigned int cn = 0; cn < 256; cn++)
225 // lowercase the uppercase chars
226 for (unsigned int cn = 65; cn < 91; cn++)
227 lowermap[cn] = tolower(cn);
228 // now replace the specific chars for scandanavian comparison
229 lowermap[(unsigned)'['] = '{';
230 lowermap[(unsigned)']'] = '}';
231 lowermap[(unsigned)'\\'] = '|';
234 InspIRCd::InspIRCd(int argc, char** argv)
237 module_sockets.clear();
238 this->startup_time = time(NULL);
240 log(DEBUG,"*** InspIRCd starting up!");
241 if (!FileExists(CONFIG_FILE))
243 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
244 log(DEFAULT,"main: no config");
245 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
250 for (int i = 1; i < argc; i++)
252 if (!strcmp(argv[i],"-nofork"))
254 Config->nofork = true;
256 else if(!strcmp(argv[i],"-debug"))
258 Config->forcedebug = true;
260 else if(!strcmp(argv[i],"-nolog"))
262 Config->writelog = false;
264 else if (!strcmp(argv[i],"-wait"))
268 else if (!strcmp(argv[i],"-nolimit"))
270 printf("WARNING: The `-nolimit' option is deprecated, and now on by default. This behaviour may change in the future.\n");
272 else if (!strcmp(argv[i],"-logfile"))
276 strlcpy(LOG_FILE,argv[i+1],MAXBUF);
277 printf("LOG: Setting logfile to %s\n",LOG_FILE);
281 printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
288 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
290 this->MakeLowerMap();
293 this->stats = new serverstats();
294 Config->ClearStack();
295 Config->Read(true,NULL);
297 this->ModeGrok = new ModeParser();
298 this->Parser = new CommandParser();
299 AddServerName(Config->ServerName);
301 stats->BoundPortCount = BindPorts(true);
303 for(int t = 0; t < 255; t++)
304 Config->global_implementation[t] = 0;
306 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
314 printf("ERROR: could not go into daemon mode. Shutting down.\n");
319 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
320 * initialize the socket engine.
322 SE = new SocketEngine();
324 /* We must load the modules AFTER initializing the socket engine, now */
329 std::string InspIRCd::GetVersionString()
331 char versiondata[MAXBUF];
333 char dnsengine[] = "multithread";
335 char dnsengine[] = "singlethread";
337 if (*Config->CustomVersion)
339 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
343 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%lu,%s,%s]",VERSION,Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
348 char* InspIRCd::ModuleError()
353 void InspIRCd::erase_factory(int j)
356 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
361 factory.push_back(NULL);
368 void InspIRCd::erase_module(int j)
371 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
377 modules.push_back(NULL);
383 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
387 Config->module_names.erase(v);
395 void InspIRCd::MoveTo(std::string modulename,int slot)
397 unsigned int v2 = 256;
398 for (unsigned int v = 0; v < Config->module_names.size(); v++)
400 if (Config->module_names[v] == modulename)
402 // found an instance, swap it with the item at MODCOUNT
407 if ((v2 != (unsigned int)slot) && (v2 < 256))
409 // Swap the module names over
410 Config->module_names[v2] = Config->module_names[slot];
411 Config->module_names[slot] = modulename;
412 // now swap the module factories
413 ircd_module* temp = factory[v2];
414 factory[v2] = factory[slot];
415 factory[slot] = temp;
416 // now swap the module objects
417 Module* temp_module = modules[v2];
418 modules[v2] = modules[slot];
419 modules[slot] = temp_module;
420 // now swap the implement lists (we dont
421 // need to swap the global or recount it)
422 for (int n = 0; n < 255; n++)
424 char x = Config->implement_lists[v2][n];
425 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
426 Config->implement_lists[slot][n] = x;
431 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
435 void InspIRCd::MoveAfter(std::string modulename, std::string after)
437 for (unsigned int v = 0; v < Config->module_names.size(); v++)
439 if (Config->module_names[v] == after)
441 MoveTo(modulename, v);
447 void InspIRCd::MoveBefore(std::string modulename, std::string before)
449 for (unsigned int v = 0; v < Config->module_names.size(); v++)
451 if (Config->module_names[v] == before)
455 MoveTo(modulename, v-1);
459 MoveTo(modulename, v);
466 void InspIRCd::MoveToFirst(std::string modulename)
468 MoveTo(modulename,0);
471 void InspIRCd::MoveToLast(std::string modulename)
473 MoveTo(modulename,MODCOUNT);
476 void InspIRCd::BuildISupport()
478 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
480 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
481 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
482 v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC NETWORK=" << Config->Network << " MAXPARA=32";
483 Config->data005 = v.str();
484 FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
487 bool InspIRCd::UnloadModule(const char* filename)
489 std::string filename_str = filename;
490 for (unsigned int j = 0; j != Config->module_names.size(); j++)
492 if (Config->module_names[j] == filename_str)
494 if (modules[j]->GetVersion().Flags & VF_STATIC)
496 log(DEFAULT,"Failed to unload STATIC module %s",filename);
497 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
500 /* Give the module a chance to tidy out all its metadata */
501 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
503 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
505 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
507 modules[j]->OnCleanup(TYPE_USER,u->second);
510 FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
512 for(int t = 0; t < 255; t++)
514 Config->global_implementation[t] -= Config->implement_lists[j][t];
517 /* We have to renumber implement_lists after unload because the module numbers change!
519 for(int j2 = j; j2 < 254; j2++)
521 for(int t = 0; t < 255; t++)
523 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
528 log(DEBUG,"Deleting module...");
530 log(DEBUG,"Erasing module entry...");
532 log(DEBUG,"Removing dependent commands...");
533 Parser->RemoveCommands(filename);
534 log(DEFAULT,"Module %s unloaded",filename);
540 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
541 snprintf(MODERR,MAXBUF,"Module not loaded");
545 bool InspIRCd::LoadModule(const char* filename)
547 char modfile[MAXBUF];
549 strlcpy(modfile,filename,MAXBUF);
551 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
553 std::string filename_str = filename;
556 if (!DirValid(modfile))
558 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
559 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
564 log(DEBUG,"Loading module: %s",modfile);
566 if (FileExists(modfile))
569 for (unsigned int j = 0; j < Config->module_names.size(); j++)
571 if (Config->module_names[j] == filename_str)
573 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
574 snprintf(MODERR,MAXBUF,"Module already loaded");
578 ircd_module* a = new ircd_module(modfile);
579 factory[MODCOUNT+1] = a;
580 if (factory[MODCOUNT+1]->LastError())
582 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
583 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
588 if (factory[MODCOUNT+1]->factory)
590 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
591 modules[MODCOUNT+1] = m;
592 /* save the module and the module's classfactory, if
593 * this isnt done, random crashes can occur :/ */
594 Config->module_names.push_back(filename);
596 char* x = &Config->implement_lists[MODCOUNT+1][0];
597 for(int t = 0; t < 255; t++)
600 modules[MODCOUNT+1]->Implements(x);
602 for(int t = 0; t < 255; t++)
603 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
607 log(DEFAULT,"Unable to load %s",modfile);
608 snprintf(MODERR,MAXBUF,"Factory function failed!");
612 catch (ModuleException& modexcept)
614 log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
615 snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
622 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
623 snprintf(MODERR,MAXBUF,"Module file could not be found");
628 FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
629 // now work out which modules, if any, want to move to the back of the queue,
630 // and if they do, move them there.
631 std::vector<std::string> put_to_back;
632 std::vector<std::string> put_to_front;
633 std::map<std::string,std::string> put_before;
634 std::map<std::string,std::string> put_after;
635 for (unsigned int j = 0; j < Config->module_names.size(); j++)
637 if (modules[j]->Prioritize() == PRIORITY_LAST)
639 put_to_back.push_back(Config->module_names[j]);
641 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
643 put_to_front.push_back(Config->module_names[j]);
645 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
647 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
649 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
651 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
654 for (unsigned int j = 0; j < put_to_back.size(); j++)
656 MoveToLast(put_to_back[j]);
658 for (unsigned int j = 0; j < put_to_front.size(); j++)
660 MoveToFirst(put_to_front[j]);
662 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
664 MoveBefore(j->first,j->second);
666 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
668 MoveAfter(j->first,j->second);
674 void InspIRCd::DoOneIteration(bool process_module_sockets)
676 int activefds[MAX_DESCRIPTORS];
680 InspSocket* s = NULL;
681 InspSocket* s_del = NULL;
682 unsigned int numberactive;
683 insp_sockaddr sock_us; // our port number
684 socklen_t uslen; // length of our port number
686 if (yield_depth > 100)
691 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
692 * Once per loop iteration is pleanty.
697 /* Run background module timers every few seconds
698 * (the docs say modules shouldnt rely on accurate
699 * timing using this event, so we dont have to
700 * time this exactly).
702 if (((TIME % 5) == 0) && (!expire_run))
705 if (process_module_sockets)
707 /* Fix by brain - the addition of DoOneIteration means that this
708 * can end up getting called recursively in the following pattern:
710 * m_spanningtree DoPingChecks
711 * (server pings out and is squit)
712 * (squit causes call to DoOneIteration)
713 * DoOneIteration enters here
714 * calls DoBackground timer
715 * enters m_spanningtree DoPingChecks... see step 1.
717 * This should do the job and fix the bug.
719 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
721 TickMissedTimers(TIME);
726 else if ((TIME % 5) == 1)
731 if (iterations++ == 15)
734 DoBackgroundUserStuff(TIME);
737 /* Once a second, do the background processing */
741 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
742 if ((TIME % 3600) == 0)
744 MaintainWhoWas(TIME);
748 /* Process timeouts on module sockets each time around
749 * the loop. There shouldnt be many module sockets, at
750 * most, 20 or so, so this won't be much of a performance
753 if (process_module_sockets)
754 DoSocketTimeouts(TIME);
758 /* Call the socket engine to wait on the active
759 * file descriptors. The socket engine has everything's
760 * descriptors in its list... dns, modules, users,
761 * servers... so its nice and easy, just one call.
763 if (!(numberactive = SE->Wait(activefds)))
770 * Now process each of the fd's. For users, we have a fast
771 * lookup table which can find a user by file descriptor, so
772 * processing them by fd isnt expensive. If we have a lot of
773 * listening ports or module sockets though, things could get
776 log(DEBUG,"There are %d fd's to process.",numberactive);
778 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
780 int socket_type = SE->GetType(activefds[activefd]);
785 log(DEBUG,"Type: X_ESTAB_CLIENT: fd=%d",activefds[activefd]);
786 cu = fd_ref_table[activefds[activefd]];
794 log(DEBUG,"Type: X_ESTAB_MODULE: fd=%d",activefds[activefd]);
796 if (!process_module_sockets)
799 /* Process module-owned sockets.
800 * Modules are encouraged to inherit their sockets from
801 * InspSocket so we can process them neatly like this.
803 s = socket_ref[activefds[activefd]];
805 if ((s) && (!s->Poll()))
807 log(DEBUG,"inspircd.cpp: Socket poll returned false, close and bail");
808 SE->DelFd(s->GetFd());
809 socket_ref[activefds[activefd]] = NULL;
810 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
812 s_del = (InspSocket*)*a;
813 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
815 module_sockets.erase(a);
824 log(DEBUG,"WTF, X_ESTAB_MODULE for nonexistent InspSocket, removed!");
825 SE->DelFd(s->GetFd());
830 /* When we are using single-threaded dns,
831 * the sockets for dns end up in our mainloop.
832 * When we are using multi-threaded dns,
833 * each thread has its own basic poll() loop
834 * within it, making them 'fire and forget'
835 * and independent of the mainloop.
838 log(DEBUG,"Type: X_ESTAB_DNS: fd=%d",activefds[activefd]);
839 dns_poll(activefds[activefd]);
845 log(DEBUG,"Type: X_LISTEN_MODULE: fd=%d",activefds[activefd]);
847 /* It's a listener */
848 uslen = sizeof(sock_us);
849 length = sizeof(client);
850 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
852 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
854 in_port = ntohs(sock_us.sin_port);
855 log(DEBUG,"Accepted socket %d",incomingSockfd);
856 /* Years and years ago, we used to resolve here
857 * using gethostbyaddr(). That is sucky and we
858 * don't do that any more...
860 NonBlocking(incomingSockfd);
861 if (Config->GetIOHook(in_port))
865 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
867 catch (ModuleException& modexcept)
869 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
872 stats->statsAccept++;
873 AddClient(incomingSockfd, in_port, false, client.sin_addr);
874 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
878 log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
879 shutdown(incomingSockfd,2);
880 close(incomingSockfd);
881 stats->statsRefused++;
886 /* Something went wrong if we're in here.
887 * In fact, so wrong, im not quite sure
888 * what we would do, so for now, its going
889 * to safely do bugger all.
891 log(DEBUG,"Type: X_WHAT_THE_FUCK_BBQ: fd=%d",activefds[activefd]);
892 SE->DelFd(activefds[activefd]);
901 /* Until THIS point, ServerInstance == NULL */
903 LoadAllModules(this);
905 /* Just in case no modules were loaded - fix for bug #101 */
906 this->BuildISupport();
908 printf("\nInspIRCd is now running!\n");
917 /* Add the listening sockets used for client inbound connections
918 * to the socket engine
920 for (int count = 0; count < stats->BoundPortCount; count++)
921 SE->AddFd(openSockfd[count],true,X_LISTEN);
923 WritePID(Config->PID);
925 /* main loop, this never returns */
932 DoOneIteration(true);
934 /* This is never reached -- we hope! */
938 /**********************************************************************************/
941 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
944 int main(int argc, char** argv)
948 ServerInstance = new InspIRCd(argc, argv);
949 ServerInstance->Run();
950 delete ServerInstance;
952 catch (std::bad_alloc)
954 log(DEFAULT,"You are out of memory! (got exception std::bad_alloc!)");
955 send_error("**** OUT OF MEMORY **** We're gonna need a bigger boat!");
956 printf("Out of memory! (got exception std::bad_alloc!");