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;
71 std::vector<InspSocket*> module_sockets;
72 std::vector<userrec*> local_users;
75 int openSockfd[MAXSOCKS];
76 sockaddr_in client,server;
79 extern InspSocket* socket_ref[65535];
81 time_t TIME = time(NULL), OLDTIME = time(NULL);
83 // This table references users by file descriptor.
84 // its an array to make it VERY fast, as all lookups are referenced
85 // by an integer, meaning there is no need for a scan/search operation.
86 userrec* fd_ref_table[65536];
88 Server* MyServer = new Server;
89 ServerConfig *Config = new ServerConfig;
94 servernamelist servernames;
97 void AddServerName(std::string servername)
99 log(DEBUG,"Adding server name: %s",servername.c_str());
100 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
102 if (*a == servername)
105 servernames.push_back(servername);
108 const char* FindServerNamePtr(std::string servername)
110 for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
112 if (*a == servername)
115 AddServerName(servername);
116 return FindServerNamePtr(servername);
119 std::string InspIRCd::GetRevision()
121 /* w00t got me to replace a bunch of strtok_r
122 * with something nicer, so i did this. Its the
123 * same thing really, only in C++. It places the
124 * text into a std::stringstream which is a readable
125 * and writeable buffer stream, and then pops two
126 * words off it, space delimited. Because it reads
127 * into the same variable twice, the first word
128 * is discarded, and the second one returned.
130 std::stringstream Revision("$Revision$");
132 Revision >> single >> single;
136 void InspIRCd::MakeLowerMap()
138 // initialize the lowercase mapping table
139 for (unsigned int cn = 0; cn < 256; cn++)
141 // lowercase the uppercase chars
142 for (unsigned int cn = 65; cn < 91; cn++)
143 lowermap[cn] = tolower(cn);
144 // now replace the specific chars for scandanavian comparison
145 lowermap[(unsigned)'['] = '{';
146 lowermap[(unsigned)']'] = '}';
147 lowermap[(unsigned)'\\'] = '|';
150 InspIRCd::InspIRCd(int argc, char** argv)
153 module_sockets.clear();
154 this->startup_time = time(NULL);
156 log(DEBUG,"*** InspIRCd starting up!");
157 if (!FileExists(CONFIG_FILE))
159 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
160 log(DEFAULT,"main: no config");
161 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
165 for (int i = 1; i < argc; i++)
167 if (!strcmp(argv[i],"-nofork")) {
168 Config->nofork = true;
170 if (!strcmp(argv[i],"-wait")) {
173 if (!strcmp(argv[i],"-nolimit")) {
174 Config->unlimitcore = true;
179 strlcpy(Config->MyExecutable,argv[0],MAXBUF);
181 this->MakeLowerMap();
184 Config->ClearStack();
185 Config->Read(true,NULL);
187 this->ModeGrok = new ModeParser();
188 this->Parser = new CommandParser();
189 this->stats = new serverstats();
190 AddServerName(Config->ServerName);
192 stats->BoundPortCount = BindPorts();
194 for(int t = 0; t < 255; t++)
195 Config->global_implementation[t] = 0;
197 memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
203 if (DaemonSeed() == ERROR)
205 printf("ERROR: could not go into daemon mode. Shutting down.\n");
210 /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
211 * initialize the socket engine.
213 SE = new SocketEngine();
215 /* We must load the modules AFTER initializing the socket engine, now */
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);
302 for(int t = 0; t < 255; t++)
304 Config->global_implementation[t] -= Config->implement_lists[j][t];
307 FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
309 log(DEBUG,"Deleting module...");
311 log(DEBUG,"Erasing module entry...");
313 log(DEBUG,"Removing dependent commands...");
314 Parser->RemoveCommands(filename);
315 log(DEFAULT,"Module %s unloaded",filename);
320 log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
321 snprintf(MODERR,MAXBUF,"Module not loaded");
325 bool InspIRCd::LoadModule(const char* filename)
327 char modfile[MAXBUF];
329 snprintf(modfile,MAXBUF,"%s",filename);
331 snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
333 std::string filename_str = filename;
335 if (!DirValid(modfile))
337 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
338 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
342 log(DEBUG,"Loading module: %s",modfile);
344 if (FileExists(modfile))
347 for (unsigned int j = 0; j < Config->module_names.size(); j++)
349 if (Config->module_names[j] == filename_str)
351 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
352 snprintf(MODERR,MAXBUF,"Module already loaded");
356 ircd_module* a = new ircd_module(modfile);
357 factory[MODCOUNT+1] = a;
358 if (factory[MODCOUNT+1]->LastError())
360 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
361 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
365 if (factory[MODCOUNT+1]->factory)
367 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
368 modules[MODCOUNT+1] = m;
369 /* save the module and the module's classfactory, if
370 * this isnt done, random crashes can occur :/ */
371 Config->module_names.push_back(filename);
373 char* x = &Config->implement_lists[MODCOUNT+1][0];
374 for(int t = 0; t < 255; t++)
377 modules[MODCOUNT+1]->Implements(x);
379 for(int t = 0; t < 255; t++)
381 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
382 if (Config->implement_lists[MODCOUNT+1][t])
384 log(DEBUG,"Add global implementation: %d %d => %d",MODCOUNT+1,t,Config->global_implementation[t]);
390 log(DEFAULT,"Unable to load %s",modfile);
391 snprintf(MODERR,MAXBUF,"Factory function failed!");
398 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
399 snprintf(MODERR,MAXBUF,"Module file could not be found");
404 FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
410 bool expire_run = false;
411 int activefds[65535];
415 InspSocket* s = NULL;
416 InspSocket* s_del = NULL;
418 unsigned int numberactive;
419 sockaddr_in sock_us; // our port number
420 socklen_t uslen; // length of our port number
422 /* Until THIS point, ServerInstance == NULL */
424 LoadAllModules(this);
426 printf("\nInspIRCd is now running!\n");
430 freopen("/dev/null","w",stdout);
431 freopen("/dev/null","w",stderr);
434 /* Add the listening sockets used for client inbound connections
435 * to the socket engine
437 for (int count = 0; count < stats->BoundPortCount; count++)
438 SE->AddFd(openSockfd[count],true,X_LISTEN);
440 WritePID(Config->PID);
442 /* main loop, this never returns */
445 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
446 * Once per loop iteration is pleanty.
451 /* Run background module timers every few seconds
452 * (the docs say modules shouldnt rely on accurate
453 * timing using this event, so we dont have to
454 * time this exactly).
456 if (((TIME % 8) == 0) && (!expire_run))
459 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
463 else if ((TIME % 8) == 1)
468 /* Once a second, do the background processing */
469 if ((TIME != OLDTIME) && ((TIME % 2) == 0))
470 DoBackgroundUserStuff(TIME);
472 /* Call the socket engine to wait on the active
473 * file descriptors. The socket engine has everything's
474 * descriptors in its list... dns, modules, users,
475 * servers... so its nice and easy, just one call.
477 numberactive = SE->Wait(activefds);
482 log(DEBUG,"%d active fds this time around",numberactive);
485 * Now process each of the fd's. For users, we have a fast
486 * lookup table which can find a user by file descriptor, so
487 * processing them by fd isnt expensive. If we have a lot of
488 * listening ports or module sockets though, things could get
491 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
493 int socket_type = SE->GetType(activefds[activefd]);
498 cu = fd_ref_table[activefds[activefd]];
506 /* Process module-owned sockets.
507 * Modules are encouraged to inherit their sockets from
508 * InspSocket so we can process them neatly like this.
510 s = socket_ref[activefds[activefd]];
512 if ((s) && (!s->Poll()))
514 log(DEBUG,"Socket poll returned false, close and bail");
515 SE->DelFd(s->GetFd());
516 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
518 s_del = (InspSocket*)*a;
519 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
521 module_sockets.erase(a);
533 /* When we are using single-threaded dns,
534 * the sockets for dns end up in our mainloop.
535 * When we are using multi-threaded dns,
536 * each thread has its own basic poll() loop
537 * within it, making them 'fire and forget'
538 * and independent of the mainloop.
541 dns_poll(activefds[activefd]);
547 /* It's a listener */
548 uslen = sizeof(sock_us);
549 length = sizeof(client);
550 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
551 if (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen))
553 in_port = ntohs(sock_us.sin_port);
554 log(DEBUG,"Accepted socket %d",incomingSockfd);
555 target = (char*)inet_ntoa(client.sin_addr);
556 /* Years and years ago, we used to resolve here
557 * using gethostbyaddr(). That is sucky and we
558 * don't do that any more...
560 if (incomingSockfd >= 0)
562 NonBlocking(incomingSockfd);
563 if (Config->GetIOHook(in_port))
565 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, target, in_port);
567 stats->statsAccept++;
568 AddClient(incomingSockfd, target, in_port, false, target);
569 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
573 WriteOpers("*** WARNING: accept() failed on port %lu (%s)",(unsigned long)in_port,target);
574 log(DEBUG,"accept failed: %lu",(unsigned long)in_port);
575 stats->statsRefused++;
580 log(DEBUG,"Couldnt look up the port number for fd %lu (OS BROKEN?!)",incomingSockfd);
581 shutdown(incomingSockfd,2);
582 close(incomingSockfd);
587 /* Something went wrong if we're in here.
588 * In fact, so wrong, im not quite sure
589 * what we would do, so for now, its going
590 * to safely do bugger all.
597 /* This is never reached -- we hope! */
601 /**********************************************************************************/
604 * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
607 int main(int argc, char** argv)
609 ServerInstance = new InspIRCd(argc, argv);
610 ServerInstance->Run();
611 delete ServerInstance;