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