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