]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Holy christ that was a LOT OF SPACES. TABS, USE THEM, LOVE THEM, APPRECIATE THEM...
[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                         {
172                                 Config->nofork = true;
173                         }
174                         if (!strcmp(argv[i],"-wait"))
175                         {
176                                 sleep(6);
177                         }
178                         if (!strcmp(argv[i],"-nolimit"))
179                         {
180                                 printf("WARNING: The `-nolimit' option is deprecated, and now on by default. This behaviour may change in the future.\n");
181                         }
182                         if (!strcmp(argv[i],"-logfile"))
183                         {
184                                 if (argc > i+1)
185                                 {
186                                         strlcpy(LOG_FILE,argv[i+1],MAXBUF);
187                                         printf("LOG: Setting logfile to %s\n",LOG_FILE);
188                                 }
189                                 else
190                                 {
191                                         printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
192                                         Exit(ERROR);
193                                 }
194                         }
195                 }
196         }
197
198         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
199
200         this->MakeLowerMap();
201
202         OpenLog(argv, argc);
203         this->stats = new serverstats();
204         Config->ClearStack();
205         Config->Read(true,NULL);
206         CheckRoot();
207         this->ModeGrok = new ModeParser();
208         this->Parser = new CommandParser();
209         AddServerName(Config->ServerName);
210         CheckDie();
211         stats->BoundPortCount = BindPorts(true);
212
213         for(int t = 0; t < 255; t++)
214                 Config->global_implementation[t] = 0;
215
216         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
217
218         printf("\n");
219         SetSignals();
220         if (!Config->nofork)
221         {
222                 if (!DaemonSeed())
223                 {
224                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
225                         Exit(ERROR);
226                 }
227         }
228
229         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
230          * initialize the socket engine.
231          */
232         SE = new SocketEngine();
233
234         /* We must load the modules AFTER initializing the socket engine, now */
235
236         return;
237 }
238
239 std::string InspIRCd::GetVersionString()
240 {
241         char versiondata[MAXBUF];
242 #ifdef THREADED_DNS
243         char dnsengine[] = "multithread";
244 #else
245         char dnsengine[] = "singlethread";
246 #endif
247         if (*Config->CustomVersion)
248         {
249                 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
250         }
251         else
252         {
253                 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%lu,%s,%s]",VERSION,Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
254         }
255         return versiondata;
256 }
257
258 char* InspIRCd::ModuleError()
259 {
260         return MODERR;
261 }
262
263 void InspIRCd::erase_factory(int j)
264 {
265         int v = 0;
266         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
267         {
268                 if (v == j)
269                 {
270                         factory.erase(t);
271                         factory.push_back(NULL);
272                         return;
273                 }
274                 v++;
275         }
276 }
277
278 void InspIRCd::erase_module(int j)
279 {
280         int v1 = 0;
281         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
282         {
283                 if (v1 == j)
284                 {
285                         delete *m;
286                         modules.erase(m);
287                         modules.push_back(NULL);
288                         break;
289                 }
290                 v1++;
291         }
292         int v2 = 0;
293         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
294         {
295                 if (v2 == j)
296                 {
297                        Config->module_names.erase(v);
298                        break;
299                 }
300                 v2++;
301         }
302
303 }
304
305 void InspIRCd::MoveTo(std::string modulename,int slot)
306 {
307         unsigned int v2 = 256;
308         for (unsigned int v = 0; v < Config->module_names.size(); v++)
309         {
310                 if (Config->module_names[v] == modulename)
311                 {
312                         // found an instance, swap it with the item at MODCOUNT
313                         v2 = v;
314                         break;
315                 }
316         }
317         if ((v2 != (unsigned int)slot) && (v2 < 256))
318         {
319                 // Swap the module names over
320                 Config->module_names[v2] = Config->module_names[slot];
321                 Config->module_names[slot] = modulename;
322                 // now swap the module factories
323                 ircd_module* temp = factory[v2];
324                 factory[v2] = factory[slot];
325                 factory[slot] = temp;
326                 // now swap the module objects
327                 Module* temp_module = modules[v2];
328                 modules[v2] = modules[slot];
329                 modules[slot] = temp_module;
330                 // now swap the implement lists (we dont
331                 // need to swap the global or recount it)
332                 for (int n = 0; n < 255; n++)
333                 {
334                         char x = Config->implement_lists[v2][n];
335                         Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
336                         Config->implement_lists[slot][n] = x;
337                 }
338         }
339         else
340         {
341                 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
342         }
343 }
344
345 void InspIRCd::MoveAfter(std::string modulename, std::string after)
346 {
347         for (unsigned int v = 0; v < Config->module_names.size(); v++)
348         {
349                 if (Config->module_names[v] == after)
350                 {
351                         MoveTo(modulename, v);
352                         return;
353                 }
354         }
355 }
356
357 void InspIRCd::MoveBefore(std::string modulename, std::string before)
358 {
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                                         Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
514                         }
515                         else
516                         {
517                                 log(DEFAULT,"Unable to load %s",modfile);
518                                 snprintf(MODERR,MAXBUF,"Factory function failed!");
519                                 return false;
520                         }
521                 }
522                 catch (ModuleException& modexcept)
523                 {
524                         log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
525                         snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
526                         return false;
527                 }
528 #ifndef STATIC_LINK
529         }
530         else
531         {
532                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
533                 snprintf(MODERR,MAXBUF,"Module file could not be found");
534                 return false;
535         }
536 #endif
537         MODCOUNT++;
538         FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
539         // now work out which modules, if any, want to move to the back of the queue,
540         // and if they do, move them there.
541         std::vector<std::string> put_to_back;
542         std::vector<std::string> put_to_front;
543         std::map<std::string,std::string> put_before;
544         std::map<std::string,std::string> put_after;
545         for (unsigned int j = 0; j < Config->module_names.size(); j++)
546         {
547                 if (modules[j]->Prioritize() == PRIORITY_LAST)
548                 {
549                         put_to_back.push_back(Config->module_names[j]);
550                 }
551                 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
552                 {
553                         put_to_front.push_back(Config->module_names[j]);
554                 }
555                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
556                 {
557                         put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
558                 }
559                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
560                 {
561                         put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
562                 }
563         }
564         for (unsigned int j = 0; j < put_to_back.size(); j++)
565         {
566                 MoveToLast(put_to_back[j]);
567         }
568         for (unsigned int j = 0; j < put_to_front.size(); j++)
569         {
570                 MoveToFirst(put_to_front[j]);
571         }
572         for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
573         {
574                 MoveBefore(j->first,j->second);
575         }
576         for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
577         {
578                 MoveAfter(j->first,j->second);
579         }
580         BuildISupport();
581         return true;
582 }
583
584 void InspIRCd::DoOneIteration(bool process_module_sockets)
585 {
586         int activefds[MAX_DESCRIPTORS];
587         int incomingSockfd;
588         int in_port;
589         userrec* cu = NULL;
590         InspSocket* s = NULL;
591         InspSocket* s_del = NULL;
592         unsigned int numberactive;
593         sockaddr_in sock_us;     // our port number
594         socklen_t uslen;         // length of our port number
595
596         if (yield_depth > 100)
597                 return;
598
599         yield_depth++;
600
601         /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
602          * Once per loop iteration is pleanty.
603          */
604         OLDTIME = TIME;
605         TIME = time(NULL);
606         
607         /* Run background module timers every few seconds
608          * (the docs say modules shouldnt rely on accurate
609          * timing using this event, so we dont have to
610          * time this exactly).
611          */
612         if (((TIME % 5) == 0) && (!expire_run))
613         {
614                 expire_lines();
615                 if (process_module_sockets)
616                 {
617                         /* Fix by brain - the addition of DoOneIteration means that this
618                          * can end up getting called recursively in the following pattern:
619                          *
620                          * m_spanningtree DoPingChecks
621                          * (server pings out and is squit)
622                          * (squit causes call to DoOneIteration)
623                          * DoOneIteration enters here
624                          * calls DoBackground timer
625                          * enters m_spanningtree DoPingChecks... see step 1.
626                          *
627                          * This should do the job and fix the bug.
628                          */
629                         FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
630                 }
631                 TickMissedTimers(TIME);
632                 expire_run = true;
633                 yield_depth--;
634                 return;
635         }   
636         else if ((TIME % 5) == 1)
637         {
638                 expire_run = false;
639         }
640
641         if (iterations++ == 15)
642         {
643                 iterations = 0;
644                 DoBackgroundUserStuff(TIME);
645         }
646  
647         /* Once a second, do the background processing */
648         if (TIME != OLDTIME)
649         {
650                 if (TIME < OLDTIME)
651                         WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
652                 if ((TIME % 3600) == 0)
653                 {
654                         MaintainWhoWas(TIME);
655                 }
656         }
657
658         /* Process timeouts on module sockets each time around
659          * the loop. There shouldnt be many module sockets, at
660          * most, 20 or so, so this won't be much of a performance
661          * hit at all.   
662          */ 
663         if (process_module_sockets)
664                 DoSocketTimeouts(TIME);  
665          
666         TickTimers(TIME);
667          
668         /* Call the socket engine to wait on the active
669          * file descriptors. The socket engine has everything's
670          * descriptors in its list... dns, modules, users,
671          * servers... so its nice and easy, just one call.
672          */
673         if (!(numberactive = SE->Wait(activefds)))
674         {
675                 yield_depth--;
676                 return;
677         }
678
679         /**
680          * Now process each of the fd's. For users, we have a fast
681          * lookup table which can find a user by file descriptor, so
682          * processing them by fd isnt expensive. If we have a lot of
683          * listening ports or module sockets though, things could get
684          * ugly.
685          */
686         log(DEBUG,"There are %d fd's to process.",numberactive);
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                                 log(DEBUG,"Type: X_ESTAB_CLIENT: fd=%d",activefds[activefd]);
696                                 cu = fd_ref_table[activefds[activefd]];
697                                 if (cu)
698                                         ProcessUser(cu);  
699         
700                         break;
701         
702                         case X_ESTAB_MODULE:
703
704                                 log(DEBUG,"Type: X_ESTAB_MODULE: fd=%d",activefds[activefd]);
705
706                                 if (!process_module_sockets)
707                                         break;
708
709                                 /* Process module-owned sockets.
710                                  * Modules are encouraged to inherit their sockets from
711                                  * InspSocket so we can process them neatly like this.
712                                  */
713                                 s = socket_ref[activefds[activefd]]; 
714               
715                                 if ((s) && (!s->Poll()))
716                                 {
717                                         log(DEBUG,"inspircd.cpp: Socket poll returned false, close and bail");
718                                         SE->DelFd(s->GetFd());
719                                         socket_ref[activefds[activefd]] = NULL;
720                                         for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
721                                         {
722                                                 s_del = (InspSocket*)*a;
723                                                 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
724                                                 {
725                                                         module_sockets.erase(a);
726                                                         break;
727                                                 }
728                                         }
729                                         s->Close();
730                                         delete s;
731                                 }
732                                 else if (!s)
733                                 {
734                                         log(DEBUG,"WTF, X_ESTAB_MODULE for nonexistent InspSocket, removed!");
735                                         SE->DelFd(s->GetFd());
736                                 }
737                         break;
738
739                         case X_ESTAB_DNS:
740                                 /* When we are using single-threaded dns,
741                                  * the sockets for dns end up in our mainloop.
742                                  * When we are using multi-threaded dns,
743                                  * each thread has its own basic poll() loop
744                                  * within it, making them 'fire and forget'
745                                  * and independent of the mainloop.
746                                  */
747 #ifndef THREADED_DNS
748                                 log(DEBUG,"Type: X_ESTAB_DNS: fd=%d",activefds[activefd]);
749                                 dns_poll(activefds[activefd]);
750 #endif
751                         break;
752
753                         case X_LISTEN:
754
755                                 log(DEBUG,"Type: X_LISTEN_MODULE: fd=%d",activefds[activefd]);
756
757                                 /* It's a listener */
758                                 uslen = sizeof(sock_us);
759                                 length = sizeof(client);
760                                 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
761         
762                                 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
763                                 {
764                                         in_port = ntohs(sock_us.sin_port);
765                                         log(DEBUG,"Accepted socket %d",incomingSockfd);
766                                         /* Years and years ago, we used to resolve here
767                                          * using gethostbyaddr(). That is sucky and we
768                                          * don't do that any more...
769                                          */
770                                         NonBlocking(incomingSockfd);
771                                         if (Config->GetIOHook(in_port))
772                                         {
773                                                 try
774                                                 {
775                                                         Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
776                                                 }
777                                                 catch (ModuleException& modexcept)
778                                                 {
779                                                         log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
780                                                 }
781                                         }
782                                         stats->statsAccept++;
783                                         AddClient(incomingSockfd, in_port, false, client.sin_addr);
784                                         log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
785                                 }
786                                 else
787                                 {
788                                         log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
789                                         shutdown(incomingSockfd,2);
790                                         close(incomingSockfd);
791                                         stats->statsRefused++;
792                                 }
793                         break;
794
795                         default:
796                                 /* Something went wrong if we're in here.
797                                  * In fact, so wrong, im not quite sure
798                                  * what we would do, so for now, its going
799                                  * to safely do bugger all.
800                                  */
801                                 log(DEBUG,"Type: X_WHAT_THE_FUCK_BBQ: fd=%d",activefds[activefd]);
802                                 SE->DelFd(activefds[activefd]);
803                         break;
804                 }
805         }
806         yield_depth--;
807 }
808
809 int InspIRCd::Run()
810 {
811         /* Until THIS point, ServerInstance == NULL */
812         
813         LoadAllModules(this);
814
815         /* Just in case no modules were loaded - fix for bug #101 */
816         this->BuildISupport();
817
818         printf("\nInspIRCd is now running!\n");
819         
820         if (!Config->nofork)
821         {
822                 fclose(stdout);
823                 fclose(stderr);
824                 fclose(stdin);
825         }
826
827         /* Add the listening sockets used for client inbound connections
828          * to the socket engine
829          */
830         for (int count = 0; count < stats->BoundPortCount; count++)
831                 SE->AddFd(openSockfd[count],true,X_LISTEN);
832
833         WritePID(Config->PID);
834
835         /* main loop, this never returns */
836         expire_run = false;
837         yield_depth = 0;
838         iterations = 0;
839
840         while (true)
841         {
842                 DoOneIteration(true);
843         }
844         /* This is never reached -- we hope! */
845         return 0;
846 }
847
848 /**********************************************************************************/
849
850 /**
851  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
852  */
853
854 int main(int argc, char** argv)
855 {
856         try
857         {
858                 ServerInstance = new InspIRCd(argc, argv);
859                 ServerInstance->Run();
860                 delete ServerInstance;
861         }
862         catch (std::bad_alloc)
863         {
864                 log(DEFAULT,"You are out of memory! (got exception std::bad_alloc!)");
865                 send_error("**** OUT OF MEMORY **** We're gonna need a bigger boat!");
866                 printf("Out of memory! (got exception std::bad_alloc!");
867         }
868         return 0;
869 }
870