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;
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);
191 Parser = new CommandParser;
192 Parser->SetupCommandTable();
193 AddServerName(Config->ServerName);
195 stats->BoundPortCount = BindPorts();
200 if (DaemonSeed() == ERROR)
202 printf("ERROR: could not go into daemon mode. Shutting down.\n");
207 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
208 * initialize the socket engine.
210 SE = new SocketEngine();
212 /* We must load the modules AFTER initializing the socket engine, now */
215 printf("\nInspIRCd is now running!\n");
220 std::string InspIRCd::GetVersionString()
222 char versiondata[MAXBUF];
224 char dnsengine[] = "multithread";
226 char dnsengine[] = "singlethread";
228 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);
232 char* InspIRCd::ModuleError()
237 void InspIRCd::erase_factory(int j)
240 for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
245 factory.push_back(NULL);
252 void InspIRCd::erase_module(int j)
255 for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
261 modules.push_back(NULL);
267 for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
271 Config->module_names.erase(v);
279 bool InspIRCd::UnloadModule(const char* filename)
281 std::string filename_str = filename;
282 for (unsigned int j = 0; j != Config->module_names.size(); j++)
284 if (Config->module_names[j] == filename_str)
286 if (modules[j]->GetVersion().Flags & VF_STATIC)
288 log(DEFAULT,"Failed to unload STATIC module %s",filename);
289 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
292 /* Give the module a chance to tidy out all its metadata */
293 for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
295 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
297 for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
299 modules[j]->OnCleanup(TYPE_USER,u->second);
301 FOREACH_MOD OnUnloadModule(modules[j],Config->module_names[j]);
303 log(DEBUG,"Deleting module...");
305 log(DEBUG,"Erasing module entry...");
307 log(DEBUG,"Removing dependent commands...");
308 Parser->RemoveCommands(filename);
309 log(DEFAULT,"Module %s unloaded",filename);
314 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
315 snprintf(MODERR,MAXBUF,"Module not loaded");
319 bool InspIRCd::LoadModule(const char* filename)
321 char modfile[MAXBUF];
323 snprintf(modfile,MAXBUF,"%s",filename);
325 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
327 std::string filename_str = filename;
329 if (!DirValid(modfile))
331 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
332 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
336 log(DEBUG,"Loading module: %s",modfile);
338 if (FileExists(modfile))
341 for (unsigned int j = 0; j < Config->module_names.size(); j++)
343 if (Config->module_names[j] == filename_str)
345 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
346 snprintf(MODERR,MAXBUF,"Module already loaded");
350 ircd_module* a = new ircd_module(modfile);
351 factory[MODCOUNT+1] = a;
352 if (factory[MODCOUNT+1]->LastError())
354 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
355 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
359 if (factory[MODCOUNT+1]->factory)
361 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
362 modules[MODCOUNT+1] = m;
363 /* save the module and the module's classfactory, if
364 * this isnt done, random crashes can occur :/ */
365 Config->module_names.push_back(filename);
369 log(DEFAULT,"Unable to load %s",modfile);
370 snprintf(MODERR,MAXBUF,"Factory function failed!");
377 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
378 snprintf(MODERR,MAXBUF,"Module file could not be found");
383 FOREACH_MOD OnLoadModule(modules[MODCOUNT],filename_str);
389 bool expire_run = false;
390 std::vector<int> activefds;
394 InspSocket* s = NULL;
395 InspSocket* s_del = NULL;
397 unsigned int numberactive;
398 sockaddr_in sock_us; // our port number
399 socklen_t uslen; // length of our port number
403 freopen("/dev/null","w",stdout);
404 freopen("/dev/null","w",stderr);
407 /* Add the listening sockets used for client inbound connections
408 * to the socket engine
410 for (int count = 0; count < stats->BoundPortCount; count++)
411 SE->AddFd(openSockfd[count],true,X_LISTEN);
413 WritePID(Config->PID);
415 /* main loop, this never returns */
418 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
419 * Once per loop iteration is pleanty.
424 /* Run background module timers every few seconds
425 * (the docs say modules shouldnt rely on accurate
426 * timing using this event, so we dont have to
427 * time this exactly).
429 if (((TIME % 8) == 0) && (!expire_run))
432 FOREACH_MOD OnBackgroundTimer(TIME);
439 /* Once a second, do the background processing */
441 while (DoBackgroundUserStuff(TIME));
443 /* Call the socket engine to wait on the active
444 * file descriptors. The socket engine has everything's
445 * descriptors in its list... dns, modules, users,
446 * servers... so its nice and easy, just one call.
451 * Now process each of the fd's. For users, we have a fast
452 * lookup table which can find a user by file descriptor, so
453 * processing them by fd isnt expensive. If we have a lot of
454 * listening ports or module sockets though, things could get
457 numberactive = activefds.size();
458 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
460 int socket_type = SE->GetType(activefds[activefd]);
465 cu = fd_ref_table[activefds[activefd]];
473 /* Process module-owned sockets.
474 * Modules are encouraged to inherit their sockets from
475 * InspSocket so we can process them neatly like this.
477 s = socket_ref[activefds[activefd]];
479 if ((s) && (!s->Poll()))
481 log(DEBUG,"Socket poll returned false, close and bail");
482 SE->DelFd(s->GetFd());
483 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
485 s_del = (InspSocket*)*a;
486 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
488 module_sockets.erase(a);
500 /* When we are using single-threaded dns,
501 * the sockets for dns end up in our mainloop.
502 * When we are using multi-threaded dns,
503 * each thread has its own basic poll() loop
504 * within it, making them 'fire and forget'
505 * and independent of the mainloop.
508 dns_poll(activefds[activefd]);
514 /* It's a listener */
515 uslen = sizeof(sock_us);
516 length = sizeof(client);
517 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
518 if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
520 in_port = ntohs(sock_us.sin_port);
521 log(DEBUG,"Accepted socket %d",incomingSockfd);
522 target = (char*)inet_ntoa(client.sin_addr);
523 /* Years and years ago, we used to resolve here
524 * using gethostbyaddr(). That is sucky and we
525 * don't do that any more...
527 if (incomingSockfd >= 0)
531 IOHookModule->OnRawSocketAccept(incomingSockfd, target, in_port);
533 stats->statsAccept++;
534 AddClient(incomingSockfd, target, in_port, false, target);
535 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
539 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
540 log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
541 stats->statsRefused++;
546 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
547 shutdown(incomingSockfd,2);
548 close(incomingSockfd);
553 /* Something went wrong if we're in here.
554 * In fact, so wrong, im not quite sure
555 * what we would do, so for now, its going
556 * to safely do bugger all.
563 /* This is never reached -- we hope! */
567 /**********************************************************************************/
570 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
573 int main(int argc, char** argv)
575 ServerInstance = new InspIRCd(argc, argv);
576 ServerInstance->Run();
577 delete ServerInstance;