]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Fixes and tweaks
[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         /* w00t got me to replace a bunch of strtok_r
131          * with something nicer, so i did this. Its the
132          * same thing really, only in C++. It places the
133          * text into a std::stringstream which is a readable
134          * and writeable buffer stream, and then pops two
135          * words off it, space delimited. Because it reads
136          * into the same variable twice, the first word
137          * is discarded, and the second one returned.
138          */
139
140         /* XXX - this revision ID is NOT bumping automatically -- w00t */
141         std::stringstream Revision("$Revision$");
142         std::string single;
143         Revision >> single >> single;
144         return single;
145 }
146
147 void InspIRCd::MakeLowerMap()
148 {
149         // initialize the lowercase mapping table
150         for (unsigned int cn = 0; cn < 256; cn++)
151                 lowermap[cn] = cn;
152         // lowercase the uppercase chars
153         for (unsigned int cn = 65; cn < 91; cn++)
154                 lowermap[cn] = tolower(cn);
155         // now replace the specific chars for scandanavian comparison
156         lowermap[(unsigned)'['] = '{';
157         lowermap[(unsigned)']'] = '}';
158         lowermap[(unsigned)'\\'] = '|';
159 }
160
161 InspIRCd::InspIRCd(int argc, char** argv)
162 {
163         Start();
164         module_sockets.clear();
165         this->startup_time = time(NULL);
166         srand(time(NULL));
167         log(DEBUG,"*** InspIRCd starting up!");
168         if (!FileExists(CONFIG_FILE))
169         {
170                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
171                 log(DEFAULT,"main: no config");
172                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
173                 Exit(ERROR);
174         }
175         *LOG_FILE = 0;
176         if (argc > 1) {
177                 for (int i = 1; i < argc; i++)
178                 {
179                         if (!strcmp(argv[i],"-nofork")) {
180                                 Config->nofork = true;
181                         }
182                         if (!strcmp(argv[i],"-wait")) {
183                                 sleep(6);
184                         }
185                         if (!strcmp(argv[i],"-nolimit")) {
186                                 Config->unlimitcore = true;
187                         }
188                         if (!strcmp(argv[i],"-logfile")) {
189                                 if (argc > i+1)
190                                 {
191                                         strlcpy(LOG_FILE,argv[i+1],MAXBUF);
192                                         printf("LOG: Setting logfile to %s\n",LOG_FILE);
193                                 }
194                                 else
195                                 {
196                                         printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
197                                         Exit(ERROR);
198                                 }
199                         }
200                 }
201         }
202
203         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
204
205         this->MakeLowerMap();
206
207         OpenLog(argv, argc);
208         Config->ClearStack();
209         Config->Read(true,NULL);
210         CheckRoot();
211         this->ModeGrok = new ModeParser();
212         this->Parser = new CommandParser();
213         this->stats = new serverstats();
214         AddServerName(Config->ServerName);
215         CheckDie();
216         stats->BoundPortCount = BindPorts();
217
218         for(int t = 0; t < 255; t++)
219                 Config->global_implementation[t] = 0;
220
221         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
222
223         printf("\n");
224         SetSignals();
225         if (!Config->nofork)
226         {
227                 if (DaemonSeed() == ERROR)
228                 {
229                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
230                         Exit(ERROR);
231                 }
232         }
233
234         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
235          * initialize the socket engine.
236          */
237         SE = new SocketEngine();
238
239         /* We must load the modules AFTER initializing the socket engine, now */
240
241         return;
242 }
243
244 std::string InspIRCd::GetVersionString()
245 {
246         char versiondata[MAXBUF];
247 #ifdef THREADED_DNS
248         char dnsengine[] = "multithread";
249 #else
250         char dnsengine[] = "singlethread";
251 #endif
252         if (*Config->CustomVersion)
253         {
254                 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s",VERSION,GetRevision().c_str(),Config->ServerName,Config->CustomVersion);
255         }
256         else
257         {
258                 snprintf(versiondata,MAXBUF,"%s Rev. %s %s :%s [FLAGS=%lu,%s,%s]",VERSION,GetRevision().c_str(),Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
259         }
260         return versiondata;
261 }
262
263 char* InspIRCd::ModuleError()
264 {
265         return MODERR;
266 }
267
268 void InspIRCd::erase_factory(int j)
269 {
270         int v = 0;
271         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
272         {
273                 if (v == j)
274                 {
275                         factory.erase(t);
276                         factory.push_back(NULL);
277                         return;
278                 }
279                 v++;
280         }
281 }
282
283 void InspIRCd::erase_module(int j)
284 {
285         int v1 = 0;
286         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
287         {
288                 if (v1 == j)
289                 {
290                         delete *m;
291                         modules.erase(m);
292                         modules.push_back(NULL);
293                         break;
294                 }
295                 v1++;
296         }
297         int v2 = 0;
298         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
299         {
300                 if (v2 == j)
301                 {
302                        Config->module_names.erase(v);
303                        break;
304                 }
305                 v2++;
306         }
307
308 }
309
310 void InspIRCd::MoveTo(std::string modulename,int slot)
311 {
312         unsigned int v2 = 256;
313         log(DEBUG,"Moving %s to slot %d",modulename.c_str(),slot);
314         for (unsigned int v = 0; v < Config->module_names.size(); v++)
315         {
316                 if (Config->module_names[v] == modulename)
317                 {
318                         // found an instance, swap it with the item at MODCOUNT
319                         v2 = v;
320                         break;
321                 }
322         }
323         if (v2 == (unsigned int)slot)
324         {
325                 log(DEBUG,"Item %s already in slot %d!",modulename.c_str(),slot);
326         }
327         else if (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                 log(DEBUG,"Moved %s to slot successfully",modulename.c_str());
349         }
350         else
351         {
352                 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
353         }
354 }
355
356 void InspIRCd::MoveAfter(std::string modulename, std::string after)
357 {
358         log(DEBUG,"Move %s after %s...",modulename.c_str(),after.c_str());
359         for (unsigned int v = 0; v < Config->module_names.size(); v++)
360         {
361                 if (Config->module_names[v] == after)
362                 {
363                         MoveTo(modulename, v);
364                         return;
365                 }
366         }
367 }
368
369 void InspIRCd::MoveBefore(std::string modulename, std::string before)
370 {
371         log(DEBUG,"Move %s before %s...",modulename.c_str(),before.c_str());
372         for (unsigned int v = 0; v < Config->module_names.size(); v++)
373         {
374                 if (Config->module_names[v] == before)
375                 {
376                         if (v > 0)
377                         {
378                                 MoveTo(modulename, v-1);
379                         }
380                         else
381                         {
382                                 MoveTo(modulename, v);
383                         }
384                         return;
385                 }
386         }
387 }
388
389 void InspIRCd::MoveToFirst(std::string modulename)
390 {
391         MoveTo(modulename,0);
392 }
393
394 void InspIRCd::MoveToLast(std::string modulename)
395 {
396         MoveTo(modulename,MODCOUNT);
397 }
398
399 void InspIRCd::BuildISupport()
400 {
401         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
402         std::stringstream v;
403         v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
404         v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
405         v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC NETWORK=" << Config->Network << " MAXPARA=32";
406         Config->data005 = v.str();
407         FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
408 }
409
410 bool InspIRCd::UnloadModule(const char* filename)
411 {
412         std::string filename_str = filename;
413         for (unsigned int j = 0; j != Config->module_names.size(); j++)
414         {
415                 if (Config->module_names[j] == filename_str)
416                 {
417                         if (modules[j]->GetVersion().Flags & VF_STATIC)
418                         {
419                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
420                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
421                                 return false;
422                         }
423                         /* Give the module a chance to tidy out all its metadata */
424                         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
425                         {
426                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
427                         }
428                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
429                         {
430                                 modules[j]->OnCleanup(TYPE_USER,u->second);
431                         }
432
433                         FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
434
435                         for(int t = 0; t < 255; t++)
436                         {
437                                 Config->global_implementation[t] -= Config->implement_lists[j][t];
438                         }
439
440                         /* We have to renumber implement_lists after unload because the module numbers change!
441                          */
442                         for(int j2 = j; j2 < 254; j2++)
443                         {
444                                 for(int t = 0; t < 255; t++)
445                                 {
446                                         Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
447                                 }
448                         }
449
450                         // found the module
451                         log(DEBUG,"Deleting module...");
452                         erase_module(j);
453                         log(DEBUG,"Erasing module entry...");
454                         erase_factory(j);
455                         log(DEBUG,"Removing dependent commands...");
456                         Parser->RemoveCommands(filename);
457                         log(DEFAULT,"Module %s unloaded",filename);
458                         MODCOUNT--;
459                         BuildISupport();
460                         return true;
461                 }
462         }
463         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
464         snprintf(MODERR,MAXBUF,"Module not loaded");
465         return false;
466 }
467
468 bool InspIRCd::LoadModule(const char* filename)
469 {
470         char modfile[MAXBUF];
471 #ifdef STATIC_LINK
472         strlcpy(modfile,filename,MAXBUF);
473 #else
474         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
475 #endif
476         std::string filename_str = filename;
477 #ifndef STATIC_LINK
478 #ifndef IS_CYGWIN
479         if (!DirValid(modfile))
480         {
481                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
482                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
483                 return false;
484         }
485 #endif
486 #endif
487         log(DEBUG,"Loading module: %s",modfile);
488 #ifndef STATIC_LINK
489         if (FileExists(modfile))
490         {
491 #endif
492                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
493                 {
494                         if (Config->module_names[j] == filename_str)
495                         {
496                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
497                                 snprintf(MODERR,MAXBUF,"Module already loaded");
498                                 return false;
499                         }
500                 }
501                 ircd_module* a = new ircd_module(modfile);
502                 factory[MODCOUNT+1] = a;
503                 if (factory[MODCOUNT+1]->LastError())
504                 {
505                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
506                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
507                         return false;
508                 }
509                 try
510                 {
511                         if (factory[MODCOUNT+1]->factory)
512                         {
513                                 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
514                                 modules[MODCOUNT+1] = m;
515                                 /* save the module and the module's classfactory, if
516                                  * this isnt done, random crashes can occur :/ */
517                                 Config->module_names.push_back(filename);
518
519                                 char* x = &Config->implement_lists[MODCOUNT+1][0];
520                                 for(int t = 0; t < 255; t++)
521                                         x[t] = 0;
522
523                                 modules[MODCOUNT+1]->Implements(x);
524
525                                 for(int t = 0; t < 255; t++)
526                                 {
527                                         Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
528                                         if (Config->implement_lists[MODCOUNT+1][t])
529                                         {
530                                                 log(DEBUG,"Add global implementation: %d %d => %d",MODCOUNT+1,t,Config->global_implementation[t]);
531                                         }
532                                 }
533                         }
534                         else
535                         {
536                                 log(DEFAULT,"Unable to load %s",modfile);
537                                 snprintf(MODERR,MAXBUF,"Factory function failed!");
538                                 return false;
539                         }
540                 }
541                 catch (ModuleException& modexcept)
542                 {
543                         log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
544                         snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
545                         return false;
546                 }
547 #ifndef STATIC_LINK
548         }
549         else
550         {
551                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
552                 snprintf(MODERR,MAXBUF,"Module file could not be found");
553                 return false;
554         }
555 #endif
556         MODCOUNT++;
557         FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
558         // now work out which modules, if any, want to move to the back of the queue,
559         // and if they do, move them there.
560         std::vector<std::string> put_to_back;
561         std::vector<std::string> put_to_front;
562         std::map<std::string,std::string> put_before;
563         std::map<std::string,std::string> put_after;
564         for (unsigned int j = 0; j < Config->module_names.size(); j++)
565         {
566                 if (modules[j]->Prioritize() == PRIORITY_LAST)
567                 {
568                         put_to_back.push_back(Config->module_names[j]);
569                 }
570                 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
571                 {
572                         put_to_front.push_back(Config->module_names[j]);
573                 }
574                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
575                 {
576                         log(DEBUG,"Module %d wants PRIORITY_BEFORE",j);
577                         put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
578                         log(DEBUG,"Before: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
579                 }
580                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
581                 {
582                         log(DEBUG,"Module %d wants PRIORITY_AFTER",j);
583                         put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
584                         log(DEBUG,"After: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
585                 }
586         }
587         for (unsigned int j = 0; j < put_to_back.size(); j++)
588         {
589                 MoveToLast(put_to_back[j]);
590         }
591         for (unsigned int j = 0; j < put_to_front.size(); j++)
592         {
593                 MoveToFirst(put_to_front[j]);
594         }
595         for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
596         {
597                 MoveBefore(j->first,j->second);
598         }
599         for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
600         {
601                 MoveAfter(j->first,j->second);
602         }
603         BuildISupport();
604         return true;
605 }
606
607 void InspIRCd::DoOneIteration(bool process_module_sockets)
608 {
609         bool expire_run = false;
610         int activefds[MAX_DESCRIPTORS];
611         int incomingSockfd;
612         int in_port;
613         userrec* cu = NULL;
614         InspSocket* s = NULL;
615         InspSocket* s_del = NULL;
616         unsigned int numberactive;
617         sockaddr_in sock_us;     // our port number
618         socklen_t uslen;         // length of our port number
619
620         /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
621          * Once per loop iteration is pleanty.
622          */
623         OLDTIME = TIME;
624         TIME = time(NULL);
625         
626         /* Run background module timers every few seconds
627          * (the docs say modules shouldnt rely on accurate
628          * timing using this event, so we dont have to
629          * time this exactly).
630          */
631         if (((TIME % 5) == 0) && (!expire_run))
632         {
633                 expire_lines();
634                 FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
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                                         return;
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         while (true)
807         {
808                 DoOneIteration(true);
809         }
810         /* This is never reached -- we hope! */
811         return 0;
812 }
813
814 /**********************************************************************************/
815
816 /**
817  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
818  */
819
820 int main(int argc, char** argv)
821 {
822         ServerInstance = new InspIRCd(argc, argv);
823         ServerInstance->Run();
824         delete ServerInstance;
825         return 0;
826 }
827