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