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