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 serverstats* stats = new serverstats;
93 Server* MyServer = new Server;
94 ServerConfig *Config = new ServerConfig;
95 CommandParser *Parser = NULL;
96 ModeParser *ModeGrok = NULL;
101 servernamelist servernames;
104 void AddServerName(std::string servername)
106 log(DEBUG,"Adding server name: %s",servername.c_str());
107 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
109 if (*a == servername)
112 servernames.push_back(servername);
115 const char* FindServerNamePtr(std::string servername)
117 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
119 if (*a == servername)
122 AddServerName(servername);
123 return FindServerNamePtr(servername);
126 std::string InspIRCd::GetRevision()
128 /* w00t got me to replace a bunch of strtok_r
129 * with something nicer, so i did this. Its the
130 * same thing really, only in C++. It places the
131 * text into a std::stringstream which is a readable
132 * and writeable buffer stream, and then pops two
133 * words off it, space delimited. Because it reads
134 * into the same variable twice, the first word
135 * is discarded, and the second one returned.
137 std::stringstream Revision("$Revision$");
139 Revision >> single >> single;
145 InspIRCd::InspIRCd(int argc, char** argv)
148 module_sockets.clear();
149 this->startup_time = time(NULL);
151 log(DEBUG,"*** InspIRCd starting up!");
152 if (!FileExists(CONFIG_FILE))
154 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
155 log(DEFAULT,"main: no config");
156 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
160 for (int i = 1; i < argc; i++)
162 if (!strcmp(argv[i],"-nofork")) {
163 Config->nofork = true;
165 if (!strcmp(argv[i],"-wait")) {
168 if (!strcmp(argv[i],"-nolimit")) {
169 Config->unlimitcore = true;
174 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
176 // initialize the lowercase mapping table
177 for (unsigned int cn = 0; cn < 256; cn++)
179 // lowercase the uppercase chars
180 for (unsigned int cn = 65; cn < 91; cn++)
181 lowermap[cn] = tolower(cn);
182 // now replace the specific chars for scandanavian comparison
183 lowermap[(unsigned)'['] = '{';
184 lowermap[(unsigned)']'] = '}';
185 lowermap[(unsigned)'\\'] = '|';
189 Config->ClearStack();
190 Config->Read(true,NULL);
192 ModeGrok = new ModeParser();
193 Parser = new CommandParser();
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 */
216 printf("\nInspIRCd is now running!\n");
221 std::string InspIRCd::GetVersionString()
223 char versiondata[MAXBUF];
225 char dnsengine[] = "multithread";
227 char dnsengine[] = "singlethread";
229 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);
233 char* InspIRCd::ModuleError()
238 void InspIRCd::erase_factory(int j)
241 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
246 factory.push_back(NULL);
253 void InspIRCd::erase_module(int j)
256 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
262 modules.push_back(NULL);
268 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
272 Config->module_names.erase(v);
280 bool InspIRCd::UnloadModule(const char* filename)
282 std::string filename_str = filename;
283 for (unsigned int j = 0; j != Config->module_names.size(); j++)
285 if (Config->module_names[j] == filename_str)
287 if (modules[j]->GetVersion().Flags & VF_STATIC)
289 log(DEFAULT,"Failed to unload STATIC module %s",filename);
290 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
293 /* Give the module a chance to tidy out all its metadata */
294 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
296 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
298 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
300 modules[j]->OnCleanup(TYPE_USER,u->second);
302 FOREACH_MOD OnUnloadModule(modules[j],Config->module_names[j]);
304 log(DEBUG,"Deleting module...");
306 log(DEBUG,"Erasing module entry...");
308 log(DEBUG,"Removing dependent commands...");
309 Parser->RemoveCommands(filename);
310 log(DEFAULT,"Module %s unloaded",filename);
315 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
316 snprintf(MODERR,MAXBUF,"Module not loaded");
320 bool InspIRCd::LoadModule(const char* filename)
322 char modfile[MAXBUF];
324 snprintf(modfile,MAXBUF,"%s",filename);
326 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
328 std::string filename_str = filename;
330 if (!DirValid(modfile))
332 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
333 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
337 log(DEBUG,"Loading module: %s",modfile);
339 if (FileExists(modfile))
342 for (unsigned int j = 0; j < Config->module_names.size(); j++)
344 if (Config->module_names[j] == filename_str)
346 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
347 snprintf(MODERR,MAXBUF,"Module already loaded");
351 ircd_module* a = new ircd_module(modfile);
352 factory[MODCOUNT+1] = a;
353 if (factory[MODCOUNT+1]->LastError())
355 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
356 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
360 if (factory[MODCOUNT+1]->factory)
362 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
363 modules[MODCOUNT+1] = m;
364 /* save the module and the module's classfactory, if
365 * this isnt done, random crashes can occur :/ */
366 Config->module_names.push_back(filename);
370 log(DEFAULT,"Unable to load %s",modfile);
371 snprintf(MODERR,MAXBUF,"Factory function failed!");
378 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
379 snprintf(MODERR,MAXBUF,"Module file could not be found");
384 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
390 bool expire_run = false;
391 std::vector<int> activefds;
395 InspSocket* s = NULL;
396 InspSocket* s_del = NULL;
398 unsigned int numberactive;
399 sockaddr_in sock_us; // our port number
400 socklen_t uslen; // length of our port number
404 freopen("/dev/null","w",stdout);
405 freopen("/dev/null","w",stderr);
408 /* Add the listening sockets used for client inbound connections
409 * to the socket engine
411 for (int count = 0; count < stats->BoundPortCount; count++)
412 SE->AddFd(openSockfd[count],true,X_LISTEN);
414 WritePID(Config->PID);
416 /* main loop, this never returns */
419 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
420 * Once per loop iteration is pleanty.
425 /* Run background module timers every few seconds
426 * (the docs say modules shouldnt rely on accurate
427 * timing using this event, so we dont have to
428 * time this exactly).
430 if (((TIME % 8) == 0) && (!expire_run))
433 FOREACH_MOD OnBackgroundTimer(TIME);
440 /* Once a second, do the background processing */
442 while (DoBackgroundUserStuff(TIME));
444 /* Call the socket engine to wait on the active
445 * file descriptors. The socket engine has everything's
446 * descriptors in its list... dns, modules, users,
447 * servers... so its nice and easy, just one call.
452 * Now process each of the fd's. For users, we have a fast
453 * lookup table which can find a user by file descriptor, so
454 * processing them by fd isnt expensive. If we have a lot of
455 * listening ports or module sockets though, things could get
458 numberactive = activefds.size();
459 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
461 int socket_type = SE->GetType(activefds[activefd]);
466 cu = fd_ref_table[activefds[activefd]];
474 /* Process module-owned sockets.
475 * Modules are encouraged to inherit their sockets from
476 * InspSocket so we can process them neatly like this.
478 s = socket_ref[activefds[activefd]];
480 if ((s) && (!s->Poll()))
482 log(DEBUG,"Socket poll returned false, close and bail");
483 SE->DelFd(s->GetFd());
484 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
486 s_del = (InspSocket*)*a;
487 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
489 module_sockets.erase(a);
501 /* When we are using single-threaded dns,
502 * the sockets for dns end up in our mainloop.
503 * When we are using multi-threaded dns,
504 * each thread has its own basic poll() loop
505 * within it, making them 'fire and forget'
506 * and independent of the mainloop.
509 dns_poll(activefds[activefd]);
515 /* It's a listener */
516 uslen = sizeof(sock_us);
517 length = sizeof(client);
518 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
519 if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
521 in_port = ntohs(sock_us.sin_port);
522 log(DEBUG,"Accepted socket %d",incomingSockfd);
523 target = (char*)inet_ntoa(client.sin_addr);
524 /* Years and years ago, we used to resolve here
525 * using gethostbyaddr(). That is sucky and we
526 * don't do that any more...
528 if (incomingSockfd >= 0)
532 IOHookModule->OnRawSocketAccept(incomingSockfd, target, in_port);
534 stats->statsAccept++;
535 AddClient(incomingSockfd, target, in_port, false, target);
536 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
540 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
541 log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
542 stats->statsRefused++;
547 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
548 shutdown(incomingSockfd,2);
549 close(incomingSockfd);
554 /* Something went wrong if we're in here.
555 * In fact, so wrong, im not quite sure
556 * what we would do, so for now, its going
557 * to safely do bugger all.
564 /* This is never reached -- we hope! */
568 /**********************************************************************************/
571 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
574 int main(int argc, char** argv)
576 ServerInstance = new InspIRCd(argc, argv);
577 ServerInstance->Run();
578 delete ServerInstance;