]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
e66d49a1e8aee1619f030f6215a8ff9bc5640c14
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "configreader.h"
16 #include <signal.h>
17 #ifndef WIN32
18 #include <dirent.h>
19 #include <unistd.h>
20 #endif
21 #include <exception>
22 #include <fstream>
23 #include "modules.h"
24 #include "mode.h"
25 #include "xline.h"
26 #include "socketengine.h"
27 #include "inspircd_se_config.h"
28 #include "socket.h"
29 #include "typedefs.h"
30 #include "command_parse.h"
31 #include "exitcodes.h"
32
33 #ifndef WIN32
34 #include <dlfcn.h>
35 #include <getopt.h>
36 #endif
37
38 using irc::sockets::NonBlocking;
39 using irc::sockets::Blocking;
40 using irc::sockets::insp_ntoa;
41 using irc::sockets::insp_inaddr;
42 using irc::sockets::insp_sockaddr;
43
44 InspIRCd* SI = NULL;
45
46 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
47 const char* ExitCodes[] =
48 {
49                 "No error", /* 0 */
50                 "DIE command", /* 1 */
51                 "execv() failed", /* 2 */
52                 "Internal error", /* 3 */
53                 "Config file error", /* 4 */
54                 "Logfile error", /* 5 */
55                 "Fork failed", /* 6 */
56                 "Bad commandline parameters", /* 7 */
57                 "No ports could be bound", /* 8 */
58                 "Can't write PID file", /* 9 */
59                 "SocketEngine could not initialize", /* 10 */
60                 "Refusing to start up as root", /* 11 */
61                 "Found a <die> tag!", /* 12 */
62                 "Couldn't load module on startup", /* 13 */
63                 "", /* 14 */
64                 "Received SIGTERM", /* 15 */
65 };
66
67 void InspIRCd::AddServerName(const std::string &servername)
68 {
69         servernamelist::iterator itr = servernames.begin();
70         for(; itr != servernames.end(); ++itr)
71                 if(**itr == servername)
72                         return;
73
74         string * ns = new string(servername);
75         servernames.push_back(ns);
76 }
77
78 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
79 {
80         servernamelist::iterator itr = servernames.begin();
81         for(; itr != servernames.end(); ++itr)
82                 if(**itr == servername)
83                         return (*itr)->c_str();
84
85         servernames.push_back(new string(servername));
86         itr = --servernames.end();
87         return (*itr)->c_str();
88 }
89
90 bool InspIRCd::FindServerName(const std::string &servername)
91 {
92         servernamelist::iterator itr = servernames.begin();
93         for(; itr != servernames.end(); ++itr)
94                 if(**itr == servername)
95                         return true;
96         return false;
97 }
98
99 void InspIRCd::Exit(int status)
100 {
101 #ifdef WINDOWS
102         CloseIPC();
103 #endif
104         if (SI)
105         {
106                 SI->SendError("Exiting with status " + ConvToStr(status) + " (" + std::string(ExitCodes[status]) + ")");
107                 SI->Cleanup();
108         }
109         exit (status);
110 }
111
112 void InspIRCd::Cleanup()
113 {
114         std::vector<std::string> mymodnames;
115         int MyModCount = this->GetModuleCount();
116
117         for (unsigned int i = 0; i < Config->ports.size(); i++)
118         {
119                 /* This calls the constructor and closes the listening socket */
120                 delete Config->ports[i];
121         }
122
123         Config->ports.clear();
124
125         /* Close all client sockets, or the new process inherits them */
126         for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
127         {
128                 (*i)->SetWriteError("Server shutdown");
129                 (*i)->CloseSocket();
130         }
131
132         /* We do this more than once, so that any service providers get a
133          * chance to be unhooked by the modules using them, but then get
134          * a chance to be removed themsleves.
135          */
136         for (int tries = 0; tries < 3; tries++)
137         {
138                 MyModCount = this->GetModuleCount();
139                 mymodnames.clear();
140
141                 /* Unload all modules, so they get a chance to clean up their listeners */
142                 for (int j = 0; j <= MyModCount; j++)
143                         mymodnames.push_back(Config->module_names[j]);
144
145                 for (int k = 0; k <= MyModCount; k++)
146                         this->UnloadModule(mymodnames[k].c_str());
147         }
148
149         /* Close logging */
150         this->Logger->Close();
151
152         /* Cleanup Server Names */
153         for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
154                 delete (*itr);
155
156 #ifdef WINDOWS
157         /* WSACleanup */
158         WSACleanup();
159 #endif
160 }
161
162 void InspIRCd::Restart(const std::string &reason)
163 {
164         /* SendError flushes each client's queue,
165          * regardless of writeability state
166          */
167         this->SendError(reason);
168
169         this->Cleanup();
170
171         /* Figure out our filename (if theyve renamed it, we're boned) */
172         std::string me;
173
174 #ifdef WINDOWS
175         char module[MAX_PATH];
176         if (GetModuleFileName(NULL, module, MAX_PATH))
177                 me = module;
178 #else
179         me = Config->MyDir + "/inspircd";
180 #endif
181
182         if (execv(me.c_str(), Config->argv) == -1)
183         {
184                 /* Will raise a SIGABRT if not trapped */
185                 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
186         }
187 }
188
189 void InspIRCd::Start()
190 {
191         printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
192         printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
193         printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey\033[0m\n");
194         printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
195 }
196
197 void InspIRCd::Rehash(int status)
198 {
199         SI->WriteOpers("*** Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(SI->ConfigFileName));
200         SI->CloseLog();
201         SI->OpenLog(SI->Config->argv, SI->Config->argc);
202         SI->RehashUsersAndChans();
203         FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
204         SI->Config->Read(false,NULL);
205         SI->ResetMaxBans();
206         SI->Res->Rehash();
207         FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
208         SI->BuildISupport();
209 }
210
211 void InspIRCd::ResetMaxBans()
212 {
213         for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
214                 i->second->ResetMaxBans();
215 }
216
217
218 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
219  * we must occasionally rehash the hash (yes really).
220  * We do this by copying the entries from the old hash to a new hash, causing all
221  * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
222  * very expensive, so instead we do it when the user types /REHASH and expects a
223  * short delay anyway.
224  */
225 void InspIRCd::RehashUsersAndChans()
226 {
227         user_hash* old_users = this->clientlist;
228         chan_hash* old_chans = this->chanlist;
229
230         this->clientlist = new user_hash();
231         this->chanlist = new chan_hash();
232
233         for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
234                 this->clientlist->insert(*n);
235
236         delete old_users;
237
238         for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
239                 this->chanlist->insert(*n);
240
241         delete old_chans;
242 }
243
244 void InspIRCd::CloseLog()
245 {
246         this->Logger->Close();
247 }
248
249 void InspIRCd::SetSignals()
250 {
251 #ifndef WIN32
252         signal(SIGALRM, SIG_IGN);
253         signal(SIGHUP, InspIRCd::Rehash);
254         signal(SIGPIPE, SIG_IGN);
255         signal(SIGCHLD, SIG_IGN);
256 #endif
257         signal(SIGTERM, InspIRCd::Exit);
258 }
259
260 void InspIRCd::QuickExit(int status)
261 {
262         exit(0);
263 }
264
265 bool InspIRCd::DaemonSeed()
266 {
267 #ifdef WINDOWS
268         // Create process, with argument --service
269         STARTUPINFO si;
270         PROCESS_INFORMATION pi;
271         memset(&si, 0, sizeof(si));
272         memset(&pi, 0, sizeof(pi));
273         SHELLEXECUTEINFO sh = {0};
274         sh.cbSize = sizeof(sh);
275         sh.fMask = SEE_MASK_NOCLOSEPROCESS;
276         sh.hwnd = 0;
277         sh.lpVerb = 0;
278         sh.lpDirectory = 0;
279         sh.hInstApp = 0;
280         sh.nShow = SW_HIDE;
281         sh.lpFile = "inspircd.exe";
282         sh.lpParameters = "--service";
283         if(!ShellExecuteEx(&sh))
284                 return false;
285
286         CloseHandle(sh.hProcess);
287         exit(0);
288         return true;
289 #else
290         signal(SIGTERM, InspIRCd::QuickExit);
291
292         int childpid;
293         if ((childpid = fork ()) < 0)
294                 return false;
295         else if (childpid > 0)
296         {
297                 /* We wait here for the child process to kill us,
298                  * so that the shell prompt doesnt come back over
299                  * the output.
300                  * Sending a kill with a signal of 0 just checks
301                  * if the child pid is still around. If theyre not,
302                  * they threw an error and we should give up.
303                  */
304                 while (kill(childpid, 0) != -1)
305                         sleep(1);
306                 exit(0);
307         }
308         setsid ();
309         umask (007);
310         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
311
312         signal(SIGTERM, InspIRCd::Exit);
313
314         rlimit rl;
315         if (getrlimit(RLIMIT_CORE, &rl) == -1)
316         {
317                 this->Log(DEFAULT,"Failed to getrlimit()!");
318                 return false;
319         }
320         else
321         {
322                 rl.rlim_cur = rl.rlim_max;
323                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
324                         this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
325         }
326
327         return true;
328 #endif
329 }
330
331 void InspIRCd::WritePID(const std::string &filename)
332 {
333         std::string fname = (filename.empty() ? "inspircd.pid" : filename);
334         if (*(fname.begin()) != '/')
335         {
336                 std::string::size_type pos;
337                 std::string confpath = this->ConfigFileName;
338                 if ((pos = confpath.rfind("/")) != std::string::npos)
339                 {
340                         /* Leaves us with just the path */
341                         fname = confpath.substr(0, pos) + std::string("/") + fname;
342                 }
343         }
344         std::ofstream outfile(fname.c_str());
345         if (outfile.is_open())
346         {
347                 outfile << getpid();
348                 outfile.close();
349         }
350         else
351         {
352                 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
353                 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
354                 Exit(EXIT_STATUS_PID);
355         }
356 }
357
358 std::string InspIRCd::GetRevision()
359 {
360         return REVISION;
361 }
362
363 InspIRCd::InspIRCd(int argc, char** argv)
364         : ModCount(-1), duration_m(60), duration_h(60*60), duration_d(60*60*24), duration_w(60*60*24*7), duration_y(60*60*24*365), GlobalCulls(this)
365 {
366 #ifdef WINDOWS
367         WSADATA wsadata;
368         WSAStartup(MAKEWORD(2,0), &wsadata);
369 #endif
370
371         int found_ports = 0;
372         FailedPortList pl;
373         int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0, is_service = 0;    /* flag variables */
374         char c = 0;
375
376         modules.resize(255);
377         factory.resize(255);
378         memset(&server, 0, sizeof(server));
379         memset(&client, 0, sizeof(client));
380
381         this->unregistered_count = 0;
382
383         this->clientlist = new user_hash();
384         this->chanlist = new chan_hash();
385
386         this->Config = new ServerConfig(this);
387
388         this->Config->argv = argv;
389         this->Config->argc = argc;
390
391         chdir(Config->GetFullProgDir().c_str());
392
393         this->Config->opertypes.clear();
394         this->Config->operclass.clear();
395         this->SNO = new SnomaskManager(this);
396         this->TIME = this->OLDTIME = this->startup_time = time(NULL);
397         this->time_delta = 0;
398         this->next_call = this->TIME + 3;
399         srand(this->TIME);
400
401         *this->LogFileName = 0;
402         strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
403
404         struct option longopts[] =
405         {
406                 { "nofork",     no_argument,            &do_nofork,     1       },
407                 { "logfile",    required_argument,      NULL,           'f'     },
408                 { "config",     required_argument,      NULL,           'c'     },
409                 { "debug",      no_argument,            &do_debug,      1       },
410                 { "nolog",      no_argument,            &do_nolog,      1       },
411                 { "runasroot",  no_argument,            &do_root,       1       },
412                 { "version",    no_argument,            &do_version,    1       },
413                 { "service",    no_argument,            &is_service,    1       },
414                 { 0, 0, 0, 0 }
415         };
416
417         while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
418         {
419                 switch (c)
420                 {
421                         case 'f':
422                                 /* Log filename was set */
423                                 strlcpy(LogFileName, optarg, MAXBUF);
424                                 printf("LOG: Setting logfile to %s\n", LogFileName);
425                         break;
426                         case 'c':
427                                 /* Config filename was set */
428                                 strlcpy(ConfigFileName, optarg, MAXBUF);
429                                 printf("CONFIG: Setting config file to %s\n", ConfigFileName);
430                         break;
431                         case 0:
432                                 /* getopt_long_only() set an int variable, just keep going */
433                         break;
434                         default:
435                                 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
436                                 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
437                                 Exit(EXIT_STATUS_ARGV);
438                         break;
439                 }
440         }
441
442 #ifdef WINDOWS
443         if(is_service)
444                 FreeConsole();
445 #endif
446
447         if (do_version)
448         {
449                 printf("\n%s r%s\n", VERSION, REVISION);
450                 Exit(EXIT_STATUS_NOERROR);
451         }
452
453         if (!ServerConfig::FileExists(this->ConfigFileName))
454         {
455                 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
456                 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
457                 Exit(EXIT_STATUS_CONFIG);
458         }
459
460         this->Start();
461
462         /* Set the finished argument values */
463         Config->nofork = do_nofork;
464         Config->forcedebug = do_debug;
465         Config->writelog = !do_nolog;
466
467         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
468
469         this->OpenLog(argv, argc);
470
471         this->stats = new serverstats();
472         this->Timers = new TimerManager(this);
473         this->Parser = new CommandParser(this);
474         this->XLines = new XLineManager(this);
475         Config->ClearStack();
476         Config->Read(true, NULL);
477
478         if (!do_root)
479                 this->CheckRoot();
480         else
481         {
482                 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
483                 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
484                 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
485                 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
486                 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
487                 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
488                 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
489                 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
490                 sleep(20);
491         }
492
493         this->SetSignals();
494
495         if (!Config->nofork)
496         {
497                 if (!is_service && !this->DaemonSeed())
498                 {
499                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
500                         Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
501                         Exit(EXIT_STATUS_FORK);
502                 }
503         }
504
505
506         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
507          * initialize the socket engine.
508          */
509         SocketEngineFactory* SEF = new SocketEngineFactory();
510         SE = SEF->Create(this);
511         delete SEF;
512
513         this->Modes = new ModeParser(this);
514         this->AddServerName(Config->ServerName);
515         CheckDie();
516         int bounditems = BindPorts(true, found_ports, pl);
517
518         for(int t = 0; t < 255; t++)
519                 Config->global_implementation[t] = 0;
520
521         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
522
523         printf("\n");
524
525         this->Res = new DNS(this);
526
527         this->LoadAllModules();
528         /* Just in case no modules were loaded - fix for bug #101 */
529         this->BuildISupport();
530         InitializeDisabledCommands(Config->DisabledCommands, this);
531
532         if ((Config->ports.size() == 0) && (found_ports > 0))
533         {
534                 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
535                 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
536                 Exit(EXIT_STATUS_BIND);
537         }
538
539         if (Config->ports.size() != (unsigned int)found_ports)
540         {
541                 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
542                 printf("The following port(s) failed to bind:\n");
543                 int j = 1;
544                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
545                 {
546                         printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
547                 }
548         }
549 #ifndef WINDOWS
550         if (!Config->nofork)
551         {
552                 if (kill(getppid(), SIGTERM) == -1)
553                 {
554                         printf("Error killing parent process: %s\n",strerror(errno));
555                         Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
556                 }
557         }
558
559         if (isatty(0) && isatty(1) && isatty(2))
560         {
561                 /* We didn't start from a TTY, we must have started from a background process -
562                  * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
563                  * close stdin/stdout
564                  */
565                 if (!do_nofork)
566                 {
567                         fclose(stdin);
568                         fclose(stderr);
569                         fclose(stdout);
570                 }
571                 else
572                 {
573                         Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
574                 }
575         }
576 #endif
577         printf("\nInspIRCd is now running!\n");
578         Log(DEFAULT,"Startup complete.");
579
580         this->WritePID(Config->PID);
581
582 #ifdef WINDOWS
583         InitIPC();
584 #endif
585 }
586
587 std::string InspIRCd::GetVersionString()
588 {
589         char versiondata[MAXBUF];
590         char dnsengine[] = "singlethread-object";
591
592         if (*Config->CustomVersion)
593         {
594                 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
595         }
596         else
597         {
598                 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%s,%s,%s]",VERSION,Config->ServerName,SYSTEM,REVISION,SE->GetName().c_str(),dnsengine);
599         }
600         return versiondata;
601 }
602
603 char* InspIRCd::ModuleError()
604 {
605         return MODERR;
606 }
607
608 void InspIRCd::EraseFactory(int j)
609 {
610         int v = 0;
611         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
612         {
613                 if (v == j)
614                 {
615                         delete *t;
616                         factory.erase(t);
617                         factory.push_back(NULL);
618                         return;
619                 }
620                 v++;
621         }
622 }
623
624 void InspIRCd::EraseModule(int j)
625 {
626         int v1 = 0;
627         for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
628         {
629                 if (v1 == j)
630                 {
631                         DELETE(*m);
632                         modules.erase(m);
633                         modules.push_back(NULL);
634                         break;
635                 }
636                 v1++;
637         }
638         int v2 = 0;
639         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
640         {
641                 if (v2 == j)
642                 {
643                         Config->module_names.erase(v);
644                         break;
645                 }
646                 v2++;
647         }
648
649 }
650
651 void InspIRCd::MoveTo(std::string modulename,int slot)
652 {
653         unsigned int v2 = 256;
654         for (unsigned int v = 0; v < Config->module_names.size(); v++)
655         {
656                 if (Config->module_names[v] == modulename)
657                 {
658                         // found an instance, swap it with the item at the end
659                         v2 = v;
660                         break;
661                 }
662         }
663         if ((v2 != (unsigned int)slot) && (v2 < 256))
664         {
665                 // Swap the module names over
666                 Config->module_names[v2] = Config->module_names[slot];
667                 Config->module_names[slot] = modulename;
668                 // now swap the module factories
669                 ircd_module* temp = factory[v2];
670                 factory[v2] = factory[slot];
671                 factory[slot] = temp;
672                 // now swap the module objects
673                 Module* temp_module = modules[v2];
674                 modules[v2] = modules[slot];
675                 modules[slot] = temp_module;
676                 // now swap the implement lists (we dont
677                 // need to swap the global or recount it)
678                 for (int n = 0; n < 255; n++)
679                 {
680                         char x = Config->implement_lists[v2][n];
681                         Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
682                         Config->implement_lists[slot][n] = x;
683                 }
684         }
685 }
686
687 void InspIRCd::MoveAfter(std::string modulename, std::string after)
688 {
689         for (unsigned int v = 0; v < Config->module_names.size(); v++)
690         {
691                 if (Config->module_names[v] == after)
692                 {
693                         MoveTo(modulename, v);
694                         return;
695                 }
696         }
697 }
698
699 void InspIRCd::MoveBefore(std::string modulename, std::string before)
700 {
701         for (unsigned int v = 0; v < Config->module_names.size(); v++)
702         {
703                 if (Config->module_names[v] == before)
704                 {
705                         if (v > 0)
706                         {
707                                 MoveTo(modulename, v-1);
708                         }
709                         else
710                         {
711                                 MoveTo(modulename, v);
712                         }
713                         return;
714                 }
715         }
716 }
717
718 void InspIRCd::MoveToFirst(std::string modulename)
719 {
720         MoveTo(modulename,0);
721 }
722
723 void InspIRCd::MoveToLast(std::string modulename)
724 {
725         MoveTo(modulename,this->GetModuleCount());
726 }
727
728 void InspIRCd::BuildISupport()
729 {
730         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
731         std::stringstream v;
732         v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES-1 << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << Config->MaxChans << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
733         v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
734         v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32 ELIST=MU";
735         Config->data005 = v.str();
736         FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
737         Config->Update005();
738 }
739
740 bool InspIRCd::UnloadModule(const char* filename)
741 {
742         std::string filename_str = filename;
743         for (unsigned int j = 0; j != Config->module_names.size(); j++)
744         {
745                 if (Config->module_names[j] == filename_str)
746                 {
747                         if (modules[j]->GetVersion().Flags & VF_STATIC)
748                         {
749                                 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
750                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
751                                 return false;
752                         }
753                         std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modules[j]);
754                         if (intercount.first > 0)
755                         {
756                                 this->Log(DEFAULT,"Failed to unload module %s, being used by %d other(s) via interface '%s'",filename, intercount.first, intercount.second.c_str());
757                                 snprintf(MODERR,MAXBUF,"Module not unloadable (Still in use by %d other module%s which %s using its interface '%s') -- unload dependent modules first!",
758                                                 intercount.first,
759                                                 intercount.first > 1 ? "s" : "",
760                                                 intercount.first > 1 ? "are" : "is",
761                                                 intercount.second.c_str());
762                                 return false;
763                         }
764                         /* Give the module a chance to tidy out all its metadata */
765                         for (chan_hash::iterator c = this->chanlist->begin(); c != this->chanlist->end(); c++)
766                         {
767                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
768                         }
769                         for (user_hash::iterator u = this->clientlist->begin(); u != this->clientlist->end(); u++)
770                         {
771                                 modules[j]->OnCleanup(TYPE_USER,u->second);
772                         }
773
774                         /* Tidy up any dangling resolvers */
775                         this->Res->CleanResolvers(modules[j]);
776
777                         FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
778
779                         for(int t = 0; t < 255; t++)
780                         {
781                                 Config->global_implementation[t] -= Config->implement_lists[j][t];
782                         }
783
784                         /* We have to renumber implement_lists after unload because the module numbers change!
785                          */
786                         for(int j2 = j; j2 < 254; j2++)
787                         {
788                                 for(int t = 0; t < 255; t++)
789                                 {
790                                         Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
791                                 }
792                         }
793
794                         // found the module
795                         Parser->RemoveCommands(filename);
796                         this->EraseModule(j);
797                         this->EraseFactory(j);
798                         this->Log(DEFAULT,"Module %s unloaded",filename);
799                         this->ModCount--;
800                         BuildISupport();
801                         return true;
802                 }
803         }
804         this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
805         snprintf(MODERR,MAXBUF,"Module not loaded");
806         return false;
807 }
808
809 bool InspIRCd::LoadModule(const char* filename)
810 {
811         /* Do we have a glob pattern in the filename?
812          * The user wants to load multiple modules which
813          * match the pattern.
814          */
815         if (strchr(filename,'*') || (strchr(filename,'?')))
816         {
817                 int n_match = 0;
818                 DIR* library = opendir(Config->ModPath);
819                 if (library)
820                 {
821                         /* Try and locate and load all modules matching the pattern */
822                         dirent* entry = NULL;
823                         while ((entry = readdir(library)))
824                         {
825                                 if (this->MatchText(entry->d_name, filename))
826                                 {
827                                         if (!this->LoadModule(entry->d_name))
828                                                 n_match++;
829                                 }
830                         }
831                         closedir(library);
832                 }
833                 /* Loadmodule will now return false if any one of the modules failed
834                  * to load (but wont abort when it encounters a bad one) and when 1 or
835                  * more modules were actually loaded.
836                  */
837                 return (n_match > 0);
838         }
839
840         char modfile[MAXBUF];
841         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
842         std::string filename_str = filename;
843
844         if (!ServerConfig::DirValid(modfile))
845         {
846                 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
847                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
848                 return false;
849         }
850         if (ServerConfig::FileExists(modfile))
851         {
852
853                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
854                 {
855                         if (Config->module_names[j] == filename_str)
856                         {
857                                 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
858                                 snprintf(MODERR,MAXBUF,"Module already loaded");
859                                 return false;
860                         }
861                 }
862                 try
863                 {
864                         ircd_module* a = new ircd_module(this, modfile);
865                         factory[this->ModCount+1] = a;
866                         if (factory[this->ModCount+1]->LastError())
867                         {
868                                 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
869                                 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
870                                 return false;
871                         }
872                         if ((long)factory[this->ModCount+1]->factory != -1)
873                         {
874                                 Module* m = factory[this->ModCount+1]->factory->CreateModule(this);
875
876                                 Version v = m->GetVersion();
877
878                                 if (v.API != API_VERSION)
879                                 {
880                                         delete m;
881                                         delete a;
882                                         this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
883                                         snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
884                                         return false;
885                                 }
886                                 else
887                                 {
888                                         this->Log(DEFAULT,"New module introduced: %s (API version %d, Module version %d.%d.%d.%d)%s", filename, v.API, v.Major, v.Minor, v.Revision, v.Build, (!(v.Flags & VF_VENDOR) ? " [3rd Party]" : " [Vendor]"));
889                                 }
890
891                                 modules[this->ModCount+1] = m;
892                                 /* save the module and the module's classfactory, if
893                                  * this isnt done, random crashes can occur :/ */
894                                 Config->module_names.push_back(filename);
895
896                                 char* x = &Config->implement_lists[this->ModCount+1][0];
897                                 for(int t = 0; t < 255; t++)
898                                         x[t] = 0;
899
900                                 modules[this->ModCount+1]->Implements(x);
901
902                                 for(int t = 0; t < 255; t++)
903                                         Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
904                         }
905                         else
906                         {
907                                 this->Log(DEFAULT,"Unable to load %s",modfile);
908                                 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
909                                 return false;
910                         }
911                 }
912                 catch (CoreException& modexcept)
913                 {
914                         this->Log(DEFAULT,"Unable to load %s: %s",modfile,modexcept.GetReason());
915                         snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
916                         return false;
917                 }
918         }
919         else
920         {
921                 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
922                 snprintf(MODERR,MAXBUF,"Module file could not be found");
923                 return false;
924         }
925         this->ModCount++;
926         FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
927         // now work out which modules, if any, want to move to the back of the queue,
928         // and if they do, move them there.
929         std::vector<std::string> put_to_back;
930         std::vector<std::string> put_to_front;
931         std::map<std::string,std::string> put_before;
932         std::map<std::string,std::string> put_after;
933         for (unsigned int j = 0; j < Config->module_names.size(); j++)
934         {
935                 if (modules[j]->Prioritize() == PRIORITY_LAST)
936                         put_to_back.push_back(Config->module_names[j]);
937                 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
938                         put_to_front.push_back(Config->module_names[j]);
939                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
940                         put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
941                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
942                         put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
943         }
944         for (unsigned int j = 0; j < put_to_back.size(); j++)
945                 MoveToLast(put_to_back[j]);
946         for (unsigned int j = 0; j < put_to_front.size(); j++)
947                 MoveToFirst(put_to_front[j]);
948         for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
949                 MoveBefore(j->first,j->second);
950         for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
951                 MoveAfter(j->first,j->second);
952         BuildISupport();
953         return true;
954 }
955
956 void InspIRCd::DoOneIteration(bool process_module_sockets)
957 {
958 #ifndef WIN32
959         static rusage ru;
960 #endif
961
962         /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
963          * Once per loop iteration is pleanty.
964          */
965         OLDTIME = TIME;
966         TIME = time(NULL);
967
968         /* Run background module timers every few seconds
969          * (the docs say modules shouldnt rely on accurate
970          * timing using this event, so we dont have to
971          * time this exactly).
972          */
973         if (TIME != OLDTIME)
974         {
975                 if (TIME < OLDTIME)
976                         WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
977                 if ((TIME % 3600) == 0)
978                 {
979                         this->RehashUsersAndChans();
980                         FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
981                 }
982                 Timers->TickTimers(TIME);
983                 this->DoBackgroundUserStuff(TIME);
984
985                 if ((TIME % 5) == 0)
986                 {
987                         XLines->expire_lines();
988                         FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
989                         Timers->TickMissedTimers(TIME);
990                 }
991 #ifndef WIN32
992                 if (!getrusage(0, &ru))
993                 {
994                         gettimeofday(&this->stats->LastSampled, NULL);
995                         this->stats->LastCPU = ru.ru_utime;
996                 }
997 #else
998                 CheckIPC(this);
999 #endif
1000         }
1001
1002         /* Call the socket engine to wait on the active
1003          * file descriptors. The socket engine has everything's
1004          * descriptors in its list... dns, modules, users,
1005          * servers... so its nice and easy, just one call.
1006          * This will cause any read or write events to be
1007          * dispatched to their handlers.
1008          */
1009         SE->DispatchEvents();
1010
1011         /* if any users was quit, take them out */
1012         GlobalCulls.Apply();
1013
1014         /* If any inspsockets closed, remove them */
1015         for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
1016         {
1017                 SE->DelFd(x->second);
1018                 x->second->Close();
1019                 delete x->second;
1020         }
1021         SocketCull.clear();
1022 }
1023
1024 int InspIRCd::Run()
1025 {
1026         while (true)
1027         {
1028                 DoOneIteration(true);
1029         }
1030         /* This is never reached -- we hope! */
1031         return 0;
1032 }
1033
1034 /**********************************************************************************/
1035
1036 /**
1037  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
1038  */
1039
1040 int main(int argc, char** argv)
1041 {
1042         SI = new InspIRCd(argc, argv);
1043         SI->Run();
1044         delete SI;
1045         return 0;
1046 }
1047
1048 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
1049  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
1050  * registration timeout maximum seconds)
1051  */
1052 bool InspIRCd::AllModulesReportReady(userrec* user)
1053 {
1054         if (!Config->global_implementation[I_OnCheckReady])
1055                 return true;
1056
1057         for (int i = 0; i <= this->GetModuleCount(); i++)
1058         {
1059                 if (Config->implement_lists[i][I_OnCheckReady])
1060                 {
1061                         int res = modules[i]->OnCheckReady(user);
1062                         if (!res)
1063                                 return false;
1064                 }
1065         }
1066         return true;
1067 }
1068
1069 int InspIRCd::GetModuleCount()
1070 {
1071         return this->ModCount;
1072 }
1073
1074 time_t InspIRCd::Time(bool delta)
1075 {
1076         if (delta)
1077                 return TIME + time_delta;
1078         return TIME;
1079 }
1080
1081 int InspIRCd::SetTimeDelta(int delta)
1082 {
1083         int old = time_delta;
1084         time_delta = delta;
1085         this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
1086         return old;
1087 }
1088
1089 void InspIRCd::AddLocalClone(userrec* user)
1090 {
1091         clonemap::iterator x = local_clones.find(user->GetIPString());
1092         if (x != local_clones.end())
1093                 x->second++;
1094         else
1095                 local_clones[user->GetIPString()] = 1;
1096 }
1097
1098 void InspIRCd::AddGlobalClone(userrec* user)
1099 {
1100         clonemap::iterator y = global_clones.find(user->GetIPString());
1101         if (y != global_clones.end())
1102                 y->second++;
1103         else
1104                 global_clones[user->GetIPString()] = 1;
1105 }
1106
1107 int InspIRCd::GetTimeDelta()
1108 {
1109         return time_delta;
1110 }
1111
1112 bool FileLogger::Readable()
1113 {
1114         return false;
1115 }
1116
1117 void FileLogger::HandleEvent(EventType et, int errornum)
1118 {
1119         this->WriteLogLine("");
1120         if (log)
1121                 ServerInstance->SE->DelFd(this);
1122 }
1123
1124 void FileLogger::WriteLogLine(const std::string &line)
1125 {
1126         if (line.length())
1127                 buffer.append(line);
1128
1129         if (log)
1130         {
1131                 int written = fprintf(log,"%s",buffer.c_str());
1132 #ifdef WINDOWS
1133                 buffer = "";
1134 #else
1135                 if ((written >= 0) && (written < (int)buffer.length()))
1136                 {
1137                         buffer.erase(0, buffer.length());
1138                         ServerInstance->SE->AddFd(this);
1139                 }
1140                 else if (written == -1)
1141                 {
1142                         if (errno == EAGAIN)
1143                                 ServerInstance->SE->AddFd(this);
1144                 }
1145                 else
1146                 {
1147                         /* Wrote the whole buffer, and no need for write callback */
1148                         buffer = "";
1149                 }
1150 #endif
1151                 if (writeops++ % 20)
1152                 {
1153                         fflush(log);
1154                 }
1155         }
1156 }
1157
1158 void FileLogger::Close()
1159 {
1160         if (log)
1161         {
1162                 /* Burlex: Windows assumes nonblocking on FILE* pointers anyway, and also "file" fd's aren't the same
1163                  * as socket fd's. */
1164 #ifndef WIN32
1165                 int flags = fcntl(fileno(log), F_GETFL, 0);
1166                 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
1167 #endif
1168                 if (buffer.size())
1169                         fprintf(log,"%s",buffer.c_str());
1170
1171 #ifndef WINDOWS
1172                 ServerInstance->SE->DelFd(this);
1173 #endif
1174
1175                 fflush(log);
1176                 fclose(log);
1177         }
1178
1179         buffer = "";
1180 }
1181
1182 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
1183 {
1184         if (log)
1185         {
1186                 irc::sockets::NonBlocking(fileno(log));
1187                 this->SetFd(fileno(log));
1188                 buffer = "";
1189         }
1190 }
1191
1192 FileLogger::~FileLogger()
1193 {
1194         this->Close();
1195 }
1196