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