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