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