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