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