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>
54 #include "inspstring.h"
56 #include "helperfuncs.h"
58 #include "socketengine.h"
59 #include "userprocess.h"
63 #include "command_parse.h"
65 InspIRCd* ServerInstance;
67 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
68 int WHOWAS_MAX = 100; // default 100 people maximum in the WHOWAS list
70 extern std::vector<Module*> modules;
71 extern std::vector<ircd_module*> factory;
72 std::vector<InspSocket*> module_sockets;
73 std::vector<userrec*> local_users;
76 int openSockfd[MAXSOCKS];
77 sockaddr_in client,server;
79 extern Module* IOHookModule;
81 extern InspSocket* socket_ref[65535];
83 time_t TIME = time(NULL), OLDTIME = time(NULL);
85 SocketEngine* SE = NULL;
87 // This table references users by file descriptor.
88 // its an array to make it VERY fast, as all lookups are referenced
89 // by an integer, meaning there is no need for a scan/search operation.
90 userrec* fd_ref_table[65536];
92 Server* MyServer = new Server;
93 ServerConfig *Config = new ServerConfig;
98 servernamelist servernames;
101 void AddServerName(std::string servername)
103 log(DEBUG,"Adding server name: %s",servername.c_str());
104 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
106 if (*a == servername)
109 servernames.push_back(servername);
112 const char* FindServerNamePtr(std::string servername)
114 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
116 if (*a == servername)
119 AddServerName(servername);
120 return FindServerNamePtr(servername);
123 std::string InspIRCd::GetRevision()
125 /* w00t got me to replace a bunch of strtok_r
126 * with something nicer, so i did this. Its the
127 * same thing really, only in C++. It places the
128 * text into a std::stringstream which is a readable
129 * and writeable buffer stream, and then pops two
130 * words off it, space delimited. Because it reads
131 * into the same variable twice, the first word
132 * is discarded, and the second one returned.
134 std::stringstream Revision("$Revision$");
136 Revision >> single >> single;
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");
169 for (int i = 1; i < argc; i++)
171 if (!strcmp(argv[i],"-nofork")) {
172 Config->nofork = true;
174 if (!strcmp(argv[i],"-wait")) {
177 if (!strcmp(argv[i],"-nolimit")) {
178 Config->unlimitcore = true;
183 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
185 this->MakeLowerMap();
188 Config->ClearStack();
189 Config->Read(true,NULL);
191 this->ModeGrok = new ModeParser();
192 this->Parser = new CommandParser();
193 this->stats = new serverstats();
194 AddServerName(Config->ServerName);
196 stats->BoundPortCount = BindPorts();
201 if (DaemonSeed() == ERROR)
203 printf("ERROR: could not go into daemon mode. Shutting down.\n");
208 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
209 * initialize the socket engine.
211 SE = new SocketEngine();
213 /* We must load the modules AFTER initializing the socket engine, now */
218 std::string InspIRCd::GetVersionString()
220 char versiondata[MAXBUF];
222 char dnsengine[] = "multithread";
224 char dnsengine[] = "singlethread";
226 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);
230 char* InspIRCd::ModuleError()
235 void InspIRCd::erase_factory(int j)
238 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
243 factory.push_back(NULL);
250 void InspIRCd::erase_module(int j)
253 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
259 modules.push_back(NULL);
265 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
269 Config->module_names.erase(v);
277 bool InspIRCd::UnloadModule(const char* filename)
279 std::string filename_str = filename;
280 for (unsigned int j = 0; j != Config->module_names.size(); j++)
282 if (Config->module_names[j] == filename_str)
284 if (modules[j]->GetVersion().Flags & VF_STATIC)
286 log(DEFAULT,"Failed to unload STATIC module %s",filename);
287 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
290 /* Give the module a chance to tidy out all its metadata */
291 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
293 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
295 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
297 modules[j]->OnCleanup(TYPE_USER,u->second);
299 FOREACH_MOD OnUnloadModule(modules[j],Config->module_names[j]);
301 log(DEBUG,"Deleting module...");
303 log(DEBUG,"Erasing module entry...");
305 log(DEBUG,"Removing dependent commands...");
306 Parser->RemoveCommands(filename);
307 log(DEFAULT,"Module %s unloaded",filename);
312 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
313 snprintf(MODERR,MAXBUF,"Module not loaded");
317 bool InspIRCd::LoadModule(const char* filename)
319 char modfile[MAXBUF];
321 snprintf(modfile,MAXBUF,"%s",filename);
323 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
325 std::string filename_str = filename;
327 if (!DirValid(modfile))
329 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
330 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
334 log(DEBUG,"Loading module: %s",modfile);
336 if (FileExists(modfile))
339 for (unsigned int j = 0; j < Config->module_names.size(); j++)
341 if (Config->module_names[j] == filename_str)
343 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
344 snprintf(MODERR,MAXBUF,"Module already loaded");
348 ircd_module* a = new ircd_module(modfile);
349 factory[MODCOUNT+1] = a;
350 if (factory[MODCOUNT+1]->LastError())
352 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
353 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
357 if (factory[MODCOUNT+1]->factory)
359 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
360 modules[MODCOUNT+1] = m;
361 /* save the module and the module's classfactory, if
362 * this isnt done, random crashes can occur :/ */
363 Config->module_names.push_back(filename);
367 log(DEFAULT,"Unable to load %s",modfile);
368 snprintf(MODERR,MAXBUF,"Factory function failed!");
375 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
376 snprintf(MODERR,MAXBUF,"Module file could not be found");
381 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
387 bool expire_run = false;
388 std::vector<int> activefds;
392 InspSocket* s = NULL;
393 InspSocket* s_del = NULL;
395 unsigned int numberactive;
396 sockaddr_in sock_us; // our port number
397 socklen_t uslen; // length of our port number
399 /* Until THIS point, ServerInstance == NULL */
403 printf("\nInspIRCd is now running!\n");
407 freopen("/dev/null","w",stdout);
408 freopen("/dev/null","w",stderr);
411 /* Add the listening sockets used for client inbound connections
412 * to the socket engine
414 for (int count = 0; count < stats->BoundPortCount; count++)
415 SE->AddFd(openSockfd[count],true,X_LISTEN);
417 WritePID(Config->PID);
419 /* main loop, this never returns */
422 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
423 * Once per loop iteration is pleanty.
428 /* Run background module timers every few seconds
429 * (the docs say modules shouldnt rely on accurate
430 * timing using this event, so we dont have to
431 * time this exactly).
433 if (((TIME % 8) == 0) && (!expire_run))
436 FOREACH_MOD OnBackgroundTimer(TIME);
443 /* Once a second, do the background processing */
445 while (DoBackgroundUserStuff(TIME));
447 /* Call the socket engine to wait on the active
448 * file descriptors. The socket engine has everything's
449 * descriptors in its list... dns, modules, users,
450 * servers... so its nice and easy, just one call.
455 * Now process each of the fd's. For users, we have a fast
456 * lookup table which can find a user by file descriptor, so
457 * processing them by fd isnt expensive. If we have a lot of
458 * listening ports or module sockets though, things could get
461 numberactive = activefds.size();
462 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
464 int socket_type = SE->GetType(activefds[activefd]);
469 cu = fd_ref_table[activefds[activefd]];
477 /* Process module-owned sockets.
478 * Modules are encouraged to inherit their sockets from
479 * InspSocket so we can process them neatly like this.
481 s = socket_ref[activefds[activefd]];
483 if ((s) && (!s->Poll()))
485 log(DEBUG,"Socket poll returned false, close and bail");
486 SE->DelFd(s->GetFd());
487 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
489 s_del = (InspSocket*)*a;
490 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
492 module_sockets.erase(a);
504 /* When we are using single-threaded dns,
505 * the sockets for dns end up in our mainloop.
506 * When we are using multi-threaded dns,
507 * each thread has its own basic poll() loop
508 * within it, making them 'fire and forget'
509 * and independent of the mainloop.
512 dns_poll(activefds[activefd]);
518 /* It's a listener */
519 uslen = sizeof(sock_us);
520 length = sizeof(client);
521 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
522 if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
524 in_port = ntohs(sock_us.sin_port);
525 log(DEBUG,"Accepted socket %d",incomingSockfd);
526 target = (char*)inet_ntoa(client.sin_addr);
527 /* Years and years ago, we used to resolve here
528 * using gethostbyaddr(). That is sucky and we
529 * don't do that any more...
531 if (incomingSockfd >= 0)
535 IOHookModule->OnRawSocketAccept(incomingSockfd, target, in_port);
537 stats->statsAccept++;
538 AddClient(incomingSockfd, target, in_port, false, target);
539 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
543 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
544 log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
545 stats->statsRefused++;
550 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
551 shutdown(incomingSockfd,2);
552 close(incomingSockfd);
557 /* Something went wrong if we're in here.
558 * In fact, so wrong, im not quite sure
559 * what we would do, so for now, its going
560 * to safely do bugger all.
567 /* This is never reached -- we hope! */
571 /**********************************************************************************/
574 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
577 int main(int argc, char** argv)
579 ServerInstance = new InspIRCd(argc, argv);
580 ServerInstance->Run();
581 delete ServerInstance;