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