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