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