]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
eb32eac493e15f9ecf36e8849434ec815fdf5ce6
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 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 #include "inspircd.h"
15 #include "configreader.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 #endif
30
31 #include <exception>
32 #include <fstream>
33 #include "modules.h"
34 #include "mode.h"
35 #include "xline.h"
36 #include "socketengine.h"
37 #include "inspircd_se_config.h"
38 #include "socket.h"
39 #include "typedefs.h"
40 #include "command_parse.h"
41 #include "exitcodes.h"
42
43 #ifdef WIN32
44
45 /* This MUST remain static and delcared outside the class, so that WriteProcessMemory can reference it properly */
46 static DWORD owner_processid = 0;
47
48 DWORD WindowsForkStart(InspIRCd * Instance)
49 {
50         /* Windows implementation of fork() :P */
51
52         char module[MAX_PATH];
53         if(!GetModuleFileName(NULL, module, MAX_PATH))
54         {
55                 printf("GetModuleFileName() failed.\n");
56                 return false;
57         }
58
59         STARTUPINFO startupinfo;
60         PROCESS_INFORMATION procinfo;
61         ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
62         ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
63
64         // Fill in the startup info struct
65         GetStartupInfo(&startupinfo);
66
67         /* Default creation flags create the processes suspended */
68         DWORD startupflags = CREATE_SUSPENDED;
69
70         /* On windows 2003/XP and above, we can use the value
71          * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
72          * to the process which we may require on these operating systems.
73          */
74         OSVERSIONINFO vi;
75         vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
76         GetVersionEx(&vi);
77         if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
78                 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
79
80         // Launch our "forked" process.
81         BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
82                 strdup(GetCommandLine()),       // Command line (exe plus parameters from the OS)
83                                                 // NOTE: We cannot return the direct value of the
84                                                 // GetCommandLine function here, as the pointer is
85                                                 // passed straight to the child process, and will be
86                                                 // invalid once we exit as it goes out of context.
87                                                 // strdup() seems ok, though.
88                 0,                              // PROCESS_SECURITY_ATTRIBUTES
89                 0,                              // THREAD_SECURITY_ATTRIBUTES
90                 TRUE,                           // We went to inherit handles.
91                 startupflags,                   // Allow us full access to the process and suspend it.
92                 0,                              // ENVIRONMENT
93                 0,                              // CURRENT_DIRECTORY
94                 &startupinfo,                   // startup info
95                 &procinfo);                     // process info
96
97         if(!bSuccess)
98         {
99                 printf("CreateProcess() error: %s\n", dlerror());
100                 return false;
101         }
102
103         // Set the owner process id in the target process.
104         SIZE_T written = 0;
105         DWORD pid = GetCurrentProcessId();
106         if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
107         {
108                 printf("WriteProcessMemory() failed: %s\n", dlerror());
109                 return false;
110         }
111
112         // Resume the other thread (let it start)
113         ResumeThread(procinfo.hThread);
114
115         // Wait for the new process to kill us. If there is some error, the new process will end and we will end up at the next line.
116         WaitForSingleObject(procinfo.hProcess, INFINITE);
117
118         // If we hit this it means startup failed, default to 14 if this fails.
119         DWORD ExitCode = 14;
120         GetExitCodeProcess(procinfo.hProcess, &ExitCode);
121         CloseHandle(procinfo.hThread);
122         CloseHandle(procinfo.hProcess);
123         return ExitCode;
124 }
125
126 void WindowsForkKillOwner(InspIRCd * Instance)
127 {
128         HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
129         if(!hProcess || !owner_processid)
130         {
131                 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
132                 Instance->Exit(14);
133         }
134
135         // die die die
136         if(!TerminateProcess(hProcess, 0))
137         {
138                 printf("Could not TerminateProcess(): %s\n", dlerror());
139                 Instance->Exit(14);
140         }
141
142         CloseHandle(hProcess);
143 }
144
145 #endif
146
147 using irc::sockets::NonBlocking;
148 using irc::sockets::Blocking;
149 using irc::sockets::insp_ntoa;
150 using irc::sockets::insp_inaddr;
151 using irc::sockets::insp_sockaddr;
152
153 InspIRCd* SI = NULL;
154
155 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
156 const char* ExitCodes[] =
157 {
158                 "No error", /* 0 */
159                 "DIE command", /* 1 */
160                 "execv() failed", /* 2 */
161                 "Internal error", /* 3 */
162                 "Config file error", /* 4 */
163                 "Logfile error", /* 5 */
164                 "POSIX fork failed", /* 6 */
165                 "Bad commandline parameters", /* 7 */
166                 "No ports could be bound", /* 8 */
167                 "Can't write PID file", /* 9 */
168                 "SocketEngine could not initialize", /* 10 */
169                 "Refusing to start up as root", /* 11 */
170                 "Found a <die> tag!", /* 12 */
171                 "Couldn't load module on startup", /* 13 */
172                 "Could not create windows forked process", /* 14 */
173                 "Received SIGTERM", /* 15 */
174 };
175
176 void InspIRCd::AddServerName(const std::string &servername)
177 {
178         servernamelist::iterator itr = servernames.begin();
179         for(; itr != servernames.end(); ++itr)
180                 if(**itr == servername)
181                         return;
182
183         string * ns = new string(servername);
184         servernames.push_back(ns);
185 }
186
187 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
188 {
189         servernamelist::iterator itr = servernames.begin();
190         for(; itr != servernames.end(); ++itr)
191                 if(**itr == servername)
192                         return (*itr)->c_str();
193
194         servernames.push_back(new string(servername));
195         itr = --servernames.end();
196         return (*itr)->c_str();
197 }
198
199 bool InspIRCd::FindServerName(const std::string &servername)
200 {
201         servernamelist::iterator itr = servernames.begin();
202         for(; itr != servernames.end(); ++itr)
203                 if(**itr == servername)
204                         return true;
205         return false;
206 }
207
208 void InspIRCd::Exit(int status)
209 {
210 #ifdef WINDOWS
211         CloseIPC();
212 #endif
213         if (SI)
214         {
215                 SI->SendError("Exiting with status " + ConvToStr(status) + " (" + std::string(ExitCodes[status]) + ")");
216                 SI->Cleanup();
217         }
218         exit (status);
219 }
220
221 void InspIRCd::Cleanup()
222 {
223         std::vector<std::string> mymodnames;
224         int MyModCount = this->GetModuleCount();
225
226         for (unsigned int i = 0; i < Config->ports.size(); i++)
227         {
228                 /* This calls the constructor and closes the listening socket */
229                 delete Config->ports[i];
230         }
231
232         Config->ports.clear();
233
234         /* Close all client sockets, or the new process inherits them */
235         for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
236         {
237                 (*i)->SetWriteError("Server shutdown");
238                 (*i)->CloseSocket();
239         }
240
241         /* We do this more than once, so that any service providers get a
242          * chance to be unhooked by the modules using them, but then get
243          * a chance to be removed themsleves.
244          */
245         for (int tries = 0; tries < 3; tries++)
246         {
247                 MyModCount = this->GetModuleCount();
248                 mymodnames.clear();
249
250                 /* Unload all modules, so they get a chance to clean up their listeners */
251                 for (int j = 0; j <= MyModCount; j++)
252                         mymodnames.push_back(Config->module_names[j]);
253
254                 for (int k = 0; k <= MyModCount; k++)
255                         this->UnloadModule(mymodnames[k].c_str());
256         }
257
258         /* Close logging */
259         this->Logger->Close();
260
261         /* Cleanup Server Names */
262         for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
263                 delete (*itr);
264
265 #ifdef WINDOWS
266         /* WSACleanup */
267         WSACleanup();
268 #endif
269 }
270
271 void InspIRCd::Restart(const std::string &reason)
272 {
273         /* SendError flushes each client's queue,
274          * regardless of writeability state
275          */
276         this->SendError(reason);
277
278         this->Cleanup();
279
280         /* Figure out our filename (if theyve renamed it, we're boned) */
281         std::string me;
282
283 #ifdef WINDOWS
284         char module[MAX_PATH];
285         if (GetModuleFileName(NULL, module, MAX_PATH))
286                 me = module;
287 #else
288         me = Config->MyDir + "/inspircd";
289 #endif
290
291         if (execv(me.c_str(), Config->argv) == -1)
292         {
293                 /* Will raise a SIGABRT if not trapped */
294                 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
295         }
296 }
297
298 void InspIRCd::Start()
299 {
300         printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
301         printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
302         printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey, Burlex\033[0m\n");
303         printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
304 }
305
306 void InspIRCd::Rehash(int status)
307 {
308         SI->WriteOpers("*** Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(SI->ConfigFileName));
309         SI->CloseLog();
310         SI->OpenLog(SI->Config->argv, SI->Config->argc);
311         SI->RehashUsersAndChans();
312         FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
313         SI->Config->Read(false,NULL);
314         SI->ResetMaxBans();
315         SI->Res->Rehash();
316         FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
317         SI->BuildISupport();
318 }
319
320 void InspIRCd::ResetMaxBans()
321 {
322         for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
323                 i->second->ResetMaxBans();
324 }
325
326
327 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
328  * we must occasionally rehash the hash (yes really).
329  * We do this by copying the entries from the old hash to a new hash, causing all
330  * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
331  * very expensive, so instead we do it when the user types /REHASH and expects a
332  * short delay anyway.
333  */
334 void InspIRCd::RehashUsersAndChans()
335 {
336         user_hash* old_users = this->clientlist;
337         chan_hash* old_chans = this->chanlist;
338
339         this->clientlist = new user_hash();
340         this->chanlist = new chan_hash();
341
342         for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
343                 this->clientlist->insert(*n);
344
345         delete old_users;
346
347         for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
348                 this->chanlist->insert(*n);
349
350         delete old_chans;
351 }
352
353 void InspIRCd::CloseLog()
354 {
355         this->Logger->Close();
356 }
357
358 void InspIRCd::SetSignals()
359 {
360 #ifndef WIN32
361         signal(SIGALRM, SIG_IGN);
362         signal(SIGHUP, InspIRCd::Rehash);
363         signal(SIGPIPE, SIG_IGN);
364         signal(SIGCHLD, SIG_IGN);
365 #endif
366         signal(SIGTERM, InspIRCd::Exit);
367 }
368
369 void InspIRCd::QuickExit(int status)
370 {
371         exit(0);
372 }
373
374 bool InspIRCd::DaemonSeed()
375 {
376 #ifdef WINDOWS
377         printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
378         return true;
379 #else
380         signal(SIGTERM, InspIRCd::QuickExit);
381
382         int childpid;
383         if ((childpid = fork ()) < 0)
384                 return false;
385         else if (childpid > 0)
386         {
387                 /* We wait here for the child process to kill us,
388                  * so that the shell prompt doesnt come back over
389                  * the output.
390                  * Sending a kill with a signal of 0 just checks
391                  * if the child pid is still around. If theyre not,
392                  * they threw an error and we should give up.
393                  */
394                 while (kill(childpid, 0) != -1)
395                         sleep(1);
396                 exit(0);
397         }
398         setsid ();
399         umask (007);
400         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
401
402         signal(SIGTERM, InspIRCd::Exit);
403
404         rlimit rl;
405         if (getrlimit(RLIMIT_CORE, &rl) == -1)
406         {
407                 this->Log(DEFAULT,"Failed to getrlimit()!");
408                 return false;
409         }
410         else
411         {
412                 rl.rlim_cur = rl.rlim_max;
413                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
414                         this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
415         }
416
417         return true;
418 #endif
419 }
420
421 void InspIRCd::WritePID(const std::string &filename)
422 {
423         std::string fname = (filename.empty() ? "inspircd.pid" : filename);
424         if (*(fname.begin()) != '/')
425         {
426                 std::string::size_type pos;
427                 std::string confpath = this->ConfigFileName;
428                 if ((pos = confpath.rfind("/")) != std::string::npos)
429                 {
430                         /* Leaves us with just the path */
431                         fname = confpath.substr(0, pos) + std::string("/") + fname;
432                 }
433         }
434         std::ofstream outfile(fname.c_str());
435         if (outfile.is_open())
436         {
437                 outfile << getpid();
438                 outfile.close();
439         }
440         else
441         {
442                 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
443                 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
444                 Exit(EXIT_STATUS_PID);
445         }
446 }
447
448 std::string InspIRCd::GetRevision()
449 {
450         return REVISION;
451 }
452
453 InspIRCd::InspIRCd(int argc, char** argv)
454         : ModCount(-1), GlobalCulls(this)
455 {
456         int found_ports = 0;
457         FailedPortList pl;
458         int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0;    /* flag variables */
459         char c = 0;
460
461         modules.resize(255);
462         factory.resize(255);
463         memset(&server, 0, sizeof(server));
464         memset(&client, 0, sizeof(client));
465
466         this->unregistered_count = 0;
467
468         this->clientlist = new user_hash();
469         this->chanlist = new chan_hash();
470
471         this->Config = new ServerConfig(this);
472
473         this->Config->argv = argv;
474         this->Config->argc = argc;
475
476         chdir(Config->GetFullProgDir().c_str());
477
478         this->Config->opertypes.clear();
479         this->Config->operclass.clear();
480         this->SNO = new SnomaskManager(this);
481         this->TIME = this->OLDTIME = this->startup_time = time(NULL);
482         this->time_delta = 0;
483         this->next_call = this->TIME + 3;
484         srand(this->TIME);
485
486         *this->LogFileName = 0;
487         strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
488
489         struct option longopts[] =
490         {
491                 { "nofork",     no_argument,            &do_nofork,     1       },
492                 { "logfile",    required_argument,      NULL,           'f'     },
493                 { "config",     required_argument,      NULL,           'c'     },
494                 { "debug",      no_argument,            &do_debug,      1       },
495                 { "nolog",      no_argument,            &do_nolog,      1       },
496                 { "runasroot",  no_argument,            &do_root,       1       },
497                 { "version",    no_argument,            &do_version,    1       },
498                 { 0, 0, 0, 0 }
499         };
500
501         while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
502         {
503                 switch (c)
504                 {
505                         case 'f':
506                                 /* Log filename was set */
507                                 strlcpy(LogFileName, optarg, MAXBUF);
508                         break;
509                         case 'c':
510                                 /* Config filename was set */
511                                 strlcpy(ConfigFileName, optarg, MAXBUF);
512                         break;
513                         case 0:
514                                 /* getopt_long_only() set an int variable, just keep going */
515                         break;
516                         default:
517                                 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
518                                 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
519                                 Exit(EXIT_STATUS_ARGV);
520                         break;
521                 }
522         }
523
524         if (do_version)
525         {
526                 printf("\n%s r%s\n", VERSION, REVISION);
527                 Exit(EXIT_STATUS_NOERROR);
528         }
529
530 #ifdef WIN32
531
532         // Handle forking
533         if(!do_nofork && !owner_processid)
534         {
535                 DWORD ExitCode = WindowsForkStart(this);
536                 if(ExitCode)
537                         Exit(ExitCode);
538         }
539
540         // Set up winsock
541         WSADATA wsadata;
542         WSAStartup(MAKEWORD(2,0), &wsadata);
543
544 #endif
545         if (!ServerConfig::FileExists(this->ConfigFileName))
546         {
547                 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
548                 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
549                 Exit(EXIT_STATUS_CONFIG);
550         }
551
552         this->Start();
553
554         /* Set the finished argument values */
555         Config->nofork = do_nofork;
556         Config->forcedebug = do_debug;
557         Config->writelog = !do_nolog;
558
559         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
560
561         this->OpenLog(argv, argc);
562
563         this->stats = new serverstats();
564         this->Timers = new TimerManager(this);
565         this->Parser = new CommandParser(this);
566         this->XLines = new XLineManager(this);
567         Config->ClearStack();
568         Config->Read(true, NULL);
569
570         if (!do_root)
571                 this->CheckRoot();
572         else
573         {
574                 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
575                 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
576                 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
577                 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
578                 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
579                 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
580                 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
581                 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
582                 sleep(20);
583         }
584
585         this->SetSignals();
586
587         if (!Config->nofork)
588         {
589                 if (!this->DaemonSeed())
590                 {
591                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
592                         Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
593                         Exit(EXIT_STATUS_FORK);
594                 }
595         }
596
597
598         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
599          * initialize the socket engine.
600          */
601         SocketEngineFactory* SEF = new SocketEngineFactory();
602         SE = SEF->Create(this);
603         delete SEF;
604
605         this->Modes = new ModeParser(this);
606         this->AddServerName(Config->ServerName);
607         CheckDie();
608         int bounditems = BindPorts(true, found_ports, pl);
609
610         for(int t = 0; t < 255; t++)
611                 Config->global_implementation[t] = 0;
612
613         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
614
615         printf("\n");
616
617         this->Res = new DNS(this);
618
619         this->LoadAllModules();
620         /* Just in case no modules were loaded - fix for bug #101 */
621         this->BuildISupport();
622         InitializeDisabledCommands(Config->DisabledCommands, this);
623
624         if ((Config->ports.size() == 0) && (found_ports > 0))
625         {
626                 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
627                 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
628                 Exit(EXIT_STATUS_BIND);
629         }
630
631         if (Config->ports.size() != (unsigned int)found_ports)
632         {
633                 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
634                 printf("The following port(s) failed to bind:\n");
635                 int j = 1;
636                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
637                 {
638                         printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
639                 }
640         }
641 #ifndef WINDOWS
642         if (!Config->nofork)
643         {
644                 if (kill(getppid(), SIGTERM) == -1)
645                 {
646                         printf("Error killing parent process: %s\n",strerror(errno));
647                         Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
648                 }
649         }
650
651         if (isatty(0) && isatty(1) && isatty(2))
652         {
653                 /* We didn't start from a TTY, we must have started from a background process -
654                  * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
655                  * close stdin/stdout
656                  */
657                 if (!do_nofork)
658                 {
659                         fclose(stdin);
660                         fclose(stderr);
661                         fclose(stdout);
662                 }
663                 else
664                 {
665                         Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
666                 }
667         }
668 #else
669         InitIPC();
670         if(!Config->nofork)
671         {
672                 WindowsForkKillOwner(this);
673                 FreeConsole();
674         }
675 #endif
676         printf("\nInspIRCd is now running!\n");
677         Log(DEFAULT,"Startup complete.");
678
679         this->WritePID(Config->PID);
680 }
681
682 std::string InspIRCd::GetVersionString()
683 {
684         char versiondata[MAXBUF];
685         char dnsengine[] = "singlethread-object";
686
687         if (*Config->CustomVersion)
688         {
689                 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
690         }
691         else
692         {
693                 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%s,%s,%s]",VERSION,Config->ServerName,SYSTEM,REVISION,SE->GetName().c_str(),dnsengine);
694         }
695         return versiondata;
696 }
697
698 void InspIRCd::BuildISupport()
699 {
700         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
701         std::stringstream v;
702         v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES-1 << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << Config->MaxChans << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
703         v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
704         v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32 ELIST=MU";
705         Config->data005 = v.str();
706         FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
707         Config->Update005();
708 }
709
710 void InspIRCd::DoOneIteration(bool process_module_sockets)
711 {
712 #ifndef WIN32
713         static rusage ru;
714 #else
715         static time_t uptime;
716         static struct tm * stime;
717         static char window_title[100];
718 #endif
719
720         /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
721          * Once per loop iteration is pleanty.
722          */
723         OLDTIME = TIME;
724         TIME = time(NULL);
725
726         /* Run background module timers every few seconds
727          * (the docs say modules shouldnt rely on accurate
728          * timing using this event, so we dont have to
729          * time this exactly).
730          */
731         if (TIME != OLDTIME)
732         {
733                 if (TIME < OLDTIME)
734                         WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
735                 if ((TIME % 3600) == 0)
736                 {
737                         this->RehashUsersAndChans();
738                         FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
739                 }
740                 Timers->TickTimers(TIME);
741                 this->DoBackgroundUserStuff(TIME);
742
743                 if ((TIME % 5) == 0)
744                 {
745                         XLines->expire_lines();
746                         FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
747                         Timers->TickMissedTimers(TIME);
748                 }
749 #ifndef WIN32
750                 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
751                 if (!getrusage(RUSAGE_SELF, &ru))
752                 {
753                         gettimeofday(&this->stats->LastSampled, NULL);
754                         this->stats->LastCPU = ru.ru_utime;
755                 }
756 #else
757                 CheckIPC(this);
758
759                 if(Config->nofork)
760                 {
761                         uptime = Time() - startup_time;
762                         stime = gmtime(&uptime);
763                         snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
764                                 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
765                         SetConsoleTitle(window_title);
766                 }
767 #endif
768         }
769
770         /* Call the socket engine to wait on the active
771          * file descriptors. The socket engine has everything's
772          * descriptors in its list... dns, modules, users,
773          * servers... so its nice and easy, just one call.
774          * This will cause any read or write events to be
775          * dispatched to their handlers.
776          */
777         SE->DispatchEvents();
778
779         /* if any users was quit, take them out */
780         GlobalCulls.Apply();
781
782         /* If any inspsockets closed, remove them */
783         this->InspSocketCull();
784 }
785
786 void InspIRCd::InspSocketCull()
787 {
788         for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
789         {
790                 SE->DelFd(x->second);
791                 x->second->Close();
792                 delete x->second;
793         }
794         SocketCull.clear();
795 }
796
797 int InspIRCd::Run()
798 {
799         while (true)
800         {
801                 DoOneIteration(true);
802         }
803         /* This is never reached -- we hope! */
804         return 0;
805 }
806
807 /**********************************************************************************/
808
809 /**
810  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
811  */
812
813 int main(int argc, char** argv)
814 {
815         SI = new InspIRCd(argc, argv);
816         SI->Run();
817         delete SI;
818         return 0;
819 }
820
821 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
822  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
823  * registration timeout maximum seconds)
824  */
825 bool InspIRCd::AllModulesReportReady(userrec* user)
826 {
827         if (!Config->global_implementation[I_OnCheckReady])
828                 return true;
829
830         for (int i = 0; i <= this->GetModuleCount(); i++)
831         {
832                 if (Config->implement_lists[i][I_OnCheckReady])
833                 {
834                         int res = modules[i]->OnCheckReady(user);
835                         if (!res)
836                                 return false;
837                 }
838         }
839         return true;
840 }
841
842 int InspIRCd::GetModuleCount()
843 {
844         return this->ModCount;
845 }
846
847 time_t InspIRCd::Time(bool delta)
848 {
849         if (delta)
850                 return TIME + time_delta;
851         return TIME;
852 }
853
854 int InspIRCd::SetTimeDelta(int delta)
855 {
856         int old = time_delta;
857         time_delta = delta;
858         this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
859         return old;
860 }
861
862 void InspIRCd::AddLocalClone(userrec* user)
863 {
864         clonemap::iterator x = local_clones.find(user->GetIPString());
865         if (x != local_clones.end())
866                 x->second++;
867         else
868                 local_clones[user->GetIPString()] = 1;
869 }
870
871 void InspIRCd::AddGlobalClone(userrec* user)
872 {
873         clonemap::iterator y = global_clones.find(user->GetIPString());
874         if (y != global_clones.end())
875                 y->second++;
876         else
877                 global_clones[user->GetIPString()] = 1;
878 }
879
880 int InspIRCd::GetTimeDelta()
881 {
882         return time_delta;
883 }
884
885 bool FileLogger::Readable()
886 {
887         return false;
888 }
889
890 void FileLogger::HandleEvent(EventType et, int errornum)
891 {
892         this->WriteLogLine("");
893         if (log)
894                 ServerInstance->SE->DelFd(this);
895 }
896
897 void FileLogger::WriteLogLine(const std::string &line)
898 {
899         if (line.length())
900                 buffer.append(line);
901
902         if (log)
903         {
904                 int written = fprintf(log,"%s",buffer.c_str());
905 #ifdef WINDOWS
906                 buffer.clear();
907 #else
908                 if ((written >= 0) && (written < (int)buffer.length()))
909                 {
910                         buffer.erase(0, buffer.length());
911                         ServerInstance->SE->AddFd(this);
912                 }
913                 else if (written == -1)
914                 {
915                         if (errno == EAGAIN)
916                                 ServerInstance->SE->AddFd(this);
917                 }
918                 else
919                 {
920                         /* Wrote the whole buffer, and no need for write callback */
921                         buffer.clear();
922                 }
923 #endif
924                 if (writeops++ % 20)
925                 {
926                         fflush(log);
927                 }
928         }
929 }
930
931 void FileLogger::Close()
932 {
933         if (log)
934         {
935                 /* Burlex: Windows assumes nonblocking on FILE* pointers anyway, and also "file" fd's aren't the same
936                  * as socket fd's. */
937 #ifndef WIN32
938                 int flags = fcntl(fileno(log), F_GETFL, 0);
939                 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
940 #endif
941                 if (buffer.size())
942                         fprintf(log,"%s",buffer.c_str());
943
944 #ifndef WINDOWS
945                 ServerInstance->SE->DelFd(this);
946 #endif
947
948                 fflush(log);
949                 fclose(log);
950         }
951
952         buffer.clear();
953 }
954
955 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
956 {
957         if (log)
958         {
959                 irc::sockets::NonBlocking(fileno(log));
960                 this->SetFd(fileno(log));
961                 buffer.clear();
962         }
963 }
964
965 FileLogger::~FileLogger()
966 {
967         this->Close();
968 }
969