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