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