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