]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Committing this as a rollback point - does not compile
[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 "mode.h"
55 #include "commands.h"
56 #include "xline.h"
57 #include "inspstring.h"
58 #include "helperfuncs.h"
59 #include "hashcomp.h"
60 #include "socketengine.h"
61 #include "inspircd_se_config.h"
62 #include "userprocess.h"
63 #include "socket.h"
64 #include "typedefs.h"
65 #include "command_parse.h"
66
67 using irc::sockets::NonBlocking;
68 using irc::sockets::insp_ntoa;
69 using irc::sockets::insp_inaddr;
70 using irc::sockets::insp_sockaddr;
71
72 InspIRCd* ServerInstance = NULL;
73
74 int iterations = 0;
75
76 insp_sockaddr client, server;
77 socklen_t length;
78
79 time_t TIME = time(NULL), OLDTIME = time(NULL);
80
81 char lowermap[255];
82
83 void InspIRCd::AddServerName(const std::string &servername)
84 {
85         log(DEBUG,"Adding server name: %s",servername.c_str());
86         
87         if(find(servernames.begin(), servernames.end(), servername) == servernames.end())
88                 servernames.push_back(servername); /* Wasn't already there. */
89 }
90
91 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
92 {
93         servernamelist::iterator iter = find(servernames.begin(), servernames.end(), servername);
94         
95         if(iter == servernames.end())
96         {               
97                 AddServerName(servername);
98                 iter = --servernames.end();
99         }
100
101         return iter->c_str();
102 }
103
104 bool InspIRCd::FindServerName(const std::string &servername)
105 {
106         return (find(servernames.begin(), servernames.end(), servername) != servernames.end());
107 }
108
109 void InspIRCd::Exit(int status)
110 {
111         if (ServerInstance->Config->log_file)
112                 fclose(ServerInstance->Config->log_file);
113         ServerInstance->SendError("Server shutdown.");
114         exit (status);
115 }
116
117 void InspIRCd::Start()
118 {
119         printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
120         printf("(C) ChatSpike Development team.\033[0m\n\n");
121         printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\033[0m\n");
122         printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
123         printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
124 }
125
126 void InspIRCd::Rehash(int status)
127 {
128         ServerInstance->WriteOpers("Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(CONFIG_FILE));
129         fclose(ServerInstance->Config->log_file);
130         ServerInstance->OpenLog(NULL,0);
131         ServerInstance->Config->Read(false,NULL);
132         FOREACH_MOD(I_OnRehash,OnRehash(""));
133 }
134
135 void InspIRCd::SetSignals(bool SEGVHandler)
136 {
137         signal (SIGALRM, SIG_IGN);
138         signal (SIGHUP, InspIRCd::Rehash);
139         signal (SIGPIPE, SIG_IGN);
140         signal (SIGTERM, InspIRCd::Exit);
141         if (SEGVHandler)
142                 signal (SIGSEGV, InspIRCd::Error);
143 }
144
145 bool InspIRCd::DaemonSeed()
146 {
147         int childpid;
148         if ((childpid = fork ()) < 0)
149                 return (ERROR);
150         else if (childpid > 0)
151         {
152                 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
153                 sleep(6);
154                 exit (0);
155         }
156         setsid ();
157         umask (007);
158         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
159
160         rlimit rl;
161         if (getrlimit(RLIMIT_CORE, &rl) == -1)
162         {
163                 log(DEFAULT,"Failed to getrlimit()!");
164                 return false;
165         }
166         else
167         {
168                 rl.rlim_cur = rl.rlim_max;
169                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
170                         log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
171         }
172   
173         return true;
174 }
175
176 void InspIRCd::WritePID(const std::string &filename)
177 {
178         std::ofstream outfile(filename.c_str());
179         if (outfile.is_open())
180         {
181                 outfile << getpid();
182                 outfile.close();
183         }
184         else
185         {
186                 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
187                 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
188                 Exit(0);
189         }
190 }
191
192 std::string InspIRCd::GetRevision()
193 {
194         return REVISION;
195 }
196
197 void InspIRCd::MakeLowerMap()
198 {
199         // initialize the lowercase mapping table
200         for (unsigned int cn = 0; cn < 256; cn++)
201                 lowermap[cn] = cn;
202         // lowercase the uppercase chars
203         for (unsigned int cn = 65; cn < 91; cn++)
204                 lowermap[cn] = tolower(cn);
205         // now replace the specific chars for scandanavian comparison
206         lowermap[(unsigned)'['] = '{';
207         lowermap[(unsigned)']'] = '}';
208         lowermap[(unsigned)'\\'] = '|';
209 }
210
211 InspIRCd::InspIRCd(int argc, char** argv) : ModCount(-1)
212 {
213         bool SEGVHandler = false;
214         ServerInstance = this;
215
216         modules.resize(255);
217         factory.resize(255);
218
219         this->Config = new ServerConfig(this);
220         this->Start();
221         this->module_sockets.clear();
222         this->startup_time = time(NULL);
223         srand(time(NULL));
224         log(DEBUG,"*** InspIRCd starting up!");
225         if (!ServerConfig::FileExists(CONFIG_FILE))
226         {
227                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
228                 log(DEFAULT,"main: no config");
229                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
230                 Exit(ERROR);
231         }
232         *this->LogFileName = 0;
233         if (argc > 1) {
234                 for (int i = 1; i < argc; i++)
235                 {
236                         if (!strcmp(argv[i],"-nofork"))
237                         {
238                                 Config->nofork = true;
239                         }
240                         else if(!strcmp(argv[i],"-debug"))
241                         {
242                                 Config->forcedebug = true;
243                         }
244                         else if(!strcmp(argv[i],"-nolog"))
245                         {
246                                 Config->writelog = false;
247                         }
248                         else if (!strcmp(argv[i],"-wait"))
249                         {
250                                 sleep(6);
251                         }
252                         else if (!strcmp(argv[i],"-nolimit"))
253                         {
254                                 printf("WARNING: The `-nolimit' option is deprecated, and now on by default. This behaviour may change in the future.\n");
255                         }
256                         else if (!strcmp(argv[i],"-notraceback"))
257                         {
258                                 SEGVHandler = false;
259                         }
260                         else if (!strcmp(argv[i],"-logfile"))
261                         {
262                                 if (argc > i+1)
263                                 {
264                                         strlcpy(LogFileName,argv[i+1],MAXBUF);
265                                         printf("LOG: Setting logfile to %s\n",LogFileName);
266                                 }
267                                 else
268                                 {
269                                         printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
270                                         Exit(ERROR);
271                                 }
272                                 i++;
273                         }
274                         else
275                         {
276                                 printf("Usage: %s [-nofork] [-nolog] [-debug] [-wait] [-nolimit] [-notraceback] [-logfile <filename>]\n",argv[0]);
277                                 Exit(ERROR);
278                         }
279                 }
280         }
281
282         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
283
284         this->MakeLowerMap();
285
286         OpenLog(argv, argc);
287         this->stats = new serverstats();
288         this->Parser = new CommandParser(this);
289         this->Timers = new TimerManager();
290         Config->ClearStack();
291         Config->Read(true, NULL);
292         CheckRoot();
293         this->ModeGrok = new ModeParser(this);
294         this->AddServerName(Config->ServerName);
295         CheckDie();
296         InitializeDisabledCommands(Config->DisabledCommands, this);
297         stats->BoundPortCount = BindPorts(true);
298
299         for(int t = 0; t < 255; t++)
300                 Config->global_implementation[t] = 0;
301
302         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
303
304         printf("\n");
305         this->SetSignals(SEGVHandler);
306         if (!Config->nofork)
307         {
308                 if (!this->DaemonSeed())
309                 {
310                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
311                         Exit(ERROR);
312                 }
313         }
314
315         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
316          * initialize the socket engine.
317          */
318         SocketEngineFactory* SEF = new SocketEngineFactory();
319         SE = SEF->Create();
320         delete SEF;
321
322         /* We must load the modules AFTER initializing the socket engine, now */
323
324         return;
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                 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_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                                 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_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                         log(DEBUG,"Removing dependent commands...");
523                         Parser->RemoveCommands(filename);
524                         log(DEBUG,"Deleting module...");
525                         this->EraseModule(j);
526                         log(DEBUG,"Erasing module entry...");
527                         this->EraseFactory(j);
528                         log(DEFAULT,"Module %s unloaded",filename);
529                         this->ModCount--;
530                         BuildISupport();
531                         return true;
532                 }
533         }
534         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                 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         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                                 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                                 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                                 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                         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                 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_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 % 5) == 0) && (!expire_run))
692         {
693                 expire_lines();
694                 if (process_module_sockets)
695                 {
696                         FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME));
697                 }
698                 Timers->TickMissedTimers(TIME);
699                 expire_run = true;
700                 return;
701         }   
702         else if ((TIME % 5) == 1)
703         {
704                 expire_run = false;
705         }
706
707         if (iterations++ == 15)
708         {
709                 iterations = 0;
710                 this->DoBackgroundUserStuff(TIME);
711         }
712  
713         /* Once a second, do the background processing */
714         if (TIME != OLDTIME)
715         {
716                 if (TIME < OLDTIME)
717                         WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
718                 if ((TIME % 3600) == 0)
719                 {
720                         irc::whowas::MaintainWhoWas(TIME);
721                 }
722         }
723
724         /* Process timeouts on module sockets each time around
725          * the loop. There shouldnt be many module sockets, at
726          * most, 20 or so, so this won't be much of a performance
727          * hit at all.   
728          */ 
729         if (process_module_sockets)
730                 this->DoSocketTimeouts(TIME);
731          
732         Timers->TickTimers(TIME);
733          
734         /* Call the socket engine to wait on the active
735          * file descriptors. The socket engine has everything's
736          * descriptors in its list... dns, modules, users,
737          * servers... so its nice and easy, just one call.
738          */
739         if (!(numberactive = SE->Wait(activefds)))
740                 return;
741
742         /**
743          * Now process each of the fd's. For users, we have a fast
744          * lookup table which can find a user by file descriptor, so
745          * processing them by fd isnt expensive. If we have a lot of
746          * listening ports or module sockets though, things could get
747          * ugly.
748          */
749         log(DEBUG,"There are %d fd's to process.",numberactive);
750
751         for (unsigned int activefd = 0; activefd < numberactive; activefd++)
752         {
753                 int socket_type = SE->GetType(activefds[activefd]);
754                 switch (socket_type)
755                 {
756                         case X_ESTAB_CLIENT:
757
758                                 log(DEBUG,"Type: X_ESTAB_CLIENT: fd=%d",activefds[activefd]);
759                                 cu = this->fd_ref_table[activefds[activefd]];
760                                 if (cu)
761                                         this->ProcessUser(cu);
762         
763                         break;
764         
765                         case X_ESTAB_MODULE:
766
767                                 log(DEBUG,"Type: X_ESTAB_MODULE: fd=%d",activefds[activefd]);
768
769                                 if (!process_module_sockets)
770                                         break;
771
772                                 /* Process module-owned sockets.
773                                  * Modules are encouraged to inherit their sockets from
774                                  * InspSocket so we can process them neatly like this.
775                                  */
776                                 s = this->socket_ref[activefds[activefd]]; 
777               
778                                 if ((s) && (!s->Poll()))
779                                 {
780                                         log(DEBUG,"Socket poll returned false, close and bail");
781                                         SE->DelFd(s->GetFd());
782                                         this->socket_ref[activefds[activefd]] = NULL;
783                                         for (std::vector<InspSocket*>::iterator a = module_sockets.begin(); a < module_sockets.end(); a++)
784                                         {
785                                                 s_del = *a;
786                                                 if ((s_del) && (s_del->GetFd() == activefds[activefd]))
787                                                 {
788                                                         module_sockets.erase(a);
789                                                         break;
790                                                 }
791                                         }
792                                         s->Close();
793                                         DELETE(s);
794                                 }
795                                 else if (!s)
796                                 {
797                                         log(DEBUG,"WTF, X_ESTAB_MODULE for nonexistent InspSocket, removed!");
798                                         SE->DelFd(s->GetFd());
799                                 }
800                         break;
801
802                         case X_ESTAB_DNS:
803                                 /* Handles instances of the Resolver class,
804                                  * a simple class extended by modules and the core for
805                                  * nonblocking resolving of addresses.
806                                  */
807                                 this->Res->MarshallReads(activefds[activefd]);
808                         break;
809
810                         case X_LISTEN:
811
812                                 log(DEBUG,"Type: X_LISTEN: fd=%d",activefds[activefd]);
813
814                                 /* It's a listener */
815                                 uslen = sizeof(sock_us);
816                                 length = sizeof(client);
817                                 incomingSockfd = accept (activefds[activefd],(struct sockaddr*)&client,&length);
818         
819                                 if ((incomingSockfd > -1) && (!getsockname(incomingSockfd,(sockaddr*)&sock_us,&uslen)))
820                                 {
821 #ifdef IPV6
822                                         in_port = ntohs(sock_us.sin6_port);
823 #else
824                                         in_port = ntohs(sock_us.sin_port);
825 #endif
826                                         log(DEBUG,"Accepted socket %d",incomingSockfd);
827                                         /* Years and years ago, we used to resolve here
828                                          * using gethostbyaddr(). That is sucky and we
829                                          * don't do that any more...
830                                          */
831                                         NonBlocking(incomingSockfd);
832                                         if (Config->GetIOHook(in_port))
833                                         {
834                                                 try
835                                                 {
836 #ifdef IPV6
837                                                         Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin6_addr), in_port);
838 #else
839                                                         Config->GetIOHook(in_port)->OnRawSocketAccept(incomingSockfd, insp_ntoa(client.sin_addr), in_port);
840 #endif
841                                                 }
842                                                 catch (ModuleException& modexcept)
843                                                 {
844                                                         log(DEBUG,"Module exception cought: %s",modexcept.GetReason());
845                                                 }
846                                         }
847                                         stats->statsAccept++;
848 #ifdef IPV6
849                                         log(DEBUG,"Add ipv6 client");
850                                         userrec::AddClient(this, incomingSockfd, in_port, false, client.sin6_addr);
851 #else
852                                         log(DEBUG,"Add ipv4 client");
853                                         userrec::AddClient(this, incomingSockfd, in_port, false, client.sin_addr);
854 #endif
855                                         log(DEBUG,"Adding client on port %d fd=%d",in_port,incomingSockfd);
856                                 }
857                                 else
858                                 {
859                                         log(DEBUG,"Accept failed on fd %d: %s",incomingSockfd,strerror(errno));
860                                         shutdown(incomingSockfd,2);
861                                         close(incomingSockfd);
862                                         stats->statsRefused++;
863                                 }
864                         break;
865
866                         default:
867                                 /* Something went wrong if we're in here.
868                                  * In fact, so wrong, im not quite sure
869                                  * what we would do, so for now, its going
870                                  * to safely do bugger all.
871                                  */
872                                 log(DEBUG,"Type: X_WHAT_THE_FUCK_BBQ: fd=%d",activefds[activefd]);
873                                 SE->DelFd(activefds[activefd]);
874                         break;
875                 }
876         }
877 }
878
879 bool InspIRCd::IsIdent(const char* n)
880 {
881         if (!n || !*n)
882                 return false;
883
884         for (char* i = (char*)n; *i; i++)
885         {
886                 if ((*i >= 'A') && (*i <= '}'))
887                 {
888                         continue;
889                 }
890                 if (((*i >= '0') && (*i <= '9')) || (*i == '-') || (*i == '.'))
891                 {
892                         continue;
893                 }
894                 return false;
895         }
896         return true;
897 }
898
899
900 bool InspIRCd::IsNick(const char* n)
901 {
902         if (!n || !*n)
903                 return false;
904
905         int p = 0; 
906         for (char* i = (char*)n; *i; i++, p++)
907         {
908                 /* "A"-"}" can occur anywhere in a nickname */
909                 if ((*i >= 'A') && (*i <= '}'))
910                 {
911                         continue;
912                 }
913                 /* "0"-"9", "-" can occur anywhere BUT the first char of a nickname */
914                 if ((((*i >= '0') && (*i <= '9')) || (*i == '-')) && (i > n))
915                 {
916                         continue;
917                 }
918                 /* invalid character! abort */
919                 return false;
920         }
921         return (p < NICKMAX - 1);
922 }
923
924 int InspIRCd::Run()
925 {
926         this->Res = new DNS(this);
927
928         log(DEBUG,"RES: %08x",this->Res);
929
930         this->LoadAllModules();
931
932         /* Just in case no modules were loaded - fix for bug #101 */
933         this->BuildISupport();
934
935         if (!stats->BoundPortCount)
936         {
937                 printf("\nI couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
938                 Exit(ERROR);
939         }
940
941         /* Add the listening sockets used for client inbound connections
942          * to the socket engine
943          */
944         log(DEBUG,"%d listeners",stats->BoundPortCount);
945         for (unsigned long count = 0; count < stats->BoundPortCount; count++)
946         {
947                 log(DEBUG,"Add listener: %d",Config->openSockfd[count]);
948                 if (!SE->AddFd(Config->openSockfd[count],true,X_LISTEN))
949                 {
950                         printf("\nEH? Could not add listener to socketengine. You screwed up, aborting.\n");
951                         Exit(ERROR);
952                 }
953         }
954
955         if (!Config->nofork)
956         {
957                 fclose(stdout);
958                 fclose(stderr);
959                 fclose(stdin);
960         }
961
962         printf("\nInspIRCd is now running!\n");
963
964         this->WritePID(Config->PID);
965
966         /* main loop, this never returns */
967         expire_run = false;
968         iterations = 0;
969
970         while (true)
971         {
972                 DoOneIteration(true);
973         }
974         /* This is never reached -- we hope! */
975         return 0;
976 }
977
978 /**********************************************************************************/
979
980 /**
981  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
982  */
983
984 int main(int argc, char** argv)
985 {
986         /* This is a MatchCIDR() test suite -
987         printf("Should be 0: %d\n",MatchCIDR("127.0.0.1","1.2.3.4/8"));
988         printf("Should be 1: %d\n",MatchCIDR("127.0.0.1","127.0.0.0/8"));
989         printf("Should be 1: %d\n",MatchCIDR("127.0.0.1","127.0.0.0/18"));
990         printf("Should be 0: %d\n",MatchCIDR("3ffe::0","2fc9::0/16"));
991         printf("Should be 1: %d\n",MatchCIDR("3ffe:1:3::0", "3ffe:1::0/32"));
992         exit(0); */
993
994         try
995         {
996                 try
997                 {
998                         ServerInstance = new InspIRCd(argc, argv);
999                         ServerInstance->Run();
1000                         DELETE(ServerInstance);
1001                 }
1002                 catch (std::bad_alloc&)
1003                 {
1004                         log(SPARSE,"You are out of memory! (got exception std::bad_alloc!)");
1005                         ServerInstance->SendError("**** OUT OF MEMORY **** We're gonna need a bigger boat!");
1006                 }
1007         }
1008         catch (...)
1009         {
1010                 log(SPARSE,"Uncaught exception, aborting.");
1011                 ServerInstance->SendError("Server terminating due to uncaught exception.");
1012         }
1013         return 0;
1014 }
1015
1016 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
1017  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
1018  * registration timeout maximum seconds)
1019  */
1020 bool InspIRCd::AllModulesReportReady(userrec* user)
1021 {
1022         if (!Config->global_implementation[I_OnCheckReady])
1023                 return true;
1024
1025         for (int i = 0; i <= this->GetModuleCount(); i++)
1026         {
1027                 if (Config->implement_lists[i][I_OnCheckReady])
1028                 {
1029                         int res = modules[i]->OnCheckReady(user);
1030                         if (!res)
1031                                 return false;
1032                 }
1033         }
1034         return true;
1035 }
1036
1037 int InspIRCd::GetModuleCount()
1038 {
1039         return this->ModCount;
1040 }
1041