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