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