]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Change some resolver stuff.
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /* ---------------------------------------------------------------------
2  * 
3  *              +------------------------------------+
4  *              | Inspire Internet Relay Chat Daemon |
5  *              +------------------------------------+
6  *
7  *         InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
8  *                             E-mail:
9  *                      <brain@chatspike.net>
10  *                      <Craig@chatspike.net>
11  *     
12  *  Written by Craig Edwards, Craig McLure, and others.
13  *  This program is free but copyrighted software; you can redistribute
14  *  it and/or modify it under the terms of the GNU General Public
15  *  License as published by the Free Software Foundation, version 2
16  *  (two) ONLY.
17  *
18  *  This program is distributed in the hope that it will be useful,
19  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  *  GNU General Public License for more details.
22  *
23  *  You should have received a copy of the GNU General Public License
24  *  along with this program; if not, write to the Free Software
25  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26  *
27  * ---------------------------------------------------------------------
28  */
29
30 #include <algorithm>
31 #include "inspircd_config.h"
32 #include "inspircd.h"
33 #include "configreader.h"
34 #include <fcntl.h>
35 #include <sys/errno.h>
36 #include <sys/ioctl.h>
37 #include <signal.h>
38 #include <time.h>
39 #include <string>
40 #include <exception>
41 #include <stdexcept>
42 #include <new>
43 #include <map>
44 #include <sstream>
45 #include <fstream>
46 #include <vector>
47 #include <deque>
48 #include "users.h"
49 #include "ctables.h"
50 #include "globals.h"
51 #include "modules.h"
52 #include "dynamic.h"
53 #include "wildcard.h"
54 #include "message.h"
55 #include "mode.h"
56 #include "commands.h"
57 #include "xline.h"
58 #include "inspstring.h"
59 #include "helperfuncs.h"
60 #include "hashcomp.h"
61 #include "socketengine.h"
62 #include "inspircd_se_config.h"
63 #include "userprocess.h"
64 #include "socket.h"
65 #include "typedefs.h"
66 #include "command_parse.h"
67
68 InspIRCd* ServerInstance;
69
70 extern ModuleList modules;
71 extern FactoryList factory;
72
73 extern int MODCOUNT;
74 extern char LOG_FILE[MAXBUF];
75
76 int iterations = 0;
77
78 insp_sockaddr client, server;
79 socklen_t length;
80
81 time_t TIME = time(NULL), OLDTIME = time(NULL);
82
83 Server* MyServer = new Server;
84 char lowermap[255];
85
86 void InspIRCd::AddServerName(const std::string &servername)
87 {
88         log(DEBUG,"Adding server name: %s",servername.c_str());
89         
90         if(find(servernames.begin(), servernames.end(), servername) == servernames.end())
91                 servernames.push_back(servername); /* Wasn't already there. */
92 }
93
94 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
95 {
96         servernamelist::iterator iter = find(servernames.begin(), servernames.end(), servername);
97         
98         if(iter == servernames.end())
99         {               
100                 AddServerName(servername);
101                 iter = --servernames.end();
102         }
103
104         return iter->c_str();
105 }
106
107 bool InspIRCd::FindServerName(const std::string &servername)
108 {
109         return (find(servernames.begin(), servernames.end(), servername) != servernames.end());
110 }
111
112 void Exit(int status)
113 {
114         if (ServerInstance->Config->log_file)
115                 fclose(ServerInstance->Config->log_file);
116         ServerInstance->SendError("Server shutdown.");
117         exit (status);
118 }
119
120 void InspIRCd::Start()
121 {
122         printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
123         printf("(C) ChatSpike Development team.\033[0m\n\n");
124         printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\033[0m\n");
125         printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
126         printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
127 }
128
129 void Killed(int status)
130 {
131         if (ServerInstance->Config->log_file)
132                 fclose(ServerInstance->Config->log_file);
133         ServerInstance->SendError("Server terminated.");
134         exit(status);
135 }
136
137 void Rehash(int status)
138 {
139         WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
140         fclose(ServerInstance->Config->log_file);
141         OpenLog(NULL,0);
142         ServerInstance->Config->Read(false,NULL);
143         FOREACH_MOD(I_OnRehash,OnRehash(""));
144 }
145
146 void InspIRCd::SetSignals(bool SEGVHandler)
147 {
148         signal (SIGALRM, SIG_IGN);
149         signal (SIGHUP, Rehash);
150         signal (SIGPIPE, SIG_IGN);
151         signal (SIGTERM, Exit);
152         if (SEGVHandler)
153                 signal (SIGSEGV, Error);
154 }
155
156 bool InspIRCd::DaemonSeed()
157 {
158         int childpid;
159         if ((childpid = fork ()) < 0)
160                 return (ERROR);
161         else if (childpid > 0)
162         {
163                 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
164                 sleep(6);
165                 exit (0);
166         }
167         setsid ();
168         umask (007);
169         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
170
171         rlimit rl;
172         if (getrlimit(RLIMIT_CORE, &rl) == -1)
173         {
174                 log(DEFAULT,"Failed to getrlimit()!");
175                 return false;
176         }
177         else
178         {
179                 rl.rlim_cur = rl.rlim_max;
180                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
181                         log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
182         }
183   
184         return true;
185 }
186
187 void InspIRCd::WritePID(const std::string &filename)
188 {
189         std::ofstream outfile(filename.c_str());
190         if (outfile.is_open())
191         {
192                 outfile << getpid();
193                 outfile.close();
194         }
195         else
196         {
197                 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
198                 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
199                 Exit(0);
200         }
201 }
202
203 std::string InspIRCd::GetRevision()
204 {
205         return REVISION;
206 }
207
208 void InspIRCd::MakeLowerMap()
209 {
210         // initialize the lowercase mapping table
211         for (unsigned int cn = 0; cn < 256; cn++)
212                 lowermap[cn] = cn;
213         // lowercase the uppercase chars
214         for (unsigned int cn = 65; cn < 91; cn++)
215                 lowermap[cn] = tolower(cn);
216         // now replace the specific chars for scandanavian comparison
217         lowermap[(unsigned)'['] = '{';
218         lowermap[(unsigned)']'] = '}';
219         lowermap[(unsigned)'\\'] = '|';
220 }
221
222 InspIRCd::InspIRCd(int argc, char** argv)
223 {
224         bool SEGVHandler = false;
225         this->Config = new ServerConfig;
226         ServerInstance = this;
227         this->Start();
228         this->module_sockets.clear();
229         this->startup_time = time(NULL);
230         srand(time(NULL));
231         log(DEBUG,"*** InspIRCd starting up!");
232         if (!FileExists(CONFIG_FILE))
233         {
234                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
235                 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         *LOG_FILE = 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],"-nolimit"))
260                         {
261                                 printf("WARNING: The `-nolimit' option is deprecated, and now on by default. This behaviour may change in the future.\n");
262                         }
263                         else if (!strcmp(argv[i],"-notraceback"))
264                         {
265                                 SEGVHandler = false;
266                         }
267                         else if (!strcmp(argv[i],"-logfile"))
268                         {
269                                 if (argc > i+1)
270                                 {
271                                         strlcpy(LOG_FILE,argv[i+1],MAXBUF);
272                                         printf("LOG: Setting logfile to %s\n",LOG_FILE);
273                                 }
274                                 else
275                                 {
276                                         printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
277                                         Exit(ERROR);
278                                 }
279                                 i++;
280                         }
281                         else
282                         {
283                                 printf("Usage: %s [-nofork] [-nolog] [-debug] [-wait] [-nolimit] [-notraceback] [-logfile <filename>]\n",argv[0]);
284                                 Exit(ERROR);
285                         }
286                 }
287         }
288
289         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
290
291         this->MakeLowerMap();
292
293         OpenLog(argv, argc);
294         this->stats = new serverstats();
295         this->Parser = new CommandParser();
296         Config->ClearStack();
297         Config->Read(true, NULL);
298         CheckRoot();
299         this->ModeGrok = new ModeParser();
300         AddServerName(Config->ServerName);
301         CheckDie();
302         InitializeDisabledCommands(Config->DisabledCommands, this);
303         stats->BoundPortCount = BindPorts(true);
304
305         for(int t = 0; t < 255; t++)
306                 Config->global_implementation[t] = 0;
307
308         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
309
310         printf("\n");
311         this->SetSignals(SEGVHandler);
312         if (!Config->nofork)
313         {
314                 if (!this->DaemonSeed())
315                 {
316                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
317                         Exit(ERROR);
318                 }
319         }
320
321         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
322          * initialize the socket engine.
323          */
324         SocketEngineFactory* SEF = new SocketEngineFactory();
325         SE = SEF->Create();
326         delete SEF;
327
328         /* We must load the modules AFTER initializing the socket engine, now */
329
330         return;
331 }
332
333 std::string InspIRCd::GetVersionString()
334 {
335         char versiondata[MAXBUF];
336         char dnsengine[] = "singlethread-object";
337         if (*Config->CustomVersion)
338         {
339                 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
340         }
341         else
342         {
343                 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%lu,%s,%s]",VERSION,Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
344         }
345         return versiondata;
346 }
347
348 char* InspIRCd::ModuleError()
349 {
350         return MODERR;
351 }
352
353 void InspIRCd::EraseFactory(int j)
354 {
355         int v = 0;
356         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
357         {
358                 if (v == j)
359                 {
360                         factory.erase(t);
361                         factory.push_back(NULL);
362                         return;
363                 }
364                 v++;
365         }
366 }
367
368 void InspIRCd::EraseModule(int j)
369 {
370         int v1 = 0;
371         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
372         {
373                 if (v1 == j)
374                 {
375                         DELETE(*m);
376                         modules.erase(m);
377                         modules.push_back(NULL);
378                         break;
379                 }
380                 v1++;
381         }
382         int v2 = 0;
383         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
384         {
385                 if (v2 == j)
386                 {
387                        Config->module_names.erase(v);
388                        break;
389                 }
390                 v2++;
391         }
392
393 }
394
395 void InspIRCd::MoveTo(std::string modulename,int slot)
396 {
397         unsigned int v2 = 256;
398         for (unsigned int v = 0; v < Config->module_names.size(); v++)
399         {
400                 if (Config->module_names[v] == modulename)
401                 {
402                         // found an instance, swap it with the item at MODCOUNT
403                         v2 = v;
404                         break;
405                 }
406         }
407         if ((v2 != (unsigned int)slot) && (v2 < 256))
408         {
409                 // Swap the module names over
410                 Config->module_names[v2] = Config->module_names[slot];
411                 Config->module_names[slot] = modulename;
412                 // now swap the module factories
413                 ircd_module* temp = factory[v2];
414                 factory[v2] = factory[slot];
415                 factory[slot] = temp;
416                 // now swap the module objects
417                 Module* temp_module = modules[v2];
418                 modules[v2] = modules[slot];
419                 modules[slot] = temp_module;
420                 // now swap the implement lists (we dont
421                 // need to swap the global or recount it)
422                 for (int n = 0; n < 255; n++)
423                 {
424                         char x = Config->implement_lists[v2][n];
425                         Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
426                         Config->implement_lists[slot][n] = x;
427                 }
428         }
429         else
430         {
431                 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
432         }
433 }
434
435 void InspIRCd::MoveAfter(std::string modulename, std::string after)
436 {
437         for (unsigned int v = 0; v < Config->module_names.size(); v++)
438         {
439                 if (Config->module_names[v] == after)
440                 {
441                         MoveTo(modulename, v);
442                         return;
443                 }
444         }
445 }
446
447 void InspIRCd::MoveBefore(std::string modulename, std::string before)
448 {
449         for (unsigned int v = 0; v < Config->module_names.size(); v++)
450         {
451                 if (Config->module_names[v] == before)
452                 {
453                         if (v > 0)
454                         {
455                                 MoveTo(modulename, v-1);
456                         }
457                         else
458                         {
459                                 MoveTo(modulename, v);
460                         }
461                         return;
462                 }
463         }
464 }
465
466 void InspIRCd::MoveToFirst(std::string modulename)
467 {
468         MoveTo(modulename,0);
469 }
470
471 void InspIRCd::MoveToLast(std::string modulename)
472 {
473         MoveTo(modulename,MODCOUNT);
474 }
475
476 void InspIRCd::BuildISupport()
477 {
478         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
479         std::stringstream v;
480         v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
481         v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
482         v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC NETWORK=" << Config->Network << " MAXPARA=32";
483         Config->data005 = v.str();
484         FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
485 }
486
487 bool InspIRCd::UnloadModule(const char* filename)
488 {
489         std::string filename_str = filename;
490         for (unsigned int j = 0; j != Config->module_names.size(); j++)
491         {
492                 if (Config->module_names[j] == filename_str)
493                 {
494                         if (modules[j]->GetVersion().Flags & VF_STATIC)
495                         {
496                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
497                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
498                                 return false;
499                         }
500                         /* Give the module a chance to tidy out all its metadata */
501                         for (chan_hash::iterator c = this->chanlist.begin(); c != this->chanlist.end(); c++)
502                         {
503                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
504                         }
505                         for (user_hash::iterator u = this->clientlist.begin(); u != this->clientlist.end(); u++)
506                         {
507                                 modules[j]->OnCleanup(TYPE_USER,u->second);
508                         }
509
510                         FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
511
512                         for(int t = 0; t < 255; t++)
513                         {
514                                 Config->global_implementation[t] -= Config->implement_lists[j][t];
515                         }
516
517                         /* We have to renumber implement_lists after unload because the module numbers change!
518                          */
519                         for(int j2 = j; j2 < 254; j2++)
520                         {
521                                 for(int t = 0; t < 255; t++)
522                                 {
523                                         Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
524                                 }
525                         }
526
527                         // found the module
528                         log(DEBUG,"Removing dependent commands...");
529                         Parser->RemoveCommands(filename);
530                         log(DEBUG,"Deleting module...");
531                         this->EraseModule(j);
532                         log(DEBUG,"Erasing module entry...");
533                         this->EraseFactory(j);
534                         log(DEFAULT,"Module %s unloaded",filename);
535                         MODCOUNT--;
536                         BuildISupport();
537                         return true;
538                 }
539         }
540         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
541         snprintf(MODERR,MAXBUF,"Module not loaded");
542         return false;
543 }
544
545 bool InspIRCd::LoadModule(const char* filename)
546 {
547         char modfile[MAXBUF];
548 #ifdef STATIC_LINK
549         strlcpy(modfile,filename,MAXBUF);
550 #else
551         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
552 #endif
553         std::string filename_str = filename;
554 #ifndef STATIC_LINK
555 #ifndef IS_CYGWIN
556         if (!DirValid(modfile))
557         {
558                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
559                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
560                 return false;
561         }
562 #endif
563 #endif
564         log(DEBUG,"Loading module: %s",modfile);
565 #ifndef STATIC_LINK
566         if (FileExists(modfile))
567         {
568 #endif
569                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
570                 {
571                         if (Config->module_names[j] == filename_str)
572                         {
573                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
574                                 snprintf(MODERR,MAXBUF,"Module already loaded");
575                                 return false;
576                         }
577                 }
578                 try
579                 {
580                         ircd_module* a = new ircd_module(modfile);
581                         factory[MODCOUNT+1] = a;
582                         if (factory[MODCOUNT+1]->LastError())
583                         {
584                                 log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
585                                 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
586                                 return false;
587                         }
588                         if ((int)factory[MODCOUNT+1]->factory != -1)
589                         {
590                                 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
591                                 modules[MODCOUNT+1] = m;
592                                 /* save the module and the module's classfactory, if
593                                  * this isnt done, random crashes can occur :/ */
594                                 Config->module_names.push_back(filename);
595
596                                 char* x = &Config->implement_lists[MODCOUNT+1][0];
597                                 for(int t = 0; t < 255; t++)
598                                         x[t] = 0;
599
600                                 modules[MODCOUNT+1]->Implements(x);
601
602                                 for(int t = 0; t < 255; t++)
603                                         Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
604                         }
605                         else
606                         {
607                                 log(DEFAULT,"Unable to load %s",modfile);
608                                 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
609                                 return false;
610                         }
611                 }
612                 catch (ModuleException& modexcept)
613                 {
614                         log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
615                         snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
616                         return false;
617                 }
618 #ifndef STATIC_LINK
619         }
620         else
621         {
622                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
623                 snprintf(MODERR,MAXBUF,"Module file could not be found");
624                 return false;
625         }
626 #endif
627         MODCOUNT++;
628         FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
629         // now work out which modules, if any, want to move to the back of the queue,
630         // and if they do, move them there.
631         std::vector<std::string> put_to_back;
632         std::vector<std::string> put_to_front;
633         std::map<std::string,std::string> put_before;
634         std::map<std::string,std::string> put_after;
635         for (unsigned int j = 0; j < Config->module_names.size(); j++)
636         {
637                 if (modules[j]->Prioritize() == PRIORITY_LAST)
638                 {
639                         put_to_back.push_back(Config->module_names[j]);
640                 }
641                 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
642                 {
643                         put_to_front.push_back(Config->module_names[j]);
644                 }
645                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
646                 {
647                         put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
648                 }
649                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
650                 {
651                         put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
652                 }
653         }
654         for (unsigned int j = 0; j < put_to_back.size(); j++)
655         {
656                 MoveToLast(put_to_back[j]);
657         }
658         for (unsigned int j = 0; j < put_to_front.size(); j++)
659         {
660                 MoveToFirst(put_to_front[j]);
661         }
662         for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
663         {
664                 MoveBefore(j->first,j->second);
665         }
666         for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
667         {
668                 MoveAfter(j->first,j->second);
669         }
670         BuildISupport();
671         return true;
672 }
673
674 void InspIRCd::DoOneIteration(bool process_module_sockets)
675 {
676         int activefds[MAX_DESCRIPTORS];
677         int incomingSockfd;
678         int in_port;
679         userrec* cu = NULL;
680         InspSocket* s = NULL;
681         InspSocket* s_del = NULL;
682         unsigned int numberactive;
683         insp_sockaddr sock_us;     // our port number
684         socklen_t uslen;         // length of our port number
685
686         /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
687          * Once per loop iteration is pleanty.
688          */
689         OLDTIME = TIME;
690         TIME = time(NULL);
691         
692         /* Run background module timers every few seconds
693          * (the docs say modules shouldnt rely on accurate
694          * timing using this event, so we dont have to
695          * time this exactly).
696          */
697         if (((TIME % 5) == 0) && (!expire_run))
698         {
699                 expire_lines();
700                 if (process_module_sockets)
701                 {
702                         FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
703                 }
704                 TickMissedTimers(TIME);
705                 expire_run = true;
706                 return;
707         }   
708         else if ((TIME % 5) == 1)
709         {
710                 expire_run = false;
711         }
712
713         if (iterations++ == 15)
714         {
715                 iterations = 0;
716                 this->DoBackgroundUserStuff(TIME);
717         }
718  
719         /* Once a second, do the background processing */
720         if (TIME != OLDTIME)
721         {
722                 if (TIME < OLDTIME)
723                         WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
724                 if ((TIME % 3600) == 0)
725                 {
726                         irc::whowas::MaintainWhoWas(TIME);
727                 }
728         }
729
730         /* Process timeouts on module sockets each time around
731          * the loop. There shouldnt be many module sockets, at
732          * most, 20 or so, so this won't be much of a performance
733          * hit at all.   
734          */ 
735         if (process_module_sockets)
736                 this->DoSocketTimeouts(TIME);
737          
738         TickTimers(TIME);
739          
740         /* Call the socket engine to wait on the active
741          * file descriptors. The socket engine has everything's
742          * descriptors in its list... dns, modules, users,
743          * servers... so its nice and easy, just one call.
744          */
745         if (!(numberactive = SE->Wait(activefds)))
746                 return;
747
748         /**
749          * Now process each of the fd's. For users, we have a fast
750          * lookup table which can find a user by file descriptor, so
751          * processing them by fd isnt expensive. If we have a lot of
752          * listening ports or module sockets though, things could get
753          * ugly.
754          */
755         log(DEBUG,"There are %d fd's to process.",numberactive);
756
757         for (unsigned int activefd = 0; activefd < numberactive; activefd++)
758         {
759                 int socket_type = SE->GetType(activefds[activefd]);
760                 switch (socket_type)
761                 {
762                         case X_ESTAB_CLIENT:
763
764                                 log(DEBUG,"Type: X_ESTAB_CLIENT: fd=%d",activefds[activefd]);
765                                 cu = this->fd_ref_table[activefds[activefd]];
766                                 if (cu)
767                                         this->ProcessUser(cu);
768         
769                         break;
770         
771                         case X_ESTAB_MODULE:
772
773                                 log(DEBUG,"Type: X_ESTAB_MODULE: fd=%d",activefds[activefd]);
774
775                                 if (!process_module_sockets)
776                                         break;
777
778                                 /* Process module-owned sockets.
779                                  * Modules are encouraged to inherit their sockets from
780                                  * InspSocket so we can process them neatly like this.
781                                  */
782                                 s = this->socket_ref[activefds[activefd]]; 
783               
784                                 if ((s) && (!s->Poll()))
785                                 {
786                                         log(DEBUG,"Socket poll returned false, close and bail");
787                                         SE->DelFd(s->GetFd());
788                                         this->socket_ref[activefds[activefd]] = NULL;
789                                         for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
790                                         {
791                                                 s_del = *a;
792                                                 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
793                                                 {
794                                                         module_sockets.erase(a);
795                                                         break;
796                                                 }
797                                         }
798                                         s->Close();
799                                         DELETE(s);
800                                 }
801                                 else if (!s)
802                                 {
803                                         log(DEBUG,"WTF, X_ESTAB_MODULE for nonexistent InspSocket, removed!");
804                                         SE->DelFd(s->GetFd());
805                                 }
806                         break;
807
808                         case X_ESTAB_DNS:
809                                 /* Handles instances of the Resolver class,
810                                  * a simple class extended by modules and the core for
811                                  * nonblocking resolving of addresses.
812                                  */
813                                 this->Res->MarshallReads(activefds[activefd]);
814                         break;
815
816                         case X_LISTEN:
817
818                                 log(DEBUG,"Type: X_LISTEN: fd=%d",activefds[activefd]);
819
820                                 /* It's a listener */
821                                 uslen = sizeof(sock_us);
822                                 length = sizeof(client);
823                                 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
824         
825                                 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
826                                 {
827 #ifdef IPV6
828                                         in_port = ntohs(sock_us.sin6_port);
829 #else
830                                         in_port = ntohs(sock_us.sin_port);
831 #endif
832                                         log(DEBUG,"Accepted socket %d",incomingSockfd);
833                                         /* Years and years ago, we used to resolve here
834                                          * using gethostbyaddr(). That is sucky and we
835                                          * don't do that any more...
836                                          */
837                                         NonBlocking(incomingSockfd);
838                                         if (Config->GetIOHook(in_port))
839                                         {
840                                                 try
841                                                 {
842 #ifdef IPV6
843                                                         Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin6_addr), in_port);
844 #else
845                                                         Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin_addr), in_port);
846 #endif
847                                                 }
848                                                 catch (ModuleException& modexcept)
849                                                 {
850                                                         log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
851                                                 }
852                                         }
853                                         stats->statsAccept++;
854 #ifdef IPV6
855                                         log(DEBUG,"Add ipv6 client");
856                                         userrec::AddClient(this, incomingSockfd, in_port, false, client.sin6_addr);
857 #else
858                                         log(DEBUG,"Add ipv4 client");
859                                         userrec::AddClient(this, incomingSockfd, in_port, false, client.sin_addr);
860 #endif
861                                         log(DEBUG,"Adding client on port %d fd=%d",in_port,incomingSockfd);
862                                 }
863                                 else
864                                 {
865                                         log(DEBUG,"Accept failed on fd %d: %s",incomingSockfd,strerror(errno));
866                                         shutdown(incomingSockfd,2);
867                                         close(incomingSockfd);
868                                         stats->statsRefused++;
869                                 }
870                         break;
871
872                         default:
873                                 /* Something went wrong if we're in here.
874                                  * In fact, so wrong, im not quite sure
875                                  * what we would do, so for now, its going
876                                  * to safely do bugger all.
877                                  */
878                                 log(DEBUG,"Type: X_WHAT_THE_FUCK_BBQ: fd=%d",activefds[activefd]);
879                                 SE->DelFd(activefds[activefd]);
880                         break;
881                 }
882         }
883 }
884
885 int InspIRCd::Run()
886 {
887         this->Res = new DNS(this);
888
889         LoadAllModules(this);
890
891         /* Just in case no modules were loaded - fix for bug #101 */
892         this->BuildISupport();
893
894         if (!stats->BoundPortCount)
895         {
896                 printf("\nI couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
897                 Exit(ERROR);
898         }
899
900         /* Add the listening sockets used for client inbound connections
901          * to the socket engine
902          */
903         log(DEBUG,"%d listeners",stats->BoundPortCount);
904         for (unsigned long count = 0; count < stats->BoundPortCount; count++)
905         {
906                 log(DEBUG,"Add listener: %d",Config->openSockfd[count]);
907                 if (!SE->AddFd(Config->openSockfd[count],true,X_LISTEN))
908                 {
909                         printf("\nEH? Could not add listener to socketengine. You screwed up, aborting.\n");
910                         Exit(ERROR);
911                 }
912         }
913
914         if (!Config->nofork)
915         {
916                 fclose(stdout);
917                 fclose(stderr);
918                 fclose(stdin);
919         }
920
921         printf("\nInspIRCd is now running!\n");
922
923         this->WritePID(Config->PID);
924
925         /* main loop, this never returns */
926         expire_run = false;
927         iterations = 0;
928
929         while (true)
930         {
931                 DoOneIteration(true);
932         }
933         /* This is never reached -- we hope! */
934         return 0;
935 }
936
937 /**********************************************************************************/
938
939 /**
940  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
941  */
942
943 int main(int argc, char** argv)
944 {
945         /* This is a MatchCIDR() test suite -
946         printf("Should be 0: %d\n",MatchCIDR("127.0.0.1","1.2.3.4/8"));
947         printf("Should be 1: %d\n",MatchCIDR("127.0.0.1","127.0.0.0/8"));
948         printf("Should be 1: %d\n",MatchCIDR("127.0.0.1","127.0.0.0/18"));
949         printf("Should be 0: %d\n",MatchCIDR("3ffe::0","2fc9::0/16"));
950         printf("Should be 1: %d\n",MatchCIDR("3ffe:1:3::0", "3ffe:1::0/32"));
951         exit(0); */
952
953         try
954         {
955                 ServerInstance = new InspIRCd(argc, argv);
956                 ServerInstance->Run();
957                 DELETE(ServerInstance);
958         }
959         catch (std::bad_alloc)
960         {
961                 log(DEFAULT,"You are out of memory! (got exception std::bad_alloc!)");
962                 ServerInstance->SendError("**** OUT OF MEMORY **** We're gonna need a bigger boat!");
963                 printf("Out of memory! (got exception std::bad_alloc!");
964         }
965         return 0;
966 }