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