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"
26 #include <sys/errno.h>
27 #include <sys/ioctl.h>
28 #include <sys/utsname.h>
32 #include <ext/hash_map>
53 #include "inspstring.h"
55 #include "helperfuncs.h"
57 #include "socketengine.h"
58 #include "userprocess.h"
61 #include "command_parse.h"
63 InspIRCd* ServerInstance;
65 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
66 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
68 extern std::vector<Module*> modules;
69 extern std::vector<ircd_module*> factory;
71 std::vector<InspSocket*> module_sockets;
72 std::vector<userrec*> local_users;
75 int openSockfd[MAXSOCKS];
76 sockaddr_in client,server;
79 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
81 time_t TIME = time(NULL), OLDTIME = time(NULL);
83 // This table references users by file descriptor.
84 // its an array to make it VERY fast, as all lookups are referenced
85 // by an integer, meaning there is no need for a scan/search operation.
86 userrec* fd_ref_table[MAX_DESCRIPTORS];
88 Server* MyServer = new Server;
89 ServerConfig *Config = new ServerConfig;
94 servernamelist servernames;
97 void AddServerName(std::string servername)
99 log(DEBUG,"Adding server name: %s",servername.c_str());
100 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
102 if (*a == servername)
105 servernames.push_back(servername);
108 const char* FindServerNamePtr(std::string servername)
110 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
112 if (*a == servername)
115 AddServerName(servername);
116 return FindServerNamePtr(servername);
119 std::string InspIRCd::GetRevision()
121 /* w00t got me to replace a bunch of strtok_r
122 * with something nicer, so i did this. Its the
123 * same thing really, only in C++. It places the
124 * text into a std::stringstream which is a readable
125 * and writeable buffer stream, and then pops two
126 * words off it, space delimited. Because it reads
127 * into the same variable twice, the first word
128 * is discarded, and the second one returned.
130 std::stringstream Revision("$Revision$");
132 Revision >> single >> single;
136 void InspIRCd::MakeLowerMap()
138 // initialize the lowercase mapping table
139 for (unsigned int cn = 0; cn < 256; cn++)
141 // lowercase the uppercase chars
142 for (unsigned int cn = 65; cn < 91; cn++)
143 lowermap[cn] = tolower(cn);
144 // now replace the specific chars for scandanavian comparison
145 lowermap[(unsigned)'['] = '{';
146 lowermap[(unsigned)']'] = '}';
147 lowermap[(unsigned)'\\'] = '|';
150 InspIRCd::InspIRCd(int argc, char** argv)
153 module_sockets.clear();
154 this->startup_time = time(NULL);
156 log(DEBUG,"*** InspIRCd starting up!");
157 if (!FileExists(CONFIG_FILE))
159 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
160 log(DEFAULT,"main: no config");
161 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;
179 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
181 this->MakeLowerMap();
184 Config->ClearStack();
185 Config->Read(true,NULL);
187 this->ModeGrok = new ModeParser();
188 this->Parser = new CommandParser();
189 this->stats = new serverstats();
190 AddServerName(Config->ServerName);
192 stats->BoundPortCount = BindPorts();
194 for(int t = 0; t < 255; t++)
195 Config->global_implementation[t] = 0;
197 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
203 if (DaemonSeed() == ERROR)
205 printf("ERROR: could not go into daemon mode. Shutting down.\n");
210 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
211 * initialize the socket engine.
213 SE = new SocketEngine();
215 /* We must load the modules AFTER initializing the socket engine, now */
220 std::string InspIRCd::GetVersionString()
222 char versiondata[MAXBUF];
224 char dnsengine[] = "multithread";
226 char dnsengine[] = "singlethread";
228 if (*Config->CustomVersion)
230 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s",VERSION,GetRevision().c_str(),Config->ServerName,Config->CustomVersion);
234 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s [FLAGS=%lu,%s,%s]",VERSION,GetRevision().c_str(),Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
239 char* InspIRCd::ModuleError()
244 void InspIRCd::erase_factory(int j)
247 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
252 factory.push_back(NULL);
259 void InspIRCd::erase_module(int j)
262 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
268 modules.push_back(NULL);
274 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
278 Config->module_names.erase(v);
286 void InspIRCd::MoveTo(std::string modulename,int slot)
288 unsigned int v2 = 256;
289 log(DEBUG,"Moving %s to slot %d",modulename.c_str(),slot);
290 for (unsigned int v = 0; v < Config->module_names.size(); v++)
292 if (Config->module_names[v] == modulename)
294 // found an instance, swap it with the item at MODCOUNT
299 if (v2 == (unsigned int)slot)
301 log(DEBUG,"Item %s already in slot %d!",modulename.c_str(),slot);
305 // Swap the module names over
306 Config->module_names[v2] = Config->module_names[slot];
307 Config->module_names[slot] = modulename;
308 // now swap the module factories
309 ircd_module* temp = factory[v2];
310 factory[v2] = factory[slot];
311 factory[slot] = temp;
312 // now swap the module objects
313 Module* temp_module = modules[v2];
314 modules[v2] = modules[slot];
315 modules[slot] = temp_module;
316 // now swap the implement lists (we dont
317 // need to swap the global or recount it)
318 for (int n = 0; n < 255; n++)
320 char x = Config->implement_lists[v2][n];
321 Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
322 Config->implement_lists[slot][n] = x;
324 log(DEBUG,"Moved %s to slot successfully",modulename.c_str());
328 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
332 void InspIRCd::MoveToFirst(std::string modulename)
334 MoveTo(modulename,0);
337 void InspIRCd::MoveToLast(std::string modulename)
339 MoveTo(modulename,MODCOUNT);
342 void InspIRCd::BuildISupport()
344 // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
346 v << "WALLCHOPS MODES=13 CHANTYPES=# PREFIX=(ohv)@%+ MAP SAFELIST MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 NICKLEN=" << NICKMAX-1;
347 v << " CASEMAPPING=rfc1459 STATUSMSG=@+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=20 AWAYLEN=";
348 v << MAXAWAY << " CHANMODES=ohvb,k,l,psmnti NETWORK=" << Config->Network;
349 Config->data005 = v.str();
350 FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
353 bool InspIRCd::UnloadModule(const char* filename)
355 std::string filename_str = filename;
356 for (unsigned int j = 0; j != Config->module_names.size(); j++)
358 if (Config->module_names[j] == filename_str)
360 if (modules[j]->GetVersion().Flags & VF_STATIC)
362 log(DEFAULT,"Failed to unload STATIC module %s",filename);
363 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
366 /* Give the module a chance to tidy out all its metadata */
367 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
369 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
371 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
373 modules[j]->OnCleanup(TYPE_USER,u->second);
376 for(int t = 0; t < 255; t++)
378 Config->global_implementation[t] -= Config->implement_lists[j][t];
381 /* We have to renumber implement_lists after unload because the module numbers change!
383 for(int j2 = j; j2 < 254; j2++)
385 for(int t = 0; t < 255; t++)
387 Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
391 FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
393 log(DEBUG,"Deleting module...");
395 log(DEBUG,"Erasing module entry...");
397 log(DEBUG,"Removing dependent commands...");
398 Parser->RemoveCommands(filename);
399 log(DEFAULT,"Module %s unloaded",filename);
405 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
406 snprintf(MODERR,MAXBUF,"Module not loaded");
410 bool InspIRCd::LoadModule(const char* filename)
412 char modfile[MAXBUF];
414 strlcpy(modfile,filename,MAXBUF);
416 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
418 std::string filename_str = filename;
420 if (!DirValid(modfile))
422 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
423 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
427 log(DEBUG,"Loading module: %s",modfile);
429 if (FileExists(modfile))
432 for (unsigned int j = 0; j < Config->module_names.size(); j++)
434 if (Config->module_names[j] == filename_str)
436 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
437 snprintf(MODERR,MAXBUF,"Module already loaded");
441 ircd_module* a = new ircd_module(modfile);
442 factory[MODCOUNT+1] = a;
443 if (factory[MODCOUNT+1]->LastError())
445 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
446 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
450 if (factory[MODCOUNT+1]->factory)
452 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
453 modules[MODCOUNT+1] = m;
454 /* save the module and the module's classfactory, if
455 * this isnt done, random crashes can occur :/ */
456 Config->module_names.push_back(filename);
458 char* x = &Config->implement_lists[MODCOUNT+1][0];
459 for(int t = 0; t < 255; t++)
462 modules[MODCOUNT+1]->Implements(x);
464 for(int t = 0; t < 255; t++)
466 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
467 if (Config->implement_lists[MODCOUNT+1][t])
469 log(DEBUG,"Add global implementation: %d %d => %d",MODCOUNT+1,t,Config->global_implementation[t]);
475 log(DEFAULT,"Unable to load %s",modfile);
476 snprintf(MODERR,MAXBUF,"Factory function failed!");
483 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
484 snprintf(MODERR,MAXBUF,"Module file could not be found");
489 FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
490 // now work out which modules, if any, want to move to the back of the queue,
491 // and if they do, move them there.
492 std::vector<std::string> put_to_back;
493 std::vector<std::string> put_to_front;
494 for (unsigned int j = 0; j < Config->module_names.size(); j++)
496 if (modules[j]->Prioritize() == PRIORITY_LAST)
498 put_to_back.push_back(Config->module_names[j]);
500 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
502 put_to_front.push_back(Config->module_names[j]);
505 for (unsigned int j = 0; j < put_to_back.size(); j++)
507 MoveToLast(put_to_back[j]);
509 for (unsigned int j = 0; j < put_to_front.size(); j++)
511 MoveToFirst(put_to_front[j]);
519 bool expire_run = false;
520 int activefds[MAX_DESCRIPTORS];
524 InspSocket* s = NULL;
525 InspSocket* s_del = NULL;
527 unsigned int numberactive;
528 sockaddr_in sock_us; // our port number
529 socklen_t uslen; // length of our port number
531 /* Until THIS point, ServerInstance == NULL */
533 LoadAllModules(this);
535 printf("\nInspIRCd is now running!\n");
539 freopen("/dev/null","w",stdout);
540 freopen("/dev/null","w",stderr);
543 /* Add the listening sockets used for client inbound connections
544 * to the socket engine
546 for (int count = 0; count < stats->BoundPortCount; count++)
547 SE->AddFd(openSockfd[count],true,X_LISTEN);
549 WritePID(Config->PID);
551 /* main loop, this never returns */
554 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
555 * Once per loop iteration is pleanty.
560 /* Run background module timers every few seconds
561 * (the docs say modules shouldnt rely on accurate
562 * timing using this event, so we dont have to
563 * time this exactly).
565 if (((TIME % 8) == 0) && (!expire_run))
568 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
572 else if ((TIME % 8) == 1)
577 /* Once a second, do the background processing */
579 DoBackgroundUserStuff(TIME);
581 /* Call the socket engine to wait on the active
582 * file descriptors. The socket engine has everything's
583 * descriptors in its list... dns, modules, users,
584 * servers... so its nice and easy, just one call.
586 if (!(numberactive = SE->Wait(activefds)))
590 * Now process each of the fd's. For users, we have a fast
591 * lookup table which can find a user by file descriptor, so
592 * processing them by fd isnt expensive. If we have a lot of
593 * listening ports or module sockets though, things could get
596 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
598 int socket_type = SE->GetType(activefds[activefd]);
603 cu = fd_ref_table[activefds[activefd]];
611 /* Process module-owned sockets.
612 * Modules are encouraged to inherit their sockets from
613 * InspSocket so we can process them neatly like this.
615 s = socket_ref[activefds[activefd]];
617 if ((s) && (!s->Poll()))
619 log(DEBUG,"Socket poll returned false, close and bail");
620 SE->DelFd(s->GetFd());
621 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
623 s_del = (InspSocket*)*a;
624 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
626 module_sockets.erase(a);
638 /* When we are using single-threaded dns,
639 * the sockets for dns end up in our mainloop.
640 * When we are using multi-threaded dns,
641 * each thread has its own basic poll() loop
642 * within it, making them 'fire and forget'
643 * and independent of the mainloop.
646 dns_poll(activefds[activefd]);
652 /* It's a listener */
653 uslen = sizeof(sock_us);
654 length = sizeof(client);
655 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
657 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
659 in_port = ntohs(sock_us.sin_port);
660 log(DEBUG,"Accepted socket %d",incomingSockfd);
661 target = (char*)inet_ntoa(client.sin_addr);
662 /* Years and years ago, we used to resolve here
663 * using gethostbyaddr(). That is sucky and we
664 * don't do that any more...
666 NonBlocking(incomingSockfd);
667 if (Config->GetIOHook(in_port))
669 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, target, in_port);
671 stats->statsAccept++;
672 AddClient(incomingSockfd, target, in_port, false, target);
673 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
677 log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
678 shutdown(incomingSockfd,2);
679 close(incomingSockfd);
680 stats->statsRefused++;
685 /* Something went wrong if we're in here.
686 * In fact, so wrong, im not quite sure
687 * what we would do, so for now, its going
688 * to safely do bugger all.
695 /* This is never reached -- we hope! */
699 /**********************************************************************************/
702 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
705 int main(int argc, char** argv)
707 ServerInstance = new InspIRCd(argc, argv);
708 ServerInstance->Run();
709 delete ServerInstance;