]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Remove dependent commands BEFORE deleting the Module*, otherwise things go tits over...
[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<InspSocket*> module_sockets;
74 std::vector<userrec*> local_users;
75
76 extern int MODCOUNT;
77 extern char LOG_FILE[MAXBUF];
78
79 int iterations = 0;
80
81 insp_sockaddr client, server;
82 socklen_t length;
83
84 extern InspSocket* socket_ref[MAX_DESCRIPTORS];
85 time_t TIME = time(NULL), OLDTIME = time(NULL);
86
87 // This table references users by file descriptor.
88 // its an array to make it VERY fast, as all lookups are referenced
89 // by an integer, meaning there is no need for a scan/search operation.
90 userrec* fd_ref_table[MAX_DESCRIPTORS];
91 Server* MyServer = new Server;
92 ServerConfig *Config = new ServerConfig;
93 user_hash clientlist;
94 chan_hash chanlist;
95 servernamelist servernames;
96 char lowermap[255];
97
98 void AddServerName(const std::string &servername)
99 {
100         log(DEBUG,"Adding server name: %s",servername.c_str());
101         
102         if(find(servernames.begin(), servernames.end(), servername) == servernames.end())
103                 servernames.push_back(servername); /* Wasn't already there. */
104 }
105
106 const char* FindServerNamePtr(const std::string &servername)
107 {
108         servernamelist::iterator iter = find(servernames.begin(), servernames.end(), servername);
109         
110         if(iter == servernames.end())
111         {               
112                 AddServerName(servername);
113                 iter = --servernames.end();
114         }
115
116         return iter->c_str();
117 }
118
119 bool FindServerName(const std::string &servername)
120 {
121         return (find(servernames.begin(), servernames.end(), servername) != servernames.end());
122 }
123
124 void Exit(int status)
125 {
126         if (Config->log_file)
127                 fclose(Config->log_file);
128         send_error("Server shutdown.");
129         exit (status);
130 }
131
132 void InspIRCd::Start()
133 {
134         printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
135         printf("(C) ChatSpike Development team.\033[0m\n\n");
136         printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\033[0m\n");
137         printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
138         printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
139 }
140
141 void Killed(int status)
142 {
143         if (Config->log_file)
144                 fclose(Config->log_file);
145         send_error("Server terminated.");
146         exit(status);
147 }
148
149 void Rehash(int status)
150 {
151         WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
152         fclose(Config->log_file);
153         OpenLog(NULL,0);
154         Config->Read(false,NULL);
155         FOREACH_MOD(I_OnRehash,OnRehash(""));
156 }
157
158 void InspIRCd::SetSignals(bool SEGVHandler)
159 {
160         signal (SIGALRM, SIG_IGN);
161         signal (SIGHUP, Rehash);
162         signal (SIGPIPE, SIG_IGN);
163         signal (SIGTERM, Exit);
164         if (SEGVHandler)
165                 signal (SIGSEGV, Error);
166 }
167
168 bool InspIRCd::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 InspIRCd::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         bool SEGVHandler = false;
237
238         this->Start();
239         module_sockets.clear();
240         this->startup_time = time(NULL);
241         srand(time(NULL));
242         log(DEBUG,"*** InspIRCd starting up!");
243         if (!FileExists(CONFIG_FILE))
244         {
245                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
246                 log(DEFAULT,"main: no config");
247                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
248                 Exit(ERROR);
249         }
250         *LOG_FILE = 0;
251         if (argc > 1) {
252                 for (int i = 1; i < argc; i++)
253                 {
254                         if (!strcmp(argv[i],"-nofork"))
255                         {
256                                 Config->nofork = true;
257                         }
258                         else if(!strcmp(argv[i],"-debug"))
259                         {
260                                 Config->forcedebug = true;
261                         }
262                         else if(!strcmp(argv[i],"-nolog"))
263                         {
264                                 Config->writelog = false;
265                         }
266                         else if (!strcmp(argv[i],"-wait"))
267                         {
268                                 sleep(6);
269                         }
270                         else if (!strcmp(argv[i],"-nolimit"))
271                         {
272                                 printf("WARNING: The `-nolimit' option is deprecated, and now on by default. This behaviour may change in the future.\n");
273                         }
274                         else if (!strcmp(argv[i],"-notraceback"))
275                         {
276                                 SEGVHandler = false;
277                         }
278                         else if (!strcmp(argv[i],"-logfile"))
279                         {
280                                 if (argc > i+1)
281                                 {
282                                         strlcpy(LOG_FILE,argv[i+1],MAXBUF);
283                                         printf("LOG: Setting logfile to %s\n",LOG_FILE);
284                                 }
285                                 else
286                                 {
287                                         printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
288                                         Exit(ERROR);
289                                 }
290                                 i++;
291                         }
292                         else
293                         {
294                                 printf("Usage: %s [-nofork] [-nolog] [-debug] [-wait] [-nolimit] [-notraceback] [-logfile <filename>]\n",argv[0]);
295                                 Exit(ERROR);
296                         }
297                 }
298         }
299
300         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
301
302         this->MakeLowerMap();
303
304         OpenLog(argv, argc);
305         this->stats = new serverstats();
306         this->Parser = new CommandParser();
307         Config->ClearStack();
308         Config->Read(true, NULL);
309         CheckRoot();
310         this->ModeGrok = new ModeParser();
311         AddServerName(Config->ServerName);
312         CheckDie();
313         InitializeDisabledCommands(Config->DisabledCommands, this);
314         stats->BoundPortCount = BindPorts(true);
315
316         for(int t = 0; t < 255; t++)
317                 Config->global_implementation[t] = 0;
318
319         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
320
321         printf("\n");
322         this->SetSignals(SEGVHandler);
323         if (!Config->nofork)
324         {
325                 if (!this->DaemonSeed())
326                 {
327                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
328                         Exit(ERROR);
329                 }
330         }
331
332         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
333          * initialize the socket engine.
334          */
335         SocketEngineFactory* SEF = new SocketEngineFactory();
336         SE = SEF->Create();
337         delete SEF;
338
339         /* We must load the modules AFTER initializing the socket engine, now */
340
341         return;
342 }
343
344 std::string InspIRCd::GetVersionString()
345 {
346         char versiondata[MAXBUF];
347         char dnsengine[] = "singlethread-object";
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::EraseFactory(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::EraseModule(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,"Removing dependent commands...");
540                         Parser->RemoveCommands(filename);
541                         log(DEBUG,"Deleting module...");
542                         this->EraseModule(j);
543                         log(DEBUG,"Erasing module entry...");
544                         this->EraseFactory(j);
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         /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
698          * Once per loop iteration is pleanty.
699          */
700         OLDTIME = TIME;
701         TIME = time(NULL);
702         
703         /* Run background module timers every few seconds
704          * (the docs say modules shouldnt rely on accurate
705          * timing using this event, so we dont have to
706          * time this exactly).
707          */
708         if (((TIME % 5) == 0) && (!expire_run))
709         {
710                 expire_lines();
711                 if (process_module_sockets)
712                 {
713                         /* Fix by brain - the addition of DoOneIteration means that this
714                          * can end up getting called recursively in the following pattern:
715                          *
716                          * m_spanningtree DoPingChecks
717                          * (server pings out and is squit)
718                          * (squit causes call to DoOneIteration)
719                          * DoOneIteration enters here
720                          * calls DoBackground timer
721                          * enters m_spanningtree DoPingChecks... see step 1.
722                          *
723                          * This should do the job and fix the bug.
724                          */
725                         FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
726                 }
727                 TickMissedTimers(TIME);
728                 expire_run = true;
729                 return;
730         }   
731         else if ((TIME % 5) == 1)
732         {
733                 expire_run = false;
734         }
735
736         if (iterations++ == 15)
737         {
738                 iterations = 0;
739                 DoBackgroundUserStuff(TIME);
740         }
741  
742         /* Once a second, do the background processing */
743         if (TIME != OLDTIME)
744         {
745                 if (TIME < OLDTIME)
746                         WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
747                 if ((TIME % 3600) == 0)
748                 {
749                         MaintainWhoWas(TIME);
750                 }
751         }
752
753         /* Process timeouts on module sockets each time around
754          * the loop. There shouldnt be many module sockets, at
755          * most, 20 or so, so this won't be much of a performance
756          * hit at all.   
757          */ 
758         if (process_module_sockets)
759                 DoSocketTimeouts(TIME);  
760          
761         TickTimers(TIME);
762          
763         /* Call the socket engine to wait on the active
764          * file descriptors. The socket engine has everything's
765          * descriptors in its list... dns, modules, users,
766          * servers... so its nice and easy, just one call.
767          */
768         if (!(numberactive = SE->Wait(activefds)))
769                 return;
770
771         /**
772          * Now process each of the fd's. For users, we have a fast
773          * lookup table which can find a user by file descriptor, so
774          * processing them by fd isnt expensive. If we have a lot of
775          * listening ports or module sockets though, things could get
776          * ugly.
777          */
778         log(DEBUG,"There are %d fd's to process.",numberactive);
779
780         for (unsigned int activefd = 0; activefd < numberactive; activefd++)
781         {
782                 int socket_type = SE->GetType(activefds[activefd]);
783                 switch (socket_type)
784                 {
785                         case X_ESTAB_CLIENT:
786
787                                 log(DEBUG,"Type: X_ESTAB_CLIENT: fd=%d",activefds[activefd]);
788                                 cu = fd_ref_table[activefds[activefd]];
789                                 if (cu)
790                                         ProcessUser(cu);  
791         
792                         break;
793         
794                         case X_ESTAB_MODULE:
795
796                                 log(DEBUG,"Type: X_ESTAB_MODULE: fd=%d",activefds[activefd]);
797
798                                 if (!process_module_sockets)
799                                         break;
800
801                                 /* Process module-owned sockets.
802                                  * Modules are encouraged to inherit their sockets from
803                                  * InspSocket so we can process them neatly like this.
804                                  */
805                                 s = socket_ref[activefds[activefd]]; 
806               
807                                 if ((s) && (!s->Poll()))
808                                 {
809                                         log(DEBUG,"Socket poll returned false, close and bail");
810                                         SE->DelFd(s->GetFd());
811                                         socket_ref[activefds[activefd]] = NULL;
812                                         for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
813                                         {
814                                                 s_del = *a;
815                                                 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
816                                                 {
817                                                         module_sockets.erase(a);
818                                                         break;
819                                                 }
820                                         }
821                                         s->Close();
822                                         DELETE(s);
823                                 }
824                                 else if (!s)
825                                 {
826                                         log(DEBUG,"WTF, X_ESTAB_MODULE for nonexistent InspSocket, removed!");
827                                         SE->DelFd(s->GetFd());
828                                 }
829                         break;
830
831                         case X_ESTAB_DNS:
832                                 /* Handles instances of the Resolver class,
833                                  * a simple class extended by modules and the core for
834                                  * nonblocking resolving of addresses.
835                                  */
836                                 this->Res->MarshallReads(activefds[activefd]);
837                         break;
838
839                         case X_LISTEN:
840
841                                 log(DEBUG,"Type: X_LISTEN: fd=%d",activefds[activefd]);
842
843                                 /* It's a listener */
844                                 uslen = sizeof(sock_us);
845                                 length = sizeof(client);
846                                 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
847         
848                                 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
849                                 {
850 #ifdef IPV6
851                                         in_port = ntohs(sock_us.sin6_port);
852 #else
853                                         in_port = ntohs(sock_us.sin_port);
854 #endif
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 #ifdef IPV6
866                                                         Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin6_addr), in_port);
867 #else
868                                                         Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin_addr), in_port);
869 #endif
870                                                 }
871                                                 catch (ModuleException& modexcept)
872                                                 {
873                                                         log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
874                                                 }
875                                         }
876                                         stats->statsAccept++;
877 #ifdef IPV6
878                                         log(DEBUG,"Add ipv6 client");
879                                         AddClient(incomingSockfd, in_port, false, client.sin6_addr);
880 #else
881                                         log(DEBUG,"Add ipv4 client");
882                                         AddClient(incomingSockfd, in_port, false, client.sin_addr);
883 #endif
884                                         log(DEBUG,"Adding client on port %d fd=%d",in_port,incomingSockfd);
885                                 }
886                                 else
887                                 {
888                                         log(DEBUG,"Accept failed on fd %d: %s",incomingSockfd,strerror(errno));
889                                         shutdown(incomingSockfd,2);
890                                         close(incomingSockfd);
891                                         stats->statsRefused++;
892                                 }
893                         break;
894
895                         default:
896                                 /* Something went wrong if we're in here.
897                                  * In fact, so wrong, im not quite sure
898                                  * what we would do, so for now, its going
899                                  * to safely do bugger all.
900                                  */
901                                 log(DEBUG,"Type: X_WHAT_THE_FUCK_BBQ: fd=%d",activefds[activefd]);
902                                 SE->DelFd(activefds[activefd]);
903                         break;
904                 }
905         }
906 }
907
908 int InspIRCd::Run()
909 {
910         /* Until THIS point, ServerInstance == NULL */
911         
912         this->Res = new DNS();
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 (unsigned long count = 0; count < stats->BoundPortCount; count++)
932                 SE->AddFd(Config->openSockfd[count],true,X_LISTEN);
933
934         this->WritePID(Config->PID);
935
936         /* main loop, this never returns */
937         expire_run = false;
938         iterations = 0;
939
940         while (true)
941         {
942                 DoOneIteration(true);
943         }
944         /* This is never reached -- we hope! */
945         return 0;
946 }
947
948 /**********************************************************************************/
949
950 /**
951  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
952  */
953
954 int main(int argc, char** argv)
955 {
956         /* This is a MatchCIDR() test suite -
957         printf("Should be 0: %d\n",MatchCIDR("127.0.0.1","1.2.3.4/8"));
958         printf("Should be 1: %d\n",MatchCIDR("127.0.0.1","127.0.0.0/8"));
959         printf("Should be 1: %d\n",MatchCIDR("127.0.0.1","127.0.0.0/18"));
960         printf("Should be 0: %d\n",MatchCIDR("3ffe::0","2fc9::0/16"));
961         printf("Should be 1: %d\n",MatchCIDR("3ffe:1:3::0", "3ffe:1::0/32"));
962         exit(0); */
963
964         try
965         {
966                 ServerInstance = new InspIRCd(argc, argv);
967                 ServerInstance->Run();
968                 DELETE(ServerInstance);
969         }
970         catch (std::bad_alloc)
971         {
972                 log(DEFAULT,"You are out of memory! (got exception std::bad_alloc!)");
973                 send_error("**** OUT OF MEMORY **** We're gonna need a bigger boat!");
974                 printf("Out of memory! (got exception std::bad_alloc!");
975         }
976         return 0;
977 }