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 = new CommandParser;
100 servernamelist servernames;
103 void AddServerName(std::string servername)
105 log(DEBUG,"Adding server name: %s",servername.c_str());
106 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
108 if (*a == servername)
111 servernames.push_back(servername);
114 const char* FindServerNamePtr(std::string servername)
116 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
118 if (*a == servername)
121 AddServerName(servername);
122 return FindServerNamePtr(servername);
125 std::string InspIRCd::GetRevision()
127 /* w00t got me to replace a bunch of strtok_r
128 * with something nicer, so i did this. Its the
129 * same thing really, only in C++. It places the
130 * text into a std::stringstream which is a readable
131 * and writeable buffer stream, and then pops two
132 * words off it, space delimited. Because it reads
133 * into the same variable twice, the first word
134 * is discarded, and the second one returned.
136 std::stringstream Revision("$Revision$");
138 Revision >> single >> single;
144 InspIRCd::InspIRCd(int argc, char** argv)
147 module_sockets.clear();
148 this->startup_time = time(NULL);
150 log(DEBUG,"*** InspIRCd starting up!");
151 if (!FileExists(CONFIG_FILE))
153 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
154 log(DEFAULT,"main: no config");
155 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
159 for (int i = 1; i < argc; i++)
161 if (!strcmp(argv[i],"-nofork")) {
162 Config->nofork = true;
164 if (!strcmp(argv[i],"-wait")) {
167 if (!strcmp(argv[i],"-nolimit")) {
168 Config->unlimitcore = true;
173 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
175 // initialize the lowercase mapping table
176 for (unsigned int cn = 0; cn < 256; cn++)
178 // lowercase the uppercase chars
179 for (unsigned int cn = 65; cn < 91; cn++)
180 lowermap[cn] = tolower(cn);
181 // now replace the specific chars for scandanavian comparison
182 lowermap[(unsigned)'['] = '{';
183 lowermap[(unsigned)']'] = '}';
184 lowermap[(unsigned)'\\'] = '|';
188 Config->ClearStack();
189 Config->Read(true,NULL);
192 AddServerName(Config->ServerName);
194 stats->BoundPortCount = BindPorts();
199 if (DaemonSeed() == ERROR)
201 printf("ERROR: could not go into daemon mode. Shutting down.\n");
206 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
207 * initialize the socket engine.
209 SE = new SocketEngine();
211 /* We must load the modules AFTER initializing the socket engine, now */
214 printf("\nInspIRCd is now running!\n");
219 std::string InspIRCd::GetVersionString()
221 char versiondata[MAXBUF];
223 char dnsengine[] = "multithread";
225 char dnsengine[] = "singlethread";
227 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);
231 char* InspIRCd::ModuleError()
236 void InspIRCd::erase_factory(int j)
239 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
244 factory.push_back(NULL);
251 void InspIRCd::erase_module(int j)
254 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
260 modules.push_back(NULL);
266 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
270 Config->module_names.erase(v);
278 bool InspIRCd::UnloadModule(const char* filename)
280 std::string filename_str = filename;
281 for (unsigned int j = 0; j != Config->module_names.size(); j++)
283 if (Config->module_names[j] == filename_str)
285 if (modules[j]->GetVersion().Flags & VF_STATIC)
287 log(DEFAULT,"Failed to unload STATIC module %s",filename);
288 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
291 /* Give the module a chance to tidy out all its metadata */
292 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
294 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
296 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
298 modules[j]->OnCleanup(TYPE_USER,u->second);
300 FOREACH_MOD OnUnloadModule(modules[j],Config->module_names[j]);
302 log(DEBUG,"Deleting module...");
304 log(DEBUG,"Erasing module entry...");
306 log(DEBUG,"Removing dependent commands...");
307 remove_commands(filename);
308 log(DEFAULT,"Module %s unloaded",filename);
313 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
314 snprintf(MODERR,MAXBUF,"Module not loaded");
318 bool InspIRCd::LoadModule(const char* filename)
320 char modfile[MAXBUF];
322 snprintf(modfile,MAXBUF,"%s",filename);
324 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
326 std::string filename_str = filename;
328 if (!DirValid(modfile))
330 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
331 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
335 log(DEBUG,"Loading module: %s",modfile);
337 if (FileExists(modfile))
340 for (unsigned int j = 0; j < Config->module_names.size(); j++)
342 if (Config->module_names[j] == filename_str)
344 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
345 snprintf(MODERR,MAXBUF,"Module already loaded");
349 ircd_module* a = new ircd_module(modfile);
350 factory[MODCOUNT+1] = a;
351 if (factory[MODCOUNT+1]->LastError())
353 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
354 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
358 if (factory[MODCOUNT+1]->factory)
360 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
361 modules[MODCOUNT+1] = m;
362 /* save the module and the module's classfactory, if
363 * this isnt done, random crashes can occur :/ */
364 Config->module_names.push_back(filename);
368 log(DEFAULT,"Unable to load %s",modfile);
369 snprintf(MODERR,MAXBUF,"Factory function failed!");
376 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
377 snprintf(MODERR,MAXBUF,"Module file could not be found");
382 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
388 bool expire_run = false;
389 std::vector<int> activefds;
393 InspSocket* s = NULL;
394 InspSocket* s_del = NULL;
396 unsigned int numberactive;
397 sockaddr_in sock_us; // our port number
398 socklen_t uslen; // length of our port number
402 freopen("/dev/null","w",stdout);
403 freopen("/dev/null","w",stderr);
406 /* Add the listening sockets used for client inbound connections
407 * to the socket engine
409 for (int count = 0; count < stats->BoundPortCount; count++)
410 SE->AddFd(openSockfd[count],true,X_LISTEN);
412 WritePID(Config->PID);
414 /* main loop, this never returns */
417 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
418 * Once per loop iteration is pleanty.
423 /* Run background module timers every few seconds
424 * (the docs say modules shouldnt rely on accurate
425 * timing using this event, so we dont have to
426 * time this exactly).
428 if (((TIME % 8) == 0) && (!expire_run))
431 FOREACH_MOD OnBackgroundTimer(TIME);
438 /* Once a second, do the background processing */
440 while (DoBackgroundUserStuff(TIME));
442 /* Call the socket engine to wait on the active
443 * file descriptors. The socket engine has everything's
444 * descriptors in its list... dns, modules, users,
445 * servers... so its nice and easy, just one call.
450 * Now process each of the fd's. For users, we have a fast
451 * lookup table which can find a user by file descriptor, so
452 * processing them by fd isnt expensive. If we have a lot of
453 * listening ports or module sockets though, things could get
456 numberactive = activefds.size();
457 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
459 int socket_type = SE->GetType(activefds[activefd]);
464 cu = fd_ref_table[activefds[activefd]];
472 /* Process module-owned sockets.
473 * Modules are encouraged to inherit their sockets from
474 * InspSocket so we can process them neatly like this.
476 s = socket_ref[activefds[activefd]];
478 if ((s) && (!s->Poll()))
480 log(DEBUG,"Socket poll returned false, close and bail");
481 SE->DelFd(s->GetFd());
482 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
484 s_del = (InspSocket*)*a;
485 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
487 module_sockets.erase(a);
499 /* When we are using single-threaded dns,
500 * the sockets for dns end up in our mainloop.
501 * When we are using multi-threaded dns,
502 * each thread has its own basic poll() loop
503 * within it, making them 'fire and forget'
504 * and independent of the mainloop.
507 dns_poll(activefds[activefd]);
513 /* It's a listener */
514 uslen = sizeof(sock_us);
515 length = sizeof(client);
516 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
517 if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
519 in_port = ntohs(sock_us.sin_port);
520 log(DEBUG,"Accepted socket %d",incomingSockfd);
521 target = (char*)inet_ntoa(client.sin_addr);
522 /* Years and years ago, we used to resolve here
523 * using gethostbyaddr(). That is sucky and we
524 * don't do that any more...
526 if (incomingSockfd >= 0)
530 IOHookModule->OnRawSocketAccept(incomingSockfd, target, in_port);
532 stats->statsAccept++;
533 AddClient(incomingSockfd, target, in_port, false, target);
534 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
538 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
539 log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
540 stats->statsRefused++;
545 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
546 shutdown(incomingSockfd,2);
547 close(incomingSockfd);
552 /* Something went wrong if we're in here.
553 * In fact, so wrong, im not quite sure
554 * what we would do, so for now, its going
555 * to safely do bugger all.
562 /* This is never reached -- we hope! */
566 /**********************************************************************************/
569 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
572 int main(int argc, char** argv)
574 ServerInstance = new InspIRCd(argc, argv);
575 ServerInstance->Run();
576 delete ServerInstance;