]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Buffer flush time now under 0.5 secs
[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         log(DEBUG,"Moving %s to slot %d",modulename.c_str(),slot);
302         for (unsigned int v = 0; v < Config->module_names.size(); v++)
303         {
304                 if (Config->module_names[v] == modulename)
305                 {
306                         // found an instance, swap it with the item at MODCOUNT
307                         v2 = v;
308                         break;
309                 }
310         }
311         if (v2 == (unsigned int)slot)
312         {
313                 log(DEBUG,"Item %s already in slot %d!",modulename.c_str(),slot);
314         }
315         else if (v2 < 256)
316         {
317                 // Swap the module names over
318                 Config->module_names[v2] = Config->module_names[slot];
319                 Config->module_names[slot] = modulename;
320                 // now swap the module factories
321                 ircd_module* temp = factory[v2];
322                 factory[v2] = factory[slot];
323                 factory[slot] = temp;
324                 // now swap the module objects
325                 Module* temp_module = modules[v2];
326                 modules[v2] = modules[slot];
327                 modules[slot] = temp_module;
328                 // now swap the implement lists (we dont
329                 // need to swap the global or recount it)
330                 for (int n = 0; n < 255; n++)
331                 {
332                         char x = Config->implement_lists[v2][n];
333                         Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
334                         Config->implement_lists[slot][n] = x;
335                 }
336                 log(DEBUG,"Moved %s to slot successfully",modulename.c_str());
337         }
338         else
339         {
340                 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
341         }
342 }
343
344 void InspIRCd::MoveAfter(std::string modulename, std::string after)
345 {
346         log(DEBUG,"Move %s after %s...",modulename.c_str(),after.c_str());
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         log(DEBUG,"Move %s before %s...",modulename.c_str(),before.c_str());
360         for (unsigned int v = 0; v < Config->module_names.size(); v++)
361         {
362                 if (Config->module_names[v] == before)
363                 {
364                         if (v > 0)
365                         {
366                                 MoveTo(modulename, v-1);
367                         }
368                         else
369                         {
370                                 MoveTo(modulename, v);
371                         }
372                         return;
373                 }
374         }
375 }
376
377 void InspIRCd::MoveToFirst(std::string modulename)
378 {
379         MoveTo(modulename,0);
380 }
381
382 void InspIRCd::MoveToLast(std::string modulename)
383 {
384         MoveTo(modulename,MODCOUNT);
385 }
386
387 void InspIRCd::BuildISupport()
388 {
389         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
390         std::stringstream v;
391         v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
392         v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
393         v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC NETWORK=" << Config->Network << " MAXPARA=32";
394         Config->data005 = v.str();
395         FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
396 }
397
398 bool InspIRCd::UnloadModule(const char* filename)
399 {
400         std::string filename_str = filename;
401         for (unsigned int j = 0; j != Config->module_names.size(); j++)
402         {
403                 if (Config->module_names[j] == filename_str)
404                 {
405                         if (modules[j]->GetVersion().Flags & VF_STATIC)
406                         {
407                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
408                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
409                                 return false;
410                         }
411                         /* Give the module a chance to tidy out all its metadata */
412                         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
413                         {
414                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
415                         }
416                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
417                         {
418                                 modules[j]->OnCleanup(TYPE_USER,u->second);
419                         }
420
421                         FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
422
423                         for(int t = 0; t < 255; t++)
424                         {
425                                 Config->global_implementation[t] -= Config->implement_lists[j][t];
426                         }
427
428                         /* We have to renumber implement_lists after unload because the module numbers change!
429                          */
430                         for(int j2 = j; j2 < 254; j2++)
431                         {
432                                 for(int t = 0; t < 255; t++)
433                                 {
434                                         Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
435                                 }
436                         }
437
438                         // found the module
439                         log(DEBUG,"Deleting module...");
440                         erase_module(j);
441                         log(DEBUG,"Erasing module entry...");
442                         erase_factory(j);
443                         log(DEBUG,"Removing dependent commands...");
444                         Parser->RemoveCommands(filename);
445                         log(DEFAULT,"Module %s unloaded",filename);
446                         MODCOUNT--;
447                         BuildISupport();
448                         return true;
449                 }
450         }
451         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
452         snprintf(MODERR,MAXBUF,"Module not loaded");
453         return false;
454 }
455
456 bool InspIRCd::LoadModule(const char* filename)
457 {
458         char modfile[MAXBUF];
459 #ifdef STATIC_LINK
460         strlcpy(modfile,filename,MAXBUF);
461 #else
462         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
463 #endif
464         std::string filename_str = filename;
465 #ifndef STATIC_LINK
466 #ifndef IS_CYGWIN
467         if (!DirValid(modfile))
468         {
469                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
470                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
471                 return false;
472         }
473 #endif
474 #endif
475         log(DEBUG,"Loading module: %s",modfile);
476 #ifndef STATIC_LINK
477         if (FileExists(modfile))
478         {
479 #endif
480                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
481                 {
482                         if (Config->module_names[j] == filename_str)
483                         {
484                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
485                                 snprintf(MODERR,MAXBUF,"Module already loaded");
486                                 return false;
487                         }
488                 }
489                 ircd_module* a = new ircd_module(modfile);
490                 factory[MODCOUNT+1] = a;
491                 if (factory[MODCOUNT+1]->LastError())
492                 {
493                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
494                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
495                         return false;
496                 }
497                 try
498                 {
499                         if (factory[MODCOUNT+1]->factory)
500                         {
501                                 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
502                                 modules[MODCOUNT+1] = m;
503                                 /* save the module and the module's classfactory, if
504                                  * this isnt done, random crashes can occur :/ */
505                                 Config->module_names.push_back(filename);
506
507                                 char* x = &Config->implement_lists[MODCOUNT+1][0];
508                                 for(int t = 0; t < 255; t++)
509                                         x[t] = 0;
510
511                                 modules[MODCOUNT+1]->Implements(x);
512
513                                 for(int t = 0; t < 255; t++)
514                                 {
515                                         Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
516                                         if (Config->implement_lists[MODCOUNT+1][t])
517                                         {
518                                                 log(DEBUG,"Add global implementation: %d %d => %d",MODCOUNT+1,t,Config->global_implementation[t]);
519                                         }
520                                 }
521                         }
522                         else
523                         {
524                                 log(DEFAULT,"Unable to load %s",modfile);
525                                 snprintf(MODERR,MAXBUF,"Factory function failed!");
526                                 return false;
527                         }
528                 }
529                 catch (ModuleException& modexcept)
530                 {
531                         log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
532                         snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
533                         return false;
534                 }
535 #ifndef STATIC_LINK
536         }
537         else
538         {
539                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
540                 snprintf(MODERR,MAXBUF,"Module file could not be found");
541                 return false;
542         }
543 #endif
544         MODCOUNT++;
545         FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
546         // now work out which modules, if any, want to move to the back of the queue,
547         // and if they do, move them there.
548         std::vector<std::string> put_to_back;
549         std::vector<std::string> put_to_front;
550         std::map<std::string,std::string> put_before;
551         std::map<std::string,std::string> put_after;
552         for (unsigned int j = 0; j < Config->module_names.size(); j++)
553         {
554                 if (modules[j]->Prioritize() == PRIORITY_LAST)
555                 {
556                         put_to_back.push_back(Config->module_names[j]);
557                 }
558                 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
559                 {
560                         put_to_front.push_back(Config->module_names[j]);
561                 }
562                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
563                 {
564                         log(DEBUG,"Module %d wants PRIORITY_BEFORE",j);
565                         put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
566                         log(DEBUG,"Before: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
567                 }
568                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
569                 {
570                         log(DEBUG,"Module %d wants PRIORITY_AFTER",j);
571                         put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
572                         log(DEBUG,"After: %s",Config->module_names[modules[j]->Prioritize() >> 8].c_str());
573                 }
574         }
575         for (unsigned int j = 0; j < put_to_back.size(); j++)
576         {
577                 MoveToLast(put_to_back[j]);
578         }
579         for (unsigned int j = 0; j < put_to_front.size(); j++)
580         {
581                 MoveToFirst(put_to_front[j]);
582         }
583         for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
584         {
585                 MoveBefore(j->first,j->second);
586         }
587         for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
588         {
589                 MoveAfter(j->first,j->second);
590         }
591         BuildISupport();
592         return true;
593 }
594
595 void InspIRCd::DoOneIteration(bool process_module_sockets)
596 {
597         int activefds[MAX_DESCRIPTORS];
598         int incomingSockfd;
599         int in_port;
600         userrec* cu = NULL;
601         InspSocket* s = NULL;
602         InspSocket* s_del = NULL;
603         unsigned int numberactive;
604         sockaddr_in sock_us;     // our port number
605         socklen_t uslen;         // length of our port number
606
607         if (yield_depth > 3)
608                 return;
609
610         yield_depth++;
611
612         /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
613          * Once per loop iteration is pleanty.
614          */
615         OLDTIME = TIME;
616         TIME = time(NULL);
617         
618         /* Run background module timers every few seconds
619          * (the docs say modules shouldnt rely on accurate
620          * timing using this event, so we dont have to
621          * time this exactly).
622          */
623         if (((TIME % 5) == 0) && (!expire_run))
624         {
625                 expire_lines();
626                 if (process_module_sockets)
627                 {
628                         /* Fix by brain - the addition of DoOneIteration means that this
629                          * can end up getting called recursively in the following pattern:
630                          *
631                          * m_spanningtree DoPingChecks
632                          * (server pings out and is squit)
633                          * (squit causes call to DoOneIteration)
634                          * DoOneIteration enters here
635                          * calls DoBackground timer
636                          * enters m_spanningtree DoPingChecks... see step 1.
637                          *
638                          * This should do the job and fix the bug.
639                          */
640                         FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
641                 }
642                 TickMissedTimers(TIME);
643                 expire_run = true;
644                 yield_depth--;
645                 return;
646         }   
647         else if ((TIME % 5) == 1)
648         {
649                 expire_run = false;
650         }
651
652         if (iterations++ == 15)
653         {
654                 iterations = 0;
655                 DoBackgroundUserStuff(TIME);
656         }
657  
658         /* Once a second, do the background processing */
659         if (TIME != OLDTIME)
660         {
661                 if (TIME < OLDTIME)
662                         WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
663                 if ((TIME % 3600) == 0)
664                 {
665                         MaintainWhoWas(TIME);
666                 }
667         }
668
669         /* Process timeouts on module sockets each time around
670          * the loop. There shouldnt be many module sockets, at
671          * most, 20 or so, so this won't be much of a performance
672          * hit at all.   
673          */ 
674         if (process_module_sockets)
675                 DoSocketTimeouts(TIME);  
676          
677         TickTimers(TIME);
678          
679         /* Call the socket engine to wait on the active
680          * file descriptors. The socket engine has everything's
681          * descriptors in its list... dns, modules, users,
682          * servers... so its nice and easy, just one call.
683          */
684         if (!(numberactive = SE->Wait(activefds)))
685         {
686                 yield_depth--;
687                 return;
688         }
689
690         /**
691          * Now process each of the fd's. For users, we have a fast
692          * lookup table which can find a user by file descriptor, so
693          * processing them by fd isnt expensive. If we have a lot of
694          * listening ports or module sockets though, things could get
695          * ugly.
696          */
697         for (unsigned int activefd = 0; activefd < numberactive; activefd++)
698         {
699                 int socket_type = SE->GetType(activefds[activefd]);
700                 switch (socket_type)
701                 {
702                         case X_ESTAB_CLIENT:
703
704                                 cu = fd_ref_table[activefds[activefd]];
705                                 if (cu)
706                                         ProcessUser(cu);  
707         
708                         break;
709         
710                         case X_ESTAB_MODULE:
711
712                                 if (!process_module_sockets)
713                                         break;
714
715                                 /* Process module-owned sockets.
716                                  * Modules are encouraged to inherit their sockets from
717                                  * InspSocket so we can process them neatly like this.
718                                  */
719                                 s = socket_ref[activefds[activefd]]; 
720               
721                                 if ((s) && (!s->Poll()))
722                                 {
723                                         log(DEBUG,"Socket poll returned false, close and bail");
724                                         SE->DelFd(s->GetFd());
725                                         for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
726                                         {
727                                                 s_del = (InspSocket*)*a;
728                                                 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
729                                                 {
730                                                         module_sockets.erase(a);
731                                                         break;
732                                                 }
733                                         }
734                                         s->Close();
735                                         delete s;
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                                 dns_poll(activefds[activefd]);
749 #endif
750                         break;
751
752                         case X_LISTEN:
753
754                                 /* It's a listener */
755                                 uslen = sizeof(sock_us);
756                                 length = sizeof(client);
757                                 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
758         
759                                 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
760                                 {
761                                         in_port = ntohs(sock_us.sin_port);
762                                         log(DEBUG,"Accepted socket %d",incomingSockfd);
763                                         /* Years and years ago, we used to resolve here
764                                          * using gethostbyaddr(). That is sucky and we
765                                          * don't do that any more...
766                                          */
767                                         NonBlocking(incomingSockfd);
768                                         if (Config->GetIOHook(in_port))
769                                         {
770                                                 try
771                                                 {
772                                                         Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
773                                                 }
774                                                 catch (ModuleException& modexcept)
775                                                 {
776                                                         log(DEBUG,"Module exception cought: %s",modexcept.GetReason()); \
777                                                 }
778                                         }
779                                         stats->statsAccept++;
780                                         AddClient(incomingSockfd, in_port, false, client.sin_addr);
781                                         log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
782                                 }
783                                 else
784                                 {
785                                         log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
786                                         shutdown(incomingSockfd,2);
787                                         close(incomingSockfd);
788                                         stats->statsRefused++;
789                                 }
790                         break;
791
792                         default:
793                                 /* Something went wrong if we're in here.
794                                  * In fact, so wrong, im not quite sure
795                                  * what we would do, so for now, its going
796                                  * to safely do bugger all.
797                                  */
798                         break;
799                 }
800         }
801         yield_depth--;
802 }
803
804 int InspIRCd::Run()
805 {
806         /* Until THIS point, ServerInstance == NULL */
807         
808         LoadAllModules(this);
809
810         printf("\nInspIRCd is now running!\n");
811         
812         if (!Config->nofork)
813         {
814                 freopen("/dev/null","w",stdout);
815                 freopen("/dev/null","w",stderr);
816         }
817
818         /* Add the listening sockets used for client inbound connections
819          * to the socket engine
820          */
821         for (int count = 0; count < stats->BoundPortCount; count++)
822                 SE->AddFd(openSockfd[count],true,X_LISTEN);
823
824         WritePID(Config->PID);
825
826         /* main loop, this never returns */
827         expire_run = false;
828         yield_depth = 0;
829         iterations = 0;
830
831         while (true)
832         {
833                 DoOneIteration(true);
834         }
835         /* This is never reached -- we hope! */
836         return 0;
837 }
838
839 /**********************************************************************************/
840
841 /**
842  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
843  */
844
845 int main(int argc, char** argv)
846 {
847         ServerInstance = new InspIRCd(argc, argv);
848         ServerInstance->Run();
849         delete ServerInstance;
850         return 0;
851 }
852