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