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