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