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