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