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