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