]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules.cpp
15e3930997a7b6ae8ba9625bf74356a9fddd57d4
[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 <iostream>
28 #include <fstream>
29 #include "inspircd.h"
30 #include "xline.h"
31 #include "socket.h"
32 #include "socketengine.h"
33 #include "command_parse.h"
34 #include "exitcodes.h"
35
36 #ifndef _WIN32
37         #include <dirent.h>
38 #endif
39
40 static std::vector<dynamic_reference_base*>* dynrefs = NULL;
41 static bool dynref_init_complete = false;
42
43 void dynamic_reference_base::reset_all()
44 {
45         dynref_init_complete = true;
46         if (!dynrefs)
47                 return;
48         for(unsigned int i = 0; i < dynrefs->size(); i++)
49                 (*dynrefs)[i]->resolve();
50 }
51
52 // Version is a simple class for holding a modules version number
53 Version::Version(const std::string &desc, int flags) : description(desc), Flags(flags)
54 {
55 }
56
57 Version::Version(const std::string &desc, int flags, const std::string& linkdata)
58 : description(desc), Flags(flags), link_data(linkdata)
59 {
60 }
61
62 Event::Event(Module* src, const std::string &eventid) : source(src), id(eventid) { }
63
64 void Event::Send()
65 {
66         FOREACH_MOD(OnEvent, (*this));
67 }
68
69 // These declarations define the behavours of the base class Module (which does nothing at all)
70
71 Module::Module() { }
72 CullResult Module::cull()
73 {
74         return classbase::cull();
75 }
76 Module::~Module()
77 {
78 }
79
80 void Module::DetachEvent(Implementation i)
81 {
82         ServerInstance->Modules->Detach(i, this);
83 }
84
85 void            Module::ReadConfig(ConfigStatus& status) { }
86 ModResult       Module::OnSendSnotice(char &snomask, std::string &type, const std::string &message) { DetachEvent(I_OnSendSnotice); return MOD_RES_PASSTHRU; }
87 void            Module::OnUserConnect(LocalUser*) { DetachEvent(I_OnUserConnect); }
88 void            Module::OnUserQuit(User*, const std::string&, const std::string&) { DetachEvent(I_OnUserQuit); }
89 void            Module::OnUserDisconnect(LocalUser*) { DetachEvent(I_OnUserDisconnect); }
90 void            Module::OnUserJoin(Membership*, bool, bool, CUList&) { DetachEvent(I_OnUserJoin); }
91 void            Module::OnPostJoin(Membership*) { DetachEvent(I_OnPostJoin); }
92 void            Module::OnUserPart(Membership*, std::string&, CUList&) { DetachEvent(I_OnUserPart); }
93 void            Module::OnPreRehash(User*, const std::string&) { DetachEvent(I_OnPreRehash); }
94 void            Module::OnModuleRehash(User*, const std::string&) { DetachEvent(I_OnModuleRehash); }
95 ModResult       Module::OnUserPreJoin(LocalUser*, Channel*, const std::string&, std::string&, const std::string&) { DetachEvent(I_OnUserPreJoin); return MOD_RES_PASSTHRU; }
96 void            Module::OnMode(User*, User*, Channel*, const std::vector<std::string>&, const std::vector<TranslateType>&) { DetachEvent(I_OnMode); }
97 void            Module::OnOper(User*, const std::string&) { DetachEvent(I_OnOper); }
98 void            Module::OnPostOper(User*, const std::string&, const std::string &) { DetachEvent(I_OnPostOper); }
99 void            Module::OnInfo(User*) { DetachEvent(I_OnInfo); }
100 void            Module::OnWhois(User*, User*) { DetachEvent(I_OnWhois); }
101 ModResult       Module::OnUserPreInvite(User*, User*, Channel*, time_t) { DetachEvent(I_OnUserPreInvite); return MOD_RES_PASSTHRU; }
102 ModResult       Module::OnUserPreMessage(User*, void*, int, std::string&, char, CUList&, MessageType) { DetachEvent(I_OnUserPreMessage); return MOD_RES_PASSTHRU; }
103 ModResult       Module::OnUserPreNick(User*, const std::string&) { DetachEvent(I_OnUserPreNick); return MOD_RES_PASSTHRU; }
104 void            Module::OnUserPostNick(User*, const std::string&) { DetachEvent(I_OnUserPostNick); }
105 ModResult       Module::OnPreMode(User*, User*, Channel*, const std::vector<std::string>&) { DetachEvent(I_OnPreMode); return MOD_RES_PASSTHRU; }
106 void            Module::On005Numeric(std::map<std::string, std::string>&) { DetachEvent(I_On005Numeric); }
107 ModResult       Module::OnKill(User*, User*, const std::string&) { DetachEvent(I_OnKill); return MOD_RES_PASSTHRU; }
108 void            Module::OnLoadModule(Module*) { DetachEvent(I_OnLoadModule); }
109 void            Module::OnUnloadModule(Module*) { DetachEvent(I_OnUnloadModule); }
110 void            Module::OnBackgroundTimer(time_t) { DetachEvent(I_OnBackgroundTimer); }
111 ModResult       Module::OnPreCommand(std::string&, std::vector<std::string>&, LocalUser*, bool, const std::string&) { DetachEvent(I_OnPreCommand); return MOD_RES_PASSTHRU; }
112 void            Module::OnPostCommand(Command*, const std::vector<std::string>&, LocalUser*, CmdResult, const std::string&) { DetachEvent(I_OnPostCommand); }
113 void            Module::OnUserInit(LocalUser*) { DetachEvent(I_OnUserInit); }
114 ModResult       Module::OnCheckReady(LocalUser*) { DetachEvent(I_OnCheckReady); return MOD_RES_PASSTHRU; }
115 ModResult       Module::OnUserRegister(LocalUser*) { DetachEvent(I_OnUserRegister); return MOD_RES_PASSTHRU; }
116 ModResult       Module::OnUserPreKick(User*, Membership*, const std::string&) { DetachEvent(I_OnUserPreKick); return MOD_RES_PASSTHRU; }
117 void            Module::OnUserKick(User*, Membership*, const std::string&, CUList&) { DetachEvent(I_OnUserKick); }
118 ModResult       Module::OnRawMode(User*, Channel*, const char, const std::string &, bool, int) { DetachEvent(I_OnRawMode); return MOD_RES_PASSTHRU; }
119 ModResult       Module::OnCheckInvite(User*, Channel*) { DetachEvent(I_OnCheckInvite); return MOD_RES_PASSTHRU; }
120 ModResult       Module::OnCheckKey(User*, Channel*, const std::string&) { DetachEvent(I_OnCheckKey); return MOD_RES_PASSTHRU; }
121 ModResult       Module::OnCheckLimit(User*, Channel*) { DetachEvent(I_OnCheckLimit); return MOD_RES_PASSTHRU; }
122 ModResult       Module::OnCheckChannelBan(User*, Channel*) { DetachEvent(I_OnCheckChannelBan); return MOD_RES_PASSTHRU; }
123 ModResult       Module::OnCheckBan(User*, Channel*, const std::string&) { DetachEvent(I_OnCheckBan); return MOD_RES_PASSTHRU; }
124 ModResult       Module::OnExtBanCheck(User*, Channel*, char) { DetachEvent(I_OnExtBanCheck); return MOD_RES_PASSTHRU; }
125 ModResult       Module::OnStats(char, User*, string_list&) { DetachEvent(I_OnStats); return MOD_RES_PASSTHRU; }
126 ModResult       Module::OnChangeLocalUserHost(LocalUser*, const std::string&) { DetachEvent(I_OnChangeLocalUserHost); return MOD_RES_PASSTHRU; }
127 ModResult       Module::OnChangeLocalUserGECOS(LocalUser*, const std::string&) { DetachEvent(I_OnChangeLocalUserGECOS); return MOD_RES_PASSTHRU; }
128 ModResult       Module::OnPreTopicChange(User*, Channel*, const std::string&) { DetachEvent(I_OnPreTopicChange); return MOD_RES_PASSTHRU; }
129 void            Module::OnEvent(Event&) { DetachEvent(I_OnEvent); }
130 ModResult       Module::OnPassCompare(Extensible* ex, const std::string &password, const std::string &input, const std::string& hashtype) { DetachEvent(I_OnPassCompare); return MOD_RES_PASSTHRU; }
131 void            Module::OnGlobalOper(User*) { DetachEvent(I_OnGlobalOper); }
132 void            Module::OnPostConnect(User*) { DetachEvent(I_OnPostConnect); }
133 void            Module::OnUserMessage(User*, void*, int, const std::string&, char, const CUList&, MessageType) { DetachEvent(I_OnUserMessage); }
134 void            Module::OnUserInvite(User*, User*, Channel*, time_t) { DetachEvent(I_OnUserInvite); }
135 void            Module::OnPostTopicChange(User*, Channel*, const std::string&) { DetachEvent(I_OnPostTopicChange); }
136 void            Module::OnGetServerDescription(const std::string&, std::string&) { DetachEvent(I_OnGetServerDescription); }
137 void            Module::OnSyncUser(User*, Module*, void*) { DetachEvent(I_OnSyncUser); }
138 void            Module::OnSyncChannel(Channel*, Module*, void*) { DetachEvent(I_OnSyncChannel); }
139 void            Module::OnSyncNetwork(Module*, void*) { DetachEvent(I_OnSyncNetwork); }
140 void            Module::ProtoSendMode(void*, TargetTypeFlags, void*, const std::vector<std::string>&, const std::vector<TranslateType>&) { }
141 void            Module::OnDecodeMetaData(Extensible*, const std::string&, const std::string&) { DetachEvent(I_OnDecodeMetaData); }
142 void            Module::ProtoSendMetaData(void*, Extensible*, const std::string&, const std::string&) { }
143 void            Module::OnChangeHost(User*, const std::string&) { DetachEvent(I_OnChangeHost); }
144 void            Module::OnChangeName(User*, const std::string&) { DetachEvent(I_OnChangeName); }
145 void            Module::OnChangeIdent(User*, const std::string&) { DetachEvent(I_OnChangeIdent); }
146 void            Module::OnAddLine(User*, XLine*) { DetachEvent(I_OnAddLine); }
147 void            Module::OnDelLine(User*, XLine*) { DetachEvent(I_OnDelLine); }
148 void            Module::OnExpireLine(XLine*) { DetachEvent(I_OnExpireLine); }
149 void            Module::OnCleanup(int, void*) { }
150 ModResult       Module::OnChannelPreDelete(Channel*) { DetachEvent(I_OnChannelPreDelete); return MOD_RES_PASSTHRU; }
151 void            Module::OnChannelDelete(Channel*) { DetachEvent(I_OnChannelDelete); }
152 ModResult       Module::OnSetAway(User*, const std::string &) { DetachEvent(I_OnSetAway); return MOD_RES_PASSTHRU; }
153 ModResult       Module::OnWhoisLine(User*, User*, int&, std::string&) { DetachEvent(I_OnWhoisLine); return MOD_RES_PASSTHRU; }
154 void            Module::OnBuildNeighborList(User*, UserChanList&, std::map<User*,bool>&) { DetachEvent(I_OnBuildNeighborList); }
155 void            Module::OnGarbageCollect() { DetachEvent(I_OnGarbageCollect); }
156 ModResult       Module::OnSetConnectClass(LocalUser* user, ConnectClass* myclass) { DetachEvent(I_OnSetConnectClass); return MOD_RES_PASSTHRU; }
157 void            Module::OnText(User*, void*, int, const std::string&, char, CUList&) { DetachEvent(I_OnText); }
158 void            Module::OnRunTestSuite() { DetachEvent(I_OnRunTestSuite); }
159 void            Module::OnNamesListItem(User*, Membership*, std::string&, std::string&) { DetachEvent(I_OnNamesListItem); }
160 ModResult       Module::OnNumeric(User*, unsigned int, const std::string&) { DetachEvent(I_OnNumeric); return MOD_RES_PASSTHRU; }
161 void            Module::OnHookIO(StreamSocket*, ListenSocket*) { DetachEvent(I_OnHookIO); }
162 ModResult   Module::OnAcceptConnection(int, ListenSocket*, irc::sockets::sockaddrs*, irc::sockets::sockaddrs*) { DetachEvent(I_OnAcceptConnection); return MOD_RES_PASSTHRU; }
163 void            Module::OnSendWhoLine(User*, const std::vector<std::string>&, User*, std::string&) { DetachEvent(I_OnSendWhoLine); }
164 void            Module::OnSetUserIP(LocalUser*) { DetachEvent(I_OnSetUserIP); }
165
166 ModuleManager::ModuleManager()
167 {
168 }
169
170 ModuleManager::~ModuleManager()
171 {
172 }
173
174 bool ModuleManager::Attach(Implementation i, Module* mod)
175 {
176         if (std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod) != EventHandlers[i].end())
177                 return false;
178
179         EventHandlers[i].push_back(mod);
180         return true;
181 }
182
183 bool ModuleManager::Detach(Implementation i, Module* mod)
184 {
185         EventHandlerIter x = std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod);
186
187         if (x == EventHandlers[i].end())
188                 return false;
189
190         EventHandlers[i].erase(x);
191         return true;
192 }
193
194 void ModuleManager::Attach(Implementation* i, Module* mod, size_t sz)
195 {
196         for (size_t n = 0; n < sz; ++n)
197                 Attach(i[n], mod);
198 }
199
200 void ModuleManager::AttachAll(Module* mod)
201 {
202         for (size_t i = I_BEGIN + 1; i != I_END; ++i)
203                 Attach((Implementation)i, mod);
204 }
205
206 void ModuleManager::DetachAll(Module* mod)
207 {
208         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
209                 Detach((Implementation)n, mod);
210 }
211
212 bool ModuleManager::SetPriority(Module* mod, Priority s)
213 {
214         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
215                 SetPriority(mod, (Implementation)n, s);
216
217         return true;
218 }
219
220 bool ModuleManager::SetPriority(Module* mod, Implementation i, Priority s, Module* which)
221 {
222         /** To change the priority of a module, we first find its position in the vector,
223          * then we find the position of the other modules in the vector that this module
224          * wants to be before/after. We pick off either the first or last of these depending
225          * on which they want, and we make sure our module is *at least* before or after
226          * the first or last of this subset, depending again on the type of priority.
227          */
228         size_t my_pos = 0;
229
230         /* Locate our module. This is O(n) but it only occurs on module load so we're
231          * not too bothered about it
232          */
233         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
234         {
235                 if (EventHandlers[i][x] == mod)
236                 {
237                         my_pos = x;
238                         goto found_src;
239                 }
240         }
241
242         /* Eh? this module doesnt exist, probably trying to set priority on an event
243          * theyre not attached to.
244          */
245         return false;
246
247 found_src:
248         // The modules registered for a hook are called in reverse order (to allow for easier removal
249         // of list entries while looping), meaning that the Priority given to us has the exact opposite effect
250         // on the list, e.g.: PRIORITY_BEFORE will actually put 'mod' after 'which', etc.
251         size_t swap_pos = my_pos;
252         switch (s)
253         {
254                 case PRIORITY_LAST:
255                         if (prioritizationState != PRIO_STATE_FIRST)
256                                 return true;
257                         else
258                                 swap_pos = 0;
259                         break;
260                 case PRIORITY_FIRST:
261                         if (prioritizationState != PRIO_STATE_FIRST)
262                                 return true;
263                         else
264                                 swap_pos = EventHandlers[i].size() - 1;
265                         break;
266                 case PRIORITY_BEFORE:
267                 {
268                         /* Find the latest possible position, only searching AFTER our position */
269                         for (size_t x = EventHandlers[i].size() - 1; x > my_pos; --x)
270                         {
271                                 if (EventHandlers[i][x] == which)
272                                 {
273                                         swap_pos = x;
274                                         goto swap_now;
275                                 }
276                         }
277                         // didn't find it - either not loaded or we're already after
278                         return true;
279                 }
280                 /* Place this module before a set of other modules */
281                 case PRIORITY_AFTER:
282                 {
283                         for (size_t x = 0; x < my_pos; ++x)
284                         {
285                                 if (EventHandlers[i][x] == which)
286                                 {
287                                         swap_pos = x;
288                                         goto swap_now;
289                                 }
290                         }
291                         // didn't find it - either not loaded or we're already before
292                         return true;
293                 }
294         }
295
296 swap_now:
297         /* Do we need to swap? */
298         if (swap_pos != my_pos)
299         {
300                 // We are going to change positions; we'll need to run again to verify all requirements
301                 if (prioritizationState == PRIO_STATE_LAST)
302                         prioritizationState = PRIO_STATE_AGAIN;
303                 /* Suggestion from Phoenix, "shuffle" the modules to better retain call order */
304                 int incrmnt = 1;
305
306                 if (my_pos > swap_pos)
307                         incrmnt = -1;
308
309                 for (unsigned int j = my_pos; j != swap_pos; j += incrmnt)
310                 {
311                         if ((j + incrmnt > EventHandlers[i].size() - 1) || ((incrmnt == -1) && (j == 0)))
312                                 continue;
313
314                         std::swap(EventHandlers[i][j], EventHandlers[i][j+incrmnt]);
315                 }
316         }
317
318         return true;
319 }
320
321 bool ModuleManager::PrioritizeHooks()
322 {
323         /* We give every module a chance to re-prioritize when we introduce a new one,
324          * not just the one thats loading, as the new module could affect the preference
325          * of others
326          */
327         for (int tries = 0; tries < 20; tries++)
328         {
329                 prioritizationState = tries > 0 ? PRIO_STATE_LAST : PRIO_STATE_FIRST;
330                 for (std::map<std::string, Module*>::iterator n = Modules.begin(); n != Modules.end(); ++n)
331                         n->second->Prioritize();
332
333                 if (prioritizationState == PRIO_STATE_LAST)
334                         break;
335                 if (tries == 19)
336                 {
337                         ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, "Hook priority dependency loop detected");
338                         return false;
339                 }
340         }
341         return true;
342 }
343
344 bool ModuleManager::CanUnload(Module* mod)
345 {
346         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
347
348         if ((modfind == Modules.end()) || (modfind->second != mod) || (mod->dying))
349         {
350                 LastModuleError = "Module " + mod->ModuleSourceFile + " is not loaded, cannot unload it!";
351                 ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, LastModuleError);
352                 return false;
353         }
354         if (mod->GetVersion().Flags & VF_STATIC)
355         {
356                 LastModuleError = "Module " + mod->ModuleSourceFile + " not unloadable (marked static)";
357                 ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, LastModuleError);
358                 return false;
359         }
360
361         mod->dying = true;
362         return true;
363 }
364
365 void ModuleManager::DoSafeUnload(Module* mod)
366 {
367         // First, notify all modules that a module is about to be unloaded, so in case
368         // they pass execution to the soon to be unloaded module, it will happen now,
369         // i.e. before we unregister the services of the module being unloaded
370         FOREACH_MOD(OnUnloadModule, (mod));
371
372         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
373
374         std::vector<reference<ExtensionItem> > items;
375         ServerInstance->Extensions.BeginUnregister(modfind->second, items);
376         /* Give the module a chance to tidy out all its metadata */
377         for (chan_hash::iterator c = ServerInstance->chanlist->begin(); c != ServerInstance->chanlist->end(); c++)
378         {
379                 mod->OnCleanup(TYPE_CHANNEL,c->second);
380                 c->second->doUnhookExtensions(items);
381                 const UserMembList* users = c->second->GetUsers();
382                 for(UserMembCIter mi = users->begin(); mi != users->end(); mi++)
383                         mi->second->doUnhookExtensions(items);
384         }
385         for (user_hash::iterator u = ServerInstance->Users->clientlist->begin(); u != ServerInstance->Users->clientlist->end(); u++)
386         {
387                 mod->OnCleanup(TYPE_USER,u->second);
388                 u->second->doUnhookExtensions(items);
389         }
390         for(char m='A'; m <= 'z'; m++)
391         {
392                 ModeHandler* mh;
393                 mh = ServerInstance->Modes->FindMode(m, MODETYPE_USER);
394                 if (mh && mh->creator == mod)
395                         this->DelService(*mh);
396                 mh = ServerInstance->Modes->FindMode(m, MODETYPE_CHANNEL);
397                 if (mh && mh->creator == mod)
398                         this->DelService(*mh);
399         }
400         for(std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.begin(); i != DataProviders.end(); )
401         {
402                 std::multimap<std::string, ServiceProvider*>::iterator curr = i++;
403                 if (curr->second->creator == mod)
404                         DataProviders.erase(curr);
405         }
406
407         dynamic_reference_base::reset_all();
408
409         DetachAll(mod);
410
411         Modules.erase(modfind);
412         ServerInstance->GlobalCulls.AddItem(mod);
413
414         ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, "Module %s unloaded",mod->ModuleSourceFile.c_str());
415         ServerInstance->ISupport.Build();
416 }
417
418 void ModuleManager::UnloadAll()
419 {
420         /* We do this more than once, so that any service providers get a
421          * chance to be unhooked by the modules using them, but then get
422          * a chance to be removed themsleves.
423          *
424          * Note: this deliberately does NOT delete the DLLManager objects
425          */
426         for (int tries = 0; tries < 4; tries++)
427         {
428                 std::map<std::string, Module*>::iterator i = Modules.begin();
429                 while (i != Modules.end())
430                 {
431                         std::map<std::string, Module*>::iterator me = i++;
432                         if (CanUnload(me->second))
433                         {
434                                 DoSafeUnload(me->second);
435                         }
436                 }
437                 ServerInstance->GlobalCulls.Apply();
438         }
439 }
440
441 namespace
442 {
443         struct UnloadAction : public HandlerBase0<void>
444         {
445                 Module* const mod;
446                 UnloadAction(Module* m) : mod(m) {}
447                 void Call()
448                 {
449                         DLLManager* dll = mod->ModuleDLLManager;
450                         ServerInstance->Modules->DoSafeUnload(mod);
451                         ServerInstance->GlobalCulls.Apply();
452                         // In pure static mode this is always NULL
453                         delete dll;
454                         ServerInstance->GlobalCulls.AddItem(this);
455                 }
456         };
457
458         struct ReloadAction : public HandlerBase0<void>
459         {
460                 Module* const mod;
461                 HandlerBase1<void, bool>* const callback;
462                 ReloadAction(Module* m, HandlerBase1<void, bool>* c)
463                         : mod(m), callback(c) {}
464                 void Call()
465                 {
466                         DLLManager* dll = mod->ModuleDLLManager;
467                         std::string name = mod->ModuleSourceFile;
468                         ServerInstance->Modules->DoSafeUnload(mod);
469                         ServerInstance->GlobalCulls.Apply();
470                         delete dll;
471                         bool rv = ServerInstance->Modules->Load(name);
472                         if (callback)
473                                 callback->Call(rv);
474                         ServerInstance->GlobalCulls.AddItem(this);
475                 }
476         };
477 }
478
479 bool ModuleManager::Unload(Module* mod)
480 {
481         if (!CanUnload(mod))
482                 return false;
483         ServerInstance->AtomicActions.AddAction(new UnloadAction(mod));
484         return true;
485 }
486
487 void ModuleManager::Reload(Module* mod, HandlerBase1<void, bool>* callback)
488 {
489         if (CanUnload(mod))
490                 ServerInstance->AtomicActions.AddAction(new ReloadAction(mod, callback));
491         else
492                 callback->Call(false);
493 }
494
495 void ModuleManager::LoadAll()
496 {
497         LoadCoreModules();
498
499         ConfigTagList tags = ServerInstance->Config->ConfTags("module");
500         for (ConfigIter i = tags.first; i != tags.second; ++i)
501         {
502                 ConfigTag* tag = i->second;
503                 std::string name = tag->getString("name");
504                 std::cout << "[" << con_green << "*" << con_reset << "] Loading module:\t" << con_green << name << con_reset << std::endl;
505
506                 if (!this->Load(name, true))
507                 {
508                         ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, this->LastError());
509                         std::cout << std::endl << "[" << con_red << "*" << con_reset << "] " << this->LastError() << std::endl << std::endl;
510                         ServerInstance->Exit(EXIT_STATUS_MODULE);
511                 }
512         }
513
514         ConfigStatus confstatus;
515
516         for (ModuleMap::const_iterator i = Modules.begin(); i != Modules.end(); ++i)
517         {
518                 Module* mod = i->second;
519                 try
520                 {
521                         ServerInstance->Logs->Log("MODULE", LOG_DEBUG, "Initializing %s", i->first.c_str());
522                         AttachAll(mod);
523                         mod->init();
524                         mod->ReadConfig(confstatus);
525                 }
526                 catch (CoreException& modexcept)
527                 {
528                         LastModuleError = "Unable to initialize " + mod->ModuleSourceFile + ": " + modexcept.GetReason();
529                         ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, LastModuleError);
530                         std::cout << std::endl << "[" << con_red << "*" << con_reset << "] " << LastModuleError << std::endl << std::endl;
531                         ServerInstance->Exit(EXIT_STATUS_MODULE);
532                 }
533         }
534
535         if (!PrioritizeHooks())
536                 ServerInstance->Exit(EXIT_STATUS_MODULE);
537 }
538
539 std::string& ModuleManager::LastError()
540 {
541         return LastModuleError;
542 }
543
544 void ModuleManager::AddService(ServiceProvider& item)
545 {
546         switch (item.service)
547         {
548                 case SERVICE_COMMAND:
549                         if (!ServerInstance->Parser->AddCommand(static_cast<Command*>(&item)))
550                                 throw ModuleException("Command "+std::string(item.name)+" already exists.");
551                         return;
552                 case SERVICE_MODE:
553                 {
554                         ModeHandler* mh = static_cast<ModeHandler*>(&item);
555                         if (!ServerInstance->Modes->AddMode(mh))
556                                 throw ModuleException("Mode "+std::string(item.name)+" already exists.");
557                         DataProviders.insert(std::make_pair((mh->GetModeType() == MODETYPE_CHANNEL ? "mode/" : "umode/") + item.name, &item));
558                         dynamic_reference_base::reset_all();
559                         return;
560                 }
561                 case SERVICE_METADATA:
562                         if (!ServerInstance->Extensions.Register(static_cast<ExtensionItem*>(&item)))
563                                 throw ModuleException("Extension " + std::string(item.name) + " already exists.");
564                         return;
565                 case SERVICE_DATA:
566                 case SERVICE_IOHOOK:
567                 {
568                         if ((item.name.substr(0, 5) == "mode/") || (item.name.substr(0, 6) == "umode/"))
569                                 throw ModuleException("The \"mode/\" and the \"umode\" service name prefixes are reserved.");
570
571                         DataProviders.insert(std::make_pair(item.name, &item));
572                         std::string::size_type slash = item.name.find('/');
573                         if (slash != std::string::npos)
574                         {
575                                 DataProviders.insert(std::make_pair(item.name.substr(0, slash), &item));
576                                 DataProviders.insert(std::make_pair(item.name.substr(slash + 1), &item));
577                         }
578                         dynamic_reference_base::reset_all();
579                         return;
580                 }
581                 default:
582                         throw ModuleException("Cannot add unknown service type");
583         }
584 }
585
586 void ModuleManager::DelService(ServiceProvider& item)
587 {
588         switch (item.service)
589         {
590                 case SERVICE_MODE:
591                         if (!ServerInstance->Modes->DelMode(static_cast<ModeHandler*>(&item)))
592                                 throw ModuleException("Mode "+std::string(item.name)+" does not exist.");
593                         // Fall through
594                 case SERVICE_DATA:
595                 case SERVICE_IOHOOK:
596                 {
597                         for(std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.begin(); i != DataProviders.end(); )
598                         {
599                                 std::multimap<std::string, ServiceProvider*>::iterator curr = i++;
600                                 if (curr->second == &item)
601                                         DataProviders.erase(curr);
602                         }
603                         dynamic_reference_base::reset_all();
604                         return;
605                 }
606                 default:
607                         throw ModuleException("Cannot delete unknown service type");
608         }
609 }
610
611 ServiceProvider* ModuleManager::FindService(ServiceType type, const std::string& name)
612 {
613         switch (type)
614         {
615                 case SERVICE_DATA:
616                 case SERVICE_IOHOOK:
617                 {
618                         std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.find(name);
619                         if (i != DataProviders.end() && i->second->service == type)
620                                 return i->second;
621                         return NULL;
622                 }
623                 // TODO implement finding of the other types
624                 default:
625                         throw ModuleException("Cannot find unknown service type");
626         }
627 }
628
629 dynamic_reference_base::dynamic_reference_base(Module* Creator, const std::string& Name)
630         : name(Name), value(NULL), creator(Creator)
631 {
632         if (!dynrefs)
633                 dynrefs = new std::vector<dynamic_reference_base*>;
634         dynrefs->push_back(this);
635         if (dynref_init_complete)
636                 resolve();
637 }
638
639 dynamic_reference_base::~dynamic_reference_base()
640 {
641         for(unsigned int i = 0; i < dynrefs->size(); i++)
642         {
643                 if (dynrefs->at(i) == this)
644                 {
645                         unsigned int last = dynrefs->size() - 1;
646                         if (i != last)
647                                 dynrefs->at(i) = dynrefs->at(last);
648                         dynrefs->erase(dynrefs->begin() + last);
649                         if (dynrefs->empty())
650                         {
651                                 delete dynrefs;
652                                 dynrefs = NULL;
653                         }
654                         return;
655                 }
656         }
657 }
658
659 void dynamic_reference_base::SetProvider(const std::string& newname)
660 {
661         name = newname;
662         resolve();
663 }
664
665 void dynamic_reference_base::resolve()
666 {
667         std::multimap<std::string, ServiceProvider*>::iterator i = ServerInstance->Modules->DataProviders.find(name);
668         if (i != ServerInstance->Modules->DataProviders.end())
669                 value = static_cast<DataProvider*>(i->second);
670         else
671                 value = NULL;
672 }
673
674 Module* ModuleManager::Find(const std::string &name)
675 {
676         std::map<std::string, Module*>::iterator modfind = Modules.find(name);
677
678         if (modfind == Modules.end())
679                 return NULL;
680         else
681                 return modfind->second;
682 }
683
684 FileReader::FileReader(const std::string& filename)
685 {
686         Load(filename);
687 }
688
689 void FileReader::Load(const std::string& filename)
690 {
691         // If the file is stored in the file cache then we used that version instead.
692         std::string realName = ServerInstance->Config->Paths.PrependConfig(filename);
693         ConfigFileCache::iterator it = ServerInstance->Config->Files.find(realName);
694         if (it != ServerInstance->Config->Files.end())
695         {
696                 this->lines = it->second;
697         }
698         else
699         {
700                 lines.clear();
701
702                 std::ifstream stream(realName.c_str());
703                 if (!stream.is_open())
704                         throw CoreException(filename + " does not exist or is not readable!");
705
706                 std::string line;
707                 while (std::getline(stream, line))
708                 {
709                         lines.push_back(line);
710                         totalSize += line.size() + 2;
711                 }
712
713                 stream.close();
714         }
715 }
716
717 std::string FileReader::GetString()
718 {
719         std::string buffer;
720         for (file_cache::iterator it = this->lines.begin(); it != this->lines.end(); ++it)
721         {
722                 buffer.append(*it);
723                 buffer.append("\r\n");
724         }
725         return buffer;
726 }