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