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];
77 sockaddr_in client,server;
80 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
82 time_t TIME = time(NULL), OLDTIME = time(NULL);
84 // This table references users by file descriptor.
85 // its an array to make it VERY fast, as all lookups are referenced
86 // by an integer, meaning there is no need for a scan/search operation.
87 userrec* fd_ref_table[MAX_DESCRIPTORS];
89 Server* MyServer = new Server;
90 ServerConfig *Config = new ServerConfig;
95 servernamelist servernames;
98 void AddServerName(std::string servername)
100 log(DEBUG,"Adding server name: %s",servername.c_str());
101 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
103 if (*a == servername)
106 servernames.push_back(servername);
109 const char* FindServerNamePtr(std::string servername)
111 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
113 if (*a == servername)
116 AddServerName(servername);
117 return FindServerNamePtr(servername);
120 bool FindServerName(std::string servername)
122 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
124 if (*a == servername)
130 std::string InspIRCd::GetRevision()
135 void InspIRCd::MakeLowerMap()
137 // initialize the lowercase mapping table
138 for (unsigned int cn = 0; cn < 256; cn++)
140 // lowercase the uppercase chars
141 for (unsigned int cn = 65; cn < 91; cn++)
142 lowermap[cn] = tolower(cn);
143 // now replace the specific chars for scandanavian comparison
144 lowermap[(unsigned)'['] = '{';
145 lowermap[(unsigned)']'] = '}';
146 lowermap[(unsigned)'\\'] = '|';
149 InspIRCd::InspIRCd(int argc, char** argv)
152 module_sockets.clear();
153 this->startup_time = time(NULL);
155 log(DEBUG,"*** InspIRCd starting up!");
156 if (!FileExists(CONFIG_FILE))
158 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
159 log(DEFAULT,"main: no config");
160 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
165 for (int i = 1; i < argc; i++)
167 if (!strcmp(argv[i],"-nofork")) {
168 Config->nofork = true;
170 if (!strcmp(argv[i],"-wait")) {
173 if (!strcmp(argv[i],"-nolimit")) {
174 Config->unlimitcore = true;
176 if (!strcmp(argv[i],"-logfile")) {
179 strlcpy(LOG_FILE,argv[i+1],MAXBUF);
180 printf("LOG: Setting logfile to %s\n",LOG_FILE);
184 printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
191 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
193 this->MakeLowerMap();
196 Config->ClearStack();
197 Config->Read(true,NULL);
199 this->ModeGrok = new ModeParser();
200 this->Parser = new CommandParser();
201 this->stats = new serverstats();
202 AddServerName(Config->ServerName);
204 stats->BoundPortCount = BindPorts();
206 for(int t = 0; t < 255; t++)
207 Config->global_implementation[t] = 0;
209 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
215 if (DaemonSeed() == ERROR)
217 printf("ERROR: could not go into daemon mode. Shutting down.\n");
222 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
223 * initialize the socket engine.
225 SE = new SocketEngine();
227 /* We must load the modules AFTER initializing the socket engine, now */
232 std::string InspIRCd::GetVersionString()
234 char versiondata[MAXBUF];
236 char dnsengine[] = "multithread";
238 char dnsengine[] = "singlethread";
240 if (*Config->CustomVersion)
242 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
246 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%lu,%s,%s]",VERSION,Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
251 char* InspIRCd::ModuleError()
256 void InspIRCd::erase_factory(int j)
259 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
264 factory.push_back(NULL);
271 void InspIRCd::erase_module(int j)
274 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
280 modules.push_back(NULL);
286 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
290 Config->module_names.erase(v);
298 void InspIRCd::MoveTo(std::string modulename,int slot)
300 unsigned int v2 = 256;
301 for (unsigned int v = 0; v < Config->module_names.size(); v++)
303 if (Config->module_names[v] == modulename)
305 // found an instance, swap it with the item at MODCOUNT
310 if ((v2 != (unsigned int)slot) && (v2 < 256))
312 // Swap the module names over
313 Config->module_names[v2] = Config->module_names[slot];
314 Config->module_names[slot] = modulename;
315 // now swap the module factories
316 ircd_module* temp = factory[v2];
317 factory[v2] = factory[slot];
318 factory[slot] = temp;
319 // now swap the module objects
320 Module* temp_module = modules[v2];
321 modules[v2] = modules[slot];
322 modules[slot] = temp_module;
323 // now swap the implement lists (we dont
324 // need to swap the global or recount it)
325 for (int n = 0; n < 255; n++)
327 char x = Config->implement_lists[v2][n];
328 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
329 Config->implement_lists[slot][n] = x;
334 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
338 void InspIRCd::MoveAfter(std::string modulename, std::string after)
340 for (unsigned int v = 0; v < Config->module_names.size(); v++)
342 if (Config->module_names[v] == after)
344 MoveTo(modulename, v);
350 void InspIRCd::MoveBefore(std::string modulename, std::string before)
352 for (unsigned int v = 0; v < Config->module_names.size(); v++)
354 if (Config->module_names[v] == before)
358 MoveTo(modulename, v-1);
362 MoveTo(modulename, v);
369 void InspIRCd::MoveToFirst(std::string modulename)
371 MoveTo(modulename,0);
374 void InspIRCd::MoveToLast(std::string modulename)
376 MoveTo(modulename,MODCOUNT);
379 void InspIRCd::BuildISupport()
381 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
383 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
384 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
385 v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC NETWORK=" << Config->Network << " MAXPARA=32";
386 Config->data005 = v.str();
387 FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
390 bool InspIRCd::UnloadModule(const char* filename)
392 std::string filename_str = filename;
393 for (unsigned int j = 0; j != Config->module_names.size(); j++)
395 if (Config->module_names[j] == filename_str)
397 if (modules[j]->GetVersion().Flags & VF_STATIC)
399 log(DEFAULT,"Failed to unload STATIC module %s",filename);
400 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
403 /* Give the module a chance to tidy out all its metadata */
404 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
406 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
408 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
410 modules[j]->OnCleanup(TYPE_USER,u->second);
413 FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
415 for(int t = 0; t < 255; t++)
417 Config->global_implementation[t] -= Config->implement_lists[j][t];
420 /* We have to renumber implement_lists after unload because the module numbers change!
422 for(int j2 = j; j2 < 254; j2++)
424 for(int t = 0; t < 255; t++)
426 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
431 log(DEBUG,"Deleting module...");
433 log(DEBUG,"Erasing module entry...");
435 log(DEBUG,"Removing dependent commands...");
436 Parser->RemoveCommands(filename);
437 log(DEFAULT,"Module %s unloaded",filename);
443 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
444 snprintf(MODERR,MAXBUF,"Module not loaded");
448 bool InspIRCd::LoadModule(const char* filename)
450 char modfile[MAXBUF];
452 strlcpy(modfile,filename,MAXBUF);
454 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
456 std::string filename_str = filename;
459 if (!DirValid(modfile))
461 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
462 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
467 log(DEBUG,"Loading module: %s",modfile);
469 if (FileExists(modfile))
472 for (unsigned int j = 0; j < Config->module_names.size(); j++)
474 if (Config->module_names[j] == filename_str)
476 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
477 snprintf(MODERR,MAXBUF,"Module already loaded");
481 ircd_module* a = new ircd_module(modfile);
482 factory[MODCOUNT+1] = a;
483 if (factory[MODCOUNT+1]->LastError())
485 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
486 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
491 if (factory[MODCOUNT+1]->factory)
493 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
494 modules[MODCOUNT+1] = m;
495 /* save the module and the module's classfactory, if
496 * this isnt done, random crashes can occur :/ */
497 Config->module_names.push_back(filename);
499 char* x = &Config->implement_lists[MODCOUNT+1][0];
500 for(int t = 0; t < 255; t++)
503 modules[MODCOUNT+1]->Implements(x);
505 for(int t = 0; t < 255; t++)
506 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
510 log(DEFAULT,"Unable to load %s",modfile);
511 snprintf(MODERR,MAXBUF,"Factory function failed!");
515 catch (ModuleException& modexcept)
517 log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
518 snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
525 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
526 snprintf(MODERR,MAXBUF,"Module file could not be found");
531 FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
532 // now work out which modules, if any, want to move to the back of the queue,
533 // and if they do, move them there.
534 std::vector<std::string> put_to_back;
535 std::vector<std::string> put_to_front;
536 std::map<std::string,std::string> put_before;
537 std::map<std::string,std::string> put_after;
538 for (unsigned int j = 0; j < Config->module_names.size(); j++)
540 if (modules[j]->Prioritize() == PRIORITY_LAST)
542 put_to_back.push_back(Config->module_names[j]);
544 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
546 put_to_front.push_back(Config->module_names[j]);
548 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
550 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
552 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
554 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
557 for (unsigned int j = 0; j < put_to_back.size(); j++)
559 MoveToLast(put_to_back[j]);
561 for (unsigned int j = 0; j < put_to_front.size(); j++)
563 MoveToFirst(put_to_front[j]);
565 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
567 MoveBefore(j->first,j->second);
569 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
571 MoveAfter(j->first,j->second);
577 void InspIRCd::DoOneIteration(bool process_module_sockets)
579 int activefds[MAX_DESCRIPTORS];
583 InspSocket* s = NULL;
584 InspSocket* s_del = NULL;
585 unsigned int numberactive;
586 sockaddr_in sock_us; // our port number
587 socklen_t uslen; // length of our port number
594 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
595 * Once per loop iteration is pleanty.
600 /* Run background module timers every few seconds
601 * (the docs say modules shouldnt rely on accurate
602 * timing using this event, so we dont have to
603 * time this exactly).
605 if (((TIME % 5) == 0) && (!expire_run))
608 if (process_module_sockets)
610 /* Fix by brain - the addition of DoOneIteration means that this
611 * can end up getting called recursively in the following pattern:
613 * m_spanningtree DoPingChecks
614 * (server pings out and is squit)
615 * (squit causes call to DoOneIteration)
616 * DoOneIteration enters here
617 * calls DoBackground timer
618 * enters m_spanningtree DoPingChecks... see step 1.
620 * This should do the job and fix the bug.
622 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
624 TickMissedTimers(TIME);
629 else if ((TIME % 5) == 1)
634 if (iterations++ == 15)
637 DoBackgroundUserStuff(TIME);
640 /* Once a second, do the background processing */
644 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
645 if ((TIME % 3600) == 0)
647 MaintainWhoWas(TIME);
651 /* Process timeouts on module sockets each time around
652 * the loop. There shouldnt be many module sockets, at
653 * most, 20 or so, so this won't be much of a performance
656 if (process_module_sockets)
657 DoSocketTimeouts(TIME);
661 /* Call the socket engine to wait on the active
662 * file descriptors. The socket engine has everything's
663 * descriptors in its list... dns, modules, users,
664 * servers... so its nice and easy, just one call.
666 if (!(numberactive = SE->Wait(activefds)))
673 * Now process each of the fd's. For users, we have a fast
674 * lookup table which can find a user by file descriptor, so
675 * processing them by fd isnt expensive. If we have a lot of
676 * listening ports or module sockets though, things could get
679 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
681 int socket_type = SE->GetType(activefds[activefd]);
686 cu = fd_ref_table[activefds[activefd]];
694 if (!process_module_sockets)
697 /* Process module-owned sockets.
698 * Modules are encouraged to inherit their sockets from
699 * InspSocket so we can process them neatly like this.
701 s = socket_ref[activefds[activefd]];
703 if ((s) && (!s->Poll()))
705 log(DEBUG,"Socket poll returned false, close and bail");
706 SE->DelFd(s->GetFd());
707 socket_ref[activefds[activefd]] = NULL;
708 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
710 s_del = (InspSocket*)*a;
711 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
713 module_sockets.erase(a);
723 /* When we are using single-threaded dns,
724 * the sockets for dns end up in our mainloop.
725 * When we are using multi-threaded dns,
726 * each thread has its own basic poll() loop
727 * within it, making them 'fire and forget'
728 * and independent of the mainloop.
731 dns_poll(activefds[activefd]);
737 /* It's a listener */
738 uslen = sizeof(sock_us);
739 length = sizeof(client);
740 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
742 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
744 in_port = ntohs(sock_us.sin_port);
745 log(DEBUG,"Accepted socket %d",incomingSockfd);
746 /* Years and years ago, we used to resolve here
747 * using gethostbyaddr(). That is sucky and we
748 * don't do that any more...
750 NonBlocking(incomingSockfd);
751 if (Config->GetIOHook(in_port))
755 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
757 catch (ModuleException& modexcept)
759 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
762 stats->statsAccept++;
763 AddClient(incomingSockfd, in_port, false, client.sin_addr);
764 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
768 log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
769 shutdown(incomingSockfd,2);
770 close(incomingSockfd);
771 stats->statsRefused++;
776 /* Something went wrong if we're in here.
777 * In fact, so wrong, im not quite sure
778 * what we would do, so for now, its going
779 * to safely do bugger all.
781 SE->DelFd(activefds[activefd]);
790 /* Until THIS point, ServerInstance == NULL */
792 LoadAllModules(this);
794 printf("\nInspIRCd is now running!\n");
803 /* Add the listening sockets used for client inbound connections
804 * to the socket engine
806 for (int count = 0; count < stats->BoundPortCount; count++)
807 SE->AddFd(openSockfd[count],true,X_LISTEN);
809 WritePID(Config->PID);
811 /* main loop, this never returns */
818 DoOneIteration(true);
820 /* This is never reached -- we hope! */
824 /**********************************************************************************/
827 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
830 int main(int argc, char** argv)
832 ServerInstance = new InspIRCd(argc, argv);
833 ServerInstance->Run();
834 delete ServerInstance;