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>
33 #include <ext/hash_map>
54 #include "inspstring.h"
56 #include "helperfuncs.h"
58 #include "socketengine.h"
59 #include "userprocess.h"
62 #include "command_parse.h"
64 InspIRCd* ServerInstance;
66 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
67 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
69 extern std::vector<Module*> modules;
70 extern std::vector<ircd_module*> factory;
72 std::vector<InspSocket*> module_sockets;
73 std::vector<userrec*> local_users;
76 extern char LOG_FILE[MAXBUF];
77 int openSockfd[MAX_DESCRIPTORS];
81 insp_sockaddr client, server;
85 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
87 time_t TIME = time(NULL), OLDTIME = time(NULL);
89 // This table references users by file descriptor.
90 // its an array to make it VERY fast, as all lookups are referenced
91 // by an integer, meaning there is no need for a scan/search operation.
92 userrec* fd_ref_table[MAX_DESCRIPTORS];
94 Server* MyServer = new Server;
95 ServerConfig *Config = new ServerConfig;
100 servernamelist servernames;
103 void AddServerName(std::string servername)
105 log(DEBUG,"Adding server name: %s",servername.c_str());
106 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
108 if (*a == servername)
111 servernames.push_back(servername);
114 const char* FindServerNamePtr(std::string servername)
116 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
118 if (*a == servername)
121 AddServerName(servername);
122 return FindServerNamePtr(servername);
125 bool FindServerName(std::string servername)
127 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
129 if (*a == servername)
135 std::string InspIRCd::GetRevision()
140 void InspIRCd::MakeLowerMap()
142 // initialize the lowercase mapping table
143 for (unsigned int cn = 0; cn < 256; cn++)
145 // lowercase the uppercase chars
146 for (unsigned int cn = 65; cn < 91; cn++)
147 lowermap[cn] = tolower(cn);
148 // now replace the specific chars for scandanavian comparison
149 lowermap[(unsigned)'['] = '{';
150 lowermap[(unsigned)']'] = '}';
151 lowermap[(unsigned)'\\'] = '|';
154 InspIRCd::InspIRCd(int argc, char** argv)
157 module_sockets.clear();
158 this->startup_time = time(NULL);
160 log(DEBUG,"*** InspIRCd starting up!");
161 if (!FileExists(CONFIG_FILE))
163 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
164 log(DEFAULT,"main: no config");
165 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
170 for (int i = 1; i < argc; i++)
172 if (!strcmp(argv[i],"-nofork"))
174 Config->nofork = true;
176 else if(!strcmp(argv[i],"-debug"))
178 Config->forcedebug = true;
180 else if(!strcmp(argv[i],"-nolog"))
182 Config->writelog = false;
184 else if (!strcmp(argv[i],"-wait"))
188 else if (!strcmp(argv[i],"-nolimit"))
190 printf("WARNING: The `-nolimit' option is deprecated, and now on by default. This behaviour may change in the future.\n");
192 else if (!strcmp(argv[i],"-logfile"))
196 strlcpy(LOG_FILE,argv[i+1],MAXBUF);
197 printf("LOG: Setting logfile to %s\n",LOG_FILE);
201 printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
208 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
210 this->MakeLowerMap();
213 this->stats = new serverstats();
214 Config->ClearStack();
215 Config->Read(true,NULL);
217 this->ModeGrok = new ModeParser();
218 this->Parser = new CommandParser();
219 AddServerName(Config->ServerName);
221 stats->BoundPortCount = BindPorts(true);
223 for(int t = 0; t < 255; t++)
224 Config->global_implementation[t] = 0;
226 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
234 printf("ERROR: could not go into daemon mode. Shutting down.\n");
239 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
240 * initialize the socket engine.
242 SE = new SocketEngine();
244 /* We must load the modules AFTER initializing the socket engine, now */
249 std::string InspIRCd::GetVersionString()
251 char versiondata[MAXBUF];
253 char dnsengine[] = "multithread";
255 char dnsengine[] = "singlethread";
257 if (*Config->CustomVersion)
259 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
263 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%lu,%s,%s]",VERSION,Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
268 char* InspIRCd::ModuleError()
273 void InspIRCd::erase_factory(int j)
276 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
281 factory.push_back(NULL);
288 void InspIRCd::erase_module(int j)
291 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
297 modules.push_back(NULL);
303 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
307 Config->module_names.erase(v);
315 void InspIRCd::MoveTo(std::string modulename,int slot)
317 unsigned int v2 = 256;
318 for (unsigned int v = 0; v < Config->module_names.size(); v++)
320 if (Config->module_names[v] == modulename)
322 // found an instance, swap it with the item at MODCOUNT
327 if ((v2 != (unsigned int)slot) && (v2 < 256))
329 // Swap the module names over
330 Config->module_names[v2] = Config->module_names[slot];
331 Config->module_names[slot] = modulename;
332 // now swap the module factories
333 ircd_module* temp = factory[v2];
334 factory[v2] = factory[slot];
335 factory[slot] = temp;
336 // now swap the module objects
337 Module* temp_module = modules[v2];
338 modules[v2] = modules[slot];
339 modules[slot] = temp_module;
340 // now swap the implement lists (we dont
341 // need to swap the global or recount it)
342 for (int n = 0; n < 255; n++)
344 char x = Config->implement_lists[v2][n];
345 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
346 Config->implement_lists[slot][n] = x;
351 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
355 void InspIRCd::MoveAfter(std::string modulename, std::string after)
357 for (unsigned int v = 0; v < Config->module_names.size(); v++)
359 if (Config->module_names[v] == after)
361 MoveTo(modulename, v);
367 void InspIRCd::MoveBefore(std::string modulename, std::string before)
369 for (unsigned int v = 0; v < Config->module_names.size(); v++)
371 if (Config->module_names[v] == before)
375 MoveTo(modulename, v-1);
379 MoveTo(modulename, v);
386 void InspIRCd::MoveToFirst(std::string modulename)
388 MoveTo(modulename,0);
391 void InspIRCd::MoveToLast(std::string modulename)
393 MoveTo(modulename,MODCOUNT);
396 void InspIRCd::BuildISupport()
398 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
400 v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
401 v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
402 v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC NETWORK=" << Config->Network << " MAXPARA=32";
403 Config->data005 = v.str();
404 FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
407 bool InspIRCd::UnloadModule(const char* filename)
409 std::string filename_str = filename;
410 for (unsigned int j = 0; j != Config->module_names.size(); j++)
412 if (Config->module_names[j] == filename_str)
414 if (modules[j]->GetVersion().Flags & VF_STATIC)
416 log(DEFAULT,"Failed to unload STATIC module %s",filename);
417 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
420 /* Give the module a chance to tidy out all its metadata */
421 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
423 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
425 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
427 modules[j]->OnCleanup(TYPE_USER,u->second);
430 FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
432 for(int t = 0; t < 255; t++)
434 Config->global_implementation[t] -= Config->implement_lists[j][t];
437 /* We have to renumber implement_lists after unload because the module numbers change!
439 for(int j2 = j; j2 < 254; j2++)
441 for(int t = 0; t < 255; t++)
443 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
448 log(DEBUG,"Deleting module...");
450 log(DEBUG,"Erasing module entry...");
452 log(DEBUG,"Removing dependent commands...");
453 Parser->RemoveCommands(filename);
454 log(DEFAULT,"Module %s unloaded",filename);
460 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
461 snprintf(MODERR,MAXBUF,"Module not loaded");
465 bool InspIRCd::LoadModule(const char* filename)
467 char modfile[MAXBUF];
469 strlcpy(modfile,filename,MAXBUF);
471 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
473 std::string filename_str = filename;
476 if (!DirValid(modfile))
478 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
479 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
484 log(DEBUG,"Loading module: %s",modfile);
486 if (FileExists(modfile))
489 for (unsigned int j = 0; j < Config->module_names.size(); j++)
491 if (Config->module_names[j] == filename_str)
493 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
494 snprintf(MODERR,MAXBUF,"Module already loaded");
498 ircd_module* a = new ircd_module(modfile);
499 factory[MODCOUNT+1] = a;
500 if (factory[MODCOUNT+1]->LastError())
502 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
503 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
508 if (factory[MODCOUNT+1]->factory)
510 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
511 modules[MODCOUNT+1] = m;
512 /* save the module and the module's classfactory, if
513 * this isnt done, random crashes can occur :/ */
514 Config->module_names.push_back(filename);
516 char* x = &Config->implement_lists[MODCOUNT+1][0];
517 for(int t = 0; t < 255; t++)
520 modules[MODCOUNT+1]->Implements(x);
522 for(int t = 0; t < 255; t++)
523 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
527 log(DEFAULT,"Unable to load %s",modfile);
528 snprintf(MODERR,MAXBUF,"Factory function failed!");
532 catch (ModuleException& modexcept)
534 log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
535 snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
542 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
543 snprintf(MODERR,MAXBUF,"Module file could not be found");
548 FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
549 // now work out which modules, if any, want to move to the back of the queue,
550 // and if they do, move them there.
551 std::vector<std::string> put_to_back;
552 std::vector<std::string> put_to_front;
553 std::map<std::string,std::string> put_before;
554 std::map<std::string,std::string> put_after;
555 for (unsigned int j = 0; j < Config->module_names.size(); j++)
557 if (modules[j]->Prioritize() == PRIORITY_LAST)
559 put_to_back.push_back(Config->module_names[j]);
561 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
563 put_to_front.push_back(Config->module_names[j]);
565 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
567 put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
569 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
571 put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
574 for (unsigned int j = 0; j < put_to_back.size(); j++)
576 MoveToLast(put_to_back[j]);
578 for (unsigned int j = 0; j < put_to_front.size(); j++)
580 MoveToFirst(put_to_front[j]);
582 for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
584 MoveBefore(j->first,j->second);
586 for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
588 MoveAfter(j->first,j->second);
594 void InspIRCd::DoOneIteration(bool process_module_sockets)
596 int activefds[MAX_DESCRIPTORS];
600 InspSocket* s = NULL;
601 InspSocket* s_del = NULL;
602 unsigned int numberactive;
603 insp_sockaddr sock_us; // our port number
604 socklen_t uslen; // length of our port number
606 if (yield_depth > 100)
611 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
612 * Once per loop iteration is pleanty.
617 /* Run background module timers every few seconds
618 * (the docs say modules shouldnt rely on accurate
619 * timing using this event, so we dont have to
620 * time this exactly).
622 if (((TIME % 5) == 0) && (!expire_run))
625 if (process_module_sockets)
627 /* Fix by brain - the addition of DoOneIteration means that this
628 * can end up getting called recursively in the following pattern:
630 * m_spanningtree DoPingChecks
631 * (server pings out and is squit)
632 * (squit causes call to DoOneIteration)
633 * DoOneIteration enters here
634 * calls DoBackground timer
635 * enters m_spanningtree DoPingChecks... see step 1.
637 * This should do the job and fix the bug.
639 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
641 TickMissedTimers(TIME);
646 else if ((TIME % 5) == 1)
651 if (iterations++ == 15)
654 DoBackgroundUserStuff(TIME);
657 /* Once a second, do the background processing */
661 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
662 if ((TIME % 3600) == 0)
664 MaintainWhoWas(TIME);
668 /* Process timeouts on module sockets each time around
669 * the loop. There shouldnt be many module sockets, at
670 * most, 20 or so, so this won't be much of a performance
673 if (process_module_sockets)
674 DoSocketTimeouts(TIME);
678 /* Call the socket engine to wait on the active
679 * file descriptors. The socket engine has everything's
680 * descriptors in its list... dns, modules, users,
681 * servers... so its nice and easy, just one call.
683 if (!(numberactive = SE->Wait(activefds)))
690 * Now process each of the fd's. For users, we have a fast
691 * lookup table which can find a user by file descriptor, so
692 * processing them by fd isnt expensive. If we have a lot of
693 * listening ports or module sockets though, things could get
696 log(DEBUG,"There are %d fd's to process.",numberactive);
698 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
700 int socket_type = SE->GetType(activefds[activefd]);
705 log(DEBUG,"Type: X_ESTAB_CLIENT: fd=%d",activefds[activefd]);
706 cu = fd_ref_table[activefds[activefd]];
714 log(DEBUG,"Type: X_ESTAB_MODULE: fd=%d",activefds[activefd]);
716 if (!process_module_sockets)
719 /* Process module-owned sockets.
720 * Modules are encouraged to inherit their sockets from
721 * InspSocket so we can process them neatly like this.
723 s = socket_ref[activefds[activefd]];
725 if ((s) && (!s->Poll()))
727 log(DEBUG,"inspircd.cpp: Socket poll returned false, close and bail");
728 SE->DelFd(s->GetFd());
729 socket_ref[activefds[activefd]] = NULL;
730 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
732 s_del = (InspSocket*)*a;
733 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
735 module_sockets.erase(a);
744 log(DEBUG,"WTF, X_ESTAB_MODULE for nonexistent InspSocket, removed!");
745 SE->DelFd(s->GetFd());
750 /* When we are using single-threaded dns,
751 * the sockets for dns end up in our mainloop.
752 * When we are using multi-threaded dns,
753 * each thread has its own basic poll() loop
754 * within it, making them 'fire and forget'
755 * and independent of the mainloop.
758 log(DEBUG,"Type: X_ESTAB_DNS: fd=%d",activefds[activefd]);
759 dns_poll(activefds[activefd]);
765 log(DEBUG,"Type: X_LISTEN_MODULE: fd=%d",activefds[activefd]);
767 /* It's a listener */
768 uslen = sizeof(sock_us);
769 length = sizeof(client);
770 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
772 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
774 in_port = ntohs(sock_us.sin_port);
775 log(DEBUG,"Accepted socket %d",incomingSockfd);
776 /* Years and years ago, we used to resolve here
777 * using gethostbyaddr(). That is sucky and we
778 * don't do that any more...
780 NonBlocking(incomingSockfd);
781 if (Config->GetIOHook(in_port))
785 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
787 catch (ModuleException& modexcept)
789 log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
792 stats->statsAccept++;
793 AddClient(incomingSockfd, in_port, false, client.sin_addr);
794 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
798 log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
799 shutdown(incomingSockfd,2);
800 close(incomingSockfd);
801 stats->statsRefused++;
806 /* Something went wrong if we're in here.
807 * In fact, so wrong, im not quite sure
808 * what we would do, so for now, its going
809 * to safely do bugger all.
811 log(DEBUG,"Type: X_WHAT_THE_FUCK_BBQ: fd=%d",activefds[activefd]);
812 SE->DelFd(activefds[activefd]);
821 /* Until THIS point, ServerInstance == NULL */
823 LoadAllModules(this);
825 /* Just in case no modules were loaded - fix for bug #101 */
826 this->BuildISupport();
828 printf("\nInspIRCd is now running!\n");
837 /* Add the listening sockets used for client inbound connections
838 * to the socket engine
840 for (int count = 0; count < stats->BoundPortCount; count++)
841 SE->AddFd(openSockfd[count],true,X_LISTEN);
843 WritePID(Config->PID);
845 /* main loop, this never returns */
852 DoOneIteration(true);
854 /* This is never reached -- we hope! */
858 /**********************************************************************************/
861 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
864 int main(int argc, char** argv)
868 ServerInstance = new InspIRCd(argc, argv);
869 ServerInstance->Run();
870 delete ServerInstance;
872 catch (std::bad_alloc)
874 log(DEFAULT,"You are out of memory! (got exception std::bad_alloc!)");
875 send_error("**** OUT OF MEMORY **** We're gonna need a bigger boat!");
876 printf("Out of memory! (got exception std::bad_alloc!");