]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
- Manually bump revision ID, apparantly it's stopped doing it itself...
[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 int openSockfd[MAXSOCKS];
74 sockaddr_in client,server;
75 socklen_t length;
76
77 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
78
79 time_t TIME = time(NULL), OLDTIME = time(NULL);
80
81 // This table references users by file descriptor.
82 // its an array to make it VERY fast, as all lookups are referenced
83 // by an integer, meaning there is no need for a scan/search operation.
84 userrec* fd_ref_table[MAX_DESCRIPTORS];
85
86 Server* MyServer = new Server;
87 ServerConfig *Config = new ServerConfig;
88
89 user_hash clientlist;
90 chan_hash chanlist;
91 whowas_hash whowas;
92 servernamelist servernames;
93 char lowermap[255];
94
95 void AddServerName(std::string servername)
96 {
97         log(DEBUG,"Adding server name: %s",servername.c_str());
98         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
99         {
100                 if (*a == servername)
101                         return;
102         }
103         servernames.push_back(servername);
104 }
105
106 const char* FindServerNamePtr(std::string servername)
107 {
108         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
109         {
110                 if (*a == servername)
111                         return a->c_str();
112         }
113         AddServerName(servername);
114         return FindServerNamePtr(servername);
115 }
116
117 bool FindServerName(std::string servername)
118 {
119         for (servernamelist::iterator a = servernames.begin(); a < servernames.end(); a++)
120         {
121                 if (*a == servername)
122                         return true;
123         }
124         return false;
125 }
126
127 std::string InspIRCd::GetRevision()
128 {
129         /* w00t got me to replace a bunch of strtok_r
130          * with something nicer, so i did this. Its the
131          * same thing really, only in C++. It places the
132          * text into a std::stringstream which is a readable
133          * and writeable buffer stream, and then pops two
134          * words off it, space delimited. Because it reads
135          * into the same variable twice, the first word
136          * is discarded, and the second one returned.
137          */
138
139         /* XXX - this revision ID is NOT bumping automatically -- w00t */
140         std::stringstream Revision("$Revision$");
141         std::string single;
142         Revision >> single >> single;
143         return single;
144 }
145
146 void InspIRCd::MakeLowerMap()
147 {
148         // initialize the lowercase mapping table
149         for (unsigned int cn = 0; cn < 256; cn++)
150                 lowermap[cn] = cn;
151         // lowercase the uppercase chars
152         for (unsigned int cn = 65; cn < 91; cn++)
153                 lowermap[cn] = tolower(cn);
154         // now replace the specific chars for scandanavian comparison
155         lowermap[(unsigned)'['] = '{';
156         lowermap[(unsigned)']'] = '}';
157         lowermap[(unsigned)'\\'] = '|';
158 }
159
160 InspIRCd::InspIRCd(int argc, char** argv)
161 {
162         Start();
163         module_sockets.clear();
164         this->startup_time = time(NULL);
165         srand(time(NULL));
166         log(DEBUG,"*** InspIRCd starting up!");
167         if (!FileExists(CONFIG_FILE))
168         {
169                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
170                 log(DEFAULT,"main: no config");
171                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
172                 Exit(ERROR);
173         }
174         if (argc > 1) {
175                 for (int i = 1; i < argc; i++)
176                 {
177                         if (!strcmp(argv[i],"-nofork")) {
178                                 Config->nofork = true;
179                         }
180                         if (!strcmp(argv[i],"-wait")) {
181                                 sleep(6);
182                         }
183                         if (!strcmp(argv[i],"-nolimit")) {
184                                 Config->unlimitcore = true;
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 Rev. %s %s :%s",VERSION,GetRevision().c_str(),Config->ServerName,Config->CustomVersion);
241         }
242         else
243         {
244                 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);
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 SAFELIST 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;
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                 if (factory[MODCOUNT+1]->factory)
496                 {
497                         Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
498                         modules[MODCOUNT+1] = m;
499                         /* save the module and the module's classfactory, if
500                          * this isnt done, random crashes can occur :/ */
501                         Config->module_names.push_back(filename);
502
503                         char* x = &Config->implement_lists[MODCOUNT+1][0];
504                         for(int t = 0; t < 255; t++)
505                                 x[t] = 0;
506
507                         modules[MODCOUNT+1]->Implements(x);
508
509                         for(int t = 0; t < 255; t++)
510                         {
511                                 Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
512                                 if (Config->implement_lists[MODCOUNT+1][t])
513                                 {
514                                         log(DEBUG,"Add global implementation: %d %d => %d",MODCOUNT+1,t,Config->global_implementation[t]);
515                                 }
516                         }
517                 }
518                 else
519                 {
520                         log(DEFAULT,"Unable to load %s",modfile);
521                         snprintf(MODERR,MAXBUF,"Factory function failed!");
522                         return false;
523                 }
524 #ifndef STATIC_LINK
525         }
526         else
527         {
528                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
529                 snprintf(MODERR,MAXBUF,"Module file could not be found");
530                 return false;
531         }
532 #endif
533         MODCOUNT++;
534         FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
535         // now work out which modules, if any, want to move to the back of the queue,
536         // and if they do, move them there.
537         std::vector<std::string> put_to_back;
538         std::vector<std::string> put_to_front;
539         std::map<std::string,std::string> put_before;
540         std::map<std::string,std::string> put_after;
541         for (unsigned int j = 0; j < Config->module_names.size(); j++)
542         {
543                 if (modules[j]->Prioritize() == PRIORITY_LAST)
544                 {
545                         put_to_back.push_back(Config->module_names[j]);
546                 }
547                 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
548                 {
549                         put_to_front.push_back(Config->module_names[j]);
550                 }
551                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
552                 {
553                         log(DEBUG,"Module %d wants PRIORITY_BEFORE",j);
554                         put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
555                         log(DEBUG,"Before: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
556                 }
557                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
558                 {
559                         log(DEBUG,"Module %d wants PRIORITY_AFTER",j);
560                         put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
561                         log(DEBUG,"After: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
562                 }
563         }
564         for (unsigned int j = 0; j < put_to_back.size(); j++)
565         {
566                 MoveToLast(put_to_back[j]);
567         }
568         for (unsigned int j = 0; j < put_to_front.size(); j++)
569         {
570                 MoveToFirst(put_to_front[j]);
571         }
572         for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
573         {
574                 MoveBefore(j->first,j->second);
575         }
576         for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
577         {
578                 MoveAfter(j->first,j->second);
579         }
580         BuildISupport();
581         return true;
582 }
583
584 int InspIRCd::Run()
585 {
586         bool expire_run = false;
587         int activefds[MAX_DESCRIPTORS];
588         int incomingSockfd;
589         int in_port;
590         userrec* cu = NULL;
591         InspSocket* s = NULL;
592         InspSocket* s_del = NULL;
593         unsigned int numberactive;
594         sockaddr_in sock_us;     // our port number
595         socklen_t uslen;         // length of our port number
596
597         /* Until THIS point, ServerInstance == NULL */
598         
599         LoadAllModules(this);
600
601         printf("\nInspIRCd is now running!\n");
602         
603         if (!Config->nofork)
604         {
605                 freopen("/dev/null","w",stdout);
606                 freopen("/dev/null","w",stderr);
607         }
608
609         /* Add the listening sockets used for client inbound connections
610          * to the socket engine
611          */
612         for (int count = 0; count < stats->BoundPortCount; count++)
613                 SE->AddFd(openSockfd[count],true,X_LISTEN);
614
615         WritePID(Config->PID);
616
617         /* main loop, this never returns */
618         for (;;)
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 % 8) == 0) && (!expire_run))
632                 {
633                         expire_lines();
634                         FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
635                         expire_run = true;
636                         continue;
637                 }
638                 else if ((TIME % 8) == 1)
639                 {
640                         expire_run = false;
641                 }
642                 
643                 /* Once a second, do the background processing */
644                 if (TIME != OLDTIME)
645                 {
646                         if (TIME < OLDTIME)
647                                 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
648                         DoBackgroundUserStuff(TIME);
649                 }
650
651                 /* Process timeouts on module sockets each time around
652                  * the loop. There shouldnt be many module sockets, at
653                  * most, 20 or so, so this won't be much of a performance
654                  * hit at all.
655                  */
656                 DoSocketTimeouts(TIME);
657
658                 /* Call the socket engine to wait on the active
659                  * file descriptors. The socket engine has everything's
660                  * descriptors in its list... dns, modules, users,
661                  * servers... so its nice and easy, just one call.
662                  */
663                 if (!(numberactive = SE->Wait(activefds)))
664                         continue;
665
666                 /**
667                  * Now process each of the fd's. For users, we have a fast
668                  * lookup table which can find a user by file descriptor, so
669                  * processing them by fd isnt expensive. If we have a lot of
670                  * listening ports or module sockets though, things could get
671                  * ugly.
672                  */
673                 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
674                 {
675                         int socket_type = SE->GetType(activefds[activefd]);
676                         switch (socket_type)
677                         {
678                                 case X_ESTAB_CLIENT:
679
680                                         cu = fd_ref_table[activefds[activefd]];
681                                         if (cu)
682                                                 ProcessUser(cu);
683
684                                 break;
685
686                                 case X_ESTAB_MODULE:
687
688                                         /* Process module-owned sockets.
689                                          * Modules are encouraged to inherit their sockets from
690                                          * InspSocket so we can process them neatly like this.
691                                          */
692                                         s = socket_ref[activefds[activefd]];
693
694                                         if ((s) && (!s->Poll()))
695                                         {
696                                                 log(DEBUG,"Socket poll returned false, close and bail");
697                                                 SE->DelFd(s->GetFd());
698                                                 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
699                                                 {
700                                                         s_del = (InspSocket*)*a;
701                                                         if ((s_del) && (s_del->GetFd() == activefds[activefd]))
702                                                         {
703                                                                 module_sockets.erase(a);
704                                                                 break;
705                                                         }
706                                                 }
707                                                 s->Close();
708                                                 delete s;
709                                         }
710
711                                 break;
712
713                                 case X_ESTAB_DNS:
714
715                                         /* When we are using single-threaded dns,
716                                          * the sockets for dns end up in our mainloop.
717                                          * When we are using multi-threaded dns,
718                                          * each thread has its own basic poll() loop
719                                          * within it, making them 'fire and forget'
720                                          * and independent of the mainloop.
721                                          */
722 #ifndef THREADED_DNS
723                                         dns_poll(activefds[activefd]);
724 #endif
725                                 break;
726                                 
727                                 case X_LISTEN:
728
729                                         /* It's a listener */
730                                         uslen = sizeof(sock_us);
731                                         length = sizeof(client);
732                                         incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
733                                         
734                                         if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
735                                         {
736                                                 in_port = ntohs(sock_us.sin_port);
737                                                 log(DEBUG,"Accepted socket %d",incomingSockfd);
738                                                 /* Years and years ago, we used to resolve here
739                                                  * using gethostbyaddr(). That is sucky and we
740                                                  * don't do that any more...
741                                                  */
742                                                 NonBlocking(incomingSockfd);
743                                                 if (Config->GetIOHook(in_port))
744                                                 {
745                                                         Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
746                                                 }
747                                                 stats->statsAccept++;
748                                                 AddClient(incomingSockfd, in_port, false, client.sin_addr);
749                                                 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
750                                         }
751                                         else
752                                         {
753                                                 log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
754                                                 shutdown(incomingSockfd,2);
755                                                 close(incomingSockfd);
756                                                 stats->statsRefused++;
757                                         }
758                                 break;
759
760                                 default:
761                                         /* Something went wrong if we're in here.
762                                          * In fact, so wrong, im not quite sure
763                                          * what we would do, so for now, its going
764                                          * to safely do bugger all.
765                                          */
766                                 break;
767                         }
768                 }
769
770         }
771         /* This is never reached -- we hope! */
772         return 0;
773 }
774
775 /**********************************************************************************/
776
777 /**
778  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
779  */
780
781 int main(int argc, char** argv)
782 {
783         ServerInstance = new InspIRCd(argc, argv);
784         ServerInstance->Run();
785         delete ServerInstance;
786         return 0;
787 }
788