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