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