]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/inspircd.cpp
Wahhhhhhhhhhhh bwahahaha. Mass commit to tidy up tons of messy include lists
[user/henk/code/inspircd.git] / src / inspircd.cpp
1 /* ---------------------------------------------------------------------
2  * 
3  *            +------------------------------------+
4  *            | Inspire Internet Relay Chat Daemon |
5  *            +------------------------------------+
6  *
7  *       InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
8  *                           E-mail:
9  *                    <brain@chatspike.net>
10  *                    <Craig@chatspike.net>
11  *     
12  *  Written by Craig Edwards, Craig McLure, and others.
13  *  This program is free but copyrighted software; you can redistribute
14  *  it and/or modify it under the terms of the GNU General Public
15  *  License as published by the Free Software Foundation, version 2
16  *  (two) ONLY.
17  *
18  *  This program is distributed in the hope that it will be useful,
19  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  *  GNU General Public License for more details.
22  *
23  *  You should have received a copy of the GNU General Public License
24  *  along with this program; if not, write to the Free Software
25  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26  *
27  * ---------------------------------------------------------------------
28  */
29
30 #include "inspircd.h"
31 #include "configreader.h"
32 #include <signal.h>
33 #include <exception>
34 #include <fstream>
35 #include "modules.h"
36 #include "mode.h"
37 #include "xline.h"
38 #include "socketengine.h"
39 #include "inspircd_se_config.h"
40 #include "socket.h"
41 #include "typedefs.h"
42 #include "command_parse.h"
43
44 using irc::sockets::NonBlocking;
45 using irc::sockets::Blocking;
46 using irc::sockets::insp_ntoa;
47 using irc::sockets::insp_inaddr;
48 using irc::sockets::insp_sockaddr;
49
50 InspIRCd* SI = NULL;
51
52 void InspIRCd::AddServerName(const std::string &servername)
53 {
54         this->Log(DEBUG,"Adding server name: %s",servername.c_str());
55         
56         if(find(servernames.begin(), servernames.end(), servername) == servernames.end())
57                 servernames.push_back(servername); /* Wasn't already there. */
58 }
59
60 const char* InspIRCd::FindServerNamePtr(const std::string &servername)
61 {
62         servernamelist::iterator iter = find(servernames.begin(), servernames.end(), servername);
63         
64         if(iter == servernames.end())
65         {               
66                 AddServerName(servername);
67                 iter = --servernames.end();
68         }
69
70         return iter->c_str();
71 }
72
73 bool InspIRCd::FindServerName(const std::string &servername)
74 {
75         return (find(servernames.begin(), servernames.end(), servername) != servernames.end());
76 }
77
78 void InspIRCd::Exit(int status)
79 {
80         exit (status);
81 }
82
83 void InspIRCd::Start()
84 {
85         printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
86         printf("(C) ChatSpike Development team.\033[0m\n\n");
87         printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om, Special\033[0m\n");
88         printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
89         printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
90 }
91
92 void InspIRCd::Rehash(int status)
93 {
94         SI->WriteOpers("Rehashing config file %s due to SIGHUP",ServerConfig::CleanFilename(CONFIG_FILE));
95         fclose(SI->Config->log_file);
96         SI->OpenLog(NULL,0);
97         SI->Config->Read(false,NULL);
98         FOREACH_MOD_I(SI,I_OnRehash,OnRehash(""));
99 }
100
101 void InspIRCd::SetSignals(bool SEGVHandler)
102 {
103         signal(SIGALRM, SIG_IGN);
104         signal(SIGHUP, InspIRCd::Rehash);
105         signal(SIGPIPE, SIG_IGN);
106         signal(SIGTERM, InspIRCd::Exit);
107         signal(SIGCHLD, SIG_IGN);
108 }
109
110 bool InspIRCd::DaemonSeed()
111 {
112         int childpid;
113         if ((childpid = fork ()) < 0)
114                 return false;
115         else if (childpid > 0)
116         {
117                 /* We wait here for the child process to kill us,
118                  * so that the shell prompt doesnt come back over
119                  * the output.
120                  * Sending a kill with a signal of 0 just checks
121                  * if the child pid is still around. If theyre not,
122                  * they threw an error and we should give up.
123                  */
124                 while (kill(childpid, 0) != -1)
125                         sleep(1);
126                 exit(ERROR);
127         }
128         setsid ();
129         umask (007);
130         printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
131
132         rlimit rl;
133         if (getrlimit(RLIMIT_CORE, &rl) == -1)
134         {
135                 this->Log(DEFAULT,"Failed to getrlimit()!");
136                 return false;
137         }
138         else
139         {
140                 rl.rlim_cur = rl.rlim_max;
141                 if (setrlimit(RLIMIT_CORE, &rl) == -1)
142                         this->Log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
143         }
144
145         return true;
146 }
147
148 void InspIRCd::WritePID(const std::string &filename)
149 {
150         std::ofstream outfile(filename.c_str());
151         if (outfile.is_open())
152         {
153                 outfile << getpid();
154                 outfile.close();
155         }
156         else
157         {
158                 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
159                 this->Log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
160                 Exit(0);
161         }
162 }
163
164 std::string InspIRCd::GetRevision()
165 {
166         return REVISION;
167 }
168
169 InspIRCd::InspIRCd(int argc, char** argv)
170         : 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)
171 {
172         bool SEGVHandler = false;
173
174         modules.resize(255);
175         factory.resize(255);
176         
177         this->Config = new ServerConfig(this);
178         this->SNO = new SnomaskManager(this);
179         this->Start();
180         this->TIME = this->OLDTIME = this->startup_time = time(NULL);
181         srand(this->TIME);
182         this->Log(DEBUG,"*** InspIRCd starting up!");
183         if (!ServerConfig::FileExists(CONFIG_FILE))
184         {
185                 printf("ERROR: Cannot open config file: %s\nExiting...\n",CONFIG_FILE);
186                 this->Log(DEFAULT,"main: no config");
187                 printf("ERROR: Your config file is missing, this IRCd will self destruct in 10 seconds!\n");
188                 Exit(ERROR);
189         }
190         *this->LogFileName = 0;
191         if (argc > 1) {
192                 for (int i = 1; i < argc; i++)
193                 {
194                         if (!strcmp(argv[i],"-nofork"))
195                         {
196                                 Config->nofork = true;
197                         }
198                         else if(!strcmp(argv[i],"-debug"))
199                         {
200                                 Config->forcedebug = true;
201                         }
202                         else if(!strcmp(argv[i],"-nolog"))
203                         {
204                                 Config->writelog = false;
205                         }
206                         else if (!strcmp(argv[i],"-wait"))
207                         {
208                                 sleep(6);
209                         }
210                         else if (!strcmp(argv[i],"-nolimit"))
211                         {
212                                 printf("WARNING: The `-nolimit' option is deprecated, and now on by default. This behaviour may change in the future.\n");
213                         }
214                         else if (!strcmp(argv[i],"-notraceback"))
215                         {
216                                 SEGVHandler = false;
217                         }
218                         else if (!strcmp(argv[i],"-logfile"))
219                         {
220                                 if (argc > i+1)
221                                 {
222                                         strlcpy(LogFileName,argv[i+1],MAXBUF);
223                                         printf("LOG: Setting logfile to %s\n",LogFileName);
224                                 }
225                                 else
226                                 {
227                                         printf("ERROR: The -logfile parameter must be followed by a log file name and path.\n");
228                                         Exit(ERROR);
229                                 }
230                                 i++;
231                         }
232                         else
233                         {
234                                 printf("Usage: %s [-nofork] [-nolog] [-debug] [-wait] [-nolimit] [-notraceback] [-logfile <filename>]\n",argv[0]);
235                                 Exit(ERROR);
236                         }
237                 }
238         }
239
240         strlcpy(Config->MyExecutable,argv[0],MAXBUF);
241
242         this->OpenLog(argv, argc);
243         this->stats = new serverstats();
244         this->Parser = new CommandParser(this);
245         this->Timers = new TimerManager();
246         this->XLines = new XLineManager(this);
247         Config->ClearStack();
248         Config->Read(true, NULL);
249         this->CheckRoot();
250         this->Modes = new ModeParser(this);
251         this->AddServerName(Config->ServerName);        
252         CheckDie();
253         InitializeDisabledCommands(Config->DisabledCommands, this);
254         stats->BoundPortCount = BindPorts(true);
255
256         for(int t = 0; t < 255; t++)
257                 Config->global_implementation[t] = 0;
258
259         memset(&Config->implement_lists,0,sizeof(Config->implement_lists));
260
261         printf("\n");
262         this->SetSignals(SEGVHandler);
263         if (!Config->nofork)
264         {
265                 if (!this->DaemonSeed())
266                 {
267                         printf("ERROR: could not go into daemon mode. Shutting down.\n");
268                         Exit(ERROR);
269                 }
270         }
271
272         /* Because of limitations in kqueue on freebsd, we must fork BEFORE we
273          * initialize the socket engine.
274          */
275         SocketEngineFactory* SEF = new SocketEngineFactory();
276         SE = SEF->Create(this);
277         delete SEF;
278
279         this->Res = new DNS(this);
280
281         this->LoadAllModules();
282         /* Just in case no modules were loaded - fix for bug #101 */
283         this->BuildISupport();
284
285         if (!stats->BoundPortCount)
286         {
287                 printf("\nERROR: I couldn't bind any ports! Are you sure you didn't start InspIRCd twice?\n");
288                 Exit(ERROR);
289         }
290
291         /* Add the listening sockets used for client inbound connections
292          * to the socket engine
293          */
294         this->Log(DEBUG,"%d listeners",stats->BoundPortCount);
295         for (unsigned long count = 0; count < stats->BoundPortCount; count++)
296         {
297                 this->Log(DEBUG,"Add listener: %d",Config->openSockfd[count]->GetFd());
298                 if (!SE->AddFd(Config->openSockfd[count]))
299                 {
300                         printf("\nEH? Could not add listener to socketengine. You screwed up, aborting.\n");
301                         Exit(ERROR);
302                 }
303         }
304
305         if (!Config->nofork)
306         {
307                 if (kill(getppid(), SIGTERM) == -1)
308                         printf("Error killing parent process: %s\n",strerror(errno));
309                 fclose(stdin);
310                 fclose(stderr);
311                 fclose(stdout);
312         }
313
314         printf("\nInspIRCd is now running!\n");
315
316         this->WritePID(Config->PID);
317 }
318
319 std::string InspIRCd::GetVersionString()
320 {
321         char versiondata[MAXBUF];
322         char dnsengine[] = "singlethread-object";
323         if (*Config->CustomVersion)
324         {
325                 snprintf(versiondata,MAXBUF,"%s %s :%s",VERSION,Config->ServerName,Config->CustomVersion);
326         }
327         else
328         {
329                 snprintf(versiondata,MAXBUF,"%s %s :%s [FLAGS=%lu,%s,%s]",VERSION,Config->ServerName,SYSTEM,(unsigned long)OPTIMISATION,SE->GetName().c_str(),dnsengine);
330         }
331         return versiondata;
332 }
333
334 char* InspIRCd::ModuleError()
335 {
336         return MODERR;
337 }
338
339 void InspIRCd::EraseFactory(int j)
340 {
341         int v = 0;
342         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
343         {
344                 if (v == j)
345                 {
346                         factory.erase(t);
347                         factory.push_back(NULL);
348                         return;
349                 }
350                 v++;
351         }
352 }
353
354 void InspIRCd::EraseModule(int j)
355 {
356         int v1 = 0;
357         for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
358         {
359                 if (v1 == j)
360                 {
361                         DELETE(*m);
362                         modules.erase(m);
363                         modules.push_back(NULL);
364                         break;
365                 }
366                 v1++;
367         }
368         int v2 = 0;
369         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
370         {
371                 if (v2 == j)
372                 {
373                        Config->module_names.erase(v);
374                        break;
375                 }
376                 v2++;
377         }
378
379 }
380
381 void InspIRCd::MoveTo(std::string modulename,int slot)
382 {
383         unsigned int v2 = 256;
384         for (unsigned int v = 0; v < Config->module_names.size(); v++)
385         {
386                 if (Config->module_names[v] == modulename)
387                 {
388                         // found an instance, swap it with the item at the end
389                         v2 = v;
390                         break;
391                 }
392         }
393         if ((v2 != (unsigned int)slot) && (v2 < 256))
394         {
395                 // Swap the module names over
396                 Config->module_names[v2] = Config->module_names[slot];
397                 Config->module_names[slot] = modulename;
398                 // now swap the module factories
399                 ircd_module* temp = factory[v2];
400                 factory[v2] = factory[slot];
401                 factory[slot] = temp;
402                 // now swap the module objects
403                 Module* temp_module = modules[v2];
404                 modules[v2] = modules[slot];
405                 modules[slot] = temp_module;
406                 // now swap the implement lists (we dont
407                 // need to swap the global or recount it)
408                 for (int n = 0; n < 255; n++)
409                 {
410                         char x = Config->implement_lists[v2][n];
411                         Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
412                         Config->implement_lists[slot][n] = x;
413                 }
414         }
415         else
416         {
417                 this->Log(DEBUG,"Move of %s to slot failed!",modulename.c_str());
418         }
419 }
420
421 void InspIRCd::MoveAfter(std::string modulename, std::string after)
422 {
423         for (unsigned int v = 0; v < Config->module_names.size(); v++)
424         {
425                 if (Config->module_names[v] == after)
426                 {
427                         MoveTo(modulename, v);
428                         return;
429                 }
430         }
431 }
432
433 void InspIRCd::MoveBefore(std::string modulename, std::string before)
434 {
435         for (unsigned int v = 0; v < Config->module_names.size(); v++)
436         {
437                 if (Config->module_names[v] == before)
438                 {
439                         if (v > 0)
440                         {
441                                 MoveTo(modulename, v-1);
442                         }
443                         else
444                         {
445                                 MoveTo(modulename, v);
446                         }
447                         return;
448                 }
449         }
450 }
451
452 void InspIRCd::MoveToFirst(std::string modulename)
453 {
454         MoveTo(modulename,0);
455 }
456
457 void InspIRCd::MoveToLast(std::string modulename)
458 {
459         MoveTo(modulename,this->GetModuleCount());
460 }
461
462 void InspIRCd::BuildISupport()
463 {
464         // the neatest way to construct the initial 005 numeric, considering the number of configure constants to go in it...
465         std::stringstream v;
466         v << "WALLCHOPS WALLVOICES MODES=" << MAXMODES << " CHANTYPES=# PREFIX=" << this->Modes->BuildPrefixes() << " MAP MAXCHANNELS=" << MAXCHANS << " MAXBANS=60 VBANLIST NICKLEN=" << NICKMAX-1;
467         v << " CASEMAPPING=rfc1459 STATUSMSG=@%+ CHARSET=ascii TOPICLEN=" << MAXTOPIC << " KICKLEN=" << MAXKICK << " MAXTARGETS=" << Config->MaxTargets << " AWAYLEN=";
468         v << MAXAWAY << " CHANMODES=" << this->Modes->ChanModes() << " FNC NETWORK=" << Config->Network << " MAXPARA=32";
469         Config->data005 = v.str();
470         FOREACH_MOD_I(this,I_On005Numeric,On005Numeric(Config->data005));
471 }
472
473 bool InspIRCd::UnloadModule(const char* filename)
474 {
475         std::string filename_str = filename;
476         for (unsigned int j = 0; j != Config->module_names.size(); j++)
477         {
478                 if (Config->module_names[j] == filename_str)
479                 {
480                         if (modules[j]->GetVersion().Flags & VF_STATIC)
481                         {
482                                 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
483                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
484                                 return false;
485                         }
486                         /* Give the module a chance to tidy out all its metadata */
487                         for (chan_hash::iterator c = this->chanlist.begin(); c != this->chanlist.end(); c++)
488                         {
489                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
490                         }
491                         for (user_hash::iterator u = this->clientlist.begin(); u != this->clientlist.end(); u++)
492                         {
493                                 modules[j]->OnCleanup(TYPE_USER,u->second);
494                         }
495
496                         FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
497
498                         for(int t = 0; t < 255; t++)
499                         {
500                                 Config->global_implementation[t] -= Config->implement_lists[j][t];
501                         }
502
503                         /* We have to renumber implement_lists after unload because the module numbers change!
504                          */
505                         for(int j2 = j; j2 < 254; j2++)
506                         {
507                                 for(int t = 0; t < 255; t++)
508                                 {
509                                         Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
510                                 }
511                         }
512
513                         // found the module
514                         this->Log(DEBUG,"Removing dependent commands...");
515                         Parser->RemoveCommands(filename);
516                         this->Log(DEBUG,"Deleting module...");
517                         this->EraseModule(j);
518                         this->Log(DEBUG,"Erasing module entry...");
519                         this->EraseFactory(j);
520                         this->Log(DEFAULT,"Module %s unloaded",filename);
521                         this->ModCount--;
522                         BuildISupport();
523                         return true;
524                 }
525         }
526         this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
527         snprintf(MODERR,MAXBUF,"Module not loaded");
528         return false;
529 }
530
531 bool InspIRCd::LoadModule(const char* filename)
532 {
533         char modfile[MAXBUF];
534 #ifdef STATIC_LINK
535         strlcpy(modfile,filename,MAXBUF);
536 #else
537         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
538 #endif
539         std::string filename_str = filename;
540 #ifndef STATIC_LINK
541 #ifndef IS_CYGWIN
542         if (!ServerConfig::DirValid(modfile))
543         {
544                 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
545                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
546                 return false;
547         }
548 #endif
549 #endif
550         this->Log(DEBUG,"Loading module: %s",modfile);
551 #ifndef STATIC_LINK
552         if (ServerConfig::FileExists(modfile))
553         {
554 #endif
555                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
556                 {
557                         if (Config->module_names[j] == filename_str)
558                         {
559                                 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
560                                 snprintf(MODERR,MAXBUF,"Module already loaded");
561                                 return false;
562                         }
563                 }
564                 try
565                 {
566                         ircd_module* a = new ircd_module(this, modfile);
567                         factory[this->ModCount+1] = a;
568                         if (factory[this->ModCount+1]->LastError())
569                         {
570                                 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
571                                 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
572                                 return false;
573                         }
574                         if ((long)factory[this->ModCount+1]->factory != -1)
575                         {
576                                 Module* m = factory[this->ModCount+1]->factory->CreateModule(this);
577                                 modules[this->ModCount+1] = m;
578                                 /* save the module and the module's classfactory, if
579                                  * this isnt done, random crashes can occur :/ */
580                                 Config->module_names.push_back(filename);
581
582                                 char* x = &Config->implement_lists[this->ModCount+1][0];
583                                 for(int t = 0; t < 255; t++)
584                                         x[t] = 0;
585
586                                 modules[this->ModCount+1]->Implements(x);
587
588                                 for(int t = 0; t < 255; t++)
589                                         Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
590                         }
591                         else
592                         {
593                                 this->Log(DEFAULT,"Unable to load %s",modfile);
594                                 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
595                                 return false;
596                         }
597                 }
598                 catch (ModuleException& modexcept)
599                 {
600                         this->Log(DEFAULT,"Unable to load %s: ",modfile,modexcept.GetReason());
601                         snprintf(MODERR,MAXBUF,"Factory function threw an exception: %s",modexcept.GetReason());
602                         return false;
603                 }
604 #ifndef STATIC_LINK
605         }
606         else
607         {
608                 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
609                 snprintf(MODERR,MAXBUF,"Module file could not be found");
610                 return false;
611         }
612 #endif
613         this->ModCount++;
614         FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
615         // now work out which modules, if any, want to move to the back of the queue,
616         // and if they do, move them there.
617         std::vector<std::string> put_to_back;
618         std::vector<std::string> put_to_front;
619         std::map<std::string,std::string> put_before;
620         std::map<std::string,std::string> put_after;
621         for (unsigned int j = 0; j < Config->module_names.size(); j++)
622         {
623                 if (modules[j]->Prioritize() == PRIORITY_LAST)
624                         put_to_back.push_back(Config->module_names[j]);
625                 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
626                         put_to_front.push_back(Config->module_names[j]);
627                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
628                         put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
629                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
630                         put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
631         }
632         for (unsigned int j = 0; j < put_to_back.size(); j++)
633                 MoveToLast(put_to_back[j]);
634         for (unsigned int j = 0; j < put_to_front.size(); j++)
635                 MoveToFirst(put_to_front[j]);
636         for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
637                 MoveBefore(j->first,j->second);
638         for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
639                 MoveAfter(j->first,j->second);
640         BuildISupport();
641         return true;
642 }
643
644 void InspIRCd::DoOneIteration(bool process_module_sockets)
645 {
646         /* time() seems to be a pretty expensive syscall, so avoid calling it too much.
647          * Once per loop iteration is pleanty.
648          */
649         OLDTIME = TIME;
650         TIME = time(NULL);
651
652         /* Run background module timers every few seconds
653          * (the docs say modules shouldnt rely on accurate
654          * timing using this event, so we dont have to
655          * time this exactly).
656          */
657         if (TIME != OLDTIME)
658         {
659                 if (TIME < OLDTIME)
660                         WriteOpers("*** \002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %d secs.",abs(OLDTIME-TIME));
661                 if ((TIME % 3600) == 0)
662                 {
663                         irc::whowas::MaintainWhoWas(TIME);
664                 }
665                 Timers->TickTimers(TIME);
666                 this->DoBackgroundUserStuff(TIME);
667
668                 if ((TIME % 5) == 0)
669                 {
670                         XLines->expire_lines();
671                         FOREACH_MOD_I(this,I_OnBackgroundTimer,OnBackgroundTimer(TIME));
672                         Timers->TickMissedTimers(TIME);
673                 }
674         }
675
676         /* Call the socket engine to wait on the active
677          * file descriptors. The socket engine has everything's
678          * descriptors in its list... dns, modules, users,
679          * servers... so its nice and easy, just one call.
680          * This will cause any read or write events to be 
681          * dispatched to their handlers.
682          */
683         SE->DispatchEvents();
684 }
685
686 bool InspIRCd::IsIdent(const char* n)
687 {
688         if (!n || !*n)
689                 return false;
690
691         for (char* i = (char*)n; *i; i++)
692         {
693                 if ((*i >= 'A') && (*i <= '}'))
694                 {
695                         continue;
696                 }
697                 if (((*i >= '0') && (*i <= '9')) || (*i == '-') || (*i == '.'))
698                 {
699                         continue;
700                 }
701                 return false;
702         }
703         return true;
704 }
705
706
707 bool InspIRCd::IsNick(const char* n)
708 {
709         if (!n || !*n)
710                 return false;
711
712         int p = 0; 
713         for (char* i = (char*)n; *i; i++, p++)
714         {
715                 /* "A"-"}" can occur anywhere in a nickname */
716                 if ((*i >= 'A') && (*i <= '}'))
717                 {
718                         continue;
719                 }
720                 /* "0"-"9", "-" can occur anywhere BUT the first char of a nickname */
721                 if ((((*i >= '0') && (*i <= '9')) || (*i == '-')) && (i > n))
722                 {
723                         continue;
724                 }
725                 /* invalid character! abort */
726                 return false;
727         }
728         return (p < NICKMAX - 1);
729 }
730
731 int InspIRCd::Run()
732 {
733         while (true)
734         {
735                 DoOneIteration(true);
736         }
737         /* This is never reached -- we hope! */
738         return 0;
739 }
740
741 /**********************************************************************************/
742
743 /**
744  * An ircd in four lines! bwahahaha. ahahahahaha. ahahah *cough*.
745  */
746
747 int main(int argc, char** argv)
748 {
749         SI = new InspIRCd(argc, argv);
750         SI->Run();
751         delete SI;
752         return 0;
753 }
754
755 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
756  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
757  * registration timeout maximum seconds)
758  */
759 bool InspIRCd::AllModulesReportReady(userrec* user)
760 {
761         if (!Config->global_implementation[I_OnCheckReady])
762                 return true;
763
764         for (int i = 0; i <= this->GetModuleCount(); i++)
765         {
766                 if (Config->implement_lists[i][I_OnCheckReady])
767                 {
768                         int res = modules[i]->OnCheckReady(user);
769                         if (!res)
770                                 return false;
771                 }
772         }
773         return true;
774 }
775
776 int InspIRCd::GetModuleCount()
777 {
778         return this->ModCount;
779 }
780
781 time_t InspIRCd::Time()
782 {
783         return TIME;
784 }
785
786 bool FileLogger::Readable()
787 {
788         return false;
789 }
790
791 void FileLogger::HandleEvent(EventType et)
792 {
793         this->WriteLogLine("");
794         ServerInstance->SE->DelFd(this);
795 }
796
797 void FileLogger::WriteLogLine(const std::string &line)
798 {
799         if (line.length())
800                 buffer.append(line);
801
802         if (log)
803         {
804                 int written = fprintf(log,"%s",buffer.c_str());
805                 if ((written >= 0) && (written < (int)buffer.length()))
806                 {
807                         buffer.erase(0, buffer.length());
808                         ServerInstance->SE->AddFd(this);
809                 }
810                 else if (written == -1)
811                 {
812                         if (errno == EAGAIN)
813                                 ServerInstance->SE->AddFd(this);
814                 }
815                 else
816                 {
817                         /* Wrote the whole buffer, and no need for write callback */
818                         buffer = "";
819                 }
820         }
821         if (writeops++ % 20)
822         {
823                 fflush(log);
824         }
825 }
826
827 void FileLogger::Close()
828 {
829         if (log)
830         {
831                 int flags = fcntl(fileno(log), F_GETFL, 0);
832                 fcntl(fileno(log), F_SETFL, flags ^ O_NONBLOCK);
833                 if (buffer.size())
834                         fprintf(log,"%s",buffer.c_str());
835                 fflush(log);
836                 fclose(log);
837         }
838         buffer = "";
839         ServerInstance->SE->DelFd(this);
840 }
841
842 FileLogger::FileLogger(InspIRCd* Instance, FILE* logfile) : ServerInstance(Instance), log(logfile), writeops(0)
843 {
844         irc::sockets::NonBlocking(fileno(log));
845         this->SetFd(fileno(log));
846         buffer = "";
847 }
848
849 FileLogger::~FileLogger()
850 {
851         this->Close();
852 }
853