]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
d040940c49730084f9964e959dae4e756e4c1c12
[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 #ifndef WIN32
18
19 #include <dirent.h>
20 #include <unistd.h>
21 #include <sys/resource.h>
22
23 /* This is just to be completely certain that the change which fixed getrusage on RH7 doesn't break anything else -- Om */  
24 #ifndef RUSAGE_SELF
25 #define RUSAGE_SELF 0
26 #endif
27
28 #endif
29 #include <exception>
30 #include <fstream>
31 #include "modules.h"
32 #include "mode.h"
33 #include "xline.h"
34 #include "socketengine.h"
35 #include "inspircd_se_config.h"
36 #include "socket.h"
37 #include "typedefs.h"
38 #include "command_parse.h"
39 #include "exitcodes.h"
40
41 #ifndef WIN32
42 #include <dlfcn.h>
43 #include <getopt.h>
44 #else
45 static DWORD owner_processid = 0;
46
47 DWORD WindowsForkStart(InspIRCd * Instance)
48 {
49         /* Windows implementation of fork() :P */
50
51         char module[MAX_PATH];
52         if(!GetModuleFileName(NULL, module, MAX_PATH))
53         {
54                 printf("GetModuleFileName() failed.\n");
55                 return false;
56         }
57
58         STARTUPINFO startupinfo;
59         PROCESS_INFORMATION procinfo;
60         ZeroMemory(&startupinfo, sizeof(STARTUPINFO));
61         ZeroMemory(&procinfo, sizeof(PROCESS_INFORMATION));
62
63         // Fill in the startup info struct
64         GetStartupInfo(&startupinfo);
65
66         /* Default creation flags create the processes suspended */
67         DWORD startupflags = CREATE_SUSPENDED;
68
69         /* On windows 2003/XP and above, we can use the value
70          * CREATE_PRESERVE_CODE_AUTHZ_LEVEL which gives more access
71          * to the process which we may require on these operating systems.
72          */
73         OSVERSIONINFO vi;
74         vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
75         GetVersionEx(&vi);
76         if ((vi.dwMajorVersion >= 5) && (vi.dwMinorVersion > 0))
77                 startupflags |= CREATE_PRESERVE_CODE_AUTHZ_LEVEL;
78
79         // Launch our "forked" process.
80         BOOL bSuccess = CreateProcess ( module, // Module (exe) filename
81                 GetCommandLine(),                                       // Command line (exe plus parameters from the OS)
82                 0,                                                                      // PROCESS_SECURITY_ATTRIBUTES
83                 0,                                                                      // THREAD_SECURITY_ATTRIBUTES
84                 TRUE,                                                           // We went to inherit handles.
85                 startupflags,                                           // Allow us full access to the process and suspend it.
86                 0,                                                                      // ENVIRONMENT
87                 0,                                                                      // CURRENT_DIRECTORY
88                 &startupinfo,                                           // startup info
89                 &procinfo);                                                     // process info
90
91         if(!bSuccess)
92         {
93                 printf("CreateProcess() error: %s\n", dlerror());
94                 return false;
95         }
96
97         // Set the owner process id in the target process.
98         SIZE_T written = 0;
99         DWORD pid = GetCurrentProcessId();
100         if(!WriteProcessMemory(procinfo.hProcess, &owner_processid, &pid, sizeof(DWORD), &written) || written != sizeof(DWORD))
101         {
102                 printf("WriteProcessMemory() failed: %s\n", dlerror());
103                 return false;
104         }
105
106         // Resume the other thread (let it start)
107         ResumeThread(procinfo.hThread);
108
109         // 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.
110         WaitForSingleObject(procinfo.hProcess, INFINITE);
111
112         // If we hit this it means startup failed, default to 14 if this fails.
113         DWORD ExitCode = 14;
114         GetExitCodeProcess(procinfo.hProcess, &ExitCode);
115         CloseHandle(procinfo.hThread);
116         CloseHandle(procinfo.hProcess);
117         return ExitCode;
118 }
119
120 void WindowsForkKillOwner(InspIRCd * Instance)
121 {
122         HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, owner_processid);
123         if(!hProcess || !owner_processid)
124         {
125                 printf("Could not open process id %u: %s.\n", owner_processid, dlerror());
126                 Instance->Exit(14);
127         }
128
129         // die die die
130         if(!TerminateProcess(hProcess, 0))
131         {
132                 printf("Could not TerminateProcess(): %s\n", dlerror());
133                 Instance->Exit(14);
134         }
135
136         CloseHandle(hProcess);
137 }
138
139 #endif
140
141 using irc::sockets::NonBlocking;
142 using irc::sockets::Blocking;
143 using irc::sockets::insp_ntoa;
144 using irc::sockets::insp_inaddr;
145 using irc::sockets::insp_sockaddr;
146
147 InspIRCd* SI = NULL;
148
149 /* Burlex: Moved from exitcodes.h -- due to duplicate symbols */
150 const char* ExitCodes[] =
151 {
152                 "No error", /* 0 */
153                 "DIE command", /* 1 */
154                 "execv() failed", /* 2 */
155                 "Internal error", /* 3 */
156                 "Config file error", /* 4 */
157                 "Logfile error", /* 5 */
158                 "POSIX fork failed", /* 6 */
159                 "Bad commandline parameters", /* 7 */
160                 "No ports could be bound", /* 8 */
161                 "Can't write PID file", /* 9 */
162                 "SocketEngine could not initialize", /* 10 */
163                 "Refusing to start up as root", /* 11 */
164                 "Found a <die> tag!", /* 12 */
165                 "Couldn't load module on startup", /* 13 */
166                 "Could not create windows forked process", /* 14 */
167                 "Received SIGTERM", /* 15 */
168 };
169
170 void InspIRCd::AddServerName(const std::string &servername)
171 {
172         servernamelist::iterator itr = servernames.begin();
173         for(; itr != servernames.end(); ++itr)
174                 if(**itr == servername)
175                         return;
176
177         string * ns = new string(servername);
178         servernames.push_back(ns);
179 }
180
181 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
182 {
183         servernamelist::iterator itr = servernames.begin();
184         for(; itr != servernames.end(); ++itr)
185                 if(**itr == servername)
186                         return (*itr)->c_str();
187
188         servernames.push_back(new string(servername));
189         itr = --servernames.end();
190         return (*itr)->c_str();
191 }
192
193 bool InspIRCd::FindServerName(const std::string &servername)
194 {
195         servernamelist::iterator itr = servernames.begin();
196         for(; itr != servernames.end(); ++itr)
197                 if(**itr == servername)
198                         return true;
199         return false;
200 }
201
202 void InspIRCd::Exit(int status)
203 {
204 #ifdef WINDOWS
205         CloseIPC();
206 #endif
207         if (SI)
208         {
209                 SI->SendError("Exiting with status " + ConvToStr(status) + " (" + std::string(ExitCodes[status]) + ")");
210                 SI->Cleanup();
211         }
212         exit (status);
213 }
214
215 void InspIRCd::Cleanup()
216 {
217         std::vector<std::string> mymodnames;
218         int MyModCount = this->GetModuleCount();
219
220         for (unsigned int i = 0; i < Config->ports.size(); i++)
221         {
222                 /* This calls the constructor and closes the listening socket */
223                 delete Config->ports[i];
224         }
225
226         Config->ports.clear();
227
228         /* Close all client sockets, or the new process inherits them */
229         for (std::vector<userrec*>::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
230         {
231                 (*i)->SetWriteError("Server shutdown");
232                 (*i)->CloseSocket();
233         }
234
235         /* We do this more than once, so that any service providers get a
236          * chance to be unhooked by the modules using them, but then get
237          * a chance to be removed themsleves.
238          */
239         for (int tries = 0; tries < 3; tries++)
240         {
241                 MyModCount = this->GetModuleCount();
242                 mymodnames.clear();
243
244                 /* Unload all modules, so they get a chance to clean up their listeners */
245                 for (int j = 0; j <= MyModCount; j++)
246                         mymodnames.push_back(Config->module_names[j]);
247
248                 for (int k = 0; k <= MyModCount; k++)
249                         this->UnloadModule(mymodnames[k].c_str());
250         }
251
252         /* Close logging */
253         this->Logger->Close();
254
255         /* Cleanup Server Names */
256         for(servernamelist::iterator itr = servernames.begin(); itr != servernames.end(); ++itr)
257                 delete (*itr);
258
259 #ifdef WINDOWS
260         /* WSACleanup */
261         WSACleanup();
262 #endif
263 }
264
265 void InspIRCd::Restart(const std::string &reason)
266 {
267         /* SendError flushes each client's queue,
268          * regardless of writeability state
269          */
270         this->SendError(reason);
271
272         this->Cleanup();
273
274         /* Figure out our filename (if theyve renamed it, we're boned) */
275         std::string me;
276
277 #ifdef WINDOWS
278         char module[MAX_PATH];
279         if (GetModuleFileName(NULL, module, MAX_PATH))
280                 me = module;
281 #else
282         me = Config->MyDir + "/inspircd";
283 #endif
284
285         if (execv(me.c_str(), Config->argv) == -1)
286         {
287                 /* Will raise a SIGABRT if not trapped */
288                 throw CoreException(std::string("Failed to execv()! error: ") + strerror(errno));
289         }
290 }
291
292 void InspIRCd::Start()
293 {
294         printf_c("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
295         printf_c("(C) InspIRCd Development Team.\033[0m\n\n");
296         printf_c("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special, pippijn, peavey, Burlex\033[0m\n");
297         printf_c("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
298 }
299
300 void InspIRCd::Rehash(int status)
301 {
302         SI->WriteOpers("*** Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(SI->ConfigFileName));
303         SI->CloseLog();
304         SI->OpenLog(SI->Config->argv, SI->Config->argc);
305         SI->RehashUsersAndChans();
306         FOREACH_MOD_I(SI, I_OnGarbageCollect, OnGarbageCollect());
307         SI->Config->Read(false,NULL);
308         SI->ResetMaxBans();
309         SI->Res->Rehash();
310         FOREACH_MOD_I(SI,I_OnRehash,OnRehash(NULL,""));
311         SI->BuildISupport();
312 }
313
314 void InspIRCd::ResetMaxBans()
315 {
316         for (chan_hash::const_iterator i = chanlist->begin(); i != chanlist->end(); i++)
317                 i->second->ResetMaxBans();
318 }
319
320
321 /** Because hash_map doesnt free its buckets when we delete items (this is a 'feature')
322  * we must occasionally rehash the hash (yes really).
323  * We do this by copying the entries from the old hash to a new hash, causing all
324  * empty buckets to be weeded out of the hash. We dont do this on a timer, as its
325  * very expensive, so instead we do it when the user types /REHASH and expects a
326  * short delay anyway.
327  */
328 void InspIRCd::RehashUsersAndChans()
329 {
330         user_hash* old_users = this->clientlist;
331         chan_hash* old_chans = this->chanlist;
332
333         this->clientlist = new user_hash();
334         this->chanlist = new chan_hash();
335
336         for (user_hash::const_iterator n = old_users->begin(); n != old_users->end(); n++)
337                 this->clientlist->insert(*n);
338
339         delete old_users;
340
341         for (chan_hash::const_iterator n = old_chans->begin(); n != old_chans->end(); n++)
342                 this->chanlist->insert(*n);
343
344         delete old_chans;
345 }
346
347 void InspIRCd::CloseLog()
348 {
349         this->Logger->Close();
350 }
351
352 void InspIRCd::SetSignals()
353 {
354 #ifndef WIN32
355         signal(SIGALRM, SIG_IGN);
356         signal(SIGHUP, InspIRCd::Rehash);
357         signal(SIGPIPE, SIG_IGN);
358         signal(SIGCHLD, SIG_IGN);
359 #endif
360         signal(SIGTERM, InspIRCd::Exit);
361 }
362
363 void InspIRCd::QuickExit(int status)
364 {
365         exit(0);
366 }
367
368 bool InspIRCd::DaemonSeed()
369 {
370 #ifdef WINDOWS
371         printf_c("InspIRCd Process ID: \033[1;32m%lu\033[0m\n", GetCurrentProcessId());
372         return true;
373 #else
374         signal(SIGTERM, InspIRCd::QuickExit);
375
376         int childpid;
377         if ((childpid = fork ()) < 0)
378                 return false;
379         else if (childpid > 0)
380         {
381                 /* We wait here for the child process to kill us,
382                  * so that the shell prompt doesnt come back over
383                  * the output.
384                  * Sending a kill with a signal of 0 just checks
385                  * if the child pid is still around. If theyre not,
386                  * they threw an error and we should give up.
387                  */
388                 while (kill(childpid, 0) != -1)
389                         sleep(1);
390                 exit(0);
391         }
392         setsid ();
393         umask (007);
394         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
395
396         signal(SIGTERM, InspIRCd::Exit);
397
398         rlimit rl;
399         if (getrlimit(RLIMIT_CORE, &rl) == -1)
400         {
401                 this->Log(DEFAULT,"Failed to getrlimit()!");
402                 return false;
403         }
404         else
405         {
406                 rl.rlim_cur = rl.rlim_max;
407                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
408                         this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
409         }
410
411         return true;
412 #endif
413 }
414
415 void InspIRCd::WritePID(const std::string &filename)
416 {
417         std::string fname = (filename.empty() ? "inspircd.pid" : filename);
418         if (*(fname.begin()) != '/')
419         {
420                 std::string::size_type pos;
421                 std::string confpath = this->ConfigFileName;
422                 if ((pos = confpath.rfind("/")) != std::string::npos)
423                 {
424                         /* Leaves us with just the path */
425                         fname = confpath.substr(0, pos) + std::string("/") + fname;
426                 }
427         }
428         std::ofstream outfile(fname.c_str());
429         if (outfile.is_open())
430         {
431                 outfile << getpid();
432                 outfile.close();
433         }
434         else
435         {
436                 printf("Failed to write PID-file '%s', exiting.\n",fname.c_str());
437                 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",fname.c_str());
438                 Exit(EXIT_STATUS_PID);
439         }
440 }
441
442 std::string InspIRCd::GetRevision()
443 {
444         return REVISION;
445 }
446
447 InspIRCd::InspIRCd(int argc, char** argv)
448         : ModCount(-1), GlobalCulls(this)
449 {
450         int found_ports = 0;
451         FailedPortList pl;
452         int do_version = 0, do_nofork = 0, do_debug = 0, do_nolog = 0, do_root = 0;    /* flag variables */
453         char c = 0;
454
455         modules.resize(255);
456         factory.resize(255);
457         memset(&server, 0, sizeof(server));
458         memset(&client, 0, sizeof(client));
459
460         this->unregistered_count = 0;
461
462         this->clientlist = new user_hash();
463         this->chanlist = new chan_hash();
464
465         this->Config = new ServerConfig(this);
466
467         this->Config->argv = argv;
468         this->Config->argc = argc;
469
470         chdir(Config->GetFullProgDir().c_str());
471
472         this->Config->opertypes.clear();
473         this->Config->operclass.clear();
474         this->SNO = new SnomaskManager(this);
475         this->TIME = this->OLDTIME = this->startup_time = time(NULL);
476         this->time_delta = 0;
477         this->next_call = this->TIME + 3;
478         srand(this->TIME);
479
480         *this->LogFileName = 0;
481         strlcpy(this->ConfigFileName, CONFIG_FILE, MAXBUF);
482
483         struct option longopts[] =
484         {
485                 { "nofork",             no_argument,            &do_nofork,             1       },
486                 { "logfile",    required_argument,      NULL,                   'f'     },
487                 { "config",             required_argument,      NULL,                   'c'     },
488                 { "debug",              no_argument,            &do_debug,              1       },
489                 { "nolog",              no_argument,            &do_nolog,              1       },
490                 { "runasroot",  no_argument,            &do_root,               1       },
491                 { "version",    no_argument,            &do_version,    1       },
492                 { 0, 0, 0, 0 }
493         };
494
495         while ((c = getopt_long_only(argc, argv, ":f:", longopts, NULL)) != -1)
496         {
497                 switch (c)
498                 {
499                         case 'f':
500                                 /* Log filename was set */
501                                 strlcpy(LogFileName, optarg, MAXBUF);
502                                 printf("LOG: Setting logfile to %s\n", LogFileName);
503                         break;
504                         case 'c':
505                                 /* Config filename was set */
506                                 strlcpy(ConfigFileName, optarg, MAXBUF);
507                                 printf("CONFIG: Setting config file to %s\n", ConfigFileName);
508                         break;
509                         case 0:
510                                 /* getopt_long_only() set an int variable, just keep going */
511                         break;
512                         default:
513                                 /* Unknown parameter! DANGER, INTRUDER.... err.... yeah. */
514                                 printf("Usage: %s [--nofork] [--nolog] [--debug] [--logfile <filename>] [--runasroot] [--version] [--config <config>]\n", argv[0]);
515                                 Exit(EXIT_STATUS_ARGV);
516                         break;
517                 }
518         }
519
520         if (do_version)
521         {
522                 printf("\n%s r%s\n", VERSION, REVISION);
523                 Exit(EXIT_STATUS_NOERROR);
524         }
525
526 #ifdef WIN32
527
528         // Handle forking
529         if(!do_nofork && !owner_processid)
530         {
531                 DWORD ExitCode = WindowsForkStart(this);
532                 if(ExitCode)
533                         Exit(ExitCode);
534         }
535
536         // Set up winsock
537         WSADATA wsadata;
538         WSAStartup(MAKEWORD(2,0), &wsadata);
539
540 #endif
541         if (!ServerConfig::FileExists(this->ConfigFileName))
542         {
543                 printf("ERROR: Cannot open config file: %s\nExiting...\n", this->ConfigFileName);
544                 this->Log(DEFAULT,"Unable to open config file %s", this->ConfigFileName);
545                 Exit(EXIT_STATUS_CONFIG);
546         }
547
548         this->Start();
549
550         /* Set the finished argument values */
551         Config->nofork = do_nofork;
552         Config->forcedebug = do_debug;
553         Config->writelog = !do_nolog;
554
555         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
556
557         this->OpenLog(argv, argc);
558
559         this->stats = new serverstats();
560         this->Timers = new TimerManager(this);
561         this->Parser = new CommandParser(this);
562         this->XLines = new XLineManager(this);
563         Config->ClearStack();
564         Config->Read(true, NULL);
565
566         if (!do_root)
567                 this->CheckRoot();
568         else
569         {
570                 printf("* WARNING * WARNING * WARNING * WARNING * WARNING * \n\n");
571                 printf("YOU ARE RUNNING INSPIRCD AS ROOT. THIS IS UNSUPPORTED\n");
572                 printf("AND IF YOU ARE HACKED, CRACKED, SPINDLED OR MUTILATED\n");
573                 printf("OR ANYTHING ELSE UNEXPECTED HAPPENS TO YOU OR YOUR\n");
574                 printf("SERVER, THEN IT IS YOUR OWN FAULT. IF YOU DID NOT MEAN\n");
575                 printf("TO START INSPIRCD AS ROOT, HIT CTRL+C NOW AND RESTART\n");
576                 printf("THE PROGRAM AS A NORMAL USER. YOU HAVE BEEN WARNED!\n");
577                 printf("\nInspIRCd starting in 20 seconds, ctrl+c to abort...\n");
578                 sleep(20);
579         }
580
581         this->SetSignals();
582
583         if (!Config->nofork)
584         {
585                 if (!this->DaemonSeed())
586                 {
587                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
588                         Log(DEFAULT,"ERROR: could not go into daemon mode. Shutting down.");
589                         Exit(EXIT_STATUS_FORK);
590                 }
591         }
592
593
594         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
595          * initialize the socket engine.
596          */
597         SocketEngineFactory* SEF = new SocketEngineFactory();
598         SE = SEF->Create(this);
599         delete SEF;
600
601         this->Modes = new ModeParser(this);
602         this->AddServerName(Config->ServerName);
603         CheckDie();
604         int bounditems = BindPorts(true, found_ports, pl);
605
606         for(int t = 0; t < 255; t++)
607                 Config->global_implementation[t] = 0;
608
609         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
610
611         printf("\n");
612
613         this->Res = new DNS(this);
614
615         this->LoadAllModules();
616         /* Just in case no modules were loaded - fix for bug #101 */
617         this->BuildISupport();
618         InitializeDisabledCommands(Config->DisabledCommands, this);
619
620         if ((Config->ports.size() == 0) && (found_ports > 0))
621         {
622                 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
623                 Log(DEFAULT,"ERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?");
624                 Exit(EXIT_STATUS_BIND);
625         }
626
627         if (Config->ports.size() != (unsigned int)found_ports)
628         {
629                 printf("\nWARNING: Not all your client ports could be bound --\nstarting anyway with %d of %d client ports bound.\n\n", bounditems, found_ports);
630                 printf("The following port(s) failed to bind:\n");
631                 int j = 1;
632                 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
633                 {
634                         printf("%d.\tIP: %s\tPort: %lu\n", j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
635                 }
636         }
637 #ifndef WINDOWS
638         if (!Config->nofork)
639         {
640                 if (kill(getppid(), SIGTERM) == -1)
641                 {
642                         printf("Error killing parent process: %s\n",strerror(errno));
643                         Log(DEFAULT,"Error killing parent process: %s",strerror(errno));
644                 }
645         }
646
647         if (isatty(0) && isatty(1) && isatty(2))
648         {
649                 /* We didn't start from a TTY, we must have started from a background process -
650                  * e.g. we are restarting, or being launched by cron. Dont kill parent, and dont
651                  * close stdin/stdout
652                  */
653                 if (!do_nofork)
654                 {
655                         fclose(stdin);
656                         fclose(stderr);
657                         fclose(stdout);
658                 }
659                 else
660                 {
661                         Log(DEFAULT,"Keeping pseudo-tty open as we are running in the foreground.");
662                 }
663         }
664 #else
665         InitIPC();
666         if(!Config->nofork)
667         {
668                 WindowsForkKillOwner(this);
669                 FreeConsole();
670         }
671 #endif
672         printf("\nInspIRCd is now running!\n");
673         Log(DEFAULT,"Startup complete.");
674
675         this->WritePID(Config->PID);
676 }
677
678 std::string InspIRCd::GetVersionString()
679 {
680         char versiondata[MAXBUF];
681         char dnsengine[] = "singlethread-object";
682
683         if (*Config->CustomVersion)
684         {
685                 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
686         }
687         else
688         {
689                 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%s,%s,%s]",VERSION,Config->ServerName,SYSTEM,REVISION,SE->GetName().c_str(),dnsengine);
690         }
691         return versiondata;
692 }
693
694 char* InspIRCd::ModuleError()
695 {
696         return MODERR;
697 }
698
699 void InspIRCd::EraseFactory(int j)
700 {
701         int v = 0;
702         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
703         {
704                 if (v == j)
705                 {
706                         delete *t;
707                         factory.erase(t);
708                         factory.push_back(NULL);
709                         return;
710                 }
711                 v++;
712         }
713 }
714
715 void InspIRCd::EraseModule(int j)
716 {
717         int v1 = 0;
718         for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
719         {
720                 if (v1 == j)
721                 {
722                         DELETE(*m);
723                         modules.erase(m);
724                         modules.push_back(NULL);
725                         break;
726                 }
727                 v1++;
728         }
729         int v2 = 0;
730         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
731         {
732                 if (v2 == j)
733                 {
734                         Config->module_names.erase(v);
735                         break;
736                 }
737                 v2++;
738         }
739
740 }
741
742 void InspIRCd::MoveTo(std::string modulename,int slot)
743 {
744         unsigned int v2 = 256;
745         for (unsigned int v = 0; v < Config->module_names.size(); v++)
746         {
747                 if (Config->module_names[v] == modulename)
748                 {
749                         // found an instance, swap it with the item at the end
750                         v2 = v;
751                         break;
752                 }
753         }
754         if ((v2 != (unsigned int)slot) && (v2 < 256))
755         {
756                 // Swap the module names over
757                 Config->module_names[v2] = Config->module_names[slot];
758                 Config->module_names[slot] = modulename;
759                 // now swap the module factories
760                 ircd_module* temp = factory[v2];
761                 factory[v2] = factory[slot];
762                 factory[slot] = temp;
763                 // now swap the module objects
764                 Module* temp_module = modules[v2];
765                 modules[v2] = modules[slot];
766                 modules[slot] = temp_module;
767                 // now swap the implement lists (we dont
768                 // need to swap the global or recount it)
769                 for (int n = 0; n < 255; n++)
770                 {
771                         char x = Config->implement_lists[v2][n];
772                         Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
773                         Config->implement_lists[slot][n] = x;
774                 }
775         }
776 }
777
778 void InspIRCd::MoveAfter(std::string modulename, std::string after)
779 {
780         for (unsigned int v = 0; v < Config->module_names.size(); v++)
781         {
782                 if (Config->module_names[v] == after)
783                 {
784                         MoveTo(modulename, v);
785                         return;
786                 }
787         }
788 }
789
790 void InspIRCd::MoveBefore(std::string modulename, std::string before)
791 {
792         for (unsigned int v = 0; v < Config->module_names.size(); v++)
793         {
794                 if (Config->module_names[v] == before)
795                 {
796                         if (v > 0)
797                         {
798                                 MoveTo(modulename, v-1);
799                         }
800                         else
801                         {
802                                 MoveTo(modulename, v);
803                         }
804                         return;
805                 }
806         }
807 }
808
809 void InspIRCd::MoveToFirst(std::string modulename)
810 {
811         MoveTo(modulename,0);
812 }
813
814 void InspIRCd::MoveToLast(std::string modulename)
815 {
816         MoveTo(modulename,this->GetModuleCount());
817 }
818
819 void InspIRCd::BuildISupport()
820 {
821         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
822         std::stringstream v;
823         v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES-1 << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << Config->MaxChans << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
824         v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
825         v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32 ELIST=MU";
826         Config->data005 = v.str();
827         FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
828         Config->Update005();
829 }
830
831 bool InspIRCd::UnloadModule(const char* filename)
832 {
833         std::string filename_str = filename;
834         for (unsigned int j = 0; j != Config->module_names.size(); j++)
835         {
836                 if (Config->module_names[j] == filename_str)
837                 {
838                         if (modules[j]->GetVersion().Flags & VF_STATIC)
839                         {
840                                 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
841                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
842                                 return false;
843                         }
844                         std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modules[j]);
845                         if (intercount.first > 0)
846                         {
847                                 this->Log(DEFAULT,"Failed to unload module %s, being used by %d other(s) via interface '%s'",filename, intercount.first, intercount.second.c_str());
848                                 snprintf(MODERR,MAXBUF,"Module not unloadable (Still in use by %d other module%s which %s using its interface '%s') -- unload dependent modules first!",
849                                                 intercount.first,
850                                                 intercount.first > 1 ? "s" : "",
851                                                 intercount.first > 1 ? "are" : "is",
852                                                 intercount.second.c_str());
853                                 return false;
854                         }
855                         /* Give the module a chance to tidy out all its metadata */
856                         for (chan_hash::iterator c = this->chanlist->begin(); c != this->chanlist->end(); c++)
857                         {
858                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
859                         }
860                         for (user_hash::iterator u = this->clientlist->begin(); u != this->clientlist->end(); u++)
861                         {
862                                 modules[j]->OnCleanup(TYPE_USER,u->second);
863                         }
864
865                         /* Tidy up any dangling resolvers */
866                         this->Res->CleanResolvers(modules[j]);
867
868                         FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
869
870                         for(int t = 0; t < 255; t++)
871                         {
872                                 Config->global_implementation[t] -= Config->implement_lists[j][t];
873                         }
874
875                         /* We have to renumber implement_lists after unload because the module numbers change!
876                          */
877                         for(int j2 = j; j2 < 254; j2++)
878                         {
879                                 for(int t = 0; t < 255; t++)
880                                 {
881                                         Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
882                                 }
883                         }
884
885                         // found the module
886                         Parser->RemoveCommands(filename);
887                         this->EraseModule(j);
888                         this->EraseFactory(j);
889                         this->Log(DEFAULT,"Module %s unloaded",filename);
890                         this->ModCount--;
891                         BuildISupport();
892                         return true;
893                 }
894         }
895         this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
896         snprintf(MODERR,MAXBUF,"Module not loaded");
897         return false;
898 }
899
900 bool InspIRCd::LoadModule(const char* filename)
901 {
902         /* Do we have a glob pattern in the filename?
903          * The user wants to load multiple modules which
904          * match the pattern.
905          */
906         if (strchr(filename,'*') || (strchr(filename,'?')))
907         {
908                 int n_match = 0;
909                 DIR* library = opendir(Config->ModPath);
910                 if (library)
911                 {
912                         /* Try and locate and load all modules matching the pattern */
913                         dirent* entry = NULL;
914                         while ((entry = readdir(library)))
915                         {
916                                 if (this->MatchText(entry->d_name, filename))
917                                 {
918                                         if (!this->LoadModule(entry->d_name))
919                                                 n_match++;
920                                 }
921                         }
922                         closedir(library);
923                 }
924                 /* Loadmodule will now return false if any one of the modules failed
925                  * to load (but wont abort when it encounters a bad one) and when 1 or
926                  * more modules were actually loaded.
927                  */
928                 return (n_match > 0);
929         }
930
931         char modfile[MAXBUF];
932         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
933         std::string filename_str = filename;
934
935         if (!ServerConfig::DirValid(modfile))
936         {
937                 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
938                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
939                 return false;
940         }
941         if (ServerConfig::FileExists(modfile))
942         {
943
944                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
945                 {
946                         if (Config->module_names[j] == filename_str)
947                         {
948                                 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
949                                 snprintf(MODERR,MAXBUF,"Module already loaded");
950                                 return false;
951                         }
952                 }
953                 try
954                 {
955                         ircd_module* a = new ircd_module(this, modfile);
956                         factory[this->ModCount+1] = a;
957                         if (factory[this->ModCount+1]->LastError())
958                         {
959                                 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
960                                 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
961                                 return false;
962                         }
963                         if ((long)factory[this->ModCount+1]->factory != -1)
964                         {
965                                 Module* m = factory[this->ModCount+1]->factory->CreateModule(this);
966
967                                 Version v = m->GetVersion();
968
969                                 if (v.API != API_VERSION)
970                                 {
971                                         delete m;
972                                         delete a;
973                                         this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
974                                         snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
975                                         return false;
976                                 }
977                                 else
978                                 {
979                                         this->Log(DEFAULT,"New module introduced: %s (API version %d, Module version %d.%d.%d.%d)%s", filename, v.API, v.Major, v.Minor, v.Revision, v.Build, (!(v.Flags & VF_VENDOR) ? " [3rd Party]" : " [Vendor]"));
980                                 }
981
982                                 modules[this->ModCount+1] = m;
983                                 /* save the module and the module's classfactory, if
984                                  * this isnt done, random crashes can occur :/ */
985                                 Config->module_names.push_back(filename);
986
987                                 char* x = &Config->implement_lists[this->ModCount+1][0];
988                                 for(int t = 0; t < 255; t++)
989                                         x[t] = 0;
990
991                                 modules[this->ModCount+1]->Implements(x);
992
993                                 for(int t = 0; t < 255; t++)
994                                         Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
995                         }
996                         else
997                         {
998                                 this->Log(DEFAULT,"Unable to load %s",modfile);
999                                 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
1000                                 return false;
1001                         }
1002                 }
1003                 catch (CoreException& modexcept)
1004                 {
1005                         this->Log(DEFAULT,"Unable to load %s: %s",modfile,modexcept.GetReason());
1006                         snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
1007                         return false;
1008                 }
1009         }
1010         else
1011         {
1012                 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
1013                 snprintf(MODERR,MAXBUF,"Module file could not be found");
1014                 return false;
1015         }
1016         this->ModCount++;
1017         FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
1018         // now work out which modules, if any, want to move to the back of the queue,
1019         // and if they do, move them there.
1020         std::vector<std::string> put_to_back;
1021         std::vector<std::string> put_to_front;
1022         std::map<std::string,std::string> put_before;
1023         std::map<std::string,std::string> put_after;
1024         for (unsigned int j = 0; j < Config->module_names.size(); j++)
1025         {
1026                 if (modules[j]->Prioritize() == PRIORITY_LAST)
1027                         put_to_back.push_back(Config->module_names[j]);
1028                 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
1029                         put_to_front.push_back(Config->module_names[j]);
1030                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
1031                         put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
1032                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
1033                         put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
1034         }
1035         for (unsigned int j = 0; j < put_to_back.size(); j++)
1036                 MoveToLast(put_to_back[j]);
1037         for (unsigned int j = 0; j < put_to_front.size(); j++)
1038                 MoveToFirst(put_to_front[j]);
1039         for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
1040                 MoveBefore(j->first,j->second);
1041         for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
1042                 MoveAfter(j->first,j->second);
1043         BuildISupport();
1044         return true;
1045 }
1046
1047 void InspIRCd::DoOneIteration(bool process_module_sockets)
1048 {
1049 #ifndef WIN32
1050         static rusage ru;
1051 #else
1052         static time_t uptime;
1053         static struct tm * stime;
1054         static char window_title[100];
1055 #endif
1056
1057         /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
1058          * Once per loop iteration is pleanty.
1059          */
1060         OLDTIME = TIME;
1061         TIME = time(NULL);
1062
1063         /* Run background module timers every few seconds
1064          * (the docs say modules shouldnt rely on accurate
1065          * timing using this event, so we dont have to
1066          * time this exactly).
1067          */
1068         if (TIME != OLDTIME)
1069         {
1070                 if (TIME < OLDTIME)
1071                         WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
1072                 if ((TIME % 3600) == 0)
1073                 {
1074                         this->RehashUsersAndChans();
1075                         FOREACH_MOD_I(this, I_OnGarbageCollect, OnGarbageCollect());
1076                 }
1077                 Timers->TickTimers(TIME);
1078                 this->DoBackgroundUserStuff(TIME);
1079
1080                 if ((TIME % 5) == 0)
1081                 {
1082                         XLines->expire_lines();
1083                         FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
1084                         Timers->TickMissedTimers(TIME);
1085                 }
1086 #ifndef WIN32
1087                 /* Same change as in cmd_stats.cpp, use RUSAGE_SELF rather than '0' -- Om */
1088                 if (!getrusage(RUSAGE_SELF, &ru))
1089                 {
1090                         gettimeofday(&this->stats->LastSampled, NULL);
1091                         this->stats->LastCPU = ru.ru_utime;
1092                 }
1093 #else
1094                 CheckIPC(this);
1095
1096                 if(Config->nofork)
1097                 {
1098                         uptime = Time() - startup_time;
1099                         stime = gmtime(&uptime);
1100                         snprintf(window_title, 100, "InspIRCd - %u clients, %u accepted connections - Up %u days, %.2u:%.2u:%.2u",
1101                                 LocalUserCount(), stats->statsAccept, stime->tm_yday, stime->tm_hour, stime->tm_min, stime->tm_sec);
1102                         SetConsoleTitle(window_title);
1103                 }
1104 #endif
1105         }
1106
1107         /* Call the socket engine to wait on the active
1108          * file descriptors. The socket engine has everything's
1109          * descriptors in its list... dns, modules, users,
1110          * servers... so its nice and easy, just one call.
1111          * This will cause any read or write events to be
1112          * dispatched to their handlers.
1113          */
1114         SE->DispatchEvents();
1115
1116         /* if any users was quit, take them out */
1117         GlobalCulls.Apply();
1118
1119         /* If any inspsockets closed, remove them */
1120         for (std::map<InspSocket*,InspSocket*>::iterator x = SocketCull.begin(); x != SocketCull.end(); ++x)
1121         {
1122                 SE->DelFd(x->second);
1123                 x->second->Close();
1124                 delete x->second;
1125         }
1126         SocketCull.clear();
1127 }
1128
1129 int InspIRCd::Run()
1130 {
1131         while (true)
1132         {
1133                 DoOneIteration(true);
1134         }
1135         /* This is never reached -- we hope! */
1136         return 0;
1137 }
1138
1139 /**********************************************************************************/
1140
1141 /**
1142  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
1143  */
1144
1145 int main(int argc, char** argv)
1146 {
1147         SI = new InspIRCd(argc, argv);
1148         SI->Run();
1149         delete SI;
1150         return 0;
1151 }
1152
1153 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
1154  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
1155  * registration timeout maximum seconds)
1156  */
1157 bool InspIRCd::AllModulesReportReady(userrec* user)
1158 {
1159         if (!Config->global_implementation[I_OnCheckReady])
1160                 return true;
1161
1162         for (int i = 0; i <= this->GetModuleCount(); i++)
1163         {
1164                 if (Config->implement_lists[i][I_OnCheckReady])
1165                 {
1166                         int res = modules[i]->OnCheckReady(user);
1167                         if (!res)
1168                                 return false;
1169                 }
1170         }
1171         return true;
1172 }
1173
1174 int InspIRCd::GetModuleCount()
1175 {
1176         return this->ModCount;
1177 }
1178
1179 time_t InspIRCd::Time(bool delta)
1180 {
1181         if (delta)
1182                 return TIME + time_delta;
1183         return TIME;
1184 }
1185
1186 int InspIRCd::SetTimeDelta(int delta)
1187 {
1188         int old = time_delta;
1189         time_delta = delta;
1190         this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
1191         return old;
1192 }
1193
1194 void InspIRCd::AddLocalClone(userrec* user)
1195 {
1196         clonemap::iterator x = local_clones.find(user->GetIPString());
1197         if (x != local_clones.end())
1198                 x->second++;
1199         else
1200                 local_clones[user->GetIPString()] = 1;
1201 }
1202
1203 void InspIRCd::AddGlobalClone(userrec* user)
1204 {
1205         clonemap::iterator y = global_clones.find(user->GetIPString());
1206         if (y != global_clones.end())
1207                 y->second++;
1208         else
1209                 global_clones[user->GetIPString()] = 1;
1210 }
1211
1212 int InspIRCd::GetTimeDelta()
1213 {
1214         return time_delta;
1215 }
1216
1217 bool FileLogger::Readable()
1218 {
1219         return false;
1220 }
1221
1222 void FileLogger::HandleEvent(EventType et, int errornum)
1223 {
1224         this->WriteLogLine("");
1225         if (log)
1226                 ServerInstance->SE->DelFd(this);
1227 }
1228
1229 void FileLogger::WriteLogLine(const std::string &line)
1230 {
1231         if (line.length())
1232                 buffer.append(line);
1233
1234         if (log)
1235         {
1236                 int written = fprintf(log,"%s",buffer.c_str());
1237 #ifdef WINDOWS
1238                 buffer.clear();
1239 #else
1240                 if ((written >= 0) && (written < (int)buffer.length()))
1241                 {
1242                         buffer.erase(0, buffer.length());
1243                         ServerInstance->SE->AddFd(this);
1244                 }
1245                 else if (written == -1)
1246                 {
1247                         if (errno == EAGAIN)
1248                                 ServerInstance->SE->AddFd(this);
1249                 }
1250                 else
1251                 {
1252                         /* Wrote the whole buffer, and no need for write callback */
1253                         buffer.clear();
1254                 }
1255 #endif
1256                 if (writeops++ % 20)
1257                 {
1258                         fflush(log);
1259                 }
1260         }
1261 }
1262
1263 void FileLogger::Close()
1264 {
1265         if (log)
1266         {
1267                 /* Burlex: Windows assumes nonblocking on FILE* pointers anyway, and also "file" fd's aren't the same
1268                  * as socket fd's. */
1269 #ifndef WIN32
1270                 int flags = fcntl(fileno(log), F_GETFL, 0);
1271                 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
1272 #endif
1273                 if (buffer.size())
1274                         fprintf(log,"%s",buffer.c_str());
1275
1276 #ifndef WINDOWS
1277                 ServerInstance->SE->DelFd(this);
1278 #endif
1279
1280                 fflush(log);
1281                 fclose(log);
1282         }
1283
1284         buffer.clear();
1285 }
1286
1287 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
1288 {
1289         if (log)
1290         {
1291                 irc::sockets::NonBlocking(fileno(log));
1292                 this->SetFd(fileno(log));
1293                 buffer.clear();
1294         }
1295 }
1296
1297 FileLogger::~FileLogger()
1298 {
1299         this->Close();
1300 }
1301