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