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