]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
2b57a2292f9a33a91b751a8f351347de851d95e7
[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 MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
390         v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
391         v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC NETWORK=" << Config->Network << " MAXPARA=32";
392         Config->data005 = v.str();
393         FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
394 }
395
396 bool InspIRCd::UnloadModule(const char* filename)
397 {
398         std::string filename_str = filename;
399         for (unsigned int j = 0; j != Config->module_names.size(); j++)
400         {
401                 if (Config->module_names[j] == filename_str)
402                 {
403                         if (modules[j]->GetVersion().Flags & VF_STATIC)
404                         {
405                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
406                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
407                                 return false;
408                         }
409                         /* Give the module a chance to tidy out all its metadata */
410                         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
411                         {
412                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
413                         }
414                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
415                         {
416                                 modules[j]->OnCleanup(TYPE_USER,u->second);
417                         }
418
419                         FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
420
421                         for(int t = 0; t < 255; t++)
422                         {
423                                 Config->global_implementation[t] -= Config->implement_lists[j][t];
424                         }
425
426                         /* We have to renumber implement_lists after unload because the module numbers change!
427                          */
428                         for(int j2 = j; j2 < 254; j2++)
429                         {
430                                 for(int t = 0; t < 255; t++)
431                                 {
432                                         Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
433                                 }
434                         }
435
436                         // found the module
437                         log(DEBUG,"Deleting module...");
438                         erase_module(j);
439                         log(DEBUG,"Erasing module entry...");
440                         erase_factory(j);
441                         log(DEBUG,"Removing dependent commands...");
442                         Parser->RemoveCommands(filename);
443                         log(DEFAULT,"Module %s unloaded",filename);
444                         MODCOUNT--;
445                         BuildISupport();
446                         return true;
447                 }
448         }
449         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
450         snprintf(MODERR,MAXBUF,"Module not loaded");
451         return false;
452 }
453
454 bool InspIRCd::LoadModule(const char* filename)
455 {
456         char modfile[MAXBUF];
457 #ifdef STATIC_LINK
458         strlcpy(modfile,filename,MAXBUF);
459 #else
460         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
461 #endif
462         std::string filename_str = filename;
463 #ifndef STATIC_LINK
464 #ifndef IS_CYGWIN
465         if (!DirValid(modfile))
466         {
467                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
468                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
469                 return false;
470         }
471 #endif
472 #endif
473         log(DEBUG,"Loading module: %s",modfile);
474 #ifndef STATIC_LINK
475         if (FileExists(modfile))
476         {
477 #endif
478                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
479                 {
480                         if (Config->module_names[j] == filename_str)
481                         {
482                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
483                                 snprintf(MODERR,MAXBUF,"Module already loaded");
484                                 return false;
485                         }
486                 }
487                 ircd_module* a = new ircd_module(modfile);
488                 factory[MODCOUNT+1] = a;
489                 if (factory[MODCOUNT+1]->LastError())
490                 {
491                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
492                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
493                         return false;
494                 }
495                 try
496                 {
497                         if (factory[MODCOUNT+1]->factory)
498                         {
499                                 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
500                                 modules[MODCOUNT+1] = m;
501                                 /* save the module and the module's classfactory, if
502                                  * this isnt done, random crashes can occur :/ */
503                                 Config->module_names.push_back(filename);
504
505                                 char* x = &Config->implement_lists[MODCOUNT+1][0];
506                                 for(int t = 0; t < 255; t++)
507                                         x[t] = 0;
508
509                                 modules[MODCOUNT+1]->Implements(x);
510
511                                 for(int t = 0; t < 255; t++)
512                                 {
513                                         Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
514                                         if (Config->implement_lists[MODCOUNT+1][t])
515                                         {
516                                                 log(DEBUG,"Add global implementation: %d %d => %d",MODCOUNT+1,t,Config->global_implementation[t]);
517                                         }
518                                 }
519                         }
520                         else
521                         {
522                                 log(DEFAULT,"Unable to load %s",modfile);
523                                 snprintf(MODERR,MAXBUF,"Factory function failed!");
524                                 return false;
525                         }
526                 }
527                 catch (ModuleException& modexcept)
528                 {
529                         log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
530                         snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
531                         return false;
532                 }
533 #ifndef STATIC_LINK
534         }
535         else
536         {
537                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
538                 snprintf(MODERR,MAXBUF,"Module file could not be found");
539                 return false;
540         }
541 #endif
542         MODCOUNT++;
543         FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
544         // now work out which modules, if any, want to move to the back of the queue,
545         // and if they do, move them there.
546         std::vector<std::string> put_to_back;
547         std::vector<std::string> put_to_front;
548         std::map<std::string,std::string> put_before;
549         std::map<std::string,std::string> put_after;
550         for (unsigned int j = 0; j < Config->module_names.size(); j++)
551         {
552                 if (modules[j]->Prioritize() == PRIORITY_LAST)
553                 {
554                         put_to_back.push_back(Config->module_names[j]);
555                 }
556                 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
557                 {
558                         put_to_front.push_back(Config->module_names[j]);
559                 }
560                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
561                 {
562                         log(DEBUG,"Module %d wants PRIORITY_BEFORE",j);
563                         put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
564                         log(DEBUG,"Before: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
565                 }
566                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
567                 {
568                         log(DEBUG,"Module %d wants PRIORITY_AFTER",j);
569                         put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
570                         log(DEBUG,"After: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
571                 }
572         }
573         for (unsigned int j = 0; j < put_to_back.size(); j++)
574         {
575                 MoveToLast(put_to_back[j]);
576         }
577         for (unsigned int j = 0; j < put_to_front.size(); j++)
578         {
579                 MoveToFirst(put_to_front[j]);
580         }
581         for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
582         {
583                 MoveBefore(j->first,j->second);
584         }
585         for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
586         {
587                 MoveAfter(j->first,j->second);
588         }
589         BuildISupport();
590         return true;
591 }
592
593 int InspIRCd::Run()
594 {
595         bool expire_run = false;
596         int activefds[MAX_DESCRIPTORS];
597         int incomingSockfd;
598         int in_port;
599         userrec* cu = NULL;
600         InspSocket* s = NULL;
601         InspSocket* s_del = NULL;
602         unsigned int numberactive;
603         sockaddr_in sock_us;     // our port number
604         socklen_t uslen;         // length of our port number
605
606         /* Until THIS point, ServerInstance == NULL */
607         
608         LoadAllModules(this);
609
610         printf("\nInspIRCd is now running!\n");
611         
612         if (!Config->nofork)
613         {
614                 freopen("/dev/null","w",stdout);
615                 freopen("/dev/null","w",stderr);
616         }
617
618         /* Add the listening sockets used for client inbound connections
619          * to the socket engine
620          */
621         for (int count = 0; count < stats->BoundPortCount; count++)
622                 SE->AddFd(openSockfd[count],true,X_LISTEN);
623
624         WritePID(Config->PID);
625
626         /* main loop, this never returns */
627         for (;;)
628         {
629                 /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
630                  * Once per loop iteration is pleanty.
631                  */
632                 OLDTIME = TIME;
633                 TIME = time(NULL);
634
635                 /* Run background module timers every few seconds
636                  * (the docs say modules shouldnt rely on accurate
637                  * timing using this event, so we dont have to
638                  * time this exactly).
639                  */
640                 if (((TIME % 5) == 0) && (!expire_run))
641                 {
642                         expire_lines();
643                         FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
644                         expire_run = true;
645                         continue;
646                 }
647                 else if ((TIME % 5) == 1)
648                 {
649                         expire_run = false;
650                 }
651                 
652                 /* Once a second, do the background processing */
653                 if (TIME != OLDTIME)
654                 {
655                         if (TIME < OLDTIME)
656                                 WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
657                         DoBackgroundUserStuff(TIME);
658                 }
659
660                 /* Process timeouts on module sockets each time around
661                  * the loop. There shouldnt be many module sockets, at
662                  * most, 20 or so, so this won't be much of a performance
663                  * hit at all.
664                  */
665                 DoSocketTimeouts(TIME);
666
667                 /* Call the socket engine to wait on the active
668                  * file descriptors. The socket engine has everything's
669                  * descriptors in its list... dns, modules, users,
670                  * servers... so its nice and easy, just one call.
671                  */
672                 if (!(numberactive = SE->Wait(activefds)))
673                         continue;
674
675                 /**
676                  * Now process each of the fd's. For users, we have a fast
677                  * lookup table which can find a user by file descriptor, so
678                  * processing them by fd isnt expensive. If we have a lot of
679                  * listening ports or module sockets though, things could get
680                  * ugly.
681                  */
682                 for (unsigned int activefd = 0; activefd < numberactive; activefd++)
683                 {
684                         int socket_type = SE->GetType(activefds[activefd]);
685                         switch (socket_type)
686                         {
687                                 case X_ESTAB_CLIENT:
688
689                                         cu = fd_ref_table[activefds[activefd]];
690                                         if (cu)
691                                                 ProcessUser(cu);
692
693                                 break;
694
695                                 case X_ESTAB_MODULE:
696
697                                         /* Process module-owned sockets.
698                                          * Modules are encouraged to inherit their sockets from
699                                          * InspSocket so we can process them neatly like this.
700                                          */
701                                         s = socket_ref[activefds[activefd]];
702
703                                         if ((s) && (!s->Poll()))
704                                         {
705                                                 log(DEBUG,"Socket poll returned false, close and bail");
706                                                 SE->DelFd(s->GetFd());
707                                                 for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
708                                                 {
709                                                         s_del = (InspSocket*)*a;
710                                                         if ((s_del) && (s_del->GetFd() == activefds[activefd]))
711                                                         {
712                                                                 module_sockets.erase(a);
713                                                                 break;
714                                                         }
715                                                 }
716                                                 s->Close();
717                                                 delete s;
718                                         }
719
720                                 break;
721
722                                 case X_ESTAB_DNS:
723
724                                         /* When we are using single-threaded dns,
725                                          * the sockets for dns end up in our mainloop.
726                                          * When we are using multi-threaded dns,
727                                          * each thread has its own basic poll() loop
728                                          * within it, making them 'fire and forget'
729                                          * and independent of the mainloop.
730                                          */
731 #ifndef THREADED_DNS
732                                         dns_poll(activefds[activefd]);
733 #endif
734                                 break;
735                                 
736                                 case X_LISTEN:
737
738                                         /* It's a listener */
739                                         uslen = sizeof(sock_us);
740                                         length = sizeof(client);
741                                         incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
742                                         
743                                         if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
744                                         {
745                                                 in_port = ntohs(sock_us.sin_port);
746                                                 log(DEBUG,"Accepted socket %d",incomingSockfd);
747                                                 /* Years and years ago, we used to resolve here
748                                                  * using gethostbyaddr(). That is sucky and we
749                                                  * don't do that any more...
750                                                  */
751                                                 NonBlocking(incomingSockfd);
752                                                 if (Config->GetIOHook(in_port))
753                                                 {
754                                                         try
755                                                         {
756                                                                 Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
757                                                         }
758                                                         catch (ModuleException& modexcept)
759                                                         {
760                                                                 log(DEBUG,"Module exception cought: %s",modexcept.GetReason()); \
761                                                         }
762                                                 }
763                                                 stats->statsAccept++;
764                                                 AddClient(incomingSockfd, in_port, false, client.sin_addr);
765                                                 log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
766                                         }
767                                         else
768                                         {
769                                                 log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
770                                                 shutdown(incomingSockfd,2);
771                                                 close(incomingSockfd);
772                                                 stats->statsRefused++;
773                                         }
774                                 break;
775
776                                 default:
777                                         /* Something went wrong if we're in here.
778                                          * In fact, so wrong, im not quite sure
779                                          * what we would do, so for now, its going
780                                          * to safely do bugger all.
781                                          */
782                                 break;
783                         }
784                 }
785
786         }
787         /* This is never reached -- we hope! */
788         return 0;
789 }
790
791 /**********************************************************************************/
792
793 /**
794  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
795  */
796
797 int main(int argc, char** argv)
798 {
799         ServerInstance = new InspIRCd(argc, argv);
800         ServerInstance->Run();
801         delete ServerInstance;
802         return 0;
803 }
804