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