1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * Inspire is copyright (C) 2002-2005 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[65535];
81 time_t TIME = time(NULL), OLDTIME = time(NULL);
83 SocketEngine* SE = 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[65536];
90 Server* MyServer = new Server;
91 ServerConfig *Config = new ServerConfig;
96 servernamelist servernames;
99 void AddServerName(std::string servername)
101 log(DEBUG,"Adding server name: %s",servername.c_str());
102 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
104 if (*a == servername)
107 servernames.push_back(servername);
110 const char* FindServerNamePtr(std::string servername)
112 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
114 if (*a == servername)
117 AddServerName(servername);
118 return FindServerNamePtr(servername);
121 std::string InspIRCd::GetRevision()
123 /* w00t got me to replace a bunch of strtok_r
124 * with something nicer, so i did this. Its the
125 * same thing really, only in C++. It places the
126 * text into a std::stringstream which is a readable
127 * and writeable buffer stream, and then pops two
128 * words off it, space delimited. Because it reads
129 * into the same variable twice, the first word
130 * is discarded, and the second one returned.
132 std::stringstream Revision("$Revision$");
134 Revision >> single >> single;
138 void InspIRCd::MakeLowerMap()
140 // initialize the lowercase mapping table
141 for (unsigned int cn = 0; cn < 256; cn++)
143 // lowercase the uppercase chars
144 for (unsigned int cn = 65; cn < 91; cn++)
145 lowermap[cn] = tolower(cn);
146 // now replace the specific chars for scandanavian comparison
147 lowermap[(unsigned)'['] = '{';
148 lowermap[(unsigned)']'] = '}';
149 lowermap[(unsigned)'\\'] = '|';
152 InspIRCd::InspIRCd(int argc, char** argv)
155 module_sockets.clear();
156 this->startup_time = time(NULL);
158 log(DEBUG,"*** InspIRCd starting up!");
159 if (!FileExists(CONFIG_FILE))
161 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
162 log(DEFAULT,"main: no config");
163 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
167 for (int i = 1; i < argc; i++)
169 if (!strcmp(argv[i],"-nofork")) {
170 Config->nofork = true;
172 if (!strcmp(argv[i],"-wait")) {
175 if (!strcmp(argv[i],"-nolimit")) {
176 Config->unlimitcore = true;
181 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
183 this->MakeLowerMap();
186 Config->ClearStack();
187 Config->Read(true,NULL);
189 this->ModeGrok = new ModeParser();
190 this->Parser = new CommandParser();
191 this->stats = new serverstats();
192 AddServerName(Config->ServerName);
194 stats->BoundPortCount = BindPorts();
196 for(int t = 0; t < 255; t++)
197 Config->global_implementation[t] = 0;
199 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
205 if (DaemonSeed() == ERROR)
207 printf("ERROR: could not go into daemon mode. Shutting down.\n");
212 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
213 * initialize the socket engine.
215 SE = new SocketEngine();
217 /* We must load the modules AFTER initializing the socket engine, now */
222 std::string InspIRCd::GetVersionString()
224 char versiondata[MAXBUF];
226 char dnsengine[] = "multithread";
228 char dnsengine[] = "singlethread";
230 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);
234 char* InspIRCd::ModuleError()
239 void InspIRCd::erase_factory(int j)
242 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
247 factory.push_back(NULL);
254 void InspIRCd::erase_module(int j)
257 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
263 modules.push_back(NULL);
269 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
273 Config->module_names.erase(v);
281 bool InspIRCd::UnloadModule(const char* filename)
283 std::string filename_str = filename;
284 for (unsigned int j = 0; j != Config->module_names.size(); j++)
286 if (Config->module_names[j] == filename_str)
288 if (modules[j]->GetVersion().Flags & VF_STATIC)
290 log(DEFAULT,"Failed to unload STATIC module %s",filename);
291 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
294 /* Give the module a chance to tidy out all its metadata */
295 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
297 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
299 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
301 modules[j]->OnCleanup(TYPE_USER,u->second);
304 for(int t = 0; t < 255; t++)
306 Config->global_implementation[t] -= Config->implement_lists[j][t];
309 FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
311 log(DEBUG,"Deleting module...");
313 log(DEBUG,"Erasing module entry...");
315 log(DEBUG,"Removing dependent commands...");
316 Parser->RemoveCommands(filename);
317 log(DEFAULT,"Module %s unloaded",filename);
322 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
323 snprintf(MODERR,MAXBUF,"Module not loaded");
327 bool InspIRCd::LoadModule(const char* filename)
329 char modfile[MAXBUF];
331 snprintf(modfile,MAXBUF,"%s",filename);
333 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
335 std::string filename_str = filename;
337 if (!DirValid(modfile))
339 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
340 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
344 log(DEBUG,"Loading module: %s",modfile);
346 if (FileExists(modfile))
349 for (unsigned int j = 0; j < Config->module_names.size(); j++)
351 if (Config->module_names[j] == filename_str)
353 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
354 snprintf(MODERR,MAXBUF,"Module already loaded");
358 ircd_module* a = new ircd_module(modfile);
359 factory[MODCOUNT+1] = a;
360 if (factory[MODCOUNT+1]->LastError())
362 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
363 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
367 if (factory[MODCOUNT+1]->factory)
369 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
370 modules[MODCOUNT+1] = m;
371 /* save the module and the module's classfactory, if
372 * this isnt done, random crashes can occur :/ */
373 Config->module_names.push_back(filename);
375 char* x = &Config->implement_lists[MODCOUNT+1][0];
376 for(int t = 0; t < 255; t++)
379 modules[MODCOUNT+1]->Implements(x);
381 for(int t = 0; t < 255; t++)
383 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
384 if (Config->implement_lists[MODCOUNT+1][t])
386 log(DEBUG,"Add global implementation: %d %d => %d",MODCOUNT+1,t,Config->global_implementation[t]);
392 log(DEFAULT,"Unable to load %s",modfile);
393 snprintf(MODERR,MAXBUF,"Factory function failed!");
400 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
401 snprintf(MODERR,MAXBUF,"Module file could not be found");
406 FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
412 bool expire_run = false;
413 int activefds[65535];
417 InspSocket* s = NULL;
418 InspSocket* s_del = NULL;
420 unsigned int numberactive;
421 sockaddr_in sock_us; // our port number
422 socklen_t uslen; // length of our port number
424 /* Until THIS point, ServerInstance == NULL */
426 LoadAllModules(this);
428 printf("\nInspIRCd is now running!\n");
432 freopen("/dev/null","w",stdout);
433 freopen("/dev/null","w",stderr);
436 /* Add the listening sockets used for client inbound connections
437 * to the socket engine
439 for (int count = 0; count < stats->BoundPortCount; count++)
440 SE->AddFd(openSockfd[count],true,X_LISTEN);
442 WritePID(Config->PID);
444 /* main loop, this never returns */
447 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
448 * Once per loop iteration is pleanty.
453 /* Run background module timers every few seconds
454 * (the docs say modules shouldnt rely on accurate
455 * timing using this event, so we dont have to
456 * time this exactly).
458 if (((TIME % 8) == 0) && (!expire_run))
461 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
465 else if ((TIME % 8) == 1)
470 /* Once a second, do the background processing */
471 if ((TIME != OLDTIME) && ((TIME % 2) == 0))
472 DoBackgroundUserStuff(TIME);
474 /* Call the socket engine to wait on the active
475 * file descriptors. The socket engine has everything's
476 * descriptors in its list... dns, modules, users,
477 * servers... so its nice and easy, just one call.
479 numberactive = SE->Wait(activefds);
484 log(DEBUG,"%d active fds this time around",numberactive);
487 * Now process each of the fd's. For users, we have a fast
488 * lookup table which can find a user by file descriptor, so
489 * processing them by fd isnt expensive. If we have a lot of
490 * listening ports or module sockets though, things could get
493 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
495 int socket_type = SE->GetType(activefds[activefd]);
500 cu = fd_ref_table[activefds[activefd]];
508 /* Process module-owned sockets.
509 * Modules are encouraged to inherit their sockets from
510 * InspSocket so we can process them neatly like this.
512 s = socket_ref[activefds[activefd]];
514 if ((s) && (!s->Poll()))
516 log(DEBUG,"Socket poll returned false, close and bail");
517 SE->DelFd(s->GetFd());
518 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
520 s_del = (InspSocket*)*a;
521 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
523 module_sockets.erase(a);
535 /* When we are using single-threaded dns,
536 * the sockets for dns end up in our mainloop.
537 * When we are using multi-threaded dns,
538 * each thread has its own basic poll() loop
539 * within it, making them 'fire and forget'
540 * and independent of the mainloop.
543 dns_poll(activefds[activefd]);
549 /* It's a listener */
550 uslen = sizeof(sock_us);
551 length = sizeof(client);
552 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
553 if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
555 in_port = ntohs(sock_us.sin_port);
556 log(DEBUG,"Accepted socket %d",incomingSockfd);
557 target = (char*)inet_ntoa(client.sin_addr);
558 /* Years and years ago, we used to resolve here
559 * using gethostbyaddr(). That is sucky and we
560 * don't do that any more...
562 if (incomingSockfd >= 0)
564 NonBlocking(incomingSockfd);
565 if (Config->GetIOHook(in_port))
567 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, target, in_port);
569 stats->statsAccept++;
570 AddClient(incomingSockfd, target, in_port, false, target);
571 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
575 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
576 log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
577 stats->statsRefused++;
582 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
583 shutdown(incomingSockfd,2);
584 close(incomingSockfd);
589 /* Something went wrong if we're in here.
590 * In fact, so wrong, im not quite sure
591 * what we would do, so for now, its going
592 * to safely do bugger all.
599 /* This is never reached -- we hope! */
603 /**********************************************************************************/
606 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
609 int main(int argc, char** argv)
611 ServerInstance = new InspIRCd(argc, argv);
612 ServerInstance->Run();
613 delete ServerInstance;