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