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