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