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];
75 sockaddr_in client,server;
78 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
80 time_t TIME = time(NULL), OLDTIME = time(NULL);
82 // This table references users by file descriptor.
83 // its an array to make it VERY fast, as all lookups are referenced
84 // by an integer, meaning there is no need for a scan/search operation.
85 userrec* fd_ref_table[MAX_DESCRIPTORS];
87 Server* MyServer = new Server;
88 ServerConfig *Config = new ServerConfig;
93 servernamelist servernames;
96 void AddServerName(std::string servername)
98 log(DEBUG,"Adding server name: %s",servername.c_str());
99 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
101 if (*a == servername)
104 servernames.push_back(servername);
107 const char* FindServerNamePtr(std::string servername)
109 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
111 if (*a == servername)
114 AddServerName(servername);
115 return FindServerNamePtr(servername);
118 bool FindServerName(std::string servername)
120 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
122 if (*a == servername)
128 std::string InspIRCd::GetRevision()
133 void InspIRCd::MakeLowerMap()
135 // initialize the lowercase mapping table
136 for (unsigned int cn = 0; cn < 256; cn++)
138 // lowercase the uppercase chars
139 for (unsigned int cn = 65; cn < 91; cn++)
140 lowermap[cn] = tolower(cn);
141 // now replace the specific chars for scandanavian comparison
142 lowermap[(unsigned)'['] = '{';
143 lowermap[(unsigned)']'] = '}';
144 lowermap[(unsigned)'\\'] = '|';
147 InspIRCd::InspIRCd(int argc, char** argv)
150 module_sockets.clear();
151 this->startup_time = time(NULL);
153 log(DEBUG,"*** InspIRCd starting up!");
154 if (!FileExists(CONFIG_FILE))
156 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
157 log(DEFAULT,"main: no config");
158 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
163 for (int i = 1; i < argc; i++)
165 if (!strcmp(argv[i],"-nofork")) {
166 Config->nofork = true;
168 if (!strcmp(argv[i],"-wait")) {
171 if (!strcmp(argv[i],"-nolimit")) {
172 Config->unlimitcore = true;
174 if (!strcmp(argv[i],"-logfile")) {
177 strlcpy(LOG_FILE,argv[i+1],MAXBUF);
178 printf("LOG: Setting logfile to %s\n",LOG_FILE);
182 printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
189 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
191 this->MakeLowerMap();
194 Config->ClearStack();
195 Config->Read(true,NULL);
197 this->ModeGrok = new ModeParser();
198 this->Parser = new CommandParser();
199 this->stats = new serverstats();
200 AddServerName(Config->ServerName);
202 stats->BoundPortCount = BindPorts();
204 for(int t = 0; t < 255; t++)
205 Config->global_implementation[t] = 0;
207 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
213 if (DaemonSeed() == ERROR)
215 printf("ERROR: could not go into daemon mode. Shutting down.\n");
220 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
221 * initialize the socket engine.
223 SE = new SocketEngine();
225 /* We must load the modules AFTER initializing the socket engine, now */
230 std::string InspIRCd::GetVersionString()
232 char versiondata[MAXBUF];
234 char dnsengine[] = "multithread";
236 char dnsengine[] = "singlethread";
238 if (*Config->CustomVersion)
240 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
244 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%lu,%s,%s]",VERSION,Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
249 char* InspIRCd::ModuleError()
254 void InspIRCd::erase_factory(int j)
257 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
262 factory.push_back(NULL);
269 void InspIRCd::erase_module(int j)
272 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
278 modules.push_back(NULL);
284 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
288 Config->module_names.erase(v);
296 void InspIRCd::MoveTo(std::string modulename,int slot)
298 unsigned int v2 = 256;
299 log(DEBUG,"Moving %s to slot %d",modulename.c_str(),slot);
300 for (unsigned int v = 0; v < Config->module_names.size(); v++)
302 if (Config->module_names[v] == modulename)
304 // found an instance, swap it with the item at MODCOUNT
309 if (v2 == (unsigned int)slot)
311 log(DEBUG,"Item %s already in slot %d!",modulename.c_str(),slot);
315 // Swap the module names over
316 Config->module_names[v2] = Config->module_names[slot];
317 Config->module_names[slot] = modulename;
318 // now swap the module factories
319 ircd_module* temp = factory[v2];
320 factory[v2] = factory[slot];
321 factory[slot] = temp;
322 // now swap the module objects
323 Module* temp_module = modules[v2];
324 modules[v2] = modules[slot];
325 modules[slot] = temp_module;
326 // now swap the implement lists (we dont
327 // need to swap the global or recount it)
328 for (int n = 0; n < 255; n++)
330 char x = Config->implement_lists[v2][n];
331 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
332 Config->implement_lists[slot][n] = x;
334 log(DEBUG,"Moved %s to slot successfully",modulename.c_str());
338 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
342 void InspIRCd::MoveAfter(std::string modulename, std::string after)
344 log(DEBUG,"Move %s after %s...",modulename.c_str(),after.c_str());
345 for (unsigned int v = 0; v < Config->module_names.size(); v++)
347 if (Config->module_names[v] == after)
349 MoveTo(modulename, v);
355 void InspIRCd::MoveBefore(std::string modulename, std::string before)
357 log(DEBUG,"Move %s before %s...",modulename.c_str(),before.c_str());
358 for (unsigned int v = 0; v < Config->module_names.size(); v++)
360 if (Config->module_names[v] == before)
364 MoveTo(modulename, v-1);
368 MoveTo(modulename, v);
375 void InspIRCd::MoveToFirst(std::string modulename)
377 MoveTo(modulename,0);
380 void InspIRCd::MoveToLast(std::string modulename)
382 MoveTo(modulename,MODCOUNT);
385 void InspIRCd::BuildISupport()
387 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
389 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
390 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
391 v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC NETWORK=" << Config->Network << " MAXPARA=32";
392 Config->data005 = v.str();
393 FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
396 bool InspIRCd::UnloadModule(const char* filename)
398 std::string filename_str = filename;
399 for (unsigned int j = 0; j != Config->module_names.size(); j++)
401 if (Config->module_names[j] == filename_str)
403 if (modules[j]->GetVersion().Flags & VF_STATIC)
405 log(DEFAULT,"Failed to unload STATIC module %s",filename);
406 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
409 /* Give the module a chance to tidy out all its metadata */
410 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
412 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
414 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
416 modules[j]->OnCleanup(TYPE_USER,u->second);
419 FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
421 for(int t = 0; t < 255; t++)
423 Config->global_implementation[t] -= Config->implement_lists[j][t];
426 /* We have to renumber implement_lists after unload because the module numbers change!
428 for(int j2 = j; j2 < 254; j2++)
430 for(int t = 0; t < 255; t++)
432 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
437 log(DEBUG,"Deleting module...");
439 log(DEBUG,"Erasing module entry...");
441 log(DEBUG,"Removing dependent commands...");
442 Parser->RemoveCommands(filename);
443 log(DEFAULT,"Module %s unloaded",filename);
449 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
450 snprintf(MODERR,MAXBUF,"Module not loaded");
454 bool InspIRCd::LoadModule(const char* filename)
456 char modfile[MAXBUF];
458 strlcpy(modfile,filename,MAXBUF);
460 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
462 std::string filename_str = filename;
465 if (!DirValid(modfile))
467 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
468 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
473 log(DEBUG,"Loading module: %s",modfile);
475 if (FileExists(modfile))
478 for (unsigned int j = 0; j < Config->module_names.size(); j++)
480 if (Config->module_names[j] == filename_str)
482 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
483 snprintf(MODERR,MAXBUF,"Module already loaded");
487 ircd_module* a = new ircd_module(modfile);
488 factory[MODCOUNT+1] = a;
489 if (factory[MODCOUNT+1]->LastError())
491 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
492 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
497 if (factory[MODCOUNT+1]->factory)
499 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
500 modules[MODCOUNT+1] = m;
501 /* save the module and the module's classfactory, if
502 * this isnt done, random crashes can occur :/ */
503 Config->module_names.push_back(filename);
505 char* x = &Config->implement_lists[MODCOUNT+1][0];
506 for(int t = 0; t < 255; t++)
509 modules[MODCOUNT+1]->Implements(x);
511 for(int t = 0; t < 255; t++)
513 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
514 if (Config->implement_lists[MODCOUNT+1][t])
516 log(DEBUG,"Add global implementation: %d %d => %d",MODCOUNT+1,t,Config->global_implementation[t]);
522 log(DEFAULT,"Unable to load %s",modfile);
523 snprintf(MODERR,MAXBUF,"Factory function failed!");
527 catch (ModuleException& modexcept)
529 log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
530 snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
537 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
538 snprintf(MODERR,MAXBUF,"Module file could not be found");
543 FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
544 // now work out which modules, if any, want to move to the back of the queue,
545 // and if they do, move them there.
546 std::vector<std::string> put_to_back;
547 std::vector<std::string> put_to_front;
548 std::map<std::string,std::string> put_before;
549 std::map<std::string,std::string> put_after;
550 for (unsigned int j = 0; j < Config->module_names.size(); j++)
552 if (modules[j]->Prioritize() == PRIORITY_LAST)
554 put_to_back.push_back(Config->module_names[j]);
556 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
558 put_to_front.push_back(Config->module_names[j]);
560 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
562 log(DEBUG,"Module %d wants PRIORITY_BEFORE",j);
563 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
564 log(DEBUG,"Before: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
566 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
568 log(DEBUG,"Module %d wants PRIORITY_AFTER",j);
569 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
570 log(DEBUG,"After: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
573 for (unsigned int j = 0; j < put_to_back.size(); j++)
575 MoveToLast(put_to_back[j]);
577 for (unsigned int j = 0; j < put_to_front.size(); j++)
579 MoveToFirst(put_to_front[j]);
581 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
583 MoveBefore(j->first,j->second);
585 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
587 MoveAfter(j->first,j->second);
593 void InspIRCd::DoOneIteration(bool process_module_sockets)
595 int activefds[MAX_DESCRIPTORS];
599 InspSocket* s = NULL;
600 InspSocket* s_del = NULL;
601 unsigned int numberactive;
602 sockaddr_in sock_us; // our port number
603 socklen_t uslen; // length of our port number
605 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
606 * Once per loop iteration is pleanty.
611 /* Run background module timers every few seconds
612 * (the docs say modules shouldnt rely on accurate
613 * timing using this event, so we dont have to
614 * time this exactly).
616 if (((TIME % 5) == 0) && (!expire_run))
619 if (process_module_sockets)
621 /* Fix by brain - the addition of DoOneIteration means that this
622 * can end up getting called recursively in the following pattern:
624 * m_spanningtree DoPingChecks
625 * (server pings out and is squit)
626 * (squit causes call to DoOneIteration)
627 * DoOneIteration enters here
628 * calls DoBackground timer
629 * enters m_spanningtree DoPingChecks... see step 1.
631 * This should do the job and fix the bug.
633 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
635 TickMissedTimers(TIME);
639 else if ((TIME % 5) == 1)
644 /* Once a second, do the background processing */
648 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
649 DoBackgroundUserStuff(TIME);
652 /* Process timeouts on module sockets each time around
653 * the loop. There shouldnt be many module sockets, at
654 * most, 20 or so, so this won't be much of a performance
657 if (process_module_sockets)
658 DoSocketTimeouts(TIME);
662 /* Call the socket engine to wait on the active
663 * file descriptors. The socket engine has everything's
664 * descriptors in its list... dns, modules, users,
665 * servers... so its nice and easy, just one call.
667 if (!(numberactive = SE->Wait(activefds)))
671 * Now process each of the fd's. For users, we have a fast
672 * lookup table which can find a user by file descriptor, so
673 * processing them by fd isnt expensive. If we have a lot of
674 * listening ports or module sockets though, things could get
677 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
679 int socket_type = SE->GetType(activefds[activefd]);
684 cu = fd_ref_table[activefds[activefd]];
692 if (!process_module_sockets)
695 /* Process module-owned sockets.
696 * Modules are encouraged to inherit their sockets from
697 * InspSocket so we can process them neatly like this.
699 s = socket_ref[activefds[activefd]];
701 if ((s) && (!s->Poll()))
703 log(DEBUG,"Socket poll returned false, close and bail");
704 SE->DelFd(s->GetFd());
705 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
707 s_del = (InspSocket*)*a;
708 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
710 module_sockets.erase(a);
720 /* When we are using single-threaded dns,
721 * the sockets for dns end up in our mainloop.
722 * When we are using multi-threaded dns,
723 * each thread has its own basic poll() loop
724 * within it, making them 'fire and forget'
725 * and independent of the mainloop.
728 dns_poll(activefds[activefd]);
734 /* It's a listener */
735 uslen = sizeof(sock_us);
736 length = sizeof(client);
737 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
739 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
741 in_port = ntohs(sock_us.sin_port);
742 log(DEBUG,"Accepted socket %d",incomingSockfd);
743 /* Years and years ago, we used to resolve here
744 * using gethostbyaddr(). That is sucky and we
745 * don't do that any more...
747 NonBlocking(incomingSockfd);
748 if (Config->GetIOHook(in_port))
752 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
754 catch (ModuleException& modexcept)
756 log(DEBUG,"Module exception cought: %s",modexcept.GetReason()); \
759 stats->statsAccept++;
760 AddClient(incomingSockfd, in_port, false, client.sin_addr);
761 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
765 log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
766 shutdown(incomingSockfd,2);
767 close(incomingSockfd);
768 stats->statsRefused++;
773 /* Something went wrong if we're in here.
774 * In fact, so wrong, im not quite sure
775 * what we would do, so for now, its going
776 * to safely do bugger all.
785 /* Until THIS point, ServerInstance == NULL */
787 LoadAllModules(this);
789 printf("\nInspIRCd is now running!\n");
793 freopen("/dev/null","w",stdout);
794 freopen("/dev/null","w",stderr);
797 /* Add the listening sockets used for client inbound connections
798 * to the socket engine
800 for (int count = 0; count < stats->BoundPortCount; count++)
801 SE->AddFd(openSockfd[count],true,X_LISTEN);
803 WritePID(Config->PID);
805 /* main loop, this never returns */
810 DoOneIteration(true);
812 /* This is never reached -- we hope! */
816 /**********************************************************************************/
819 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
822 int main(int argc, char** argv)
824 ServerInstance = new InspIRCd(argc, argv);
825 ServerInstance->Run();
826 delete ServerInstance;