]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules.cpp
2d8c9387f5cbd49db8a50116d983772b669a76d4
[user/henk/code/inspircd.git] / src / modules.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 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 /* $Core */
15
16 #include "inspircd.h"
17 #include "xline.h"
18 #include "socket.h"
19 #include "socketengine.h"
20 #include "command_parse.h"
21 #include "dns.h"
22 #include "exitcodes.h"
23
24 #ifndef WIN32
25         #include <dirent.h>
26 #endif
27
28
29 // version is a simple class for holding a modules version number
30 Version::Version(const std::string &sversion, int flags, int api_ver)
31 : version(sversion), Flags(flags), API(api_ver)
32 {
33 }
34
35 Request::Request(char* anydata, Module* src, Module* dst)
36 : data(anydata), source(src), dest(dst)
37 {
38         /* Ensure that because this module doesnt support ID strings, it doesnt break modules that do
39          * by passing them uninitialized pointers (could happen)
40          */
41         id = '\0';
42 }
43
44 Request::Request(Module* src, Module* dst, const char* idstr)
45 : id(idstr), source(src), dest(dst)
46 {
47 }
48
49 char* Request::GetData()
50 {
51         return this->data;
52 }
53
54 const char* Request::GetId()
55 {
56         return this->id;
57 }
58
59 Module* Request::GetSource()
60 {
61         return this->source;
62 }
63
64 Module* Request::GetDest()
65 {
66         return this->dest;
67 }
68
69 const char* Request::Send()
70 {
71         if (this->dest)
72         {
73                 return dest->OnRequest(this);
74         }
75         else
76         {
77                 return NULL;
78         }
79 }
80
81 Event::Event(char* anydata, Module* src, const std::string &eventid) : data(anydata), source(src), id(eventid) { }
82
83 char* Event::GetData()
84 {
85         return (char*)this->data;
86 }
87
88 Module* Event::GetSource()
89 {
90         return this->source;
91 }
92
93 char* Event::Send(InspIRCd* ServerInstance)
94 {
95         FOREACH_MOD(I_OnEvent,OnEvent(this));
96         return NULL;
97 }
98
99 std::string Event::GetEventID()
100 {
101         return this->id;
102 }
103
104
105 // These declarations define the behavours of the base class Module (which does nothing at all)
106
107 Module::Module(InspIRCd* Me) : ServerInstance(Me) { }
108 Module::~Module() { }
109
110 int             Module::OnSendSnotice(char &snomask, std::string &type, const std::string &message) { return 0; }
111 void            Module::OnUserConnect(User*) { }
112 void            Module::OnUserQuit(User*, const std::string&, const std::string&) { }
113 void            Module::OnUserDisconnect(User*) { }
114 void            Module::OnUserJoin(User*, Channel*, bool, bool&) { }
115 void            Module::OnPostJoin(User*, Channel*) { }
116 void            Module::OnUserPart(User*, Channel*, std::string&, bool&) { }
117 void            Module::OnRehash(User*, const std::string&) { }
118 int             Module::OnUserPreJoin(User*, Channel*, const char*, std::string&, const std::string&) { return 0; }
119 void            Module::OnMode(User*, void*, int, const std::string&, const std::vector<TranslateType>&) { }
120 Version         Module::GetVersion() { return Version("Misconfigured", VF_VENDOR, -1); }
121 void            Module::OnOper(User*, const std::string&) { }
122 void            Module::OnPostOper(User*, const std::string&, const std::string &) { }
123 void            Module::OnInfo(User*) { }
124 void            Module::OnWhois(User*, User*) { }
125 int             Module::OnUserPreInvite(User*, User*, Channel*, time_t) { return 0; }
126 int             Module::OnUserPreMessage(User*, void*, int, std::string&, char, CUList&) { return 0; }
127 int             Module::OnUserPreNotice(User*, void*, int, std::string&, char, CUList&) { return 0; }
128 int             Module::OnUserPreNick(User*, const std::string&) { return 0; }
129 void            Module::OnUserPostNick(User*, const std::string&) { }
130 int             Module::OnAccessCheck(User*, User*, Channel*, int) { return ACR_DEFAULT; }
131 void            Module::On005Numeric(std::string&) { }
132 int             Module::OnKill(User*, User*, const std::string&) { return 0; }
133 void            Module::OnLoadModule(Module*, const std::string&) { }
134 void            Module::OnUnloadModule(Module*, const std::string&) { }
135 void            Module::OnBackgroundTimer(time_t) { }
136 int             Module::OnPreCommand(std::string&, std::vector<std::string>&, User *, bool, const std::string&) { return 0; }
137 void            Module::OnPostCommand(const std::string&, const std::vector<std::string>&, User *, CmdResult, const std::string&) { }
138 bool            Module::OnCheckReady(User*) { return true; }
139 int             Module::OnUserRegister(User*) { return 0; }
140 int             Module::OnUserPreKick(User*, User*, Channel*, const std::string&) { return 0; }
141 void            Module::OnUserKick(User*, User*, Channel*, const std::string&, bool&) { }
142 int             Module::OnRawMode(User*, Channel*, const char, const std::string &, bool, int, bool) { return 0; }
143 int             Module::OnCheckInvite(User*, Channel*) { return 0; }
144 int             Module::OnCheckKey(User*, Channel*, const std::string&) { return 0; }
145 int             Module::OnCheckLimit(User*, Channel*) { return 0; }
146 int             Module::OnCheckBan(User*, Channel*) { return 0; }
147 int             Module::OnCheckExtBan(User *, Channel *, char) { return 0; }
148 int             Module::OnCheckStringExtBan(const std::string &s, Channel *c, char type) { return 0; }
149 int             Module::OnStats(char, User*, string_list&) { return 0; }
150 int             Module::OnChangeLocalUserHost(User*, const std::string&) { return 0; }
151 int             Module::OnChangeLocalUserGECOS(User*, const std::string&) { return 0; }
152 int             Module::OnLocalTopicChange(User*, Channel*, const std::string&) { return 0; }
153 void            Module::OnEvent(Event*) { return; }
154 const char*             Module::OnRequest(Request*) { return NULL; }
155 int             Module::OnPassCompare(Extensible* ex, const std::string &password, const std::string &input, const std::string& hashtype) { return 0; }
156 void            Module::OnGlobalOper(User*) { }
157 void            Module::OnPostConnect(User*) { }
158 int             Module::OnAddBan(User*, Channel*, const std::string &) { return 0; }
159 int             Module::OnDelBan(User*, Channel*, const std::string &) { return 0; }
160 void            Module::OnRawSocketAccept(int, const std::string&, int) { }
161 int             Module::OnRawSocketWrite(int, const char*, int) { return 0; }
162 void            Module::OnRawSocketClose(int) { }
163 void            Module::OnRawSocketConnect(int) { }
164 int             Module::OnRawSocketRead(int, char*, unsigned int, int&) { return 0; }
165 void            Module::OnUserMessage(User*, void*, int, const std::string&, char, const CUList&) { }
166 void            Module::OnUserNotice(User*, void*, int, const std::string&, char, const CUList&) { }
167 void            Module::OnRemoteKill(User*, User*, const std::string&, const std::string&) { }
168 void            Module::OnUserInvite(User*, User*, Channel*, time_t) { }
169 void            Module::OnPostLocalTopicChange(User*, Channel*, const std::string&) { }
170 void            Module::OnGetServerDescription(const std::string&, std::string&) { }
171 void            Module::OnSyncUser(User*, Module*, void*) { }
172 void            Module::OnSyncChannel(Channel*, Module*, void*) { }
173 void            Module::ProtoSendMode(void*, TargetTypeFlags, void*, const std::string&, const std::vector<TranslateType>&) { }
174 void            Module::OnSyncChannelMetaData(Channel*, Module*, void*, const std::string&, bool) { }
175 void            Module::OnSyncUserMetaData(User*, Module*, void*, const std::string&, bool) { }
176 void            Module::OnSyncOtherMetaData(Module*, void*, bool) { }
177 void            Module::OnDecodeMetaData(int, void*, const std::string&, const std::string&) { }
178 void            Module::ProtoSendMetaData(void*, TargetTypeFlags, void*, const std::string&, const std::string&) { }
179 void            Module::OnWallops(User*, const std::string&) { }
180 void            Module::OnChangeHost(User*, const std::string&) { }
181 void            Module::OnChangeName(User*, const std::string&) { }
182 void            Module::OnAddLine(User*, XLine*) { }
183 void            Module::OnDelLine(User*, XLine*) { }
184 void            Module::OnExpireLine(XLine*) { }
185 void            Module::OnCleanup(int, void*) { }
186 int             Module::OnChannelPreDelete(Channel*) { return 0; }
187 void            Module::OnChannelDelete(Channel*) { }
188 int             Module::OnSetAway(User*, const std::string &) { return 0; }
189 int             Module::OnUserList(User*, Channel*, CUList*&) { return 0; }
190 int             Module::OnWhoisLine(User*, User*, int&, std::string&) { return 0; }
191 void            Module::OnBuildExemptList(MessageType, Channel*, User*, char, CUList&, const std::string&) { }
192 void            Module::OnGarbageCollect() { }
193 void            Module::OnBufferFlushed(User*) { }
194 void            Module::OnText(User*, void*, int, const std::string&, char, CUList&) { }
195 void            Module::OnRunTestSuite() { }
196 void            Module::OnNamesListItem(User*, User*, Channel*, std::string&, std::string&) { }
197 int             Module::OnNumeric(User*, unsigned int, const std::string&) { return 0; }
198 void            Module::OnHookUserIO(User*, const std::string&) { }
199 bool            Module::OnHostCycle(User* user) { return false; }
200
201 ModuleManager::ModuleManager(InspIRCd* Ins) : ModCount(0), Instance(Ins)
202 {
203 }
204
205 ModuleManager::~ModuleManager()
206 {
207 }
208
209 bool ModuleManager::Attach(Implementation i, Module* mod)
210 {
211         if (std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod) != EventHandlers[i].end())
212                 return false;
213
214         EventHandlers[i].push_back(mod);
215         return true;
216 }
217
218 bool ModuleManager::Detach(Implementation i, Module* mod)
219 {
220         EventHandlerIter x = std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod);
221
222         if (x == EventHandlers[i].end())
223                 return false;
224
225         EventHandlers[i].erase(x);
226         return true;
227 }
228
229 void ModuleManager::Attach(Implementation* i, Module* mod, size_t sz)
230 {
231         for (size_t n = 0; n < sz; ++n)
232                 Attach(i[n], mod);
233 }
234
235 void ModuleManager::DetachAll(Module* mod)
236 {
237         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
238                 Detach((Implementation)n, mod);
239 }
240
241 bool ModuleManager::SetPriority(Module* mod, Priority s)
242 {
243         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
244                 SetPriority(mod, (Implementation)n, s);
245
246         return true;
247 }
248
249 bool ModuleManager::SetPriority(Module* mod, Implementation i, Priority s, Module** modules, size_t sz)
250 {
251         /** To change the priority of a module, we first find its position in the vector,
252          * then we find the position of the other modules in the vector that this module
253          * wants to be before/after. We pick off either the first or last of these depending
254          * on which they want, and we make sure our module is *at least* before or after
255          * the first or last of this subset, depending again on the type of priority.
256          */
257         size_t swap_pos = 0;
258         size_t source = 0;
259         bool swap = true;
260         bool found = false;
261
262         /* Locate our module. This is O(n) but it only occurs on module load so we're
263          * not too bothered about it
264          */
265         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
266         {
267                 if (EventHandlers[i][x] == mod)
268                 {
269                         source = x;
270                         found = true;
271                         break;
272                 }
273         }
274
275         /* Eh? this module doesnt exist, probably trying to set priority on an event
276          * theyre not attached to.
277          */
278         if (!found)
279                 return false;
280
281         switch (s)
282         {
283                 /* Dummy value */
284                 case PRIORITY_DONTCARE:
285                         swap = false;
286                 break;
287                 /* Module wants to be first, sod everything else */
288                 case PRIORITY_FIRST:
289                         swap_pos = 0;
290                 break;
291                 /* Module is submissive and wants to be last... awww. */
292                 case PRIORITY_LAST:
293                         if (EventHandlers[i].empty())
294                                 swap_pos = 0;
295                         else
296                                 swap_pos = EventHandlers[i].size() - 1;
297                 break;
298                 /* Place this module after a set of other modules */
299                 case PRIORITY_AFTER:
300                 {
301                         /* Find the latest possible position */
302                         swap_pos = 0;
303                         swap = false;
304                         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
305                         {
306                                 for (size_t n = 0; n < sz; ++n)
307                                 {
308                                         if ((modules[n]) && (EventHandlers[i][x] == modules[n]) && (x >= swap_pos) && (source <= swap_pos))
309                                         {
310                                                 swap_pos = x;
311                                                 swap = true;
312                                         }
313                                 }
314                         }
315                 }
316                 break;
317                 /* Place this module before a set of other modules */
318                 case PRIORITY_BEFORE:
319                 {
320                         swap_pos = EventHandlers[i].size() - 1;
321                         swap = false;
322                         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
323                         {
324                                 for (size_t n = 0; n < sz; ++n)
325                                 {
326                                         if ((modules[n]) && (EventHandlers[i][x] == modules[n]) && (x <= swap_pos) && (source >= swap_pos))
327                                         {
328                                                 swap = true;
329                                                 swap_pos = x;
330                                         }
331                                 }
332                         }
333                 }
334                 break;
335         }
336
337         /* Do we need to swap? */
338         if (swap && (swap_pos != source))
339         {
340                 /* Suggestion from Phoenix, "shuffle" the modules to better retain call order */
341                 int incrmnt = 1;
342
343                 if (source > swap_pos)
344                         incrmnt = -1;
345
346                 for (unsigned int j = source; j != swap_pos; j += incrmnt)
347                 {
348                         if (( j + incrmnt > EventHandlers[i].size() - 1) || (j + incrmnt < 0))
349                                 continue;
350
351                         std::swap(EventHandlers[i][j], EventHandlers[i][j+incrmnt]);
352                 }
353         }
354
355         return true;
356 }
357
358 std::string& ModuleManager::LastError()
359 {
360         return LastModuleError;
361 }
362
363 bool ModuleManager::Load(const char* filename)
364 {
365         /* Do we have a glob pattern in the filename?
366          * The user wants to load multiple modules which
367          * match the pattern.
368          */
369         if (strchr(filename,'*') || (strchr(filename,'?')))
370         {
371                 int n_match = 0;
372                 DIR* library = opendir(Instance->Config->ModPath);
373                 if (library)
374                 {
375                         /* Try and locate and load all modules matching the pattern */
376                         dirent* entry = NULL;
377                         while (0 != (entry = readdir(library)))
378                         {
379                                 if (InspIRCd::Match(entry->d_name, filename, ascii_case_insensitive_map))
380                                 {
381                                         if (!this->Load(entry->d_name))
382                                                 n_match++;
383                                 }
384                         }
385                         closedir(library);
386                 }
387                 /* Loadmodule will now return false if any one of the modules failed
388                  * to load (but wont abort when it encounters a bad one) and when 1 or
389                  * more modules were actually loaded.
390                  */
391                 return (n_match > 0 ? false : true);
392         }
393
394         char modfile[MAXBUF];
395         snprintf(modfile,MAXBUF,"%s/%s",Instance->Config->ModPath,filename);
396         std::string filename_str = filename;
397
398         if (!ServerConfig::DirValid(modfile))
399         {
400                 LastModuleError = "Module " + std::string(filename) + " is not in the module directory that i am configured to look in (is "+Instance->Config->ModPath+" really a symlink?)";
401                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
402                 return false;
403         }
404
405         if (!ServerConfig::FileExists(modfile))
406         {
407                 LastModuleError = "Module file could not be found: " + filename_str;
408                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
409                 return false;
410         }
411
412         if (Modules.find(filename_str) != Modules.end())
413         {
414                 LastModuleError = "Module " + filename_str + " is already loaded, cannot load a module twice!";
415                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
416                 return false;
417         }
418
419         Module* newmod = NULL;
420         ircd_module* newhandle = NULL;
421
422         try
423         {
424                 /* This will throw a CoreException if there's a problem loading
425                  * the module file or getting a pointer to the init_module symbol.
426                  */
427                 newhandle = new ircd_module(Instance, modfile, "init_module");
428                 newmod = newhandle->CallInit();
429
430                 if (newmod)
431                 {
432                         Version v = newmod->GetVersion();
433
434                         if (v.API != API_VERSION)
435                         {
436                                 DetachAll(newmod);
437                                 delete newmod;
438                                 delete newhandle;
439                                 LastModuleError = "Unable to load " + filename_str + ": Incorrect module API version: " + ConvToStr(v.API) + " (our version: " + ConvToStr(API_VERSION) + ")";
440                                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
441                                 return false;
442                         }
443                         else
444                         {
445                                 Instance->Logs->Log("MODULE", DEFAULT,"New module introduced: %s (API version %d, Module version %s)%s", filename, v.API, v.version.c_str(), (!(v.Flags & VF_VENDOR) ? " [3rd Party]" : " [Vendor]"));
446                         }
447
448                         Modules[filename_str] = std::make_pair(newhandle, newmod);
449                 }
450                 else
451                 {
452                         delete newhandle;
453                         LastModuleError = "Unable to load " + filename_str + ": Probably missing init_module() entrypoint, but dlsym() didn't notice a problem";
454                         Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
455                         return false;
456                 }
457         }
458         /** XXX: Is there anything we can do about this mess? -- Brain */
459         catch (LoadModuleException& modexcept)
460         {
461                 DetachAll(newmod);
462                 if (newmod)
463                         delete newmod;
464                 if (newhandle)
465                         delete newhandle;
466                 LastModuleError = "Unable to load " + filename_str + ": Error when loading: " + modexcept.GetReason();
467                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
468                 return false;
469         }
470         catch (FindSymbolException& modexcept)
471         {
472                 DetachAll(newmod);
473                 if (newmod)
474                         delete newmod;
475                 if (newhandle)
476                         delete newhandle;
477                 LastModuleError = "Unable to load " + filename_str + ": Error finding symbol: " + modexcept.GetReason();
478                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
479                 return false;
480         }
481         catch (CoreException& modexcept)
482         {
483                 DetachAll(newmod);
484                 if (newmod)
485                         delete newmod;
486                 if (newhandle)
487                         delete newhandle;
488                 LastModuleError = "Unable to load " + filename_str + ": " + modexcept.GetReason();
489                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
490                 return false;
491         }
492
493         this->ModCount++;
494         FOREACH_MOD_I(Instance,I_OnLoadModule,OnLoadModule(newmod, filename_str));
495
496         /* We give every module a chance to re-prioritize when we introduce a new one,
497          * not just the one thats loading, as the new module could affect the preference
498          * of others
499          */
500         for (std::map<std::string, std::pair<ircd_module*, Module*> >::iterator n = Modules.begin(); n != Modules.end(); ++n)
501                 n->second.second->Prioritize();
502
503         Instance->BuildISupport();
504         return true;
505 }
506
507 bool ModuleManager::Unload(const char* filename)
508 {
509         std::string filename_str(filename);
510         std::map<std::string, std::pair<ircd_module*, Module*> >::iterator modfind = Modules.find(filename);
511
512         if (modfind != Modules.end())
513         {
514                 if (modfind->second.second->GetVersion().Flags & VF_STATIC)
515                 {
516                         LastModuleError = "Module " + filename_str + " not unloadable (marked static)";
517                         Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
518                         return false;
519                 }
520                 std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modfind->second.second);
521                 if (intercount.first > 0)
522                 {
523                         LastModuleError = "Failed to unload module " + filename_str + ", being used by " + ConvToStr(intercount.first) + " other(s) via interface '" + intercount.second + "'";
524                         Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
525                         return false;
526                 }
527
528                 /* Give the module a chance to tidy out all its metadata */
529                 for (chan_hash::iterator c = Instance->chanlist->begin(); c != Instance->chanlist->end(); c++)
530                 {
531                         modfind->second.second->OnCleanup(TYPE_CHANNEL,c->second);
532                 }
533                 for (user_hash::iterator u = Instance->Users->clientlist->begin(); u != Instance->Users->clientlist->end(); u++)
534                 {
535                         modfind->second.second->OnCleanup(TYPE_USER,u->second);
536                 }
537
538                 /* Tidy up any dangling resolvers */
539                 Instance->Res->CleanResolvers(modfind->second.second);
540
541
542                 FOREACH_MOD_I(Instance,I_OnUnloadModule,OnUnloadModule(modfind->second.second, modfind->first));
543
544                 this->DetachAll(modfind->second.second);
545
546                 Instance->Parser->RemoveCommands(filename);
547
548                 delete modfind->second.second;
549                 delete modfind->second.first;
550                 Modules.erase(modfind);
551
552                 Instance->Logs->Log("MODULE", DEFAULT,"Module %s unloaded",filename);
553                 this->ModCount--;
554                 Instance->BuildISupport();
555                 return true;
556         }
557
558         LastModuleError = "Module " + filename_str + " is not loaded, cannot unload it!";
559         Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
560         return false;
561 }
562
563 /* We must load the modules AFTER initializing the socket engine, now */
564 void ModuleManager::LoadAll()
565 {
566         char configToken[MAXBUF];
567         ModCount = -1;
568
569         for(int count = 0; count < Instance->Config->ConfValueEnum(Instance->Config->config_data, "module"); count++)
570         {
571                 Instance->Config->ConfValue(Instance->Config->config_data, "module", "name", count, configToken, MAXBUF);
572                 printf_c("[\033[1;32m*\033[0m] Loading module:\t\033[1;32m%s\033[0m\n",configToken);
573
574                 if (!this->Load(configToken))
575                 {
576                         Instance->Logs->Log("MODULE", DEFAULT, this->LastError());
577                         printf_c("\n[\033[1;31m*\033[0m] %s\n\n", this->LastError().c_str());
578                         Instance->Exit(EXIT_STATUS_MODULE);
579                 }
580         }
581 }
582
583 bool ModuleManager::PublishFeature(const std::string &FeatureName, Module* Mod)
584 {
585         if (Features.find(FeatureName) == Features.end())
586         {
587                 Features[FeatureName] = Mod;
588                 return true;
589         }
590         return false;
591 }
592
593 bool ModuleManager::UnpublishFeature(const std::string &FeatureName)
594 {
595         featurelist::iterator iter = Features.find(FeatureName);
596
597         if (iter == Features.end())
598                 return false;
599
600         Features.erase(iter);
601         return true;
602 }
603
604 Module* ModuleManager::FindFeature(const std::string &FeatureName)
605 {
606         featurelist::iterator iter = Features.find(FeatureName);
607
608         if (iter == Features.end())
609                 return NULL;
610
611         return iter->second;
612 }
613
614 bool ModuleManager::PublishInterface(const std::string &InterfaceName, Module* Mod)
615 {
616         interfacelist::iterator iter = Interfaces.find(InterfaceName);
617
618         if (iter == Interfaces.end())
619         {
620                 modulelist ml;
621                 ml.push_back(Mod);
622                 Interfaces[InterfaceName] = std::make_pair(0, ml);
623         }
624         else
625         {
626                 iter->second.second.push_back(Mod);
627         }
628         return true;
629 }
630
631 bool ModuleManager::UnpublishInterface(const std::string &InterfaceName, Module* Mod)
632 {
633         interfacelist::iterator iter = Interfaces.find(InterfaceName);
634
635         if (iter == Interfaces.end())
636                 return false;
637
638         for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
639         {
640                 if (*x == Mod)
641                 {
642                         iter->second.second.erase(x);
643                         if (iter->second.second.empty())
644                                 Interfaces.erase(InterfaceName);
645                         return true;
646                 }
647         }
648         return false;
649 }
650
651 modulelist* ModuleManager::FindInterface(const std::string &InterfaceName)
652 {
653         interfacelist::iterator iter = Interfaces.find(InterfaceName);
654         if (iter == Interfaces.end())
655                 return NULL;
656         else
657                 return &(iter->second.second);
658 }
659
660 bool ModuleManager::ModuleHasInterface(Module* mod, const std::string& InterfaceName)
661 {
662         interfacelist::iterator iter = Interfaces.find(InterfaceName);
663         if (iter == Interfaces.end())
664                 return false;
665         else
666         {
667                 modulelist& ml = iter->second.second;
668                 modulelist::iterator mi = std::find(ml.begin(), ml.end(), mod);
669                 return (mi != ml.end());
670         }
671 }
672
673 void ModuleManager::UseInterface(const std::string &InterfaceName)
674 {
675         interfacelist::iterator iter = Interfaces.find(InterfaceName);
676         if (iter != Interfaces.end())
677                 iter->second.first++;
678
679 }
680
681 void ModuleManager::DoneWithInterface(const std::string &InterfaceName)
682 {
683         interfacelist::iterator iter = Interfaces.find(InterfaceName);
684         if (iter != Interfaces.end())
685                 iter->second.first--;
686 }
687
688 std::pair<int,std::string> ModuleManager::GetInterfaceInstanceCount(Module* m)
689 {
690         for (interfacelist::iterator iter = Interfaces.begin(); iter != Interfaces.end(); iter++)
691         {
692                 for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
693                 {
694                         if (*x == m)
695                         {
696                                 return std::make_pair(iter->second.first, iter->first);
697                         }
698                 }
699         }
700         return std::make_pair(0, "");
701 }
702
703 const std::string& ModuleManager::GetModuleName(Module* m)
704 {
705         static std::string nothing;
706
707         for (std::map<std::string, std::pair<ircd_module*, Module*> >::iterator n = Modules.begin(); n != Modules.end(); ++n)
708         {
709                 if (n->second.second == m)
710                         return n->first;
711         }
712
713         return nothing;
714 }
715
716 /* This is ugly, yes, but hash_map's arent designed to be
717  * addressed in this manner, and this is a bit of a kludge.
718  * Luckily its a specialist function and rarely used by
719  * many modules (in fact, it was specially created to make
720  * m_safelist possible, initially).
721  */
722
723 Channel* InspIRCd::GetChannelIndex(long index)
724 {
725         int target = 0;
726         for (chan_hash::iterator n = this->chanlist->begin(); n != this->chanlist->end(); n++, target++)
727         {
728                 if (index == target)
729                         return n->second;
730         }
731         return NULL;
732 }
733
734 CmdResult InspIRCd::CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user)
735 {
736         return this->Parser->CallHandler(commandname, parameters, user);
737 }
738
739 bool InspIRCd::IsValidModuleCommand(const std::string &commandname, int pcnt, User* user)
740 {
741         return this->Parser->IsValidCommand(commandname, pcnt, user);
742 }
743
744 void InspIRCd::AddCommand(Command *f)
745 {
746         if (!this->Parser->CreateCommand(f))
747         {
748                 ModuleException err("Command "+std::string(f->command)+" already exists.");
749                 throw (err);
750         }
751 }
752
753 void InspIRCd::SendMode(const std::vector<std::string>& parameters, User *user)
754 {
755         this->Modes->Process(parameters, user, true);
756 }
757
758 void InspIRCd::DumpText(User* User, const std::string &LinePrefix, std::stringstream &TextStream)
759 {
760         std::string CompleteLine = LinePrefix;
761         std::string Word;
762         while (TextStream >> Word)
763         {
764                 if (CompleteLine.length() + Word.length() + 3 > 500)
765                 {
766                         User->WriteServ(CompleteLine);
767                         CompleteLine = LinePrefix;
768                 }
769                 CompleteLine = CompleteLine + Word + " ";
770         }
771         User->WriteServ(CompleteLine);
772 }
773
774 User* FindDescriptorHandler::Call(int socket)
775 {
776         return reinterpret_cast<User*>(Server->SE->GetRef(socket));
777 }
778
779 bool InspIRCd::AddResolver(Resolver* r, bool cached)
780 {
781         if (!cached)
782                 return this->Res->AddResolverClass(r);
783         else
784         {
785                 r->TriggerCachedResult();
786                 delete r;
787                 return true;
788         }
789 }
790
791 Module* ModuleManager::Find(const std::string &name)
792 {
793         std::map<std::string, std::pair<ircd_module*, Module*> >::iterator modfind = Modules.find(name);
794
795         if (modfind == Modules.end())
796                 return NULL;
797         else
798                 return modfind->second.second;
799 }
800
801 const std::vector<std::string> ModuleManager::GetAllModuleNames(int filter)
802 {
803         std::vector<std::string> retval;
804         for (std::map<std::string, std::pair<ircd_module*, Module*> >::iterator x = Modules.begin(); x != Modules.end(); ++x)
805                 if (!filter || (x->second.second->GetVersion().Flags & filter))
806                         retval.push_back(x->first);
807         return retval;
808 }
809
810 ConfigReader::ConfigReader(InspIRCd* Instance) : ServerInstance(Instance)
811 {
812         this->errorlog = new std::ostringstream(std::stringstream::in | std::stringstream::out);
813         this->error = CONF_NO_ERROR;
814         this->data = &ServerInstance->Config->config_data;
815         this->privatehash = false;
816         this->error = 0;
817 }
818
819
820 ConfigReader::~ConfigReader()
821 {
822         if (this->errorlog)
823                 delete this->errorlog;
824         if(this->privatehash)
825                 delete this->data;
826 }
827
828
829 ConfigReader::ConfigReader(InspIRCd* Instance, const std::string &filename) : ServerInstance(Instance)
830 {
831         ServerInstance->Config->ClearStack();
832
833         this->error = CONF_NO_ERROR;
834         this->data = new ConfigDataHash;
835         this->privatehash = true;
836         this->errorlog = new std::ostringstream(std::stringstream::in | std::stringstream::out);
837         /*** XXX: This might block! */
838         this->readerror = ServerInstance->Config->DoInclude(*this->data, filename, *this->errorlog);
839         if (!this->readerror)
840                 this->error = CONF_FILE_NOT_FOUND;
841         this->error = 0;
842 }
843
844
845 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool allow_linefeeds)
846 {
847         /* Don't need to strlcpy() tag and name anymore, ReadConf() takes const char* */
848         std::string result;
849
850         if (!ServerInstance->Config->ConfValue(*this->data, tag, name, default_value, index, result, allow_linefeeds))
851         {
852                 this->error = CONF_VALUE_NOT_FOUND;
853         }
854         return result;
855 }
856
857 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, int index, bool allow_linefeeds)
858 {
859         return ReadValue(tag, name, "", index, allow_linefeeds);
860 }
861
862 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, const std::string &default_value, int index)
863 {
864         return ServerInstance->Config->ConfValueBool(*this->data, tag, name, default_value, index);
865 }
866
867 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, int index)
868 {
869         return ReadFlag(tag, name, "", index);
870 }
871
872
873 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool need_positive)
874 {
875         int result;
876
877         if(!ServerInstance->Config->ConfValueInteger(*this->data, tag, name, default_value, index, result))
878         {
879                 this->error = CONF_VALUE_NOT_FOUND;
880                 return 0;
881         }
882
883         if ((need_positive) && (result < 0))
884         {
885                 this->error = CONF_INT_NEGATIVE;
886                 return 0;
887         }
888
889         return result;
890 }
891
892 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, int index, bool need_positive)
893 {
894         return ReadInteger(tag, name, "", index, need_positive);
895 }
896
897 long ConfigReader::GetError()
898 {
899         long olderr = this->error;
900         this->error = 0;
901         return olderr;
902 }
903
904 void ConfigReader::DumpErrors(bool bail, User* user)
905 {
906         ServerInstance->Config->ReportConfigError(this->errorlog->str(), bail, user->uuid);
907 }
908
909
910 int ConfigReader::Enumerate(const std::string &tag)
911 {
912         return ServerInstance->Config->ConfValueEnum(*this->data, tag);
913 }
914
915 int ConfigReader::EnumerateValues(const std::string &tag, int index)
916 {
917         return ServerInstance->Config->ConfVarEnum(*this->data, tag, index);
918 }
919
920 bool ConfigReader::Verify()
921 {
922         return this->readerror;
923 }
924
925
926 FileReader::FileReader(InspIRCd* Instance, const std::string &filename) : ServerInstance(Instance)
927 {
928         LoadFile(filename);
929 }
930
931 FileReader::FileReader(InspIRCd* Instance) : ServerInstance(Instance)
932 {
933 }
934
935 std::string FileReader::Contents()
936 {
937         std::string x;
938         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
939         {
940                 x.append(*a);
941                 x.append("\r\n");
942         }
943         return x;
944 }
945
946 unsigned long FileReader::ContentSize()
947 {
948         return this->contentsize;
949 }
950
951 void FileReader::CalcSize()
952 {
953         unsigned long n = 0;
954         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
955                 n += (a->length() + 2);
956         this->contentsize = n;
957 }
958
959 void FileReader::LoadFile(const std::string &filename)
960 {
961         file_cache c;
962         c.clear();
963         if (ServerInstance->Config->ReadFile(c,filename.c_str()))
964         {
965                 this->fc = c;
966                 this->CalcSize();
967         }
968 }
969
970
971 FileReader::~FileReader()
972 {
973 }
974
975 bool FileReader::Exists()
976 {
977         return (!(fc.size() == 0));
978 }
979
980 std::string FileReader::GetLine(int x)
981 {
982         if ((x<0) || ((unsigned)x>fc.size()))
983                 return "";
984         return fc[x];
985 }
986
987 int FileReader::FileSize()
988 {
989         return fc.size();
990 }