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