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