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