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