]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Add /usr/local/include (why isnt this included as default?!)
[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 #include <algorithm>
20 #include "inspircd_config.h"
21 #include "inspircd.h"
22 #include "configreader.h"
23 #include <fcntl.h>
24 #include <sys/errno.h>
25 #include <sys/ioctl.h>
26 #include <signal.h>
27 #include <time.h>
28 #include <string>
29 #include <exception>
30 #include <stdexcept>
31 #include <new>
32 #include <map>
33 #include <sstream>
34 #include <fstream>
35 #include <vector>
36 #include <deque>
37 #ifdef THREADED_DNS
38 #include <pthread.h>
39 #endif
40 #ifdef HAS_EXECINFO
41 #include <execinfo.h>
42 #endif
43 #include "users.h"
44 #include "ctables.h"
45 #include "globals.h"
46 #include "modules.h"
47 #include "dynamic.h"
48 #include "wildcard.h"
49 #include "message.h"
50 #include "mode.h"
51 #include "commands.h"
52 #include "xline.h"
53 #include "inspstring.h"
54 #include "dnsqueue.h"
55 #include "helperfuncs.h"
56 #include "hashcomp.h"
57 #include "socketengine.h"
58 #include "userprocess.h"
59 #include "socket.h"
60 #include "typedefs.h"
61 #include "command_parse.h"
62
63 InspIRCd* ServerInstance;
64
65 int WHOWAS_STALE = 48; // default WHOWAS Entries last 2 days before they go 'stale'
66 int WHOWAS_MAX = 100;  // default 100 people maximum in the WHOWAS list
67
68 extern ModuleList modules;
69 extern FactoryList factory;
70
71 std::vector<InspSocket*> module_sockets;
72 std::vector<userrec*> local_users;
73
74 extern int MODCOUNT;
75 extern char LOG_FILE[MAXBUF];
76 int openSockfd[MAX_DESCRIPTORS];
77 int yield_depth;
78 int iterations = 0;
79
80 insp_sockaddr client, server;
81
82 socklen_t length;
83
84 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
85
86 time_t TIME = time(NULL), OLDTIME = time(NULL);
87
88 // This table references users by file descriptor.
89 // its an array to make it VERY fast, as all lookups are referenced
90 // by an integer, meaning there is no need for a scan/search operation.
91 userrec* fd_ref_table[MAX_DESCRIPTORS];
92
93 Server* MyServer = new Server;
94 ServerConfig *Config = new ServerConfig;
95
96 user_hash clientlist;
97 chan_hash chanlist;
98
99 servernamelist servernames;
100 char lowermap[255];
101
102 void AddServerName(const std::string &servername)
103 {
104         log(DEBUG,"Adding server name: %s",servername.c_str());
105         
106         if(find(servernames.begin(), servernames.end(), servername) == servernames.end())
107                 servernames.push_back(servername); /* Wasn't already there. */
108 }
109
110 const char* FindServerNamePtr(const std::string &servername)
111 {
112         servernamelist::iterator iter = find(servernames.begin(), servernames.end(), servername);
113         
114         if(iter == servernames.end())
115         {               
116                 AddServerName(servername);
117                 iter = --servernames.end();
118         }
119
120         return iter->c_str();
121 }
122
123 bool FindServerName(const std::string &servername)
124 {
125         return (find(servernames.begin(), servernames.end(), servername) != servernames.end());
126 }
127
128 void Exit(int status)
129 {
130         if (Config->log_file)
131                 fclose(Config->log_file);
132         send_error("Server shutdown.");
133         exit (status);
134 }
135
136 void Start()
137 {
138         printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
139         printf("(C) ChatSpike Development team.\033[0m\n\n");
140         printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om\033[0m\n");
141         printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
142         printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
143 }
144
145 void Killed(int status)
146 {
147         if (Config->log_file)
148                 fclose(Config->log_file);
149         send_error("Server terminated.");
150         exit(status);
151 }
152
153 void Rehash(int status)
154 {
155         WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
156         fclose(Config->log_file);
157         OpenLog(NULL,0);
158         Config->Read(false,NULL);
159         FOREACH_MOD(I_OnRehash,OnRehash(""));
160 }
161
162 void SetSignals()
163 {
164         signal (SIGALRM, SIG_IGN);
165         signal (SIGHUP, Rehash);
166         signal (SIGPIPE, SIG_IGN);
167         signal (SIGTERM, Exit);
168         signal (SIGSEGV, Error);
169 }
170
171 bool DaemonSeed()
172 {
173         int childpid;
174         if ((childpid = fork ()) < 0)
175                 return (ERROR);
176         else if (childpid > 0)
177         {
178                 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
179                 sleep(6);
180                 exit (0);
181         }
182         setsid ();
183         umask (007);
184         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
185
186         rlimit rl;
187         if (getrlimit(RLIMIT_CORE, &rl) == -1)
188         {
189                 log(DEFAULT,"Failed to getrlimit()!");
190                 return false;
191         }
192         else
193         {
194                 rl.rlim_cur = rl.rlim_max;
195                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
196                         log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
197         }
198   
199         return true;
200 }
201
202 void WritePID(const std::string &filename)
203 {
204         std::ofstream outfile(filename.c_str());
205         if (outfile.is_open())
206         {
207                 outfile << getpid();
208                 outfile.close();
209         }
210         else
211         {
212                 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
213                 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
214                 Exit(0);
215         }
216 }
217
218 std::string InspIRCd::GetRevision()
219 {
220         return REVISION;
221 }
222
223 void InspIRCd::MakeLowerMap()
224 {
225         // initialize the lowercase mapping table
226         for (unsigned int cn = 0; cn < 256; cn++)
227                 lowermap[cn] = cn;
228         // lowercase the uppercase chars
229         for (unsigned int cn = 65; cn < 91; cn++)
230                 lowermap[cn] = tolower(cn);
231         // now replace the specific chars for scandanavian comparison
232         lowermap[(unsigned)'['] = '{';
233         lowermap[(unsigned)']'] = '}';
234         lowermap[(unsigned)'\\'] = '|';
235 }
236
237 InspIRCd::InspIRCd(int argc, char** argv)
238 {
239         Start();
240         module_sockets.clear();
241         this->startup_time = time(NULL);
242         srand(time(NULL));
243         log(DEBUG,"*** InspIRCd starting up!");
244         if (!FileExists(CONFIG_FILE))
245         {
246                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
247                 log(DEFAULT,"main: no config");
248                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
249                 Exit(ERROR);
250         }
251         *LOG_FILE = 0;
252         if (argc > 1) {
253                 for (int i = 1; i < argc; i++)
254                 {
255                         if (!strcmp(argv[i],"-nofork"))
256                         {
257                                 Config->nofork = true;
258                         }
259                         else if(!strcmp(argv[i],"-debug"))
260                         {
261                                 Config->forcedebug = true;
262                         }
263                         else if(!strcmp(argv[i],"-nolog"))
264                         {
265                                 Config->writelog = false;
266                         }
267                         else if (!strcmp(argv[i],"-wait"))
268                         {
269                                 sleep(6);
270                         }
271                         else if (!strcmp(argv[i],"-nolimit"))
272                         {
273                                 printf("WARNING: The `-nolimit' option is deprecated, and now on by default. This behaviour may change in the future.\n");
274                         }
275                         else if (!strcmp(argv[i],"-logfile"))
276                         {
277                                 if (argc > i+1)
278                                 {
279                                         strlcpy(LOG_FILE,argv[i+1],MAXBUF);
280                                         printf("LOG: Setting logfile to %s\n",LOG_FILE);
281                                 }
282                                 else
283                                 {
284                                         printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
285                                         Exit(ERROR);
286                                 }
287                         }
288                 }
289         }
290
291         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
292
293         this->MakeLowerMap();
294
295         OpenLog(argv, argc);
296         this->stats = new serverstats();
297         Config->ClearStack();
298         Config->Read(true,NULL);
299         CheckRoot();
300         this->ModeGrok = new ModeParser();
301         this->Parser = new CommandParser();
302         AddServerName(Config->ServerName);
303         CheckDie();
304         stats->BoundPortCount = BindPorts(true);
305
306         for(int t = 0; t < 255; t++)
307                 Config->global_implementation[t] = 0;
308
309         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
310
311         printf("\n");
312         SetSignals();
313         if (!Config->nofork)
314         {
315                 if (!DaemonSeed())
316                 {
317                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
318                         Exit(ERROR);
319                 }
320         }
321
322         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
323          * initialize the socket engine.
324          */
325         SE = new SocketEngine();
326
327         /* We must load the modules AFTER initializing the socket engine, now */
328
329         return;
330 }
331
332 std::string InspIRCd::GetVersionString()
333 {
334         char versiondata[MAXBUF];
335 #ifdef THREADED_DNS
336         char dnsengine[] = "multithread";
337 #else
338         char dnsengine[] = "singlethread";
339 #endif
340         if (*Config->CustomVersion)
341         {
342                 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
343         }
344         else
345         {
346                 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%lu,%s,%s]",VERSION,Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
347         }
348         return versiondata;
349 }
350
351 char* InspIRCd::ModuleError()
352 {
353         return MODERR;
354 }
355
356 void InspIRCd::erase_factory(int j)
357 {
358         int v = 0;
359         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
360         {
361                 if (v == j)
362                 {
363                         factory.erase(t);
364                         factory.push_back(NULL);
365                         return;
366                 }
367                 v++;
368         }
369 }
370
371 void InspIRCd::erase_module(int j)
372 {
373         int v1 = 0;
374         for (std::vector<Module*>::iterator m = modules.begin(); m!= modules.end(); m++)
375         {
376                 if (v1 == j)
377                 {
378                         delete *m;
379                         modules.erase(m);
380                         modules.push_back(NULL);
381                         break;
382                 }
383                 v1++;
384         }
385         int v2 = 0;
386         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
387         {
388                 if (v2 == j)
389                 {
390                        Config->module_names.erase(v);
391                        break;
392                 }
393                 v2++;
394         }
395
396 }
397
398 void InspIRCd::MoveTo(std::string modulename,int slot)
399 {
400         unsigned int v2 = 256;
401         for (unsigned int v = 0; v < Config->module_names.size(); v++)
402         {
403                 if (Config->module_names[v] == modulename)
404                 {
405                         // found an instance, swap it with the item at MODCOUNT
406                         v2 = v;
407                         break;
408                 }
409         }
410         if ((v2 != (unsigned int)slot) && (v2 < 256))
411         {
412                 // Swap the module names over
413                 Config->module_names[v2] = Config->module_names[slot];
414                 Config->module_names[slot] = modulename;
415                 // now swap the module factories
416                 ircd_module* temp = factory[v2];
417                 factory[v2] = factory[slot];
418                 factory[slot] = temp;
419                 // now swap the module objects
420                 Module* temp_module = modules[v2];
421                 modules[v2] = modules[slot];
422                 modules[slot] = temp_module;
423                 // now swap the implement lists (we dont
424                 // need to swap the global or recount it)
425                 for (int n = 0; n < 255; n++)
426                 {
427                         char x = Config->implement_lists[v2][n];
428                         Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
429                         Config->implement_lists[slot][n] = x;
430                 }
431         }
432         else
433         {
434                 log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
435         }
436 }
437
438 void InspIRCd::MoveAfter(std::string modulename, std::string after)
439 {
440         for (unsigned int v = 0; v < Config->module_names.size(); v++)
441         {
442                 if (Config->module_names[v] == after)
443                 {
444                         MoveTo(modulename, v);
445                         return;
446                 }
447         }
448 }
449
450 void InspIRCd::MoveBefore(std::string modulename, std::string before)
451 {
452         for (unsigned int v = 0; v < Config->module_names.size(); v++)
453         {
454                 if (Config->module_names[v] == before)
455                 {
456                         if (v > 0)
457                         {
458                                 MoveTo(modulename, v-1);
459                         }
460                         else
461                         {
462                                 MoveTo(modulename, v);
463                         }
464                         return;
465                 }
466         }
467 }
468
469 void InspIRCd::MoveToFirst(std::string modulename)
470 {
471         MoveTo(modulename,0);
472 }
473
474 void InspIRCd::MoveToLast(std::string modulename)
475 {
476         MoveTo(modulename,MODCOUNT);
477 }
478
479 void InspIRCd::BuildISupport()
480 {
481         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
482         std::stringstream v;
483         v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=(ohv)@%+ MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
484         v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
485         v << MAXAWAY << " CHANMODES=b,k,l,psmnti FNC NETWORK=" << Config->Network << " MAXPARA=32";
486         Config->data005 = v.str();
487         FOREACH_MOD(I_On005Numeric,On005Numeric(Config->data005));
488 }
489
490 bool InspIRCd::UnloadModule(const char* filename)
491 {
492         std::string filename_str = filename;
493         for (unsigned int j = 0; j != Config->module_names.size(); j++)
494         {
495                 if (Config->module_names[j] == filename_str)
496                 {
497                         if (modules[j]->GetVersion().Flags & VF_STATIC)
498                         {
499                                 log(DEFAULT,"Failed to unload STATIC module %s",filename);
500                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
501                                 return false;
502                         }
503                         /* Give the module a chance to tidy out all its metadata */
504                         for (chan_hash::iterator c = chanlist.begin(); c != chanlist.end(); c++)
505                         {
506                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
507                         }
508                         for (user_hash::iterator u = clientlist.begin(); u != clientlist.end(); u++)
509                         {
510                                 modules[j]->OnCleanup(TYPE_USER,u->second);
511                         }
512
513                         FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
514
515                         for(int t = 0; t < 255; t++)
516                         {
517                                 Config->global_implementation[t] -= Config->implement_lists[j][t];
518                         }
519
520                         /* We have to renumber implement_lists after unload because the module numbers change!
521                          */
522                         for(int j2 = j; j2 < 254; j2++)
523                         {
524                                 for(int t = 0; t < 255; t++)
525                                 {
526                                         Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
527                                 }
528                         }
529
530                         // found the module
531                         log(DEBUG,"Deleting module...");
532                         erase_module(j);
533                         log(DEBUG,"Erasing module entry...");
534                         erase_factory(j);
535                         log(DEBUG,"Removing dependent commands...");
536                         Parser->RemoveCommands(filename);
537                         log(DEFAULT,"Module %s unloaded",filename);
538                         MODCOUNT--;
539                         BuildISupport();
540                         return true;
541                 }
542         }
543         log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
544         snprintf(MODERR,MAXBUF,"Module not loaded");
545         return false;
546 }
547
548 bool InspIRCd::LoadModule(const char* filename)
549 {
550         char modfile[MAXBUF];
551 #ifdef STATIC_LINK
552         strlcpy(modfile,filename,MAXBUF);
553 #else
554         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
555 #endif
556         std::string filename_str = filename;
557 #ifndef STATIC_LINK
558 #ifndef IS_CYGWIN
559         if (!DirValid(modfile))
560         {
561                 log(DEFAULT,"Module %s is not within the modules directory.",modfile);
562                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
563                 return false;
564         }
565 #endif
566 #endif
567         log(DEBUG,"Loading module: %s",modfile);
568 #ifndef STATIC_LINK
569         if (FileExists(modfile))
570         {
571 #endif
572                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
573                 {
574                         if (Config->module_names[j] == filename_str)
575                         {
576                                 log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
577                                 snprintf(MODERR,MAXBUF,"Module already loaded");
578                                 return false;
579                         }
580                 }
581                 ircd_module* a = new ircd_module(modfile);
582                 factory[MODCOUNT+1] = a;
583                 if (factory[MODCOUNT+1]->LastError())
584                 {
585                         log(DEFAULT,"Unable to load %s: %s",modfile,factory[MODCOUNT+1]->LastError());
586                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[MODCOUNT+1]->LastError());
587                         return false;
588                 }
589                 try
590                 {
591                         if (factory[MODCOUNT+1]->factory)
592                         {
593                                 Module* m = factory[MODCOUNT+1]->factory->CreateModule(MyServer);
594                                 modules[MODCOUNT+1] = m;
595                                 /* save the module and the module's classfactory, if
596                                  * this isnt done, random crashes can occur :/ */
597                                 Config->module_names.push_back(filename);
598
599                                 char* x = &Config->implement_lists[MODCOUNT+1][0];
600                                 for(int t = 0; t < 255; t++)
601                                         x[t] = 0;
602
603                                 modules[MODCOUNT+1]->Implements(x);
604
605                                 for(int t = 0; t < 255; t++)
606                                         Config->global_implementation[t] += Config->implement_lists[MODCOUNT+1][t];
607                         }
608                         else
609                         {
610                                 log(DEFAULT,"Unable to load %s",modfile);
611                                 snprintf(MODERR,MAXBUF,"Factory function failed!");
612                                 return false;
613                         }
614                 }
615                 catch (ModuleException& modexcept)
616                 {
617                         log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
618                         snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
619                         return false;
620                 }
621 #ifndef STATIC_LINK
622         }
623         else
624         {
625                 log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
626                 snprintf(MODERR,MAXBUF,"Module file could not be found");
627                 return false;
628         }
629 #endif
630         MODCOUNT++;
631         FOREACH_MOD(I_OnLoadModule,OnLoadModule(modules[MODCOUNT],filename_str));
632         // now work out which modules, if any, want to move to the back of the queue,
633         // and if they do, move them there.
634         std::vector<std::string> put_to_back;
635         std::vector<std::string> put_to_front;
636         std::map<std::string,std::string> put_before;
637         std::map<std::string,std::string> put_after;
638         for (unsigned int j = 0; j < Config->module_names.size(); j++)
639         {
640                 if (modules[j]->Prioritize() == PRIORITY_LAST)
641                 {
642                         put_to_back.push_back(Config->module_names[j]);
643                 }
644                 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
645                 {
646                         put_to_front.push_back(Config->module_names[j]);
647                 }
648                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
649                 {
650                         put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
651                 }
652                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
653                 {
654                         put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
655                 }
656         }
657         for (unsigned int j = 0; j < put_to_back.size(); j++)
658         {
659                 MoveToLast(put_to_back[j]);
660         }
661         for (unsigned int j = 0; j < put_to_front.size(); j++)
662         {
663                 MoveToFirst(put_to_front[j]);
664         }
665         for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
666         {
667                 MoveBefore(j->first,j->second);
668         }
669         for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
670         {
671                 MoveAfter(j->first,j->second);
672         }
673         BuildISupport();
674         return true;
675 }
676
677 void InspIRCd::DoOneIteration(bool process_module_sockets)
678 {
679         int activefds[MAX_DESCRIPTORS];
680         int incomingSockfd;
681         int in_port;
682         userrec* cu = NULL;
683         InspSocket* s = NULL;
684         InspSocket* s_del = NULL;
685         unsigned int numberactive;
686         insp_sockaddr sock_us;     // our port number
687         socklen_t uslen;         // length of our port number
688
689         if (yield_depth > 100)
690                 return;
691
692         yield_depth++;
693
694         /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
695          * Once per loop iteration is pleanty.
696          */
697         OLDTIME = TIME;
698         TIME = time(NULL);
699         
700         /* Run background module timers every few seconds
701          * (the docs say modules shouldnt rely on accurate
702          * timing using this event, so we dont have to
703          * time this exactly).
704          */
705         if (((TIME % 5) == 0) && (!expire_run))
706         {
707                 expire_lines();
708                 if (process_module_sockets)
709                 {
710                         /* Fix by brain - the addition of DoOneIteration means that this
711                          * can end up getting called recursively in the following pattern:
712                          *
713                          * m_spanningtree DoPingChecks
714                          * (server pings out and is squit)
715                          * (squit causes call to DoOneIteration)
716                          * DoOneIteration enters here
717                          * calls DoBackground timer
718                          * enters m_spanningtree DoPingChecks... see step 1.
719                          *
720                          * This should do the job and fix the bug.
721                          */
722                         FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
723                 }
724                 TickMissedTimers(TIME);
725                 expire_run = true;
726                 yield_depth--;
727                 return;
728         }   
729         else if ((TIME % 5) == 1)
730         {
731                 expire_run = false;
732         }
733
734         if (iterations++ == 15)
735         {
736                 iterations = 0;
737                 DoBackgroundUserStuff(TIME);
738         }
739  
740         /* Once a second, do the background processing */
741         if (TIME != OLDTIME)
742         {
743                 if (TIME < OLDTIME)
744                         WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
745                 if ((TIME % 3600) == 0)
746                 {
747                         MaintainWhoWas(TIME);
748                 }
749         }
750
751         /* Process timeouts on module sockets each time around
752          * the loop. There shouldnt be many module sockets, at
753          * most, 20 or so, so this won't be much of a performance
754          * hit at all.   
755          */ 
756         if (process_module_sockets)
757                 DoSocketTimeouts(TIME);  
758          
759         TickTimers(TIME);
760          
761         /* Call the socket engine to wait on the active
762          * file descriptors. The socket engine has everything's
763          * descriptors in its list... dns, modules, users,
764          * servers... so its nice and easy, just one call.
765          */
766         if (!(numberactive = SE->Wait(activefds)))
767         {
768                 yield_depth--;
769                 return;
770         }
771
772         /**
773          * Now process each of the fd's. For users, we have a fast
774          * lookup table which can find a user by file descriptor, so
775          * processing them by fd isnt expensive. If we have a lot of
776          * listening ports or module sockets though, things could get
777          * ugly.
778          */
779         log(DEBUG,"There are %d fd's to process.",numberactive);
780
781         for (unsigned int activefd = 0; activefd < numberactive; activefd++)
782         {
783                 int socket_type = SE->GetType(activefds[activefd]);
784                 switch (socket_type)
785                 {
786                         case X_ESTAB_CLIENT:
787
788                                 log(DEBUG,"Type: X_ESTAB_CLIENT: fd=%d",activefds[activefd]);
789                                 cu = fd_ref_table[activefds[activefd]];
790                                 if (cu)
791                                         ProcessUser(cu);  
792         
793                         break;
794         
795                         case X_ESTAB_MODULE:
796
797                                 log(DEBUG,"Type: X_ESTAB_MODULE: fd=%d",activefds[activefd]);
798
799                                 if (!process_module_sockets)
800                                         break;
801
802                                 /* Process module-owned sockets.
803                                  * Modules are encouraged to inherit their sockets from
804                                  * InspSocket so we can process them neatly like this.
805                                  */
806                                 s = socket_ref[activefds[activefd]]; 
807               
808                                 if ((s) && (!s->Poll()))
809                                 {
810                                         log(DEBUG,"inspircd.cpp: Socket poll returned false, close and bail");
811                                         SE->DelFd(s->GetFd());
812                                         socket_ref[activefds[activefd]] = NULL;
813                                         for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
814                                         {
815                                                 s_del = (InspSocket*)*a;
816                                                 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
817                                                 {
818                                                         module_sockets.erase(a);
819                                                         break;
820                                                 }
821                                         }
822                                         s->Close();
823                                         delete s;
824                                 }
825                                 else if (!s)
826                                 {
827                                         log(DEBUG,"WTF, X_ESTAB_MODULE for nonexistent InspSocket, removed!");
828                                         SE->DelFd(s->GetFd());
829                                 }
830                         break;
831
832                         case X_ESTAB_DNS:
833                                 /* When we are using single-threaded dns,
834                                  * the sockets for dns end up in our mainloop.
835                                  * When we are using multi-threaded dns,
836                                  * each thread has its own basic poll() loop
837                                  * within it, making them 'fire and forget'
838                                  * and independent of the mainloop.
839                                  */
840 #ifndef THREADED_DNS
841                                 log(DEBUG,"Type: X_ESTAB_DNS: fd=%d",activefds[activefd]);
842                                 dns_poll(activefds[activefd]);
843 #endif
844                         break;
845
846                         case X_LISTEN:
847
848                                 log(DEBUG,"Type: X_LISTEN_MODULE: fd=%d",activefds[activefd]);
849
850                                 /* It's a listener */
851                                 uslen = sizeof(sock_us);
852                                 length = sizeof(client);
853                                 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
854         
855                                 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
856                                 {
857                                         in_port = ntohs(sock_us.sin_port);
858                                         log(DEBUG,"Accepted socket %d",incomingSockfd);
859                                         /* Years and years ago, we used to resolve here
860                                          * using gethostbyaddr(). That is sucky and we
861                                          * don't do that any more...
862                                          */
863                                         NonBlocking(incomingSockfd);
864                                         if (Config->GetIOHook(in_port))
865                                         {
866                                                 try
867                                                 {
868                                                         Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, (char*)inet_ntoa(client.sin_addr), in_port);
869                                                 }
870                                                 catch (ModuleException& modexcept)
871                                                 {
872                                                         log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
873                                                 }
874                                         }
875                                         stats->statsAccept++;
876                                         AddClient(incomingSockfd, in_port, false, client.sin_addr);
877                                         log(DEBUG,"Adding client on port %lu fd=%lu",(unsigned long)in_port,(unsigned long)incomingSockfd);
878                                 }
879                                 else
880                                 {
881                                         log(DEBUG,"Accept failed on fd %lu: %s",(unsigned long)incomingSockfd,strerror(errno));
882                                         shutdown(incomingSockfd,2);
883                                         close(incomingSockfd);
884                                         stats->statsRefused++;
885                                 }
886                         break;
887
888                         default:
889                                 /* Something went wrong if we're in here.
890                                  * In fact, so wrong, im not quite sure
891                                  * what we would do, so for now, its going
892                                  * to safely do bugger all.
893                                  */
894                                 log(DEBUG,"Type: X_WHAT_THE_FUCK_BBQ: fd=%d",activefds[activefd]);
895                                 SE->DelFd(activefds[activefd]);
896                         break;
897                 }
898         }
899         yield_depth--;
900 }
901
902 int InspIRCd::Run()
903 {
904         /* Until THIS point, ServerInstance == NULL */
905         
906         LoadAllModules(this);
907
908         /* Just in case no modules were loaded - fix for bug #101 */
909         this->BuildISupport();
910
911         printf("\nInspIRCd is now running!\n");
912         
913         if (!Config->nofork)
914         {
915                 fclose(stdout);
916                 fclose(stderr);
917                 fclose(stdin);
918         }
919
920         /* Add the listening sockets used for client inbound connections
921          * to the socket engine
922          */
923         for (int count = 0; count < stats->BoundPortCount; count++)
924                 SE->AddFd(openSockfd[count],true,X_LISTEN);
925
926         WritePID(Config->PID);
927
928         /* main loop, this never returns */
929         expire_run = false;
930         yield_depth = 0;
931         iterations = 0;
932
933         while (true)
934         {
935                 DoOneIteration(true);
936         }
937         /* This is never reached -- we hope! */
938         return 0;
939 }
940
941 /**********************************************************************************/
942
943 /**
944  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
945  */
946
947 int main(int argc, char** argv)
948 {
949         try
950         {
951                 ServerInstance = new InspIRCd(argc, argv);
952                 ServerInstance->Run();
953                 delete ServerInstance;
954         }
955         catch (std::bad_alloc)
956         {
957                 log(DEFAULT,"You are out of memory! (got exception std::bad_alloc!)");
958                 send_error("**** OUT OF MEMORY **** We're gonna need a bigger boat!");
959                 printf("Out of memory! (got exception std::bad_alloc!");
960         }
961         return 0;
962 }