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