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