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