]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules.cpp
Add stdalgo::erase() and use it to simplify code
[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 Event::Event(Module* src, const std::string &eventid) : source(src), id(eventid) { }
56
57 void Event::Send()
58 {
59         FOREACH_MOD(OnEvent, (*this));
60 }
61
62 // These declarations define the behavours of the base class Module (which does nothing at all)
63
64 Module::Module() { }
65 CullResult Module::cull()
66 {
67         return classbase::cull();
68 }
69 Module::~Module()
70 {
71 }
72
73 void Module::DetachEvent(Implementation i)
74 {
75         ServerInstance->Modules->Detach(i, this);
76 }
77
78 void            Module::ReadConfig(ConfigStatus& status) { }
79 ModResult       Module::OnSendSnotice(char &snomask, std::string &type, const std::string &message) { DetachEvent(I_OnSendSnotice); return MOD_RES_PASSTHRU; }
80 void            Module::OnUserConnect(LocalUser*) { DetachEvent(I_OnUserConnect); }
81 void            Module::OnUserQuit(User*, const std::string&, const std::string&) { DetachEvent(I_OnUserQuit); }
82 void            Module::OnUserDisconnect(LocalUser*) { DetachEvent(I_OnUserDisconnect); }
83 void            Module::OnUserJoin(Membership*, bool, bool, CUList&) { DetachEvent(I_OnUserJoin); }
84 void            Module::OnPostJoin(Membership*) { DetachEvent(I_OnPostJoin); }
85 void            Module::OnUserPart(Membership*, std::string&, CUList&) { DetachEvent(I_OnUserPart); }
86 void            Module::OnPreRehash(User*, const std::string&) { DetachEvent(I_OnPreRehash); }
87 void            Module::OnModuleRehash(User*, const std::string&) { DetachEvent(I_OnModuleRehash); }
88 ModResult       Module::OnUserPreJoin(LocalUser*, Channel*, const std::string&, std::string&, const std::string&) { DetachEvent(I_OnUserPreJoin); return MOD_RES_PASSTHRU; }
89 void            Module::OnMode(User*, User*, Channel*, const Modes::ChangeList&, ModeParser::ModeProcessFlag, const std::string&) { DetachEvent(I_OnMode); }
90 void            Module::OnOper(User*, const std::string&) { DetachEvent(I_OnOper); }
91 void            Module::OnPostOper(User*, const std::string&, const std::string &) { DetachEvent(I_OnPostOper); }
92 void            Module::OnInfo(User*) { DetachEvent(I_OnInfo); }
93 void            Module::OnWhois(User*, User*) { DetachEvent(I_OnWhois); }
94 ModResult       Module::OnUserPreInvite(User*, User*, Channel*, time_t) { DetachEvent(I_OnUserPreInvite); return MOD_RES_PASSTHRU; }
95 ModResult       Module::OnUserPreMessage(User*, void*, int, std::string&, char, CUList&, MessageType) { DetachEvent(I_OnUserPreMessage); return MOD_RES_PASSTHRU; }
96 ModResult       Module::OnUserPreNick(LocalUser*, const std::string&) { DetachEvent(I_OnUserPreNick); return MOD_RES_PASSTHRU; }
97 void            Module::OnUserPostNick(User*, const std::string&) { DetachEvent(I_OnUserPostNick); }
98 ModResult       Module::OnPreMode(User*, User*, Channel*, Modes::ChangeList&) { DetachEvent(I_OnPreMode); return MOD_RES_PASSTHRU; }
99 void            Module::On005Numeric(std::map<std::string, std::string>&) { DetachEvent(I_On005Numeric); }
100 ModResult       Module::OnKill(User*, User*, const std::string&) { DetachEvent(I_OnKill); return MOD_RES_PASSTHRU; }
101 void            Module::OnLoadModule(Module*) { DetachEvent(I_OnLoadModule); }
102 void            Module::OnUnloadModule(Module*) { DetachEvent(I_OnUnloadModule); }
103 void            Module::OnBackgroundTimer(time_t) { DetachEvent(I_OnBackgroundTimer); }
104 ModResult       Module::OnPreCommand(std::string&, std::vector<std::string>&, LocalUser*, bool, const std::string&) { DetachEvent(I_OnPreCommand); return MOD_RES_PASSTHRU; }
105 void            Module::OnPostCommand(Command*, const std::vector<std::string>&, LocalUser*, CmdResult, const std::string&) { DetachEvent(I_OnPostCommand); }
106 void            Module::OnUserInit(LocalUser*) { DetachEvent(I_OnUserInit); }
107 ModResult       Module::OnCheckReady(LocalUser*) { DetachEvent(I_OnCheckReady); return MOD_RES_PASSTHRU; }
108 ModResult       Module::OnUserRegister(LocalUser*) { DetachEvent(I_OnUserRegister); return MOD_RES_PASSTHRU; }
109 ModResult       Module::OnUserPreKick(User*, Membership*, const std::string&) { DetachEvent(I_OnUserPreKick); return MOD_RES_PASSTHRU; }
110 void            Module::OnUserKick(User*, Membership*, const std::string&, CUList&) { DetachEvent(I_OnUserKick); }
111 ModResult       Module::OnRawMode(User*, Channel*, ModeHandler*, const std::string&, bool) { DetachEvent(I_OnRawMode); return MOD_RES_PASSTHRU; }
112 ModResult       Module::OnCheckInvite(User*, Channel*) { DetachEvent(I_OnCheckInvite); return MOD_RES_PASSTHRU; }
113 ModResult       Module::OnCheckKey(User*, Channel*, const std::string&) { DetachEvent(I_OnCheckKey); return MOD_RES_PASSTHRU; }
114 ModResult       Module::OnCheckLimit(User*, Channel*) { DetachEvent(I_OnCheckLimit); return MOD_RES_PASSTHRU; }
115 ModResult       Module::OnCheckChannelBan(User*, Channel*) { DetachEvent(I_OnCheckChannelBan); return MOD_RES_PASSTHRU; }
116 ModResult       Module::OnCheckBan(User*, Channel*, const std::string&) { DetachEvent(I_OnCheckBan); return MOD_RES_PASSTHRU; }
117 ModResult       Module::OnExtBanCheck(User*, Channel*, char) { DetachEvent(I_OnExtBanCheck); return MOD_RES_PASSTHRU; }
118 ModResult       Module::OnStats(char, User*, string_list&) { DetachEvent(I_OnStats); return MOD_RES_PASSTHRU; }
119 ModResult       Module::OnChangeLocalUserHost(LocalUser*, const std::string&) { DetachEvent(I_OnChangeLocalUserHost); return MOD_RES_PASSTHRU; }
120 ModResult       Module::OnChangeLocalUserGECOS(LocalUser*, const std::string&) { DetachEvent(I_OnChangeLocalUserGECOS); return MOD_RES_PASSTHRU; }
121 ModResult       Module::OnPreTopicChange(User*, Channel*, const std::string&) { DetachEvent(I_OnPreTopicChange); return MOD_RES_PASSTHRU; }
122 void            Module::OnEvent(Event&) { DetachEvent(I_OnEvent); }
123 ModResult       Module::OnPassCompare(Extensible* ex, const std::string &password, const std::string &input, const std::string& hashtype) { DetachEvent(I_OnPassCompare); return MOD_RES_PASSTHRU; }
124 void            Module::OnGlobalOper(User*) { DetachEvent(I_OnGlobalOper); }
125 void            Module::OnPostConnect(User*) { DetachEvent(I_OnPostConnect); }
126 void            Module::OnUserMessage(User*, void*, int, const std::string&, char, const CUList&, MessageType) { DetachEvent(I_OnUserMessage); }
127 void            Module::OnUserInvite(User*, User*, Channel*, time_t) { DetachEvent(I_OnUserInvite); }
128 void            Module::OnPostTopicChange(User*, Channel*, const std::string&) { DetachEvent(I_OnPostTopicChange); }
129 void            Module::OnSyncUser(User*, ProtocolInterface::Server&) { DetachEvent(I_OnSyncUser); }
130 void            Module::OnSyncChannel(Channel*, ProtocolInterface::Server&) { DetachEvent(I_OnSyncChannel); }
131 void            Module::OnSyncNetwork(ProtocolInterface::Server&) { DetachEvent(I_OnSyncNetwork); }
132 void            Module::OnDecodeMetaData(Extensible*, const std::string&, const std::string&) { DetachEvent(I_OnDecodeMetaData); }
133 void            Module::OnChangeHost(User*, const std::string&) { DetachEvent(I_OnChangeHost); }
134 void            Module::OnChangeName(User*, const std::string&) { DetachEvent(I_OnChangeName); }
135 void            Module::OnChangeIdent(User*, const std::string&) { DetachEvent(I_OnChangeIdent); }
136 void            Module::OnAddLine(User*, XLine*) { DetachEvent(I_OnAddLine); }
137 void            Module::OnDelLine(User*, XLine*) { DetachEvent(I_OnDelLine); }
138 void            Module::OnExpireLine(XLine*) { DetachEvent(I_OnExpireLine); }
139 void            Module::OnCleanup(int, void*) { }
140 ModResult       Module::OnChannelPreDelete(Channel*) { DetachEvent(I_OnChannelPreDelete); return MOD_RES_PASSTHRU; }
141 void            Module::OnChannelDelete(Channel*) { DetachEvent(I_OnChannelDelete); }
142 ModResult       Module::OnSetAway(User*, const std::string &) { DetachEvent(I_OnSetAway); return MOD_RES_PASSTHRU; }
143 ModResult       Module::OnWhoisLine(User*, User*, int&, std::string&) { DetachEvent(I_OnWhoisLine); return MOD_RES_PASSTHRU; }
144 void            Module::OnBuildNeighborList(User*, IncludeChanList&, std::map<User*,bool>&) { DetachEvent(I_OnBuildNeighborList); }
145 void            Module::OnGarbageCollect() { DetachEvent(I_OnGarbageCollect); }
146 ModResult       Module::OnSetConnectClass(LocalUser* user, ConnectClass* myclass) { DetachEvent(I_OnSetConnectClass); return MOD_RES_PASSTHRU; }
147 void            Module::OnText(User*, void*, int, const std::string&, char, CUList&) { DetachEvent(I_OnText); }
148 ModResult       Module::OnNamesListItem(User*, Membership*, std::string&, std::string&) { DetachEvent(I_OnNamesListItem); return MOD_RES_PASSTHRU; }
149 ModResult       Module::OnNumeric(User*, unsigned int, const std::string&) { DetachEvent(I_OnNumeric); return MOD_RES_PASSTHRU; }
150 ModResult   Module::OnAcceptConnection(int, ListenSocket*, irc::sockets::sockaddrs*, irc::sockets::sockaddrs*) { DetachEvent(I_OnAcceptConnection); return MOD_RES_PASSTHRU; }
151 void            Module::OnSendWhoLine(User*, const std::vector<std::string>&, User*, Membership*, std::string&) { DetachEvent(I_OnSendWhoLine); }
152 void            Module::OnSetUserIP(LocalUser*) { DetachEvent(I_OnSetUserIP); }
153
154 #ifdef INSPIRCD_ENABLE_TESTSUITE
155 void            Module::OnRunTestSuite() { }
156 #endif
157
158 ServiceProvider::ServiceProvider(Module* Creator, const std::string& Name, ServiceType Type)
159         : creator(Creator), name(Name), service(Type)
160 {
161         if ((ServerInstance) && (ServerInstance->Modules->NewServices))
162                 ServerInstance->Modules->NewServices->push_back(this);
163 }
164
165 void ServiceProvider::DisableAutoRegister()
166 {
167         if ((ServerInstance) && (ServerInstance->Modules->NewServices))
168                 stdalgo::erase(*ServerInstance->Modules->NewServices, this);
169 }
170
171 ModuleManager::ModuleManager()
172 {
173 }
174
175 ModuleManager::~ModuleManager()
176 {
177 }
178
179 bool ModuleManager::Attach(Implementation i, Module* mod)
180 {
181         if (std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod) != EventHandlers[i].end())
182                 return false;
183
184         EventHandlers[i].push_back(mod);
185         return true;
186 }
187
188 bool ModuleManager::Detach(Implementation i, Module* mod)
189 {
190         return stdalgo::erase(EventHandlers[i], mod);
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::PrioritizeHooks()
321 {
322         /* We give every module a chance to re-prioritize when we introduce a new one,
323          * not just the one thats loading, as the new module could affect the preference
324          * of others
325          */
326         for (int tries = 0; tries < 20; tries++)
327         {
328                 prioritizationState = tries > 0 ? PRIO_STATE_LAST : PRIO_STATE_FIRST;
329                 for (std::map<std::string, Module*>::iterator n = Modules.begin(); n != Modules.end(); ++n)
330                         n->second->Prioritize();
331
332                 if (prioritizationState == PRIO_STATE_LAST)
333                         break;
334                 if (tries == 19)
335                 {
336                         ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, "Hook priority dependency loop detected");
337                         return false;
338                 }
339         }
340         return true;
341 }
342
343 bool ModuleManager::CanUnload(Module* mod)
344 {
345         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
346
347         if ((modfind == Modules.end()) || (modfind->second != mod) || (mod->dying))
348         {
349                 LastModuleError = "Module " + mod->ModuleSourceFile + " is not loaded, cannot unload it!";
350                 ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, LastModuleError);
351                 return false;
352         }
353         if (mod->GetVersion().Flags & VF_STATIC)
354         {
355                 LastModuleError = "Module " + mod->ModuleSourceFile + " not unloadable (marked static)";
356                 ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, LastModuleError);
357                 return false;
358         }
359
360         mod->dying = true;
361         return true;
362 }
363
364 void ModuleManager::DoSafeUnload(Module* mod)
365 {
366         // First, notify all modules that a module is about to be unloaded, so in case
367         // they pass execution to the soon to be unloaded module, it will happen now,
368         // i.e. before we unregister the services of the module being unloaded
369         FOREACH_MOD(OnUnloadModule, (mod));
370
371         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
372
373         std::vector<reference<ExtensionItem> > items;
374         ServerInstance->Extensions.BeginUnregister(modfind->second, items);
375         /* Give the module a chance to tidy out all its metadata */
376         const chan_hash& chans = ServerInstance->GetChans();
377         for (chan_hash::const_iterator c = chans.begin(); c != chans.end(); )
378         {
379                 Channel* chan = c->second;
380                 ++c;
381                 mod->OnCleanup(TYPE_CHANNEL, chan);
382                 chan->doUnhookExtensions(items);
383                 const Channel::MemberMap& users = chan->GetUsers();
384                 for (Channel::MemberMap::const_iterator mi = users.begin(); mi != users.end(); ++mi)
385                         mi->second->doUnhookExtensions(items);
386         }
387
388         const user_hash& users = ServerInstance->Users->GetUsers();
389         for (user_hash::const_iterator u = users.begin(); u != users.end(); )
390         {
391                 User* user = u->second;
392                 // The module may quit the user (e.g. SSL mod unloading) and that will remove it from the container
393                 ++u;
394                 mod->OnCleanup(TYPE_USER, user);
395                 user->doUnhookExtensions(items);
396         }
397
398         const ModeParser::ModeHandlerMap& usermodes = ServerInstance->Modes->GetModes(MODETYPE_USER);
399         for (ModeParser::ModeHandlerMap::const_iterator i = usermodes.begin(); i != usermodes.end(); )
400         {
401                 ModeHandler* mh = i->second;
402                 ++i;
403                 if (mh->creator == mod)
404                         this->DelService(*mh);
405         }
406
407         const ModeParser::ModeHandlerMap& chanmodes = ServerInstance->Modes->GetModes(MODETYPE_CHANNEL);
408         for (ModeParser::ModeHandlerMap::const_iterator i = chanmodes.begin(); i != chanmodes.end(); )
409         {
410                 ModeHandler* mh = i->second;
411                 ++i;
412                 if (mh->creator == mod)
413                         this->DelService(*mh);
414         }
415
416         for(std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.begin(); i != DataProviders.end(); )
417         {
418                 std::multimap<std::string, ServiceProvider*>::iterator curr = i++;
419                 if (curr->second->creator == mod)
420                         DataProviders.erase(curr);
421         }
422
423         dynamic_reference_base::reset_all();
424
425         DetachAll(mod);
426
427         Modules.erase(modfind);
428         ServerInstance->GlobalCulls.AddItem(mod);
429
430         ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, "Module %s unloaded",mod->ModuleSourceFile.c_str());
431         ServerInstance->ISupport.Build();
432 }
433
434 void ModuleManager::UnloadAll()
435 {
436         /* We do this more than once, so that any service providers get a
437          * chance to be unhooked by the modules using them, but then get
438          * a chance to be removed themsleves.
439          *
440          * Note: this deliberately does NOT delete the DLLManager objects
441          */
442         for (int tries = 0; tries < 4; tries++)
443         {
444                 std::map<std::string, Module*>::iterator i = Modules.begin();
445                 while (i != Modules.end())
446                 {
447                         std::map<std::string, Module*>::iterator me = i++;
448                         if (CanUnload(me->second))
449                         {
450                                 DoSafeUnload(me->second);
451                         }
452                 }
453                 ServerInstance->GlobalCulls.Apply();
454         }
455 }
456
457 namespace
458 {
459         struct UnloadAction : public HandlerBase0<void>
460         {
461                 Module* const mod;
462                 UnloadAction(Module* m) : mod(m) {}
463                 void Call()
464                 {
465                         DLLManager* dll = mod->ModuleDLLManager;
466                         ServerInstance->Modules->DoSafeUnload(mod);
467                         ServerInstance->GlobalCulls.Apply();
468                         // In pure static mode this is always NULL
469                         delete dll;
470                         ServerInstance->GlobalCulls.AddItem(this);
471                 }
472         };
473
474         struct ReloadAction : public HandlerBase0<void>
475         {
476                 Module* const mod;
477                 HandlerBase1<void, bool>* const callback;
478                 ReloadAction(Module* m, HandlerBase1<void, bool>* c)
479                         : mod(m), callback(c) {}
480                 void Call()
481                 {
482                         DLLManager* dll = mod->ModuleDLLManager;
483                         std::string name = mod->ModuleSourceFile;
484                         ServerInstance->Modules->DoSafeUnload(mod);
485                         ServerInstance->GlobalCulls.Apply();
486                         delete dll;
487                         bool rv = ServerInstance->Modules->Load(name);
488                         if (callback)
489                                 callback->Call(rv);
490                         ServerInstance->GlobalCulls.AddItem(this);
491                 }
492         };
493 }
494
495 bool ModuleManager::Unload(Module* mod)
496 {
497         if (!CanUnload(mod))
498                 return false;
499         ServerInstance->AtomicActions.AddAction(new UnloadAction(mod));
500         return true;
501 }
502
503 void ModuleManager::Reload(Module* mod, HandlerBase1<void, bool>* callback)
504 {
505         if (CanUnload(mod))
506                 ServerInstance->AtomicActions.AddAction(new ReloadAction(mod, callback));
507         else if (callback)
508                 callback->Call(false);
509 }
510
511 void ModuleManager::LoadAll()
512 {
513         std::map<std::string, ServiceList> servicemap;
514         LoadCoreModules(servicemap);
515
516         ConfigTagList tags = ServerInstance->Config->ConfTags("module");
517         for (ConfigIter i = tags.first; i != tags.second; ++i)
518         {
519                 ConfigTag* tag = i->second;
520                 std::string name = tag->getString("name");
521                 this->NewServices = &servicemap[name];
522                 std::cout << "[" << con_green << "*" << con_reset << "] Loading module:\t" << con_green << name << con_reset << std::endl;
523
524                 if (!this->Load(name, true))
525                 {
526                         ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, this->LastError());
527                         std::cout << std::endl << "[" << con_red << "*" << con_reset << "] " << this->LastError() << std::endl << std::endl;
528                         ServerInstance->Exit(EXIT_STATUS_MODULE);
529                 }
530         }
531
532         ConfigStatus confstatus;
533
534         for (ModuleMap::const_iterator i = Modules.begin(); i != Modules.end(); ++i)
535         {
536                 Module* mod = i->second;
537                 try
538                 {
539                         ServerInstance->Logs->Log("MODULE", LOG_DEBUG, "Initializing %s", i->first.c_str());
540                         AttachAll(mod);
541                         AddServices(servicemap[i->first]);
542                         mod->init();
543                         mod->ReadConfig(confstatus);
544                 }
545                 catch (CoreException& modexcept)
546                 {
547                         LastModuleError = "Unable to initialize " + mod->ModuleSourceFile + ": " + modexcept.GetReason();
548                         ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, LastModuleError);
549                         std::cout << std::endl << "[" << con_red << "*" << con_reset << "] " << LastModuleError << std::endl << std::endl;
550                         ServerInstance->Exit(EXIT_STATUS_MODULE);
551                 }
552         }
553
554         this->NewServices = NULL;
555
556         if (!PrioritizeHooks())
557                 ServerInstance->Exit(EXIT_STATUS_MODULE);
558 }
559
560 std::string& ModuleManager::LastError()
561 {
562         return LastModuleError;
563 }
564
565 void ModuleManager::AddServices(const ServiceList& list)
566 {
567         for (ServiceList::const_iterator i = list.begin(); i != list.end(); ++i)
568         {
569                 ServiceProvider& s = **i;
570                 AddService(s);
571         }
572 }
573
574 void ModuleManager::AddService(ServiceProvider& item)
575 {
576         switch (item.service)
577         {
578                 case SERVICE_COMMAND:
579                         if (!ServerInstance->Parser.AddCommand(static_cast<Command*>(&item)))
580                                 throw ModuleException("Command "+std::string(item.name)+" already exists.");
581                         return;
582                 case SERVICE_MODE:
583                 {
584                         ModeHandler* mh = static_cast<ModeHandler*>(&item);
585                         ServerInstance->Modes->AddMode(mh);
586                         DataProviders.insert(std::make_pair((mh->GetModeType() == MODETYPE_CHANNEL ? "mode/" : "umode/") + item.name, &item));
587                         dynamic_reference_base::reset_all();
588                         return;
589                 }
590                 case SERVICE_METADATA:
591                         if (!ServerInstance->Extensions.Register(static_cast<ExtensionItem*>(&item)))
592                                 throw ModuleException("Extension " + std::string(item.name) + " already exists.");
593                         return;
594                 case SERVICE_DATA:
595                 case SERVICE_IOHOOK:
596                 {
597                         if ((!item.name.compare(0, 5, "mode/", 5)) || (!item.name.compare(0, 6, "umode/", 6)))
598                                 throw ModuleException("The \"mode/\" and the \"umode\" service name prefixes are reserved.");
599
600                         DataProviders.insert(std::make_pair(item.name, &item));
601                         std::string::size_type slash = item.name.find('/');
602                         if (slash != std::string::npos)
603                         {
604                                 DataProviders.insert(std::make_pair(item.name.substr(0, slash), &item));
605                                 DataProviders.insert(std::make_pair(item.name.substr(slash + 1), &item));
606                         }
607                         dynamic_reference_base::reset_all();
608                         return;
609                 }
610                 default:
611                         throw ModuleException("Cannot add unknown service type");
612         }
613 }
614
615 void ModuleManager::DelService(ServiceProvider& item)
616 {
617         switch (item.service)
618         {
619                 case SERVICE_MODE:
620                         if (!ServerInstance->Modes->DelMode(static_cast<ModeHandler*>(&item)))
621                                 throw ModuleException("Mode "+std::string(item.name)+" does not exist.");
622                         // Fall through
623                 case SERVICE_DATA:
624                 case SERVICE_IOHOOK:
625                 {
626                         for(std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.begin(); i != DataProviders.end(); )
627                         {
628                                 std::multimap<std::string, ServiceProvider*>::iterator curr = i++;
629                                 if (curr->second == &item)
630                                         DataProviders.erase(curr);
631                         }
632                         dynamic_reference_base::reset_all();
633                         return;
634                 }
635                 default:
636                         throw ModuleException("Cannot delete unknown service type");
637         }
638 }
639
640 ServiceProvider* ModuleManager::FindService(ServiceType type, const std::string& name)
641 {
642         switch (type)
643         {
644                 case SERVICE_DATA:
645                 case SERVICE_IOHOOK:
646                 {
647                         std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.find(name);
648                         if (i != DataProviders.end() && i->second->service == type)
649                                 return i->second;
650                         return NULL;
651                 }
652                 // TODO implement finding of the other types
653                 default:
654                         throw ModuleException("Cannot find unknown service type");
655         }
656 }
657
658 dynamic_reference_base::dynamic_reference_base(Module* Creator, const std::string& Name)
659         : name(Name), value(NULL), creator(Creator)
660 {
661         if (!dynrefs)
662                 dynrefs = new insp::intrusive_list<dynamic_reference_base>;
663         dynrefs->push_front(this);
664
665         // Resolve unless there is no ModuleManager (part of class InspIRCd)
666         if (ServerInstance)
667                 resolve();
668 }
669
670 dynamic_reference_base::~dynamic_reference_base()
671 {
672         dynrefs->erase(this);
673         if (dynrefs->empty())
674         {
675                 delete dynrefs;
676                 dynrefs = NULL;
677         }
678 }
679
680 void dynamic_reference_base::SetProvider(const std::string& newname)
681 {
682         name = newname;
683         resolve();
684 }
685
686 void dynamic_reference_base::resolve()
687 {
688         std::multimap<std::string, ServiceProvider*>::iterator i = ServerInstance->Modules->DataProviders.find(name);
689         if (i != ServerInstance->Modules->DataProviders.end())
690                 value = static_cast<DataProvider*>(i->second);
691         else
692                 value = NULL;
693 }
694
695 Module* ModuleManager::Find(const std::string &name)
696 {
697         std::map<std::string, Module*>::iterator modfind = Modules.find(name);
698
699         if (modfind == Modules.end())
700                 return NULL;
701         else
702                 return modfind->second;
703 }