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