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