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