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