]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Move a bundle of stuff to server.cpp from inspircd.cpp
[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::Exit(int status)
177 {
178 #ifdef WINDOWS
179         CloseIPC();
180 #endif
181         if (SI)
182         {
183                 SI->SendError("Exiting with status " + ConvToStr(status) + " (" + std::string(ExitCodes[status]) + ")");
184                 SI->Cleanup();
185         }
186         exit (status);
187 }
188
189 void InspIRCd::Cleanup()
190 {
191         std::vector<std::string> mymodnames;
192         int MyModCount = this->GetModuleCount();
193
194         for (unsigned int i = 0; i < Config->ports.size(); i++)
195         {
196                 /* This calls the constructor and closes the listening socket */
197                 delete Config->ports[i];
198         }
199
200         Config->ports.clear();
201
202         /* Close all client sockets, or the new process inherits them */
203         for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
204         {
205                 (*i)->SetWriteError("Server shutdown");
206                 (*i)->CloseSocket();
207         }
208
209         /* We do this more than once, so that any service providers get a
210          * chance to be unhooked by the modules using them, but then get
211          * a chance to be removed themsleves.
212          */
213         for (int tries = 0; tries < 3; tries++)
214         {
215                 MyModCount = this->GetModuleCount();
216                 mymodnames.clear();
217
218                 /* Unload all modules, so they get a chance to clean up their listeners */
219                 for (int j = 0; j <= MyModCount; j++)
220                         mymodnames.push_back(Config->module_names[j]);
221
222                 for (int k = 0; k <= MyModCount; k++)
223                         this->UnloadModule(mymodnames[k].c_str());
224         }
225
226         /* Close logging */
227         this->Logger->Close();
228
229         /* Cleanup Server Names */
230         for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
231                 delete (*itr);
232
233 #ifdef WINDOWS
234         /* WSACleanup */
235         WSACleanup();
236 #endif
237 }
238
239 void InspIRCd::Restart(const std::string &reason)
240 {
241         /* SendError flushes each client's queue,
242          * regardless of writeability state
243          */
244         this->SendError(reason);
245
246         this->Cleanup();
247
248         /* Figure out our filename (if theyve renamed it, we're boned) */
249         std::string me;
250
251 #ifdef WINDOWS
252         char module[MAX_PATH];
253         if (GetModuleFileName(NULL, module, MAX_PATH))
254                 me = module;
255 #else
256         me = Config->MyDir + "/inspircd";
257 #endif
258
259         if (execv(me.c_str(), Config->argv) == -1)
260         {
261                 /* Will raise a SIGABRT if not trapped */
262                 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
263         }
264 }
265
266 void InspIRCd::Rehash(int status)
267 {
268         SI->WriteOpers("*** Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(SI->ConfigFileName));
269         SI->CloseLog();
270         SI->OpenLog(SI->Config->argv, SI->Config->argc);
271         SI->RehashUsersAndChans();
272         FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
273         SI->Config->Read(false,NULL);
274         SI->ResetMaxBans();
275         SI->Res->Rehash();
276         FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
277         SI->BuildISupport();
278 }
279
280 void InspIRCd::ResetMaxBans()
281 {
282         for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
283                 i->second->ResetMaxBans();
284 }
285
286
287 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
288  * we must occasionally rehash the hash (yes really).
289  * We do this by copying the entries from the old hash to a new hash, causing all
290  * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
291  * very expensive, so instead we do it when the user types /REHASH and expects a
292  * short delay anyway.
293  */
294 void InspIRCd::RehashUsersAndChans()
295 {
296         user_hash* old_users = this->clientlist;
297         chan_hash* old_chans = this->chanlist;
298
299         this->clientlist = new user_hash();
300         this->chanlist = new chan_hash();
301
302         for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
303                 this->clientlist->insert(*n);
304
305         delete old_users;
306
307         for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
308                 this->chanlist->insert(*n);
309
310         delete old_chans;
311 }
312
313 void InspIRCd::CloseLog()
314 {
315         this->Logger->Close();
316 }
317
318 void InspIRCd::SetSignals()
319 {
320 #ifndef WIN32
321         signal(SIGALRM, SIG_IGN);
322         signal(SIGHUP, InspIRCd::Rehash);
323         signal(SIGPIPE, SIG_IGN);
324         signal(SIGCHLD, SIG_IGN);
325 #endif
326         signal(SIGTERM, InspIRCd::Exit);
327 }
328
329 void InspIRCd::QuickExit(int status)
330 {
331         exit(0);
332 }
333
334 bool InspIRCd::DaemonSeed()
335 {
336 #ifdef WINDOWS
337         printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
338         return true;
339 #else
340         signal(SIGTERM, InspIRCd::QuickExit);
341
342         int childpid;
343         if ((childpid = fork ()) < 0)
344                 return false;
345         else if (childpid > 0)
346         {
347                 /* We wait here for the child process to kill us,
348                  * so that the shell prompt doesnt come back over
349                  * the output.
350                  * Sending a kill with a signal of 0 just checks
351                  * if the child pid is still around. If theyre not,
352                  * they threw an error and we should give up.
353                  */
354                 while (kill(childpid, 0) != -1)
355                         sleep(1);
356                 exit(0);
357         }
358         setsid ();
359         umask (007);
360         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
361
362         signal(SIGTERM, InspIRCd::Exit);
363
364         rlimit rl;
365         if (getrlimit(RLIMIT_CORE, &rl) == -1)
366         {
367                 this->Log(DEFAULT,"Failed to getrlimit()!");
368                 return false;
369         }
370         else
371         {
372                 rl.rlim_cur = rl.rlim_max;
373                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
374                         this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
375         }
376
377         return true;
378 #endif
379 }
380
381 void InspIRCd::WritePID(const std::string &filename)
382 {
383         std::string fname = (filename.empty() ? "inspircd.pid" : filename);
384         if (*(fname.begin()) != '/')
385         {
386                 std::string::size_type pos;
387                 std::string confpath = this->ConfigFileName;
388                 if ((pos = confpath.rfind("/")) != std::string::npos)
389                 {
390                         /* Leaves us with just the path */
391                         fname = confpath.substr(0, pos) + std::string("/") + fname;
392                 }
393         }
394         std::ofstream outfile(fname.c_str());
395         if (outfile.is_open())
396         {
397                 outfile << getpid();
398                 outfile.close();
399         }
400         else
401         {
402                 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
403                 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
404                 Exit(EXIT_STATUS_PID);
405         }
406 }
407
408 InspIRCd::InspIRCd(int argc, char** argv)
409         : ModCount(-1), GlobalCulls(this)
410 {
411         int found_ports = 0;
412         FailedPortList pl;
413         int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0;    /* flag variables */
414         char c = 0;
415
416         modules.resize(255);
417         factory.resize(255);
418         memset(&server, 0, sizeof(server));
419         memset(&client, 0, sizeof(client));
420
421         this->unregistered_count = 0;
422
423         this->clientlist = new user_hash();
424         this->chanlist = new chan_hash();
425
426         this->Config = new ServerConfig(this);
427
428         this->Config->argv = argv;
429         this->Config->argc = argc;
430
431         chdir(Config->GetFullProgDir().c_str());
432
433         this->Config->opertypes.clear();
434         this->Config->operclass.clear();
435         this->SNO = new SnomaskManager(this);
436         this->TIME = this->OLDTIME = this->startup_time = time(NULL);
437         this->time_delta = 0;
438         this->next_call = this->TIME + 3;
439         srand(this->TIME);
440
441         *this->LogFileName = 0;
442         strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
443
444         struct option longopts[] =
445         {
446                 { "nofork",     no_argument,            &do_nofork,     1       },
447                 { "logfile",    required_argument,      NULL,           'f'     },
448                 { "config",     required_argument,      NULL,           'c'     },
449                 { "debug",      no_argument,            &do_debug,      1       },
450                 { "nolog",      no_argument,            &do_nolog,      1       },
451                 { "runasroot",  no_argument,            &do_root,       1       },
452                 { "version",    no_argument,            &do_version,    1       },
453                 { 0, 0, 0, 0 }
454         };
455
456         while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
457         {
458                 switch (c)
459                 {
460                         case 'f':
461                                 /* Log filename was set */
462                                 strlcpy(LogFileName, optarg, MAXBUF);
463                         break;
464                         case 'c':
465                                 /* Config filename was set */
466                                 strlcpy(ConfigFileName, optarg, MAXBUF);
467                         break;
468                         case 0:
469                                 /* getopt_long_only() set an int variable, just keep going */
470                         break;
471                         default:
472                                 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
473                                 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
474                                 Exit(EXIT_STATUS_ARGV);
475                         break;
476                 }
477         }
478
479         if (do_version)
480         {
481                 printf("\n%s r%s\n", VERSION, REVISION);
482                 Exit(EXIT_STATUS_NOERROR);
483         }
484
485 #ifdef WIN32
486
487         // Handle forking
488         if(!do_nofork && !owner_processid)
489         {
490                 DWORD ExitCode = WindowsForkStart(this);
491                 if(ExitCode)
492                         Exit(ExitCode);
493         }
494
495         // Set up winsock
496         WSADATA wsadata;
497         WSAStartup(MAKEWORD(2,0), &wsadata);
498
499 #endif
500         if (!ServerConfig::FileExists(this->ConfigFileName))
501         {
502                 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
503                 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
504                 Exit(EXIT_STATUS_CONFIG);
505         }
506
507         printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
508         printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
509         printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey, Burlex\033[0m\n");
510         printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
511
512         /* Set the finished argument values */
513         Config->nofork = do_nofork;
514         Config->forcedebug = do_debug;
515         Config->writelog = !do_nolog;
516
517         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
518
519         this->OpenLog(argv, argc);
520
521         this->stats = new serverstats();
522         this->Timers = new TimerManager(this);
523         this->Parser = new CommandParser(this);
524         this->XLines = new XLineManager(this);
525         Config->ClearStack();
526         Config->Read(true, NULL);
527
528         if (!do_root)
529                 this->CheckRoot();
530         else
531         {
532                 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
533                 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
534                 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
535                 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
536                 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
537                 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
538                 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
539                 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
540                 sleep(20);
541         }
542
543         this->SetSignals();
544
545         if (!Config->nofork)
546         {
547                 if (!this->DaemonSeed())
548                 {
549                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
550                         Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
551                         Exit(EXIT_STATUS_FORK);
552                 }
553         }
554
555
556         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
557          * initialize the socket engine.
558          */
559         SocketEngineFactory* SEF = new SocketEngineFactory();
560         SE = SEF->Create(this);
561         delete SEF;
562
563         this->Modes = new ModeParser(this);
564         this->AddServerName(Config->ServerName);
565         CheckDie();
566         int bounditems = BindPorts(true, found_ports, pl);
567
568         for(int t = 0; t < 255; t++)
569                 Config->global_implementation[t] = 0;
570
571         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
572
573         printf("\n");
574
575         this->Res = new DNS(this);
576
577         this->LoadAllModules();
578         /* Just in case no modules were loaded - fix for bug #101 */
579         this->BuildISupport();
580         InitializeDisabledCommands(Config->DisabledCommands, this);
581
582         if ((Config->ports.size() == 0) && (found_ports > 0))
583         {
584                 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
585                 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
586                 Exit(EXIT_STATUS_BIND);
587         }
588
589         if (Config->ports.size() != (unsigned int)found_ports)
590         {
591                 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
592                 printf("The following port(s) failed to bind:\n");
593                 int j = 1;
594                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
595                 {
596                         printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
597                 }
598         }
599 #ifndef WINDOWS
600         if (!Config->nofork)
601         {
602                 if (kill(getppid(), SIGTERM) == -1)
603                 {
604                         printf("Error killing parent process: %s\n",strerror(errno));
605                         Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
606                 }
607         }
608
609         if (isatty(0) && isatty(1) && isatty(2))
610         {
611                 /* We didn't start from a TTY, we must have started from a background process -
612                  * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
613                  * close stdin/stdout
614                  */
615                 if (!do_nofork)
616                 {
617                         fclose(stdin);
618                         fclose(stderr);
619                         fclose(stdout);
620                 }
621                 else
622                 {
623                         Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
624                 }
625         }
626 #else
627         InitIPC();
628         if(!Config->nofork)
629         {
630                 WindowsForkKillOwner(this);
631                 FreeConsole();
632         }
633 #endif
634         printf("\nInspIRCd is now running!\n");
635         Log(DEFAULT,"Startup complete.");
636
637         this->WritePID(Config->PID);
638 }
639
640 void InspIRCd::DoOneIteration(bool process_module_sockets)
641 {
642 #ifndef WIN32
643         static rusage ru;
644 #else
645         static time_t uptime;
646         static struct tm * stime;
647         static char window_title[100];
648 #endif
649
650         /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
651          * Once per loop iteration is pleanty.
652          */
653         OLDTIME = TIME;
654         TIME = time(NULL);
655
656         /* Run background module timers every few seconds
657          * (the docs say modules shouldnt rely on accurate
658          * timing using this event, so we dont have to
659          * time this exactly).
660          */
661         if (TIME != OLDTIME)
662         {
663                 if (TIME < OLDTIME)
664                         WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
665                 if ((TIME % 3600) == 0)
666                 {
667                         this->RehashUsersAndChans();
668                         FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
669                 }
670                 Timers->TickTimers(TIME);
671                 this->DoBackgroundUserStuff(TIME);
672
673                 if ((TIME % 5) == 0)
674                 {
675                         XLines->expire_lines();
676                         FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
677                         Timers->TickMissedTimers(TIME);
678                 }
679 #ifndef WIN32
680                 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
681                 if (!getrusage(RUSAGE_SELF, &ru))
682                 {
683                         gettimeofday(&this->stats->LastSampled, NULL);
684                         this->stats->LastCPU = ru.ru_utime;
685                 }
686 #else
687                 CheckIPC(this);
688
689                 if(Config->nofork)
690                 {
691                         uptime = Time() - startup_time;
692                         stime = gmtime(&uptime);
693                         snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
694                                 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
695                         SetConsoleTitle(window_title);
696                 }
697 #endif
698         }
699
700         /* Call the socket engine to wait on the active
701          * file descriptors. The socket engine has everything's
702          * descriptors in its list... dns, modules, users,
703          * servers... so its nice and easy, just one call.
704          * This will cause any read or write events to be
705          * dispatched to their handlers.
706          */
707         this->SE->DispatchEvents();
708
709         /* if any users was quit, take them out */
710         this->GlobalCulls.Apply();
711
712         /* If any inspsockets closed, remove them */
713         this->InspSocketCull();
714 }
715
716 void InspIRCd::InspSocketCull()
717 {
718         for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
719         {
720                 SE->DelFd(x->second);
721                 x->second->Close();
722                 delete x->second;
723         }
724         SocketCull.clear();
725 }
726
727 int InspIRCd::Run()
728 {
729         while (true)
730         {
731                 DoOneIteration(true);
732         }
733         /* This is never reached -- we hope! */
734         return 0;
735 }
736
737 /**********************************************************************************/
738
739 /**
740  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
741  */
742
743 int main(int argc, char** argv)
744 {
745         SI = new InspIRCd(argc, argv);
746         SI->Run();
747         delete SI;
748         return 0;
749 }
750
751 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
752  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
753  * registration timeout maximum seconds)
754  */
755 bool InspIRCd::AllModulesReportReady(userrec* user)
756 {
757         if (!Config->global_implementation[I_OnCheckReady])
758                 return true;
759
760         for (int i = 0; i <= this->GetModuleCount(); i++)
761         {
762                 if (Config->implement_lists[i][I_OnCheckReady])
763                 {
764                         int res = modules[i]->OnCheckReady(user);
765                         if (!res)
766                                 return false;
767                 }
768         }
769         return true;
770 }
771
772 int InspIRCd::GetModuleCount()
773 {
774         return this->ModCount;
775 }
776
777 time_t InspIRCd::Time(bool delta)
778 {
779         if (delta)
780                 return TIME + time_delta;
781         return TIME;
782 }
783
784 int InspIRCd::SetTimeDelta(int delta)
785 {
786         int old = time_delta;
787         time_delta = delta;
788         this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
789         return old;
790 }
791
792 void InspIRCd::AddLocalClone(userrec* user)
793 {
794         clonemap::iterator x = local_clones.find(user->GetIPString());
795         if (x != local_clones.end())
796                 x->second++;
797         else
798                 local_clones[user->GetIPString()] = 1;
799 }
800
801 void InspIRCd::AddGlobalClone(userrec* user)
802 {
803         clonemap::iterator y = global_clones.find(user->GetIPString());
804         if (y != global_clones.end())
805                 y->second++;
806         else
807                 global_clones[user->GetIPString()] = 1;
808 }
809
810 int InspIRCd::GetTimeDelta()
811 {
812         return time_delta;
813 }
814
815 bool FileLogger::Readable()
816 {
817         return false;
818 }
819
820 void FileLogger::HandleEvent(EventType et, int errornum)
821 {
822         this->WriteLogLine("");
823         if (log)
824                 ServerInstance->SE->DelFd(this);
825 }
826
827 void FileLogger::WriteLogLine(const std::string &line)
828 {
829         if (line.length())
830                 buffer.append(line);
831
832         if (log)
833         {
834                 int written = fprintf(log,"%s",buffer.c_str());
835 #ifdef WINDOWS
836                 buffer.clear();
837 #else
838                 if ((written >= 0) && (written < (int)buffer.length()))
839                 {
840                         buffer.erase(0, buffer.length());
841                         ServerInstance->SE->AddFd(this);
842                 }
843                 else if (written == -1)
844                 {
845                         if (errno == EAGAIN)
846                                 ServerInstance->SE->AddFd(this);
847                 }
848                 else
849                 {
850                         /* Wrote the whole buffer, and no need for write callback */
851                         buffer.clear();
852                 }
853 #endif
854                 if (writeops++ % 20)
855                 {
856                         fflush(log);
857                 }
858         }
859 }
860
861 void FileLogger::Close()
862 {
863         if (log)
864         {
865                 /* Burlex: Windows assumes nonblocking on FILE* pointers anyway, and also "file" fd's aren't the same
866                  * as socket fd's. */
867 #ifndef WIN32
868                 int flags = fcntl(fileno(log), F_GETFL, 0);
869                 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
870 #endif
871                 if (buffer.size())
872                         fprintf(log,"%s",buffer.c_str());
873
874 #ifndef WINDOWS
875                 ServerInstance->SE->DelFd(this);
876 #endif
877
878                 fflush(log);
879                 fclose(log);
880         }
881
882         buffer.clear();
883 }
884
885 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
886 {
887         if (log)
888         {
889                 irc::sockets::NonBlocking(fileno(log));
890                 this->SetFd(fileno(log));
891                 buffer.clear();
892         }
893 }
894
895 FileLogger::~FileLogger()
896 {
897         this->Close();
898 }
899