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