]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
c56744b40bae74672d5c043e5d6905e1b63e1805
[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
18 #ifndef WIN32
19         #include <dirent.h>
20         #include <unistd.h>
21         #include <sys/resource.h>
22         #include <dlfcn.h>
23         #include <getopt.h>
24
25         /* Some systems don't define RUSAGE_SELF. This should fix them. */
26         #ifndef RUSAGE_SELF
27                 #define RUSAGE_SELF 0
28         #endif
29 #endif
30
31 #include <exception>
32 #include <fstream>
33 #include "modules.h"
34 #include "mode.h"
35 #include "xline.h"
36 #include "socketengine.h"
37 #include "inspircd_se_config.h"
38 #include "socket.h"
39 #include "typedefs.h"
40 #include "command_parse.h"
41 #include "exitcodes.h"
42
43 #ifdef WIN32
44
45 /* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
46 static DWORD owner_processid = 0;
47
48 DWORD WindowsForkStart(InspIRCd * Instance)
49 {
50         /* Windows implementation of fork() :P */
51
52         char module[MAX_PATH];
53         if(!GetModuleFileName(NULL, module, MAX_PATH))
54         {
55                 printf("GetModuleFileName() failed.\n");
56                 return false;
57         }
58
59         STARTUPINFO startupinfo;
60         PROCESS_INFORMATION procinfo;
61         ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
62         ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
63
64         // Fill in the startup info struct
65         GetStartupInfo(&startupinfo);
66
67         /* Default creation flags create the processes suspended */
68         DWORD startupflags = CREATE_SUSPENDED;
69
70         /* On windows 2003/XP and above, we can use the value
71          * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
72          * to the process which we may require on these operating systems.
73          */
74         OSVERSIONINFO vi;
75         vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
76         GetVersionEx(&vi);
77         if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
78                 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
79
80         // Launch our "forked" process.
81         BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
82                 strdup(GetCommandLine()),       // Command line (exe plus parameters from the OS)
83                                                 // NOTE: We cannot return the direct value of the
84                                                 // GetCommandLine function here, as the pointer is
85                                                 // passed straight to the child process, and will be
86                                                 // invalid once we exit as it goes out of context.
87                                                 // strdup() seems ok, though.
88                 0,                              // PROCESS_SECURITY_ATTRIBUTES
89                 0,                              // THREAD_SECURITY_ATTRIBUTES
90                 TRUE,                           // We went to inherit handles.
91                 startupflags,                   // Allow us full access to the process and suspend it.
92                 0,                              // ENVIRONMENT
93                 0,                              // CURRENT_DIRECTORY
94                 &startupinfo,                   // startup info
95                 &procinfo);                     // process info
96
97         if(!bSuccess)
98         {
99                 printf("CreateProcess() error: %s\n", dlerror());
100                 return false;
101         }
102
103         // Set the owner process id in the target process.
104         SIZE_T written = 0;
105         DWORD pid = GetCurrentProcessId();
106         if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
107         {
108                 printf("WriteProcessMemory() failed: %s\n", dlerror());
109                 return false;
110         }
111
112         // Resume the other thread (let it start)
113         ResumeThread(procinfo.hThread);
114
115         // Wait for the new process to kill us. If there is some error, the new process will end and we will end up at the next line.
116         WaitForSingleObject(procinfo.hProcess, INFINITE);
117
118         // If we hit this it means startup failed, default to 14 if this fails.
119         DWORD ExitCode = 14;
120         GetExitCodeProcess(procinfo.hProcess, &ExitCode);
121         CloseHandle(procinfo.hThread);
122         CloseHandle(procinfo.hProcess);
123         return ExitCode;
124 }
125
126 void WindowsForkKillOwner(InspIRCd * Instance)
127 {
128         HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
129         if(!hProcess || !owner_processid)
130         {
131                 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
132                 Instance->Exit(14);
133         }
134
135         // die die die
136         if(!TerminateProcess(hProcess, 0))
137         {
138                 printf("Could not TerminateProcess(): %s\n", dlerror());
139                 Instance->Exit(14);
140         }
141
142         CloseHandle(hProcess);
143 }
144
145 #endif
146
147 using irc::sockets::NonBlocking;
148 using irc::sockets::Blocking;
149 using irc::sockets::insp_ntoa;
150 using irc::sockets::insp_inaddr;
151 using irc::sockets::insp_sockaddr;
152
153 InspIRCd* SI = NULL;
154
155 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
156 const char* ExitCodes[] =
157 {
158                 "No error", /* 0 */
159                 "DIE command", /* 1 */
160                 "execv() failed", /* 2 */
161                 "Internal error", /* 3 */
162                 "Config file error", /* 4 */
163                 "Logfile error", /* 5 */
164                 "POSIX fork failed", /* 6 */
165                 "Bad commandline parameters", /* 7 */
166                 "No ports could be bound", /* 8 */
167                 "Can't write PID file", /* 9 */
168                 "SocketEngine could not initialize", /* 10 */
169                 "Refusing to start up as root", /* 11 */
170                 "Found a <die> tag!", /* 12 */
171                 "Couldn't load module on startup", /* 13 */
172                 "Could not create windows forked process", /* 14 */
173                 "Received SIGTERM", /* 15 */
174 };
175
176 void InspIRCd::AddServerName(const std::string &servername)
177 {
178         servernamelist::iterator itr = servernames.begin();
179         for(; itr != servernames.end(); ++itr)
180                 if(**itr == servername)
181                         return;
182
183         string * ns = new string(servername);
184         servernames.push_back(ns);
185 }
186
187 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
188 {
189         servernamelist::iterator itr = servernames.begin();
190         for(; itr != servernames.end(); ++itr)
191                 if(**itr == servername)
192                         return (*itr)->c_str();
193
194         servernames.push_back(new string(servername));
195         itr = --servernames.end();
196         return (*itr)->c_str();
197 }
198
199 bool InspIRCd::FindServerName(const std::string &servername)
200 {
201         servernamelist::iterator itr = servernames.begin();
202         for(; itr != servernames.end(); ++itr)
203                 if(**itr == servername)
204                         return true;
205         return false;
206 }
207
208 void InspIRCd::Exit(int status)
209 {
210 #ifdef WINDOWS
211         CloseIPC();
212 #endif
213         if (SI)
214         {
215                 SI->SendError("Exiting with status " + ConvToStr(status) + " (" + std::string(ExitCodes[status]) + ")");
216                 SI->Cleanup();
217         }
218         exit (status);
219 }
220
221 void InspIRCd::Cleanup()
222 {
223         std::vector<std::string> mymodnames;
224         int MyModCount = this->GetModuleCount();
225
226         for (unsigned int i = 0; i < Config->ports.size(); i++)
227         {
228                 /* This calls the constructor and closes the listening socket */
229                 delete Config->ports[i];
230         }
231
232         Config->ports.clear();
233
234         /* Close all client sockets, or the new process inherits them */
235         for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
236         {
237                 (*i)->SetWriteError("Server shutdown");
238                 (*i)->CloseSocket();
239         }
240
241         /* We do this more than once, so that any service providers get a
242          * chance to be unhooked by the modules using them, but then get
243          * a chance to be removed themsleves.
244          */
245         for (int tries = 0; tries < 3; tries++)
246         {
247                 MyModCount = this->GetModuleCount();
248                 mymodnames.clear();
249
250                 /* Unload all modules, so they get a chance to clean up their listeners */
251                 for (int j = 0; j <= MyModCount; j++)
252                         mymodnames.push_back(Config->module_names[j]);
253
254                 for (int k = 0; k <= MyModCount; k++)
255                         this->UnloadModule(mymodnames[k].c_str());
256         }
257
258         /* Close logging */
259         this->Logger->Close();
260
261         /* Cleanup Server Names */
262         for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
263                 delete (*itr);
264
265 #ifdef WINDOWS
266         /* WSACleanup */
267         WSACleanup();
268 #endif
269 }
270
271 void InspIRCd::Restart(const std::string &reason)
272 {
273         /* SendError flushes each client's queue,
274          * regardless of writeability state
275          */
276         this->SendError(reason);
277
278         this->Cleanup();
279
280         /* Figure out our filename (if theyve renamed it, we're boned) */
281         std::string me;
282
283 #ifdef WINDOWS
284         char module[MAX_PATH];
285         if (GetModuleFileName(NULL, module, MAX_PATH))
286                 me = module;
287 #else
288         me = Config->MyDir + "/inspircd";
289 #endif
290
291         if (execv(me.c_str(), Config->argv) == -1)
292         {
293                 /* Will raise a SIGABRT if not trapped */
294                 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
295         }
296 }
297
298 void InspIRCd::Rehash(int status)
299 {
300         SI->WriteOpers("*** Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(SI->ConfigFileName));
301         SI->CloseLog();
302         SI->OpenLog(SI->Config->argv, SI->Config->argc);
303         SI->RehashUsersAndChans();
304         FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
305         SI->Config->Read(false,NULL);
306         SI->ResetMaxBans();
307         SI->Res->Rehash();
308         FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
309         SI->BuildISupport();
310 }
311
312 void InspIRCd::ResetMaxBans()
313 {
314         for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
315                 i->second->ResetMaxBans();
316 }
317
318
319 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
320  * we must occasionally rehash the hash (yes really).
321  * We do this by copying the entries from the old hash to a new hash, causing all
322  * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
323  * very expensive, so instead we do it when the user types /REHASH and expects a
324  * short delay anyway.
325  */
326 void InspIRCd::RehashUsersAndChans()
327 {
328         user_hash* old_users = this->clientlist;
329         chan_hash* old_chans = this->chanlist;
330
331         this->clientlist = new user_hash();
332         this->chanlist = new chan_hash();
333
334         for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
335                 this->clientlist->insert(*n);
336
337         delete old_users;
338
339         for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
340                 this->chanlist->insert(*n);
341
342         delete old_chans;
343 }
344
345 void InspIRCd::CloseLog()
346 {
347         this->Logger->Close();
348 }
349
350 void InspIRCd::SetSignals()
351 {
352 #ifndef WIN32
353         signal(SIGALRM, SIG_IGN);
354         signal(SIGHUP, InspIRCd::Rehash);
355         signal(SIGPIPE, SIG_IGN);
356         signal(SIGCHLD, SIG_IGN);
357 #endif
358         signal(SIGTERM, InspIRCd::Exit);
359 }
360
361 void InspIRCd::QuickExit(int status)
362 {
363         exit(0);
364 }
365
366 bool InspIRCd::DaemonSeed()
367 {
368 #ifdef WINDOWS
369         printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
370         return true;
371 #else
372         signal(SIGTERM, InspIRCd::QuickExit);
373
374         int childpid;
375         if ((childpid = fork ()) < 0)
376                 return false;
377         else if (childpid > 0)
378         {
379                 /* We wait here for the child process to kill us,
380                  * so that the shell prompt doesnt come back over
381                  * the output.
382                  * Sending a kill with a signal of 0 just checks
383                  * if the child pid is still around. If theyre not,
384                  * they threw an error and we should give up.
385                  */
386                 while (kill(childpid, 0) != -1)
387                         sleep(1);
388                 exit(0);
389         }
390         setsid ();
391         umask (007);
392         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
393
394         signal(SIGTERM, InspIRCd::Exit);
395
396         rlimit rl;
397         if (getrlimit(RLIMIT_CORE, &rl) == -1)
398         {
399                 this->Log(DEFAULT,"Failed to getrlimit()!");
400                 return false;
401         }
402         else
403         {
404                 rl.rlim_cur = rl.rlim_max;
405                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
406                         this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
407         }
408
409         return true;
410 #endif
411 }
412
413 void InspIRCd::WritePID(const std::string &filename)
414 {
415         std::string fname = (filename.empty() ? "inspircd.pid" : filename);
416         if (*(fname.begin()) != '/')
417         {
418                 std::string::size_type pos;
419                 std::string confpath = this->ConfigFileName;
420                 if ((pos = confpath.rfind("/")) != std::string::npos)
421                 {
422                         /* Leaves us with just the path */
423                         fname = confpath.substr(0, pos) + std::string("/") + fname;
424                 }
425         }
426         std::ofstream outfile(fname.c_str());
427         if (outfile.is_open())
428         {
429                 outfile << getpid();
430                 outfile.close();
431         }
432         else
433         {
434                 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
435                 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
436                 Exit(EXIT_STATUS_PID);
437         }
438 }
439
440 std::string InspIRCd::GetRevision()
441 {
442         return REVISION;
443 }
444
445 InspIRCd::InspIRCd(int argc, char** argv)
446         : ModCount(-1), GlobalCulls(this)
447 {
448         int found_ports = 0;
449         FailedPortList pl;
450         int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0;    /* flag variables */
451         char c = 0;
452
453         modules.resize(255);
454         factory.resize(255);
455         memset(&server, 0, sizeof(server));
456         memset(&client, 0, sizeof(client));
457
458         this->unregistered_count = 0;
459
460         this->clientlist = new user_hash();
461         this->chanlist = new chan_hash();
462
463         this->Config = new ServerConfig(this);
464
465         this->Config->argv = argv;
466         this->Config->argc = argc;
467
468         chdir(Config->GetFullProgDir().c_str());
469
470         this->Config->opertypes.clear();
471         this->Config->operclass.clear();
472         this->SNO = new SnomaskManager(this);
473         this->TIME = this->OLDTIME = this->startup_time = time(NULL);
474         this->time_delta = 0;
475         this->next_call = this->TIME + 3;
476         srand(this->TIME);
477
478         *this->LogFileName = 0;
479         strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
480
481         struct option longopts[] =
482         {
483                 { "nofork",     no_argument,            &do_nofork,     1       },
484                 { "logfile",    required_argument,      NULL,           'f'     },
485                 { "config",     required_argument,      NULL,           'c'     },
486                 { "debug",      no_argument,            &do_debug,      1       },
487                 { "nolog",      no_argument,            &do_nolog,      1       },
488                 { "runasroot",  no_argument,            &do_root,       1       },
489                 { "version",    no_argument,            &do_version,    1       },
490                 { 0, 0, 0, 0 }
491         };
492
493         while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
494         {
495                 switch (c)
496                 {
497                         case 'f':
498                                 /* Log filename was set */
499                                 strlcpy(LogFileName, optarg, MAXBUF);
500                         break;
501                         case 'c':
502                                 /* Config filename was set */
503                                 strlcpy(ConfigFileName, optarg, MAXBUF);
504                         break;
505                         case 0:
506                                 /* getopt_long_only() set an int variable, just keep going */
507                         break;
508                         default:
509                                 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
510                                 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
511                                 Exit(EXIT_STATUS_ARGV);
512                         break;
513                 }
514         }
515
516         if (do_version)
517         {
518                 printf("\n%s r%s\n", VERSION, REVISION);
519                 Exit(EXIT_STATUS_NOERROR);
520         }
521
522 #ifdef WIN32
523
524         // Handle forking
525         if(!do_nofork && !owner_processid)
526         {
527                 DWORD ExitCode = WindowsForkStart(this);
528                 if(ExitCode)
529                         Exit(ExitCode);
530         }
531
532         // Set up winsock
533         WSADATA wsadata;
534         WSAStartup(MAKEWORD(2,0), &wsadata);
535
536 #endif
537         if (!ServerConfig::FileExists(this->ConfigFileName))
538         {
539                 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
540                 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
541                 Exit(EXIT_STATUS_CONFIG);
542         }
543
544         printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
545         printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
546         printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey, Burlex\033[0m\n");
547         printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
548
549         /* Set the finished argument values */
550         Config->nofork = do_nofork;
551         Config->forcedebug = do_debug;
552         Config->writelog = !do_nolog;
553
554         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
555
556         this->OpenLog(argv, argc);
557
558         this->stats = new serverstats();
559         this->Timers = new TimerManager(this);
560         this->Parser = new CommandParser(this);
561         this->XLines = new XLineManager(this);
562         Config->ClearStack();
563         Config->Read(true, NULL);
564
565         if (!do_root)
566                 this->CheckRoot();
567         else
568         {
569                 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
570                 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
571                 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
572                 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
573                 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
574                 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
575                 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
576                 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
577                 sleep(20);
578         }
579
580         this->SetSignals();
581
582         if (!Config->nofork)
583         {
584                 if (!this->DaemonSeed())
585                 {
586                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
587                         Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
588                         Exit(EXIT_STATUS_FORK);
589                 }
590         }
591
592
593         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
594          * initialize the socket engine.
595          */
596         SocketEngineFactory* SEF = new SocketEngineFactory();
597         SE = SEF->Create(this);
598         delete SEF;
599
600         this->Modes = new ModeParser(this);
601         this->AddServerName(Config->ServerName);
602         CheckDie();
603         int bounditems = BindPorts(true, found_ports, pl);
604
605         for(int t = 0; t < 255; t++)
606                 Config->global_implementation[t] = 0;
607
608         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
609
610         printf("\n");
611
612         this->Res = new DNS(this);
613
614         this->LoadAllModules();
615         /* Just in case no modules were loaded - fix for bug #101 */
616         this->BuildISupport();
617         InitializeDisabledCommands(Config->DisabledCommands, this);
618
619         if ((Config->ports.size() == 0) && (found_ports > 0))
620         {
621                 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
622                 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
623                 Exit(EXIT_STATUS_BIND);
624         }
625
626         if (Config->ports.size() != (unsigned int)found_ports)
627         {
628                 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
629                 printf("The following port(s) failed to bind:\n");
630                 int j = 1;
631                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
632                 {
633                         printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
634                 }
635         }
636 #ifndef WINDOWS
637         if (!Config->nofork)
638         {
639                 if (kill(getppid(), SIGTERM) == -1)
640                 {
641                         printf("Error killing parent process: %s\n",strerror(errno));
642                         Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
643                 }
644         }
645
646         if (isatty(0) && isatty(1) && isatty(2))
647         {
648                 /* We didn't start from a TTY, we must have started from a background process -
649                  * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
650                  * close stdin/stdout
651                  */
652                 if (!do_nofork)
653                 {
654                         fclose(stdin);
655                         fclose(stderr);
656                         fclose(stdout);
657                 }
658                 else
659                 {
660                         Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
661                 }
662         }
663 #else
664         InitIPC();
665         if(!Config->nofork)
666         {
667                 WindowsForkKillOwner(this);
668                 FreeConsole();
669         }
670 #endif
671         printf("\nInspIRCd is now running!\n");
672         Log(DEFAULT,"Startup complete.");
673
674         this->WritePID(Config->PID);
675 }
676
677 std::string InspIRCd::GetVersionString()
678 {
679         char versiondata[MAXBUF];
680         char dnsengine[] = "singlethread-object";
681
682         if (*Config->CustomVersion)
683         {
684                 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
685         }
686         else
687         {
688                 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%s,%s,%s]",VERSION,Config->ServerName,SYSTEM,REVISION,SE->GetName().c_str(),dnsengine);
689         }
690         return versiondata;
691 }
692
693 void InspIRCd::BuildISupport()
694 {
695         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
696         std::stringstream v;
697         v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES-1 << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << Config->MaxChans << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
698         v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
699         v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32 ELIST=MU";
700         Config->data005 = v.str();
701         FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
702         Config->Update005();
703 }
704
705 void InspIRCd::DoOneIteration(bool process_module_sockets)
706 {
707 #ifndef WIN32
708         static rusage ru;
709 #else
710         static time_t uptime;
711         static struct tm * stime;
712         static char window_title[100];
713 #endif
714
715         /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
716          * Once per loop iteration is pleanty.
717          */
718         OLDTIME = TIME;
719         TIME = time(NULL);
720
721         /* Run background module timers every few seconds
722          * (the docs say modules shouldnt rely on accurate
723          * timing using this event, so we dont have to
724          * time this exactly).
725          */
726         if (TIME != OLDTIME)
727         {
728                 if (TIME < OLDTIME)
729                         WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
730                 if ((TIME % 3600) == 0)
731                 {
732                         this->RehashUsersAndChans();
733                         FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
734                 }
735                 Timers->TickTimers(TIME);
736                 this->DoBackgroundUserStuff(TIME);
737
738                 if ((TIME % 5) == 0)
739                 {
740                         XLines->expire_lines();
741                         FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
742                         Timers->TickMissedTimers(TIME);
743                 }
744 #ifndef WIN32
745                 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
746                 if (!getrusage(RUSAGE_SELF, &ru))
747                 {
748                         gettimeofday(&this->stats->LastSampled, NULL);
749                         this->stats->LastCPU = ru.ru_utime;
750                 }
751 #else
752                 CheckIPC(this);
753
754                 if(Config->nofork)
755                 {
756                         uptime = Time() - startup_time;
757                         stime = gmtime(&uptime);
758                         snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
759                                 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
760                         SetConsoleTitle(window_title);
761                 }
762 #endif
763         }
764
765         /* Call the socket engine to wait on the active
766          * file descriptors. The socket engine has everything's
767          * descriptors in its list... dns, modules, users,
768          * servers... so its nice and easy, just one call.
769          * This will cause any read or write events to be
770          * dispatched to their handlers.
771          */
772         this->SE->DispatchEvents();
773
774         /* if any users was quit, take them out */
775         this->GlobalCulls.Apply();
776
777         /* If any inspsockets closed, remove them */
778         this->InspSocketCull();
779 }
780
781 void InspIRCd::InspSocketCull()
782 {
783         for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
784         {
785                 SE->DelFd(x->second);
786                 x->second->Close();
787                 delete x->second;
788         }
789         SocketCull.clear();
790 }
791
792 int InspIRCd::Run()
793 {
794         while (true)
795         {
796                 DoOneIteration(true);
797         }
798         /* This is never reached -- we hope! */
799         return 0;
800 }
801
802 /**********************************************************************************/
803
804 /**
805  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
806  */
807
808 int main(int argc, char** argv)
809 {
810         SI = new InspIRCd(argc, argv);
811         SI->Run();
812         delete SI;
813         return 0;
814 }
815
816 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
817  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
818  * registration timeout maximum seconds)
819  */
820 bool InspIRCd::AllModulesReportReady(userrec* user)
821 {
822         if (!Config->global_implementation[I_OnCheckReady])
823                 return true;
824
825         for (int i = 0; i <= this->GetModuleCount(); i++)
826         {
827                 if (Config->implement_lists[i][I_OnCheckReady])
828                 {
829                         int res = modules[i]->OnCheckReady(user);
830                         if (!res)
831                                 return false;
832                 }
833         }
834         return true;
835 }
836
837 int InspIRCd::GetModuleCount()
838 {
839         return this->ModCount;
840 }
841
842 time_t InspIRCd::Time(bool delta)
843 {
844         if (delta)
845                 return TIME + time_delta;
846         return TIME;
847 }
848
849 int InspIRCd::SetTimeDelta(int delta)
850 {
851         int old = time_delta;
852         time_delta = delta;
853         this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
854         return old;
855 }
856
857 void InspIRCd::AddLocalClone(userrec* user)
858 {
859         clonemap::iterator x = local_clones.find(user->GetIPString());
860         if (x != local_clones.end())
861                 x->second++;
862         else
863                 local_clones[user->GetIPString()] = 1;
864 }
865
866 void InspIRCd::AddGlobalClone(userrec* user)
867 {
868         clonemap::iterator y = global_clones.find(user->GetIPString());
869         if (y != global_clones.end())
870                 y->second++;
871         else
872                 global_clones[user->GetIPString()] = 1;
873 }
874
875 int InspIRCd::GetTimeDelta()
876 {
877         return time_delta;
878 }
879
880 bool FileLogger::Readable()
881 {
882         return false;
883 }
884
885 void FileLogger::HandleEvent(EventType et, int errornum)
886 {
887         this->WriteLogLine("");
888         if (log)
889                 ServerInstance->SE->DelFd(this);
890 }
891
892 void FileLogger::WriteLogLine(const std::string &line)
893 {
894         if (line.length())
895                 buffer.append(line);
896
897         if (log)
898         {
899                 int written = fprintf(log,"%s",buffer.c_str());
900 #ifdef WINDOWS
901                 buffer.clear();
902 #else
903                 if ((written >= 0) && (written < (int)buffer.length()))
904                 {
905                         buffer.erase(0, buffer.length());
906                         ServerInstance->SE->AddFd(this);
907                 }
908                 else if (written == -1)
909                 {
910                         if (errno == EAGAIN)
911                                 ServerInstance->SE->AddFd(this);
912                 }
913                 else
914                 {
915                         /* Wrote the whole buffer, and no need for write callback */
916                         buffer.clear();
917                 }
918 #endif
919                 if (writeops++ % 20)
920                 {
921                         fflush(log);
922                 }
923         }
924 }
925
926 void FileLogger::Close()
927 {
928         if (log)
929         {
930                 /* Burlex: Windows assumes nonblocking on FILE* pointers anyway, and also "file" fd's aren't the same
931                  * as socket fd's. */
932 #ifndef WIN32
933                 int flags = fcntl(fileno(log), F_GETFL, 0);
934                 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
935 #endif
936                 if (buffer.size())
937                         fprintf(log,"%s",buffer.c_str());
938
939 #ifndef WINDOWS
940                 ServerInstance->SE->DelFd(this);
941 #endif
942
943                 fflush(log);
944                 fclose(log);
945         }
946
947         buffer.clear();
948 }
949
950 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
951 {
952         if (log)
953         {
954                 irc::sockets::NonBlocking(fileno(log));
955                 this->SetFd(fileno(log));
956                 buffer.clear();
957         }
958 }
959
960 FileLogger::~FileLogger()
961 {
962         this->Close();
963 }
964