]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules.cpp
Rename <options:moronbanner> to <options:xlinemessage>.
[user/henk/code/inspircd.git] / src / modules.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2007, 2009 Dennis Friis <peavey@inspircd.org>
6  *   Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
8  *   Copyright (C) 2006-2007 Robin Burchell <robin+git@viroteck.net>
9  *   Copyright (C) 2006-2007 Oliver Lupton <oliverlupton@gmail.com>
10  *   Copyright (C) 2007 Pippijn van Steenhoven <pip88nl@gmail.com>
11  *   Copyright (C) 2003 randomdan <???@???>
12  *
13  * This file is part of InspIRCd.  InspIRCd is free software: you can
14  * redistribute it and/or modify it under the terms of the GNU General Public
15  * License as published by the Free Software Foundation, version 2.
16  *
17  * This program is distributed in the hope that it will be useful, but WITHOUT
18  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
20  * details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24  */
25
26
27 #include <fstream>
28 #include "inspircd.h"
29 #include "xline.h"
30 #include "socket.h"
31 #include "socketengine.h"
32 #include "command_parse.h"
33 #include "exitcodes.h"
34
35 #ifndef _WIN32
36         #include <dirent.h>
37 #endif
38
39 static std::vector<dynamic_reference_base*>* dynrefs = NULL;
40 static bool dynref_init_complete = false;
41
42 void dynamic_reference_base::reset_all()
43 {
44         dynref_init_complete = true;
45         if (!dynrefs)
46                 return;
47         for(unsigned int i = 0; i < dynrefs->size(); i++)
48                 (*dynrefs)[i]->resolve();
49 }
50
51 // Version is a simple class for holding a modules version number
52 Version::Version(const std::string &desc, int flags) : description(desc), Flags(flags)
53 {
54 }
55
56 Version::Version(const std::string &desc, int flags, const std::string& linkdata)
57 : description(desc), Flags(flags), link_data(linkdata)
58 {
59 }
60
61 Event::Event(Module* src, const std::string &eventid) : source(src), id(eventid) { }
62
63 void Event::Send()
64 {
65         FOREACH_MOD(OnEvent, (*this));
66 }
67
68 // These declarations define the behavours of the base class Module (which does nothing at all)
69
70 Module::Module() { }
71 CullResult Module::cull()
72 {
73         return classbase::cull();
74 }
75 Module::~Module()
76 {
77 }
78
79 void Module::DetachEvent(Implementation i)
80 {
81         ServerInstance->Modules->Detach(i, this);
82 }
83
84 ModResult       Module::OnSendSnotice(char &snomask, std::string &type, const std::string &message) { DetachEvent(I_OnSendSnotice); return MOD_RES_PASSTHRU; }
85 void            Module::OnUserConnect(LocalUser*) { DetachEvent(I_OnUserConnect); }
86 void            Module::OnUserQuit(User*, const std::string&, const std::string&) { DetachEvent(I_OnUserQuit); }
87 void            Module::OnUserDisconnect(LocalUser*) { DetachEvent(I_OnUserDisconnect); }
88 void            Module::OnUserJoin(Membership*, bool, bool, CUList&) { DetachEvent(I_OnUserJoin); }
89 void            Module::OnPostJoin(Membership*) { DetachEvent(I_OnPostJoin); }
90 void            Module::OnUserPart(Membership*, std::string&, CUList&) { DetachEvent(I_OnUserPart); }
91 void            Module::OnPreRehash(User*, const std::string&) { DetachEvent(I_OnPreRehash); }
92 void            Module::OnModuleRehash(User*, const std::string&) { DetachEvent(I_OnModuleRehash); }
93 void            Module::OnRehash(User*) { DetachEvent(I_OnRehash); }
94 ModResult       Module::OnUserPreJoin(LocalUser*, Channel*, const std::string&, std::string&, const std::string&) { DetachEvent(I_OnUserPreJoin); return MOD_RES_PASSTHRU; }
95 void            Module::OnMode(User*, User*, Channel*, const std::vector<std::string>&, const std::vector<TranslateType>&) { DetachEvent(I_OnMode); }
96 void            Module::OnOper(User*, const std::string&) { DetachEvent(I_OnOper); }
97 void            Module::OnPostOper(User*, const std::string&, const std::string &) { DetachEvent(I_OnPostOper); }
98 void            Module::OnInfo(User*) { DetachEvent(I_OnInfo); }
99 void            Module::OnWhois(User*, User*) { DetachEvent(I_OnWhois); }
100 ModResult       Module::OnUserPreInvite(User*, User*, Channel*, time_t) { DetachEvent(I_OnUserPreInvite); return MOD_RES_PASSTHRU; }
101 ModResult       Module::OnUserPreMessage(User*, void*, int, std::string&, char, CUList&, MessageType) { DetachEvent(I_OnUserPreMessage); return MOD_RES_PASSTHRU; }
102 ModResult       Module::OnUserPreNick(User*, const std::string&) { DetachEvent(I_OnUserPreNick); return MOD_RES_PASSTHRU; }
103 void            Module::OnUserPostNick(User*, const std::string&) { DetachEvent(I_OnUserPostNick); }
104 ModResult       Module::OnPreMode(User*, User*, Channel*, const std::vector<std::string>&) { DetachEvent(I_OnPreMode); return MOD_RES_PASSTHRU; }
105 void            Module::On005Numeric(std::map<std::string, std::string>&) { DetachEvent(I_On005Numeric); }
106 ModResult       Module::OnKill(User*, User*, const std::string&) { DetachEvent(I_OnKill); return MOD_RES_PASSTHRU; }
107 void            Module::OnLoadModule(Module*) { DetachEvent(I_OnLoadModule); }
108 void            Module::OnUnloadModule(Module*) { DetachEvent(I_OnUnloadModule); }
109 void            Module::OnBackgroundTimer(time_t) { DetachEvent(I_OnBackgroundTimer); }
110 ModResult       Module::OnPreCommand(std::string&, std::vector<std::string>&, LocalUser*, bool, const std::string&) { DetachEvent(I_OnPreCommand); return MOD_RES_PASSTHRU; }
111 void            Module::OnPostCommand(Command*, const std::vector<std::string>&, LocalUser*, CmdResult, const std::string&) { DetachEvent(I_OnPostCommand); }
112 void            Module::OnUserInit(LocalUser*) { DetachEvent(I_OnUserInit); }
113 ModResult       Module::OnCheckReady(LocalUser*) { DetachEvent(I_OnCheckReady); return MOD_RES_PASSTHRU; }
114 ModResult       Module::OnUserRegister(LocalUser*) { DetachEvent(I_OnUserRegister); return MOD_RES_PASSTHRU; }
115 ModResult       Module::OnUserPreKick(User*, Membership*, const std::string&) { DetachEvent(I_OnUserPreKick); return MOD_RES_PASSTHRU; }
116 void            Module::OnUserKick(User*, Membership*, const std::string&, CUList&) { DetachEvent(I_OnUserKick); }
117 ModResult       Module::OnRawMode(User*, Channel*, const char, const std::string &, bool, int) { DetachEvent(I_OnRawMode); return MOD_RES_PASSTHRU; }
118 ModResult       Module::OnCheckInvite(User*, Channel*) { DetachEvent(I_OnCheckInvite); return MOD_RES_PASSTHRU; }
119 ModResult       Module::OnCheckKey(User*, Channel*, const std::string&) { DetachEvent(I_OnCheckKey); return MOD_RES_PASSTHRU; }
120 ModResult       Module::OnCheckLimit(User*, Channel*) { DetachEvent(I_OnCheckLimit); return MOD_RES_PASSTHRU; }
121 ModResult       Module::OnCheckChannelBan(User*, Channel*) { DetachEvent(I_OnCheckChannelBan); return MOD_RES_PASSTHRU; }
122 ModResult       Module::OnCheckBan(User*, Channel*, const std::string&) { DetachEvent(I_OnCheckBan); return MOD_RES_PASSTHRU; }
123 ModResult       Module::OnExtBanCheck(User*, Channel*, char) { DetachEvent(I_OnExtBanCheck); return MOD_RES_PASSTHRU; }
124 ModResult       Module::OnStats(char, User*, string_list&) { DetachEvent(I_OnStats); return MOD_RES_PASSTHRU; }
125 ModResult       Module::OnChangeLocalUserHost(LocalUser*, const std::string&) { DetachEvent(I_OnChangeLocalUserHost); return MOD_RES_PASSTHRU; }
126 ModResult       Module::OnChangeLocalUserGECOS(LocalUser*, const std::string&) { DetachEvent(I_OnChangeLocalUserGECOS); return MOD_RES_PASSTHRU; }
127 ModResult       Module::OnPreTopicChange(User*, Channel*, const std::string&) { DetachEvent(I_OnPreTopicChange); return MOD_RES_PASSTHRU; }
128 void            Module::OnEvent(Event&) { DetachEvent(I_OnEvent); }
129 ModResult       Module::OnPassCompare(Extensible* ex, const std::string &password, const std::string &input, const std::string& hashtype) { DetachEvent(I_OnPassCompare); return MOD_RES_PASSTHRU; }
130 void            Module::OnGlobalOper(User*) { DetachEvent(I_OnGlobalOper); }
131 void            Module::OnPostConnect(User*) { DetachEvent(I_OnPostConnect); }
132 void            Module::OnUserMessage(User*, void*, int, const std::string&, char, const CUList&, MessageType) { DetachEvent(I_OnUserMessage); }
133 void            Module::OnUserInvite(User*, User*, Channel*, time_t) { DetachEvent(I_OnUserInvite); }
134 void            Module::OnPostTopicChange(User*, Channel*, const std::string&) { DetachEvent(I_OnPostTopicChange); }
135 void            Module::OnGetServerDescription(const std::string&, std::string&) { DetachEvent(I_OnGetServerDescription); }
136 void            Module::OnSyncUser(User*, Module*, void*) { DetachEvent(I_OnSyncUser); }
137 void            Module::OnSyncChannel(Channel*, Module*, void*) { DetachEvent(I_OnSyncChannel); }
138 void            Module::OnSyncNetwork(Module*, void*) { DetachEvent(I_OnSyncNetwork); }
139 void            Module::ProtoSendMode(void*, TargetTypeFlags, void*, const std::vector<std::string>&, const std::vector<TranslateType>&) { }
140 void            Module::OnDecodeMetaData(Extensible*, const std::string&, const std::string&) { DetachEvent(I_OnDecodeMetaData); }
141 void            Module::ProtoSendMetaData(void*, Extensible*, const std::string&, const std::string&) { }
142 void            Module::OnChangeHost(User*, const std::string&) { DetachEvent(I_OnChangeHost); }
143 void            Module::OnChangeName(User*, const std::string&) { DetachEvent(I_OnChangeName); }
144 void            Module::OnChangeIdent(User*, const std::string&) { DetachEvent(I_OnChangeIdent); }
145 void            Module::OnAddLine(User*, XLine*) { DetachEvent(I_OnAddLine); }
146 void            Module::OnDelLine(User*, XLine*) { DetachEvent(I_OnDelLine); }
147 void            Module::OnExpireLine(XLine*) { DetachEvent(I_OnExpireLine); }
148 void            Module::OnCleanup(int, void*) { }
149 ModResult       Module::OnChannelPreDelete(Channel*) { DetachEvent(I_OnChannelPreDelete); return MOD_RES_PASSTHRU; }
150 void            Module::OnChannelDelete(Channel*) { DetachEvent(I_OnChannelDelete); }
151 ModResult       Module::OnSetAway(User*, const std::string &) { DetachEvent(I_OnSetAway); return MOD_RES_PASSTHRU; }
152 ModResult       Module::OnWhoisLine(User*, User*, int&, std::string&) { DetachEvent(I_OnWhoisLine); return MOD_RES_PASSTHRU; }
153 void            Module::OnBuildNeighborList(User*, UserChanList&, std::map<User*,bool>&) { DetachEvent(I_OnBuildNeighborList); }
154 void            Module::OnGarbageCollect() { DetachEvent(I_OnGarbageCollect); }
155 ModResult       Module::OnSetConnectClass(LocalUser* user, ConnectClass* myclass) { DetachEvent(I_OnSetConnectClass); return MOD_RES_PASSTHRU; }
156 void            Module::OnText(User*, void*, int, const std::string&, char, CUList&) { DetachEvent(I_OnText); }
157 void            Module::OnRunTestSuite() { DetachEvent(I_OnRunTestSuite); }
158 void            Module::OnNamesListItem(User*, Membership*, std::string&, std::string&) { DetachEvent(I_OnNamesListItem); }
159 ModResult       Module::OnNumeric(User*, unsigned int, const std::string&) { DetachEvent(I_OnNumeric); return MOD_RES_PASSTHRU; }
160 void            Module::OnHookIO(StreamSocket*, ListenSocket*) { DetachEvent(I_OnHookIO); }
161 ModResult   Module::OnAcceptConnection(int, ListenSocket*, irc::sockets::sockaddrs*, irc::sockets::sockaddrs*) { DetachEvent(I_OnAcceptConnection); return MOD_RES_PASSTHRU; }
162 void            Module::OnSendWhoLine(User*, const std::vector<std::string>&, User*, std::string&) { DetachEvent(I_OnSendWhoLine); }
163 void            Module::OnSetUserIP(LocalUser*) { DetachEvent(I_OnSetUserIP); }
164
165 ModuleManager::ModuleManager() : ModCount(0)
166 {
167 }
168
169 ModuleManager::~ModuleManager()
170 {
171 }
172
173 bool ModuleManager::Attach(Implementation i, Module* mod)
174 {
175         if (std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod) != EventHandlers[i].end())
176                 return false;
177
178         EventHandlers[i].push_back(mod);
179         return true;
180 }
181
182 bool ModuleManager::Detach(Implementation i, Module* mod)
183 {
184         EventHandlerIter x = std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod);
185
186         if (x == EventHandlers[i].end())
187                 return false;
188
189         EventHandlers[i].erase(x);
190         return true;
191 }
192
193 void ModuleManager::Attach(Implementation* i, Module* mod, size_t sz)
194 {
195         for (size_t n = 0; n < sz; ++n)
196                 Attach(i[n], mod);
197 }
198
199 void ModuleManager::AttachAll(Module* mod)
200 {
201         for (size_t i = I_BEGIN + 1; i != I_END; ++i)
202                 Attach((Implementation)i, mod);
203 }
204
205 void ModuleManager::DetachAll(Module* mod)
206 {
207         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
208                 Detach((Implementation)n, mod);
209 }
210
211 bool ModuleManager::SetPriority(Module* mod, Priority s)
212 {
213         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
214                 SetPriority(mod, (Implementation)n, s);
215
216         return true;
217 }
218
219 bool ModuleManager::SetPriority(Module* mod, Implementation i, Priority s, Module* which)
220 {
221         /** To change the priority of a module, we first find its position in the vector,
222          * then we find the position of the other modules in the vector that this module
223          * wants to be before/after. We pick off either the first or last of these depending
224          * on which they want, and we make sure our module is *at least* before or after
225          * the first or last of this subset, depending again on the type of priority.
226          */
227         size_t my_pos = 0;
228
229         /* Locate our module. This is O(n) but it only occurs on module load so we're
230          * not too bothered about it
231          */
232         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
233         {
234                 if (EventHandlers[i][x] == mod)
235                 {
236                         my_pos = x;
237                         goto found_src;
238                 }
239         }
240
241         /* Eh? this module doesnt exist, probably trying to set priority on an event
242          * theyre not attached to.
243          */
244         return false;
245
246 found_src:
247         // The modules registered for a hook are called in reverse order (to allow for easier removal
248         // of list entries while looping), meaning that the Priority given to us has the exact opposite effect
249         // on the list, e.g.: PRIORITY_BEFORE will actually put 'mod' after 'which', etc.
250         size_t swap_pos = my_pos;
251         switch (s)
252         {
253                 case PRIORITY_LAST:
254                         if (prioritizationState != PRIO_STATE_FIRST)
255                                 return true;
256                         else
257                                 swap_pos = 0;
258                         break;
259                 case PRIORITY_FIRST:
260                         if (prioritizationState != PRIO_STATE_FIRST)
261                                 return true;
262                         else
263                                 swap_pos = EventHandlers[i].size() - 1;
264                         break;
265                 case PRIORITY_BEFORE:
266                 {
267                         /* Find the latest possible position, only searching AFTER our position */
268                         for (size_t x = EventHandlers[i].size() - 1; x > my_pos; --x)
269                         {
270                                 if (EventHandlers[i][x] == which)
271                                 {
272                                         swap_pos = x;
273                                         goto swap_now;
274                                 }
275                         }
276                         // didn't find it - either not loaded or we're already after
277                         return true;
278                 }
279                 /* Place this module before a set of other modules */
280                 case PRIORITY_AFTER:
281                 {
282                         for (size_t x = 0; x < my_pos; ++x)
283                         {
284                                 if (EventHandlers[i][x] == which)
285                                 {
286                                         swap_pos = x;
287                                         goto swap_now;
288                                 }
289                         }
290                         // didn't find it - either not loaded or we're already before
291                         return true;
292                 }
293         }
294
295 swap_now:
296         /* Do we need to swap? */
297         if (swap_pos != my_pos)
298         {
299                 // We are going to change positions; we'll need to run again to verify all requirements
300                 if (prioritizationState == PRIO_STATE_LAST)
301                         prioritizationState = PRIO_STATE_AGAIN;
302                 /* Suggestion from Phoenix, "shuffle" the modules to better retain call order */
303                 int incrmnt = 1;
304
305                 if (my_pos > swap_pos)
306                         incrmnt = -1;
307
308                 for (unsigned int j = my_pos; j != swap_pos; j += incrmnt)
309                 {
310                         if ((j + incrmnt > EventHandlers[i].size() - 1) || ((incrmnt == -1) && (j == 0)))
311                                 continue;
312
313                         std::swap(EventHandlers[i][j], EventHandlers[i][j+incrmnt]);
314                 }
315         }
316
317         return true;
318 }
319
320 bool ModuleManager::CanUnload(Module* mod)
321 {
322         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
323
324         if ((modfind == Modules.end()) || (modfind->second != mod) || (mod->dying))
325         {
326                 LastModuleError = "Module " + mod->ModuleSourceFile + " is not loaded, cannot unload it!";
327                 ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, LastModuleError);
328                 return false;
329         }
330         if (mod->GetVersion().Flags & VF_STATIC)
331         {
332                 LastModuleError = "Module " + mod->ModuleSourceFile + " not unloadable (marked static)";
333                 ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, LastModuleError);
334                 return false;
335         }
336
337         mod->dying = true;
338         return true;
339 }
340
341 void ModuleManager::DoSafeUnload(Module* mod)
342 {
343         // First, notify all modules that a module is about to be unloaded, so in case
344         // they pass execution to the soon to be unloaded module, it will happen now,
345         // i.e. before we unregister the services of the module being unloaded
346         FOREACH_MOD(OnUnloadModule, (mod));
347
348         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
349
350         std::vector<reference<ExtensionItem> > items;
351         ServerInstance->Extensions.BeginUnregister(modfind->second, items);
352         /* Give the module a chance to tidy out all its metadata */
353         for (chan_hash::iterator c = ServerInstance->chanlist->begin(); c != ServerInstance->chanlist->end(); c++)
354         {
355                 mod->OnCleanup(TYPE_CHANNEL,c->second);
356                 c->second->doUnhookExtensions(items);
357                 const UserMembList* users = c->second->GetUsers();
358                 for(UserMembCIter mi = users->begin(); mi != users->end(); mi++)
359                         mi->second->doUnhookExtensions(items);
360         }
361         for (user_hash::iterator u = ServerInstance->Users->clientlist->begin(); u != ServerInstance->Users->clientlist->end(); u++)
362         {
363                 mod->OnCleanup(TYPE_USER,u->second);
364                 u->second->doUnhookExtensions(items);
365         }
366         for(char m='A'; m <= 'z'; m++)
367         {
368                 ModeHandler* mh;
369                 mh = ServerInstance->Modes->FindMode(m, MODETYPE_USER);
370                 if (mh && mh->creator == mod)
371                         this->DelService(*mh);
372                 mh = ServerInstance->Modes->FindMode(m, MODETYPE_CHANNEL);
373                 if (mh && mh->creator == mod)
374                         this->DelService(*mh);
375         }
376         for(std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.begin(); i != DataProviders.end(); )
377         {
378                 std::multimap<std::string, ServiceProvider*>::iterator curr = i++;
379                 if (curr->second->creator == mod)
380                         DataProviders.erase(curr);
381         }
382
383         dynamic_reference_base::reset_all();
384
385         DetachAll(mod);
386
387         Modules.erase(modfind);
388         ServerInstance->GlobalCulls.AddItem(mod);
389
390         ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, "Module %s unloaded",mod->ModuleSourceFile.c_str());
391         this->ModCount--;
392         ServerInstance->ISupport.Build();
393 }
394
395 void ModuleManager::UnloadAll()
396 {
397         /* We do this more than once, so that any service providers get a
398          * chance to be unhooked by the modules using them, but then get
399          * a chance to be removed themsleves.
400          *
401          * Note: this deliberately does NOT delete the DLLManager objects
402          */
403         for (int tries = 0; tries < 4; tries++)
404         {
405                 std::map<std::string, Module*>::iterator i = Modules.begin();
406                 while (i != Modules.end())
407                 {
408                         std::map<std::string, Module*>::iterator me = i++;
409                         if (CanUnload(me->second))
410                         {
411                                 DoSafeUnload(me->second);
412                         }
413                 }
414                 ServerInstance->GlobalCulls.Apply();
415         }
416 }
417
418 std::string& ModuleManager::LastError()
419 {
420         return LastModuleError;
421 }
422
423 void ModuleManager::AddService(ServiceProvider& item)
424 {
425         switch (item.service)
426         {
427                 case SERVICE_COMMAND:
428                         if (!ServerInstance->Parser->AddCommand(static_cast<Command*>(&item)))
429                                 throw ModuleException("Command "+std::string(item.name)+" already exists.");
430                         return;
431                 case SERVICE_MODE:
432                 {
433                         ModeHandler* mh = static_cast<ModeHandler*>(&item);
434                         if (!ServerInstance->Modes->AddMode(mh))
435                                 throw ModuleException("Mode "+std::string(item.name)+" already exists.");
436                         DataProviders.insert(std::make_pair((mh->GetModeType() == MODETYPE_CHANNEL ? "mode/" : "umode/") + item.name, &item));
437                         dynamic_reference_base::reset_all();
438                         return;
439                 }
440                 case SERVICE_METADATA:
441                         if (!ServerInstance->Extensions.Register(static_cast<ExtensionItem*>(&item)))
442                                 throw ModuleException("Extension " + std::string(item.name) + " already exists.");
443                         return;
444                 case SERVICE_DATA:
445                 case SERVICE_IOHOOK:
446                 {
447                         if ((item.name.substr(0, 5) == "mode/") || (item.name.substr(0, 6) == "umode/"))
448                                 throw ModuleException("The \"mode/\" and the \"umode\" service name prefixes are reserved.");
449
450                         DataProviders.insert(std::make_pair(item.name, &item));
451                         std::string::size_type slash = item.name.find('/');
452                         if (slash != std::string::npos)
453                         {
454                                 DataProviders.insert(std::make_pair(item.name.substr(0, slash), &item));
455                                 DataProviders.insert(std::make_pair(item.name.substr(slash + 1), &item));
456                         }
457                         dynamic_reference_base::reset_all();
458                         return;
459                 }
460                 default:
461                         throw ModuleException("Cannot add unknown service type");
462         }
463 }
464
465 void ModuleManager::DelService(ServiceProvider& item)
466 {
467         switch (item.service)
468         {
469                 case SERVICE_MODE:
470                         if (!ServerInstance->Modes->DelMode(static_cast<ModeHandler*>(&item)))
471                                 throw ModuleException("Mode "+std::string(item.name)+" does not exist.");
472                         // Fall through
473                 case SERVICE_DATA:
474                 case SERVICE_IOHOOK:
475                 {
476                         for(std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.begin(); i != DataProviders.end(); )
477                         {
478                                 std::multimap<std::string, ServiceProvider*>::iterator curr = i++;
479                                 if (curr->second == &item)
480                                         DataProviders.erase(curr);
481                         }
482                         dynamic_reference_base::reset_all();
483                         return;
484                 }
485                 default:
486                         throw ModuleException("Cannot delete unknown service type");
487         }
488 }
489
490 ServiceProvider* ModuleManager::FindService(ServiceType type, const std::string& name)
491 {
492         switch (type)
493         {
494                 case SERVICE_DATA:
495                 case SERVICE_IOHOOK:
496                 {
497                         std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.find(name);
498                         if (i != DataProviders.end() && i->second->service == type)
499                                 return i->second;
500                         return NULL;
501                 }
502                 // TODO implement finding of the other types
503                 default:
504                         throw ModuleException("Cannot find unknown service type");
505         }
506 }
507
508 dynamic_reference_base::dynamic_reference_base(Module* Creator, const std::string& Name)
509         : name(Name), value(NULL), creator(Creator)
510 {
511         if (!dynrefs)
512                 dynrefs = new std::vector<dynamic_reference_base*>;
513         dynrefs->push_back(this);
514         if (dynref_init_complete)
515                 resolve();
516 }
517
518 dynamic_reference_base::~dynamic_reference_base()
519 {
520         for(unsigned int i = 0; i < dynrefs->size(); i++)
521         {
522                 if (dynrefs->at(i) == this)
523                 {
524                         unsigned int last = dynrefs->size() - 1;
525                         if (i != last)
526                                 dynrefs->at(i) = dynrefs->at(last);
527                         dynrefs->erase(dynrefs->begin() + last);
528                         if (dynrefs->empty())
529                         {
530                                 delete dynrefs;
531                                 dynrefs = NULL;
532                         }
533                         return;
534                 }
535         }
536 }
537
538 void dynamic_reference_base::SetProvider(const std::string& newname)
539 {
540         name = newname;
541         resolve();
542 }
543
544 void dynamic_reference_base::resolve()
545 {
546         std::multimap<std::string, ServiceProvider*>::iterator i = ServerInstance->Modules->DataProviders.find(name);
547         if (i != ServerInstance->Modules->DataProviders.end())
548                 value = static_cast<DataProvider*>(i->second);
549         else
550                 value = NULL;
551 }
552
553 Module* ModuleManager::Find(const std::string &name)
554 {
555         std::map<std::string, Module*>::iterator modfind = Modules.find(name);
556
557         if (modfind == Modules.end())
558                 return NULL;
559         else
560                 return modfind->second;
561 }
562
563 const std::vector<std::string> ModuleManager::GetAllModuleNames(int filter)
564 {
565         std::vector<std::string> retval;
566         for (std::map<std::string, Module*>::iterator x = Modules.begin(); x != Modules.end(); ++x)
567                 if (!filter || (x->second->GetVersion().Flags & filter))
568                         retval.push_back(x->first);
569         return retval;
570 }
571
572 FileReader::FileReader(const std::string& filename)
573 {
574         Load(filename);
575 }
576
577 void FileReader::Load(const std::string& filename)
578 {
579         // If the file is stored in the file cache then we used that version instead.
580         ConfigFileCache::iterator it = ServerInstance->Config->Files.find(filename);
581         if (it != ServerInstance->Config->Files.end())
582         {
583                 this->lines = it->second;
584         }
585         else
586         {
587                 lines.clear();
588
589                 std::ifstream stream(filename.c_str());
590                 if (!stream.is_open())
591                         throw CoreException(filename + " does not exist or is not readable!");
592
593                 std::string line;
594                 while (std::getline(stream, line))
595                 {
596                         lines.push_back(line);
597                         totalSize += line.size() + 2;
598                 }
599
600                 stream.close();
601         }
602 }
603
604 std::string FileReader::GetString()
605 {
606         std::string buffer;
607         for (file_cache::iterator it = this->lines.begin(); it != this->lines.end(); ++it)
608         {
609                 buffer.append(*it);
610                 buffer.append("\r\n");
611         }
612         return buffer;
613 }