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