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;
70 std::vector<InspSocket*> module_sockets;
71 std::vector<userrec*> local_users;
74 int openSockfd[MAXSOCKS];
75 sockaddr_in client,server;
78 extern InspSocket* socket_ref[65535];
80 time_t TIME = time(NULL), OLDTIME = time(NULL);
82 SocketEngine* SE = NULL;
84 // This table references users by file descriptor.
85 // its an array to make it VERY fast, as all lookups are referenced
86 // by an integer, meaning there is no need for a scan/search operation.
87 userrec* fd_ref_table[65536];
89 Server* MyServer = new Server;
90 ServerConfig *Config = new ServerConfig;
95 servernamelist servernames;
98 void AddServerName(std::string servername)
100 log(DEBUG,"Adding server name: %s",servername.c_str());
101 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
103 if (*a == servername)
106 servernames.push_back(servername);
109 const char* FindServerNamePtr(std::string servername)
111 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
113 if (*a == servername)
116 AddServerName(servername);
117 return FindServerNamePtr(servername);
120 std::string InspIRCd::GetRevision()
122 /* w00t got me to replace a bunch of strtok_r
123 * with something nicer, so i did this. Its the
124 * same thing really, only in C++. It places the
125 * text into a std::stringstream which is a readable
126 * and writeable buffer stream, and then pops two
127 * words off it, space delimited. Because it reads
128 * into the same variable twice, the first word
129 * is discarded, and the second one returned.
131 std::stringstream Revision("$Revision$");
133 Revision >> single >> single;
137 void InspIRCd::MakeLowerMap()
139 // initialize the lowercase mapping table
140 for (unsigned int cn = 0; cn < 256; cn++)
142 // lowercase the uppercase chars
143 for (unsigned int cn = 65; cn < 91; cn++)
144 lowermap[cn] = tolower(cn);
145 // now replace the specific chars for scandanavian comparison
146 lowermap[(unsigned)'['] = '{';
147 lowermap[(unsigned)']'] = '}';
148 lowermap[(unsigned)'\\'] = '|';
151 InspIRCd::InspIRCd(int argc, char** argv)
154 module_sockets.clear();
155 this->startup_time = time(NULL);
157 log(DEBUG,"*** InspIRCd starting up!");
158 if (!FileExists(CONFIG_FILE))
160 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
161 log(DEFAULT,"main: no config");
162 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
166 for (int i = 1; i < argc; i++)
168 if (!strcmp(argv[i],"-nofork")) {
169 Config->nofork = true;
171 if (!strcmp(argv[i],"-wait")) {
174 if (!strcmp(argv[i],"-nolimit")) {
175 Config->unlimitcore = true;
180 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
182 this->MakeLowerMap();
185 Config->ClearStack();
186 Config->Read(true,NULL);
188 this->ModeGrok = new ModeParser();
189 this->Parser = new CommandParser();
190 this->stats = new serverstats();
191 AddServerName(Config->ServerName);
193 stats->BoundPortCount = BindPorts();
198 if (DaemonSeed() == ERROR)
200 printf("ERROR: could not go into daemon mode. Shutting down.\n");
205 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
206 * initialize the socket engine.
208 SE = new SocketEngine();
210 /* We must load the modules AFTER initializing the socket engine, now */
215 std::string InspIRCd::GetVersionString()
217 char versiondata[MAXBUF];
219 char dnsengine[] = "multithread";
221 char dnsengine[] = "singlethread";
223 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);
227 char* InspIRCd::ModuleError()
232 void InspIRCd::erase_factory(int j)
235 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
240 factory.push_back(NULL);
247 void InspIRCd::erase_module(int j)
250 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
256 modules.push_back(NULL);
262 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
266 Config->module_names.erase(v);
274 bool InspIRCd::UnloadModule(const char* filename)
276 std::string filename_str = filename;
277 for (unsigned int j = 0; j != Config->module_names.size(); j++)
279 if (Config->module_names[j] == filename_str)
281 if (modules[j]->GetVersion().Flags & VF_STATIC)
283 log(DEFAULT,"Failed to unload STATIC module %s",filename);
284 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
287 /* Give the module a chance to tidy out all its metadata */
288 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
290 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
292 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
294 modules[j]->OnCleanup(TYPE_USER,u->second);
296 FOREACH_MOD OnUnloadModule(modules[j],Config->module_names[j]);
298 log(DEBUG,"Deleting module...");
300 log(DEBUG,"Erasing module entry...");
302 log(DEBUG,"Removing dependent commands...");
303 Parser->RemoveCommands(filename);
304 log(DEFAULT,"Module %s unloaded",filename);
309 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
310 snprintf(MODERR,MAXBUF,"Module not loaded");
314 bool InspIRCd::LoadModule(const char* filename)
316 char modfile[MAXBUF];
318 snprintf(modfile,MAXBUF,"%s",filename);
320 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
322 std::string filename_str = filename;
324 if (!DirValid(modfile))
326 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
327 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
331 log(DEBUG,"Loading module: %s",modfile);
333 if (FileExists(modfile))
336 for (unsigned int j = 0; j < Config->module_names.size(); j++)
338 if (Config->module_names[j] == filename_str)
340 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
341 snprintf(MODERR,MAXBUF,"Module already loaded");
345 ircd_module* a = new ircd_module(modfile);
346 factory[MODCOUNT+1] = a;
347 if (factory[MODCOUNT+1]->LastError())
349 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
350 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
354 if (factory[MODCOUNT+1]->factory)
356 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
357 modules[MODCOUNT+1] = m;
358 /* save the module and the module's classfactory, if
359 * this isnt done, random crashes can occur :/ */
360 Config->module_names.push_back(filename);
364 log(DEFAULT,"Unable to load %s",modfile);
365 snprintf(MODERR,MAXBUF,"Factory function failed!");
372 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
373 snprintf(MODERR,MAXBUF,"Module file could not be found");
378 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
384 bool expire_run = false;
385 std::vector<int> activefds;
389 InspSocket* s = NULL;
390 InspSocket* s_del = NULL;
392 unsigned int numberactive;
393 sockaddr_in sock_us; // our port number
394 socklen_t uslen; // length of our port number
396 /* Until THIS point, ServerInstance == NULL */
398 LoadAllModules(this);
400 printf("\nInspIRCd is now running!\n");
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)
530 NonBlocking(incomingSockfd);
531 if (Config->GetIOHook(in_port))
533 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, target, in_port);
535 stats->statsAccept++;
536 AddClient(incomingSockfd, target, in_port, false, target);
537 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
541 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
542 log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
543 stats->statsRefused++;
548 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
549 shutdown(incomingSockfd,2);
550 close(incomingSockfd);
555 /* Something went wrong if we're in here.
556 * In fact, so wrong, im not quite sure
557 * what we would do, so for now, its going
558 * to safely do bugger all.
565 /* This is never reached -- we hope! */
569 /**********************************************************************************/
572 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
575 int main(int argc, char** argv)
577 ServerInstance = new InspIRCd(argc, argv);
578 ServerInstance->Run();
579 delete ServerInstance;