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