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