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