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