]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
550baa027d2c4e34500e16d51af887a2656c383b
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 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 /* w00t was here. ;p */
15
16 /* $Install: src/inspircd $(BINPATH) */
17 #include "inspircd.h"
18 #include <signal.h>
19
20 #ifndef WIN32
21         #include <dirent.h>
22         #include <unistd.h>
23         #include <sys/resource.h>
24         #include <dlfcn.h>
25         #include <getopt.h>
26
27         /* Some systems don't define RUSAGE_SELF. This should fix them. */
28         #ifndef RUSAGE_SELF
29                 #define RUSAGE_SELF 0
30         #endif
31
32         /* CRT memory debugging */
33         #ifdef DEBUG
34         #define _CRTDBG_MAP_ALLOC
35         #include <stdlib.h>
36         #include <crtdbg.h>
37         #endif
38 #endif
39
40 #include <fstream>
41 #include "xline.h"
42 #include "bancache.h"
43 #include "socketengine.h"
44 #include "inspircd_se_config.h"
45 #include "socket.h"
46 #include "command_parse.h"
47 #include "exitcodes.h"
48 #include "caller.h"
49 #include "testsuite.h"
50
51 using irc::sockets::insp_ntoa;
52 using irc::sockets::insp_inaddr;
53 using irc::sockets::insp_sockaddr;
54
55 InspIRCd* SI = NULL;
56 int* mysig = NULL;
57
58
59 /* Moved from exitcodes.h -- due to duplicate symbols -- Burlex
60  * XXX this is a bit ugly. -- w00t
61  */
62 const char* ExitCodes[] =
63 {
64                 "No error", /* 0 */
65                 "DIE command", /* 1 */
66                 "execv() failed", /* 2 */
67                 "Internal error", /* 3 */
68                 "Config file error", /* 4 */
69                 "Logfile error", /* 5 */
70                 "POSIX fork failed", /* 6 */
71                 "Bad commandline parameters", /* 7 */
72                 "No ports could be bound", /* 8 */
73                 "Can't write PID file", /* 9 */
74                 "SocketEngine could not initialize", /* 10 */
75                 "Refusing to start up as root", /* 11 */
76                 "Found a <die> tag!", /* 12 */
77                 "Couldn't load module on startup", /* 13 */
78                 "Could not create windows forked process", /* 14 */
79                 "Received SIGTERM", /* 15 */
80                 "Bad command handler loaded", /* 16 */
81                 "Windows service specific error 1", /* 17 - Dont know what to call these yet, will give them */
82                 "Windows service specific error 2", /* 18 - better descriptions later on */
83                 "Windows service specific error 3", /* 19 */
84                 "Windows service specific error 4", /* 20 */
85                 "Windows service specific error 5", /* 21 */
86                 "Windows service specific error 6"  /* 22 */
87 };
88
89 void InspIRCd::Cleanup()
90 {
91         if (Config)
92         {
93                 for (unsigned int i = 0; i < Config->ports.size(); i++)
94                 {
95                         /* This calls the constructor and closes the listening socket */
96                         delete Config->ports[i];
97                 }
98
99                 Config->ports.clear();
100         }
101
102         /* Close all client sockets, or the new process inherits them */
103         for (std::vector<User*>::const_iterator i = this->Users->local_users.begin(); i != this->Users->local_users.end(); i++)
104         {
105                 this->Users->QuitUser((*i), "Server shutdown");
106                 (*i)->CloseSocket();
107         }
108
109         /* We do this more than once, so that any service providers get a
110          * chance to be unhooked by the modules using them, but then get
111          * a chance to be removed themsleves.
112          *
113          * XXX there may be a better way to do this with 1.2
114          */
115         for (int tries = 0; tries < 3; tries++)
116         {
117                 std::vector<std::string> module_names = Modules->GetAllModuleNames(0);
118                 for (std::vector<std::string>::iterator k = module_names.begin(); k != module_names.end(); ++k)
119                 {
120                         /* Unload all modules, so they get a chance to clean up their listeners */
121                         this->Modules->Unload(k->c_str());
122                 }
123         }
124         /* Remove core commands */
125         Parser->RemoveCommands("<core>");
126
127         /* Cleanup Server Names */
128         for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
129                 delete (*itr);
130
131         /* Delete objects dynamically allocated in constructor
132          * (destructor would be more appropriate, but we're likely exiting)
133          */
134
135         // Must be deleted before modes as it decrements modelines
136         if (this->Users)
137         {
138                 delete this->Users;
139                 this->Users = 0;
140         }
141         
142         if (this->Modes)
143         {
144                 delete this->Modes;
145                 this->Modes = 0;
146         }
147
148         if (this->XLines)
149         {
150                 delete this->XLines;
151                 this->XLines = 0;
152         }
153
154         if (this->Parser)
155         {
156                 delete this->Parser;
157                 this->Parser = 0;
158
159         if (this->stats)
160         {
161                 delete this->stats;
162                 this->stats = 0;
163         }
164
165         if (this->Modules)
166         {
167                 delete this->Modules;
168                 this->Modules = 0;
169         }
170
171         if (this->BanCache)
172                 delete this->BanCache;
173                 this->BanCache = 0;
174         }
175
176         if (this->SNO)
177         {
178                 delete this->SNO;
179                 this->SNO = 0;
180         }
181
182         if (this->Config)
183         {
184                 delete this->Config;
185                 this->Config = 0;
186         }
187
188         if (this->Res)
189         {
190                 delete this->Res;
191                 this->Res = 0;
192         }
193
194         if (this->chanlist)
195         {
196                 delete chanlist;
197                 chanlist = 0;
198         }
199
200         if (this->PI)
201         {
202                 delete this->PI;
203                 this->PI = 0;
204         }
205         
206         if (this->Threads)
207         {
208                 delete this->Threads;
209                 this->Threads = 0;
210         }
211
212         /* Needs to be deleted after Res, DNS has a timer */
213         if (this->Timers)
214         {
215                 delete this->Timers;
216                 this->Timers = 0;
217         }
218
219         /* Close logging */
220         this->Logs->CloseLogs();
221
222         if (this->Logs)
223         {
224                 delete this->Logs;
225                 this->Logs = 0;
226         }
227 }
228
229 void InspIRCd::Restart(const std::string &reason)
230 {
231         /* SendError flushes each client's queue,
232          * regardless of writeability state
233          */
234         this->SendError(reason);
235
236         /* Figure out our filename (if theyve renamed it, we're boned) */
237         std::string me;
238
239 #ifdef WINDOWS
240         char module[MAX_PATH];
241         if (GetModuleFileName(NULL, module, MAX_PATH))
242                 me = module;
243 #else
244         me = Config->MyDir + "/inspircd";
245 #endif
246
247         char** argv = Config->argv;
248
249         this->Cleanup();
250
251         if (execv(me.c_str(), argv) == -1)
252         {
253                 /* Will raise a SIGABRT if not trapped */
254                 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
255         }
256 }
257
258 void InspIRCd::ResetMaxBans()
259 {
260         for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
261                 i->second->ResetMaxBans();
262 }
263
264 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
265  * we must occasionally rehash the hash (yes really).
266  * We do this by copying the entries from the old hash to a new hash, causing all
267  * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
268  * very expensive, so instead we do it when the user types /REHASH and expects a
269  * short delay anyway.
270  */
271 void InspIRCd::RehashUsersAndChans()
272 {
273         user_hash* old_users = this->Users->clientlist;
274         user_hash* old_uuid  = this->Users->uuidlist;
275         chan_hash* old_chans = this->chanlist;
276
277         this->Users->clientlist = new user_hash();
278         this->Users->uuidlist = new user_hash();
279         this->chanlist = new chan_hash();
280
281         for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
282                 this->Users->clientlist->insert(*n);
283
284         delete old_users;
285
286         for (user_hash::const_iterator n = old_uuid->begin(); n != old_uuid->end(); n++)
287                 this->Users->uuidlist->insert(*n);
288
289         delete old_uuid;
290
291         for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
292                 this->chanlist->insert(*n);
293
294         delete old_chans;
295 }
296
297 void InspIRCd::SetSignals()
298 {
299 #ifndef WIN32
300         signal(SIGALRM, SIG_IGN);
301         signal(SIGHUP, InspIRCd::SetSignal);
302         signal(SIGPIPE, SIG_IGN);
303         signal(SIGCHLD, SIG_IGN);
304 #endif
305         signal(SIGTERM, InspIRCd::SetSignal);
306 }
307
308 void InspIRCd::QuickExit(int status)
309 {
310         exit(0);
311 }
312
313 bool InspIRCd::DaemonSeed()
314 {
315 #ifdef WINDOWS
316         printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
317         return true;
318 #else
319         signal(SIGTERM, InspIRCd::QuickExit);
320
321         int childpid;
322         if ((childpid = fork ()) < 0)
323                 return false;
324         else if (childpid > 0)
325         {
326                 /* We wait here for the child process to kill us,
327                  * so that the shell prompt doesnt come back over
328                  * the output.
329                  * Sending a kill with a signal of 0 just checks
330                  * if the child pid is still around. If theyre not,
331                  * they threw an error and we should give up.
332                  */
333                 while (kill(childpid, 0) != -1)
334                         sleep(1);
335                 exit(0);
336         }
337         setsid ();
338         umask (007);
339         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
340
341         signal(SIGTERM, InspIRCd::SetSignal);
342
343         rlimit rl;
344         if (getrlimit(RLIMIT_CORE, &rl) == -1)
345         {
346                 this->Logs->Log("STARTUP",DEFAULT,"Failed to getrlimit()!");
347                 return false;
348         }
349         else
350         {
351                 rl.rlim_cur = rl.rlim_max;
352                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
353                         this->Logs->Log("STARTUP",DEFAULT,"setrlimit() failed, cannot increase coredump size.");
354         }
355
356         return true;
357 #endif
358 }
359
360 void InspIRCd::WritePID(const std::string &filename)
361 {
362         std::string fname = (filename.empty() ? "inspircd.pid" : filename);
363         std::replace(fname.begin(), fname.end(), '\\', '/');
364         if ((fname[0] != '/') && (!Config->StartsWithWindowsDriveLetter(filename)))
365         {
366                 std::string::size_type pos;
367                 std::string confpath = this->ConfigFileName;
368                 if ((pos = confpath.rfind("/")) != std::string::npos)
369                 {
370                         /* Leaves us with just the path */
371                         fname = confpath.substr(0, pos) + std::string("/") + fname;
372                 }
373         }
374         std::ofstream outfile(fname.c_str());
375         if (outfile.is_open())
376         {
377                 outfile << getpid();
378                 outfile.close();
379         }
380         else
381         {
382                 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
383                 this->Logs->Log("STARTUP",DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
384                 Exit(EXIT_STATUS_PID);
385         }
386 }
387
388 InspIRCd::InspIRCd(int argc, char** argv)
389         : GlobalCulls(this),
390
391          /* Functor initialisation. Note that the ordering here is very important. 
392           *
393           * THIS MUST MATCH ORDER OF DECLARATION OF THE HandleWhateverFunc classes
394           * within class InspIRCd.
395           */
396          HandleProcessUser(this),
397          HandleIsNick(this),
398          HandleIsIdent(this),
399          HandleFindDescriptor(this),
400          HandleFloodQuitUser(this),
401          HandleIsChannel(this),
402          HandleIsSID(this),
403          HandleRehash(this),
404
405          /* Functor pointer initialisation. Must match the order of the list above
406           *
407           * THIS MUST MATCH THE ORDER OF DECLARATION OF THE FUNCTORS, e.g. the methods
408           * themselves within the class.
409           */
410          ProcessUser(&HandleProcessUser),
411          IsChannel(&HandleIsChannel),
412          IsSID(&HandleIsSID),
413          Rehash(&HandleRehash),
414          IsNick(&HandleIsNick),
415          IsIdent(&HandleIsIdent),
416          FindDescriptor(&HandleFindDescriptor),
417          FloodQuitUser(&HandleFloodQuitUser)
418
419 {
420 #ifdef WIN32
421         // Strict, frequent checking of memory on debug builds
422         _CrtSetDbgFlag ( _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
423         
424         // Avoid erroneous frees on early exit
425         WindowsIPC = 0;
426 #endif
427         int found_ports = 0;
428         FailedPortList pl;
429         int do_version = 0, do_nofork = 0, do_debug = 0,
430             do_nolog = 0, do_root = 0, do_testsuite = 0;    /* flag variables */
431         char c = 0;
432
433         // Initialize so that if we exit before proper initialization they're not deleted
434         this->Logs = 0;
435         this->Threads = 0;
436         this->PI = 0;
437         this->Users = 0;
438         this->chanlist = 0;
439         this->Config = 0;
440         this->SNO = 0;
441         this->BanCache = 0;
442         this->Modules = 0;
443         this->stats = 0;
444         this->Timers = 0;
445         this->Parser = 0;
446         this->XLines = 0;
447         this->Modes = 0;
448         this->Res = 0;
449
450
451         memset(&server, 0, sizeof(server));
452         memset(&client, 0, sizeof(client));
453
454         // This must be created first, so other parts of Insp can use it while starting up
455         this->Logs = new LogManager(this);
456
457         SocketEngineFactory* SEF = new SocketEngineFactory();
458         SE = SEF->Create(this);
459         delete SEF;
460
461         ThreadEngineFactory* tef = new ThreadEngineFactory();
462         this->Threads = tef->Create(this);
463         delete tef;
464
465         /* Default implementation does nothing */
466         this->PI = new ProtocolInterface(this);
467
468         this->s_signal = 0;
469         
470         // Create base manager classes early, so nothing breaks
471         this->Users = new UserManager(this);
472         
473         this->Users->unregistered_count = 0;
474
475         this->Users->clientlist = new user_hash();
476         this->Users->uuidlist = new user_hash();
477         this->chanlist = new chan_hash();
478
479         this->Config = new ServerConfig(this);
480         this->SNO = new SnomaskManager(this);
481         this->BanCache = new BanCacheManager(this);
482         this->Modules = new ModuleManager(this);
483         this->stats = new serverstats();
484         this->Timers = new TimerManager(this);
485         this->Parser = new CommandParser(this);
486         this->XLines = new XLineManager(this);
487
488         this->Config->argv = argv;
489         this->Config->argc = argc;
490
491         if (chdir(Config->GetFullProgDir().c_str()))
492         {
493                 printf("Unable to change to my directory: %s\nAborted.", strerror(errno));
494                 exit(0);
495         }
496
497         this->Config->opertypes.clear();
498         this->Config->operclass.clear();
499
500         this->TIME = this->OLDTIME = this->startup_time = time(NULL);
501         srand(this->TIME);
502
503         *this->LogFileName = 0;
504         strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
505
506         struct option longopts[] =
507         {
508                 { "nofork",     no_argument,            &do_nofork,     1       },
509                 { "logfile",    required_argument,      NULL,           'f'     },
510                 { "config",     required_argument,      NULL,           'c'     },
511                 { "debug",      no_argument,            &do_debug,      1       },
512                 { "nolog",      no_argument,            &do_nolog,      1       },
513                 { "runasroot",  no_argument,            &do_root,       1       },
514                 { "version",    no_argument,            &do_version,    1       },
515                 { "testsuite",  no_argument,            &do_testsuite,  1       },
516                 { 0, 0, 0, 0 }
517         };
518
519         while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
520         {
521                 switch (c)
522                 {
523                         case 'f':
524                                 /* Log filename was set */
525                                 strlcpy(LogFileName, optarg, MAXBUF);
526                         break;
527                         case 'c':
528                                 /* Config filename was set */
529                                 strlcpy(ConfigFileName, optarg, MAXBUF);
530                         break;
531                         case 0:
532                                 /* getopt_long_only() set an int variable, just keep going */
533                         break;
534                         default:
535                                 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
536                                 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>]\n\
537                                                   [--runasroot] [--version] [--config <config>] [--testsuite]\n", argv[0]);
538                                 Exit(EXIT_STATUS_ARGV);
539                         break;
540                 }
541         }
542
543         if (do_testsuite)
544                 do_nofork = do_debug = true;
545
546         if (do_version)
547         {
548                 printf("\n%s r%s\n", VERSION, REVISION);
549                 Exit(EXIT_STATUS_NOERROR);
550         }
551
552 #ifdef WIN32
553
554         // Handle forking
555         if(!do_nofork)
556         {
557                 DWORD ExitCode = WindowsForkStart(this);
558                 if(ExitCode)
559                         exit(ExitCode);
560         }
561
562         // Set up winsock
563         WSADATA wsadata;
564         WSAStartup(MAKEWORD(2,0), &wsadata);
565         ChangeWindowsSpecificPointers(this);
566 #endif
567         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
568
569         /* Set the finished argument values */
570         Config->nofork = do_nofork;
571         Config->forcedebug = do_debug;
572         Config->writelog = !do_nolog;
573         Config->TestSuite = do_testsuite;
574
575         if (!this->OpenLog(argv, argc))
576         {
577                 printf("ERROR: Could not open logfile %s: %s\n\n", Config->logpath.c_str(), strerror(errno));
578                 Exit(EXIT_STATUS_LOG);
579         }
580
581         if (!ServerConfig::FileExists(this->ConfigFileName))
582         {
583                 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
584                 this->Logs->Log("STARTUP",DEFAULT,"Unable to open config file %s", this->ConfigFileName);
585                 Exit(EXIT_STATUS_CONFIG);
586         }
587
588         printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
589         printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
590         printf_c("Developers:\n");
591         printf_c("\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\n");
592         printf_c("\t\033[1;32mpippijn, peavey, aquanight, fez\033[0m\n\n");
593         printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
594
595         Config->ClearStack();
596
597         this->Modes = new ModeParser(this);
598
599         if (!do_root)
600                 this->CheckRoot();
601         else
602         {
603                 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
604                 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
605                 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
606                 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
607                 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
608                 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
609                 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
610                 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
611                 sleep(20);
612         }
613
614         this->SetSignals();
615
616         if (!Config->nofork)
617         {
618                 if (!this->DaemonSeed())
619                 {
620                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
621                         Logs->Log("STARTUP", DEFAULT, "ERROR: could not go into daemon mode. Shutting down.");
622                         Exit(EXIT_STATUS_FORK);
623                 }
624         }
625
626         SE->RecoverFromFork();
627
628         /* During startup we don't actually initialize this
629          * in the thread engine.
630          */
631         this->ConfigThread = new ConfigReaderThread(this, true, NULL);
632         ConfigThread->Run();
633         delete ConfigThread;
634         this->ConfigThread = NULL;
635
636         this->Res = new DNS(this);
637
638         this->AddServerName(Config->ServerName);
639
640         /*
641          * Initialise SID/UID.
642          * For an explanation as to exactly how this works, and why it works this way, see GetUID().
643          *   -- w00t
644          */
645         if (!*Config->sid)
646         {
647                 // Generate one
648                 size_t sid = 0;
649
650                 for (const char* x = Config->ServerName; *x; ++x)
651                         sid = 5 * sid + *x;
652                 for (const char* y = Config->ServerDesc; *y; ++y)
653                         sid = 5 * sid + *y;
654                 sid = sid % 999;
655
656                 Config->sid[0] = (char)(sid / 100 + 48);
657                 Config->sid[1] = (char)(((sid / 10) % 10) + 48);
658                 Config->sid[2] = (char)(sid % 10 + 48);
659                 Config->sid[3] = '\0';
660         }
661
662         /* set up fake client again this time with the correct uid */
663         this->FakeClient = new User(this, "#INVALID");
664         this->FakeClient->SetFd(FD_MAGIC_NUMBER);
665
666         // Get XLine to do it's thing.
667         this->XLines->CheckELines();
668         this->XLines->ApplyLines();
669
670         CheckDie();
671         int bounditems = BindPorts(true, found_ports, pl);
672
673         printf("\n");
674
675         this->Modules->LoadAll();
676         
677         /* Just in case no modules were loaded - fix for bug #101 */
678         this->BuildISupport();
679         InitializeDisabledCommands(Config->DisabledCommands, this);
680
681         if (Config->ports.size() != (unsigned int)found_ports)
682         {
683                 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
684                 printf("The following port(s) failed to bind:\n");
685                 printf("Hint: Try using a public IP instead of blank or *\n\n");
686                 int j = 1;
687                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
688                 {
689                         printf("%d.\tAddress: %s\tReason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
690                 }
691         }
692
693         printf("\nInspIRCd is now running as '%s'[%s] with %d max open sockets\n", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
694         
695 #ifndef WINDOWS
696         if (!Config->nofork)
697         {
698                 if (kill(getppid(), SIGTERM) == -1)
699                 {
700                         printf("Error killing parent process: %s\n",strerror(errno));
701                         Logs->Log("STARTUP", DEFAULT, "Error killing parent process: %s",strerror(errno));
702                 }
703         }
704
705         if (isatty(0) && isatty(1) && isatty(2))
706         {
707                 /* We didn't start from a TTY, we must have started from a background process -
708                  * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
709                  * close stdin/stdout
710                  */
711                 if ((!do_nofork) && (!do_testsuite))
712                 {
713                         fclose(stdin);
714                         fclose(stderr);
715                         fclose(stdout);
716                 }
717                 else
718                 {
719                         Logs->Log("STARTUP", DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
720                 }
721         }
722 #else
723         WindowsIPC = new IPC(this);
724         if(!Config->nofork)
725         {
726                 WindowsForkKillOwner(this);
727                 FreeConsole();
728         }
729         /* Set win32 service as running, if we are running as a service */
730         SetServiceRunning();
731 #endif
732
733         Logs->Log("STARTUP", DEFAULT, "Startup complete as '%s'[%s], %d max open sockets", Config->ServerName,Config->GetSID().c_str(), SE->GetMaxFds());
734
735         this->WritePID(Config->PID);
736 }
737
738 int InspIRCd::Run()
739 {
740         /* See if we're supposed to be running the test suite rather than entering the mainloop */
741         if (Config->TestSuite)
742         {
743                 TestSuite* ts = new TestSuite(this);
744                 delete ts;
745                 Exit(0);
746         }
747
748         while (true)
749         {
750 #ifndef WIN32
751                 static rusage ru;
752 #else
753                 static time_t uptime;
754                 static struct tm * stime;
755                 static char window_title[100];
756 #endif
757
758                 /* Check if there is a config thread which has finished executing but has not yet been freed */
759                 if (this->ConfigThread && this->ConfigThread->GetExitFlag())
760                 {
761                         /* Rehash has completed */
762                         this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");
763
764                         /* IMPORTANT: This delete may hang if you fuck up your thread syncronization.
765                          * It will hang waiting for the ConfigThread to 'join' to avoid race conditons,
766                          * until the other thread is completed.
767                          */
768                         delete ConfigThread;
769                         ConfigThread = NULL;
770
771                         /* These are currently not known to be threadsafe, so they are executed outside
772                          * of the thread. It would be pretty simple to move them to the thread Run method
773                          * once they are known threadsafe with all the correct mutexes in place.
774                          *
775                          * XXX: The order of these is IMPORTANT, do not reorder them without testing
776                          * thoroughly!!!
777                          */
778                         this->XLines->CheckELines();
779                         this->XLines->ApplyLines();
780                         this->Res->Rehash();
781                         this->ResetMaxBans();
782                         InitializeDisabledCommands(Config->DisabledCommands, this);
783                         FOREACH_MOD_I(this, I_OnRehash, OnRehash(Config->RehashUser, Config->RehashParameter));
784                         this->BuildISupport();
785                 }
786
787                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
788                  * Once per loop iteration is pleanty.
789                  */
790                 OLDTIME = TIME;
791                 TIME = time(NULL);
792
793                 /* Run background module timers every few seconds
794                  * (the docs say modules shouldnt rely on accurate
795                  * timing using this event, so we dont have to
796                  * time this exactly).
797                  */
798                 if (TIME != OLDTIME)
799                 {
800                         /* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
801                         if (TIME < OLDTIME - 2)
802                         {
803                                 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME);
804                         }
805                         else if (TIME > OLDTIME + 2)
806                         {
807                                 SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME - OLDTIME);
808                         }
809
810                         if ((TIME % 3600) == 0)
811                         {
812                                 this->RehashUsersAndChans();
813                                 FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
814                         }
815
816                         Timers->TickTimers(TIME);
817                         this->DoBackgroundUserStuff();
818
819                         if ((TIME % 5) == 0)
820                         {
821                                 FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
822                                 SNO->FlushSnotices();
823                         }
824 #ifndef WIN32
825                         /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
826                         if (!getrusage(RUSAGE_SELF, &ru))
827                         {
828                                 gettimeofday(&this->stats->LastSampled, NULL);
829                                 this->stats->LastCPU = ru.ru_utime;
830                         }
831 #else
832                         WindowsIPC->Check();    
833 #endif
834                 }
835
836                 /* Call the socket engine to wait on the active
837                  * file descriptors. The socket engine has everything's
838                  * descriptors in its list... dns, modules, users,
839                  * servers... so its nice and easy, just one call.
840                  * This will cause any read or write events to be
841                  * dispatched to their handlers.
842                  */
843                 this->SE->DispatchEvents();
844
845                 /* if any users were quit, take them out */
846                 this->GlobalCulls.Apply();
847
848                 /* If any inspsockets closed, remove them */
849                 this->BufferedSocketCull();
850
851                 if (this->s_signal)
852                 {
853                         this->SignalHandler(s_signal);
854                         this->s_signal = 0;
855                 }
856         }
857
858         return 0;
859 }
860
861 void InspIRCd::BufferedSocketCull()
862 {
863         for (std::map<BufferedSocket*,BufferedSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
864         {
865                 this->Logs->Log("MISC",DEBUG,"Cull socket");
866                 SE->DelFd(x->second);
867                 x->second->Close();
868                 delete x->second;
869         }
870         SocketCull.clear();
871 }
872
873 /**********************************************************************************/
874
875 /**
876  * An ircd in five lines! bwahahaha. ahahahahaha. ahahah *cough*.
877  */
878
879 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
880  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
881  * registration timeout maximum seconds)
882  */
883 bool InspIRCd::AllModulesReportReady(User* user)
884 {
885         for (EventHandlerIter i = Modules->EventHandlers[I_OnCheckReady].begin(); i != Modules->EventHandlers[I_OnCheckReady].end(); ++i)
886         {
887                 if (!(*i)->OnCheckReady(user))
888                         return false;
889         }
890         return true;
891 }
892
893 time_t InspIRCd::Time()
894 {
895         return TIME;
896 }
897
898 void InspIRCd::SetSignal(int signal)
899 {
900         *mysig = signal;
901 }
902
903 /* On posix systems, the flow of the program starts right here, with
904  * ENTRYPOINT being a #define that defines main(). On Windows, ENTRYPOINT
905  * defines smain() and the real main() is in the service code under
906  * win32service.cpp. This allows the service control manager to control
907  * the process where we are running as a windows service.
908  */
909 ENTRYPOINT
910 {
911         SI = new InspIRCd(argc, argv);
912         mysig = &SI->s_signal;
913         SI->Run();
914         delete SI;
915         return 0;
916 }