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