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