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