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