]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
b74fb40468551c035523b9836fda823650dfeff0
[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 = this->GetModuleCount();
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 = this->GetModuleCount();
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                         Parser->RemoveCommands(filename);
583                         this->EraseModule(j);
584                         this->EraseFactory(j);
585                         this->Log(DEFAULT,"Module %s unloaded",filename);
586                         this->ModCount--;
587                         BuildISupport();
588                         return true;
589                 }
590         }
591         this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
592         snprintf(MODERR,MAXBUF,"Module not loaded");
593         return false;
594 }
595
596 bool InspIRCd::LoadModule(const char* filename)
597 {
598         /* Do we have a glob pattern in the filename?
599          * The user wants to load multiple modules which
600          * match the pattern.
601          */
602         if (strchr(filename,'*') || (strchr(filename,'?')))
603         {
604                 int n_match = 0;
605                 DIR* library = opendir(Config->ModPath);
606                 if (library)
607                 {
608                         /* Try and locate and load all modules matching the pattern */
609                         dirent* entry = NULL;
610                         while ((entry = readdir(library)))
611                         {
612                                 if (this->MatchText(entry->d_name, filename))
613                                 {
614                                         if (!this->LoadModule(entry->d_name))
615                                                 n_match++;
616                                 }
617                         }
618                         closedir(library);
619                 }
620                 /* Loadmodule will now return false if any one of the modules failed
621                  * to load (but wont abort when it encounters a bad one) and when 1 or
622                  * more modules were actually loaded.
623                  */
624                 return (n_match > 0);
625         }
626
627         char modfile[MAXBUF];
628         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
629         std::string filename_str = filename;
630
631         if (!ServerConfig::DirValid(modfile))
632         {
633                 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
634                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
635                 return false;
636         }
637         this->Log(DEBUG,"Loading module: %s",modfile);
638
639         if (ServerConfig::FileExists(modfile))
640         {
641
642                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
643                 {
644                         if (Config->module_names[j] == filename_str)
645                         {
646                                 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
647                                 snprintf(MODERR,MAXBUF,"Module already loaded");
648                                 return false;
649                         }
650                 }
651                 try
652                 {
653                         ircd_module* a = new ircd_module(this, modfile);
654                         factory[this->ModCount+1] = a;
655                         if (factory[this->ModCount+1]->LastError())
656                         {
657                                 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
658                                 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
659                                 return false;
660                         }
661                         if ((long)factory[this->ModCount+1]->factory != -1)
662                         {
663                                 Module* m = factory[this->ModCount+1]->factory->CreateModule(this);
664
665                                 Version v = m->GetVersion();
666
667                                 if (v.API != API_VERSION)
668                                 {
669                                         delete m;
670                                         delete a;
671                                         this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
672                                         snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
673                                         return false;
674                                 }
675                                 else
676                                 {
677                                         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]"));
678                                 }
679
680                                 modules[this->ModCount+1] = m;
681                                 /* save the module and the module's classfactory, if
682                                  * this isnt done, random crashes can occur :/ */
683                                 Config->module_names.push_back(filename);
684
685                                 char* x = &Config->implement_lists[this->ModCount+1][0];
686                                 for(int t = 0; t < 255; t++)
687                                         x[t] = 0;
688
689                                 modules[this->ModCount+1]->Implements(x);
690
691                                 for(int t = 0; t < 255; t++)
692                                         Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
693                         }
694                         else
695                         {
696                                 this->Log(DEFAULT,"Unable to load %s",modfile);
697                                 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
698                                 return false;
699                         }
700                 }
701                 catch (CoreException& modexcept)
702                 {
703                         this->Log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
704                         snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
705                         return false;
706                 }
707         }
708         else
709         {
710                 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
711                 snprintf(MODERR,MAXBUF,"Module file could not be found");
712                 return false;
713         }
714         this->ModCount++;
715         FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
716         // now work out which modules, if any, want to move to the back of the queue,
717         // and if they do, move them there.
718         std::vector<std::string> put_to_back;
719         std::vector<std::string> put_to_front;
720         std::map<std::string,std::string> put_before;
721         std::map<std::string,std::string> put_after;
722         for (unsigned int j = 0; j < Config->module_names.size(); j++)
723         {
724                 if (modules[j]->Prioritize() == PRIORITY_LAST)
725                         put_to_back.push_back(Config->module_names[j]);
726                 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
727                         put_to_front.push_back(Config->module_names[j]);
728                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
729                         put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
730                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
731                         put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
732         }
733         for (unsigned int j = 0; j < put_to_back.size(); j++)
734                 MoveToLast(put_to_back[j]);
735         for (unsigned int j = 0; j < put_to_front.size(); j++)
736                 MoveToFirst(put_to_front[j]);
737         for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
738                 MoveBefore(j->first,j->second);
739         for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
740                 MoveAfter(j->first,j->second);
741         BuildISupport();
742         return true;
743 }
744
745 void InspIRCd::DoOneIteration(bool process_module_sockets)
746 {
747         static rusage ru;
748
749         /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
750          * Once per loop iteration is pleanty.
751          */
752         OLDTIME = TIME;
753         TIME = time(NULL);
754
755         /* Run background module timers every few seconds
756          * (the docs say modules shouldnt rely on accurate
757          * timing using this event, so we dont have to
758          * time this exactly).
759          */
760         if (TIME != OLDTIME)
761         {
762                 if (TIME < OLDTIME)
763                         WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
764                 if ((TIME % 3600) == 0)
765                 {
766                         irc::whowas::MaintainWhoWas(this, TIME);
767                 }
768                 Timers->TickTimers(TIME);
769                 this->DoBackgroundUserStuff(TIME);
770
771                 if ((TIME % 5) == 0)
772                 {
773                         XLines->expire_lines();
774                         FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
775                         Timers->TickMissedTimers(TIME);
776                 }
777
778                 if (!getrusage(0, &ru))
779                 {
780                         gettimeofday(&this->stats->LastSampled, NULL);
781                         this->stats->LastCPU = ru.ru_utime;
782                 }
783         }
784
785         /* Call the socket engine to wait on the active
786          * file descriptors. The socket engine has everything's
787          * descriptors in its list... dns, modules, users,
788          * servers... so its nice and easy, just one call.
789          * This will cause any read or write events to be 
790          * dispatched to their handlers.
791          */
792         SE->DispatchEvents();
793 }
794
795 bool InspIRCd::IsIdent(const char* n)
796 {
797         if (!n || !*n)
798                 return false;
799
800         for (char* i = (char*)n; *i; i++)
801         {
802                 if ((*i >= 'A') && (*i <= '}'))
803                 {
804                         continue;
805                 }
806                 if (((*i >= '0') && (*i <= '9')) || (*i == '-') || (*i == '.'))
807                 {
808                         continue;
809                 }
810                 return false;
811         }
812         return true;
813 }
814
815
816 int InspIRCd::Run()
817 {
818         while (true)
819         {
820                 DoOneIteration(true);
821         }
822         /* This is never reached -- we hope! */
823         return 0;
824 }
825
826 /**********************************************************************************/
827
828 /**
829  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
830  */
831
832 int main(int argc, char** argv)
833 {
834         SI = new InspIRCd(argc, argv);
835         SI->Run();
836         delete SI;
837         return 0;
838 }
839
840 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
841  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
842  * registration timeout maximum seconds)
843  */
844 bool InspIRCd::AllModulesReportReady(userrec* user)
845 {
846         if (!Config->global_implementation[I_OnCheckReady])
847                 return true;
848
849         for (int i = 0; i <= this->GetModuleCount(); i++)
850         {
851                 if (Config->implement_lists[i][I_OnCheckReady])
852                 {
853                         int res = modules[i]->OnCheckReady(user);
854                         if (!res)
855                                 return false;
856                 }
857         }
858         return true;
859 }
860
861 int InspIRCd::GetModuleCount()
862 {
863         return this->ModCount;
864 }
865
866 time_t InspIRCd::Time(bool delta)
867 {
868         if (delta)
869                 return TIME + time_delta;
870         return TIME;
871 }
872
873 int InspIRCd::SetTimeDelta(int delta)
874 {
875         int old = time_delta;
876         time_delta += delta;
877         this->Log(DEBUG, "Time delta set to %d (was %d)", time_delta, old);
878         return old;
879 }
880
881 void InspIRCd::AddLocalClone(userrec* user)
882 {
883         clonemap::iterator x = local_clones.find(user->GetIPString());
884         if (x != local_clones.end())
885                 x->second++;
886         else
887                 local_clones[user->GetIPString()] = 1;
888 }
889
890 void InspIRCd::AddGlobalClone(userrec* user)
891 {
892         clonemap::iterator y = global_clones.find(user->GetIPString());
893         if (y != global_clones.end())
894                 y->second++;
895         else
896                 global_clones[user->GetIPString()] = 1;
897 }
898
899 int InspIRCd::GetTimeDelta()
900 {
901         return time_delta;
902 }
903
904 bool FileLogger::Readable()
905 {
906         return false;
907 }
908
909 void FileLogger::HandleEvent(EventType et, int errornum)
910 {
911         this->WriteLogLine("");
912         ServerInstance->SE->DelFd(this);
913 }
914
915 void FileLogger::WriteLogLine(const std::string &line)
916 {
917         if (line.length())
918                 buffer.append(line);
919
920         if (log)
921         {
922                 int written = fprintf(log,"%s",buffer.c_str());
923                 if ((written >= 0) && (written < (int)buffer.length()))
924                 {
925                         buffer.erase(0, buffer.length());
926                         ServerInstance->SE->AddFd(this);
927                 }
928                 else if (written == -1)
929                 {
930                         if (errno == EAGAIN)
931                                 ServerInstance->SE->AddFd(this);
932                 }
933                 else
934                 {
935                         /* Wrote the whole buffer, and no need for write callback */
936                         buffer = "";
937                 }
938         }
939         if (writeops++ % 20)
940         {
941                 fflush(log);
942         }
943 }
944
945 void FileLogger::Close()
946 {
947         if (log)
948         {
949                 int flags = fcntl(fileno(log), F_GETFL, 0);
950                 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
951                 if (buffer.size())
952                         fprintf(log,"%s",buffer.c_str());
953                 fflush(log);
954                 fclose(log);
955         }
956         buffer = "";
957         ServerInstance->SE->DelFd(this);
958 }
959
960 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
961 {
962         irc::sockets::NonBlocking(fileno(log));
963         this->SetFd(fileno(log));
964         buffer = "";
965 }
966
967 FileLogger::~FileLogger()
968 {
969         this->Close();
970 }
971