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