]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules.cpp
core_ison Extract duplicated code into a function
[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 <iostream>
28 #include "inspircd.h"
29 #include "exitcodes.h"
30
31 #ifndef _WIN32
32         #include <dirent.h>
33 #endif
34
35 static intrusive_list<dynamic_reference_base>* dynrefs = NULL;
36 static bool dynref_init_complete = false;
37
38 void dynamic_reference_base::reset_all()
39 {
40         dynref_init_complete = true;
41         if (!dynrefs)
42                 return;
43         for (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 Event::Event(Module* src, const std::string &eventid) : source(src), id(eventid) { }
58
59 void Event::Send()
60 {
61         FOREACH_MOD(OnEvent, (*this));
62 }
63
64 // These declarations define the behavours of the base class Module (which does nothing at all)
65
66 Module::Module() { }
67 CullResult Module::cull()
68 {
69         return classbase::cull();
70 }
71 Module::~Module()
72 {
73 }
74
75 void Module::DetachEvent(Implementation i)
76 {
77         ServerInstance->Modules->Detach(i, this);
78 }
79
80 void            Module::ReadConfig(ConfigStatus& status) { }
81 ModResult       Module::OnSendSnotice(char &snomask, std::string &type, const std::string &message) { DetachEvent(I_OnSendSnotice); return MOD_RES_PASSTHRU; }
82 void            Module::OnUserConnect(LocalUser*) { DetachEvent(I_OnUserConnect); }
83 void            Module::OnUserQuit(User*, const std::string&, const std::string&) { DetachEvent(I_OnUserQuit); }
84 void            Module::OnUserDisconnect(LocalUser*) { DetachEvent(I_OnUserDisconnect); }
85 void            Module::OnUserJoin(Membership*, bool, bool, CUList&) { DetachEvent(I_OnUserJoin); }
86 void            Module::OnPostJoin(Membership*) { DetachEvent(I_OnPostJoin); }
87 void            Module::OnUserPart(Membership*, std::string&, CUList&) { DetachEvent(I_OnUserPart); }
88 void            Module::OnPreRehash(User*, const std::string&) { DetachEvent(I_OnPreRehash); }
89 void            Module::OnModuleRehash(User*, const std::string&) { DetachEvent(I_OnModuleRehash); }
90 ModResult       Module::OnUserPreJoin(LocalUser*, Channel*, const std::string&, std::string&, const std::string&) { DetachEvent(I_OnUserPreJoin); return MOD_RES_PASSTHRU; }
91 void            Module::OnMode(User*, User*, Channel*, const std::vector<std::string>&, const std::vector<TranslateType>&) { DetachEvent(I_OnMode); }
92 void            Module::OnOper(User*, const std::string&) { DetachEvent(I_OnOper); }
93 void            Module::OnPostOper(User*, const std::string&, const std::string &) { DetachEvent(I_OnPostOper); }
94 void            Module::OnInfo(User*) { DetachEvent(I_OnInfo); }
95 void            Module::OnWhois(User*, User*) { DetachEvent(I_OnWhois); }
96 ModResult       Module::OnUserPreInvite(User*, User*, Channel*, time_t) { DetachEvent(I_OnUserPreInvite); return MOD_RES_PASSTHRU; }
97 ModResult       Module::OnUserPreMessage(User*, void*, int, std::string&, char, CUList&, MessageType) { DetachEvent(I_OnUserPreMessage); return MOD_RES_PASSTHRU; }
98 ModResult       Module::OnUserPreNick(LocalUser*, const std::string&) { DetachEvent(I_OnUserPreNick); return MOD_RES_PASSTHRU; }
99 void            Module::OnUserPostNick(User*, const std::string&) { DetachEvent(I_OnUserPostNick); }
100 ModResult       Module::OnPreMode(User*, User*, Channel*, const std::vector<std::string>&) { DetachEvent(I_OnPreMode); return MOD_RES_PASSTHRU; }
101 void            Module::On005Numeric(std::map<std::string, std::string>&) { DetachEvent(I_On005Numeric); }
102 ModResult       Module::OnKill(User*, User*, const std::string&) { DetachEvent(I_OnKill); return MOD_RES_PASSTHRU; }
103 void            Module::OnLoadModule(Module*) { DetachEvent(I_OnLoadModule); }
104 void            Module::OnUnloadModule(Module*) { DetachEvent(I_OnUnloadModule); }
105 void            Module::OnBackgroundTimer(time_t) { DetachEvent(I_OnBackgroundTimer); }
106 ModResult       Module::OnPreCommand(std::string&, std::vector<std::string>&, LocalUser*, bool, const std::string&) { DetachEvent(I_OnPreCommand); return MOD_RES_PASSTHRU; }
107 void            Module::OnPostCommand(Command*, const std::vector<std::string>&, LocalUser*, CmdResult, const std::string&) { DetachEvent(I_OnPostCommand); }
108 void            Module::OnUserInit(LocalUser*) { DetachEvent(I_OnUserInit); }
109 ModResult       Module::OnCheckReady(LocalUser*) { DetachEvent(I_OnCheckReady); return MOD_RES_PASSTHRU; }
110 ModResult       Module::OnUserRegister(LocalUser*) { DetachEvent(I_OnUserRegister); return MOD_RES_PASSTHRU; }
111 ModResult       Module::OnUserPreKick(User*, Membership*, const std::string&) { DetachEvent(I_OnUserPreKick); return MOD_RES_PASSTHRU; }
112 void            Module::OnUserKick(User*, Membership*, const std::string&, CUList&) { DetachEvent(I_OnUserKick); }
113 ModResult       Module::OnRawMode(User*, Channel*, ModeHandler*, const std::string&, bool) { DetachEvent(I_OnRawMode); return MOD_RES_PASSTHRU; }
114 ModResult       Module::OnCheckInvite(User*, Channel*) { DetachEvent(I_OnCheckInvite); return MOD_RES_PASSTHRU; }
115 ModResult       Module::OnCheckKey(User*, Channel*, const std::string&) { DetachEvent(I_OnCheckKey); return MOD_RES_PASSTHRU; }
116 ModResult       Module::OnCheckLimit(User*, Channel*) { DetachEvent(I_OnCheckLimit); return MOD_RES_PASSTHRU; }
117 ModResult       Module::OnCheckChannelBan(User*, Channel*) { DetachEvent(I_OnCheckChannelBan); return MOD_RES_PASSTHRU; }
118 ModResult       Module::OnCheckBan(User*, Channel*, const std::string&) { DetachEvent(I_OnCheckBan); return MOD_RES_PASSTHRU; }
119 ModResult       Module::OnExtBanCheck(User*, Channel*, char) { DetachEvent(I_OnExtBanCheck); return MOD_RES_PASSTHRU; }
120 ModResult       Module::OnStats(char, User*, string_list&) { DetachEvent(I_OnStats); return MOD_RES_PASSTHRU; }
121 ModResult       Module::OnChangeLocalUserHost(LocalUser*, const std::string&) { DetachEvent(I_OnChangeLocalUserHost); return MOD_RES_PASSTHRU; }
122 ModResult       Module::OnChangeLocalUserGECOS(LocalUser*, const std::string&) { DetachEvent(I_OnChangeLocalUserGECOS); return MOD_RES_PASSTHRU; }
123 ModResult       Module::OnPreTopicChange(User*, Channel*, const std::string&) { DetachEvent(I_OnPreTopicChange); return MOD_RES_PASSTHRU; }
124 void            Module::OnEvent(Event&) { DetachEvent(I_OnEvent); }
125 ModResult       Module::OnPassCompare(Extensible* ex, const std::string &password, const std::string &input, const std::string& hashtype) { DetachEvent(I_OnPassCompare); return MOD_RES_PASSTHRU; }
126 void            Module::OnGlobalOper(User*) { DetachEvent(I_OnGlobalOper); }
127 void            Module::OnPostConnect(User*) { DetachEvent(I_OnPostConnect); }
128 void            Module::OnUserMessage(User*, void*, int, const std::string&, char, const CUList&, MessageType) { DetachEvent(I_OnUserMessage); }
129 void            Module::OnUserInvite(User*, User*, Channel*, time_t) { DetachEvent(I_OnUserInvite); }
130 void            Module::OnPostTopicChange(User*, Channel*, const std::string&) { DetachEvent(I_OnPostTopicChange); }
131 void            Module::OnSyncUser(User*, ProtocolInterface::Server&) { DetachEvent(I_OnSyncUser); }
132 void            Module::OnSyncChannel(Channel*, ProtocolInterface::Server&) { DetachEvent(I_OnSyncChannel); }
133 void            Module::OnSyncNetwork(ProtocolInterface::Server&) { DetachEvent(I_OnSyncNetwork); }
134 void            Module::OnDecodeMetaData(Extensible*, const std::string&, const std::string&) { DetachEvent(I_OnDecodeMetaData); }
135 void            Module::OnChangeHost(User*, const std::string&) { DetachEvent(I_OnChangeHost); }
136 void            Module::OnChangeName(User*, const std::string&) { DetachEvent(I_OnChangeName); }
137 void            Module::OnChangeIdent(User*, const std::string&) { DetachEvent(I_OnChangeIdent); }
138 void            Module::OnAddLine(User*, XLine*) { DetachEvent(I_OnAddLine); }
139 void            Module::OnDelLine(User*, XLine*) { DetachEvent(I_OnDelLine); }
140 void            Module::OnExpireLine(XLine*) { DetachEvent(I_OnExpireLine); }
141 void            Module::OnCleanup(int, void*) { }
142 ModResult       Module::OnChannelPreDelete(Channel*) { DetachEvent(I_OnChannelPreDelete); return MOD_RES_PASSTHRU; }
143 void            Module::OnChannelDelete(Channel*) { DetachEvent(I_OnChannelDelete); }
144 ModResult       Module::OnSetAway(User*, const std::string &) { DetachEvent(I_OnSetAway); return MOD_RES_PASSTHRU; }
145 ModResult       Module::OnWhoisLine(User*, User*, int&, std::string&) { DetachEvent(I_OnWhoisLine); return MOD_RES_PASSTHRU; }
146 void            Module::OnBuildNeighborList(User*, IncludeChanList&, std::map<User*,bool>&) { DetachEvent(I_OnBuildNeighborList); }
147 void            Module::OnGarbageCollect() { DetachEvent(I_OnGarbageCollect); }
148 ModResult       Module::OnSetConnectClass(LocalUser* user, ConnectClass* myclass) { DetachEvent(I_OnSetConnectClass); return MOD_RES_PASSTHRU; }
149 void            Module::OnText(User*, void*, int, const std::string&, char, CUList&) { DetachEvent(I_OnText); }
150 ModResult       Module::OnNamesListItem(User*, Membership*, std::string&, std::string&) { DetachEvent(I_OnNamesListItem); return MOD_RES_PASSTHRU; }
151 ModResult       Module::OnNumeric(User*, unsigned int, const std::string&) { DetachEvent(I_OnNumeric); return MOD_RES_PASSTHRU; }
152 ModResult   Module::OnAcceptConnection(int, ListenSocket*, irc::sockets::sockaddrs*, irc::sockets::sockaddrs*) { DetachEvent(I_OnAcceptConnection); return MOD_RES_PASSTHRU; }
153 void            Module::OnSendWhoLine(User*, const std::vector<std::string>&, User*, Membership*, std::string&) { DetachEvent(I_OnSendWhoLine); }
154 void            Module::OnSetUserIP(LocalUser*) { DetachEvent(I_OnSetUserIP); }
155
156 #ifdef INSPIRCD_ENABLE_TESTSUITE
157 void            Module::OnRunTestSuite() { }
158 #endif
159
160 ServiceProvider::ServiceProvider(Module* Creator, const std::string& Name, ServiceType Type)
161         : creator(Creator), name(Name), service(Type)
162 {
163         if ((ServerInstance) && (ServerInstance->Modules->NewServices))
164                 ServerInstance->Modules->NewServices->push_back(this);
165 }
166
167 void ServiceProvider::DisableAutoRegister()
168 {
169         if ((ServerInstance) && (ServerInstance->Modules->NewServices))
170         {
171                 ModuleManager::ServiceList& list = *ServerInstance->Modules->NewServices;
172                 ModuleManager::ServiceList::iterator it = std::find(list.begin(), list.end(), this);
173                 if (it != list.end())
174                         list.erase(it);
175         }
176 }
177
178 ModuleManager::ModuleManager()
179 {
180 }
181
182 ModuleManager::~ModuleManager()
183 {
184 }
185
186 bool ModuleManager::Attach(Implementation i, Module* mod)
187 {
188         if (std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod) != EventHandlers[i].end())
189                 return false;
190
191         EventHandlers[i].push_back(mod);
192         return true;
193 }
194
195 bool ModuleManager::Detach(Implementation i, Module* mod)
196 {
197         EventHandlerIter x = std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod);
198
199         if (x == EventHandlers[i].end())
200                 return false;
201
202         EventHandlers[i].erase(x);
203         return true;
204 }
205
206 void ModuleManager::Attach(Implementation* i, Module* mod, size_t sz)
207 {
208         for (size_t n = 0; n < sz; ++n)
209                 Attach(i[n], mod);
210 }
211
212 void ModuleManager::AttachAll(Module* mod)
213 {
214         for (size_t i = I_BEGIN + 1; i != I_END; ++i)
215                 Attach((Implementation)i, mod);
216 }
217
218 void ModuleManager::DetachAll(Module* mod)
219 {
220         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
221                 Detach((Implementation)n, mod);
222 }
223
224 bool ModuleManager::SetPriority(Module* mod, Priority s)
225 {
226         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
227                 SetPriority(mod, (Implementation)n, s);
228
229         return true;
230 }
231
232 bool ModuleManager::SetPriority(Module* mod, Implementation i, Priority s, Module* which)
233 {
234         /** To change the priority of a module, we first find its position in the vector,
235          * then we find the position of the other modules in the vector that this module
236          * wants to be before/after. We pick off either the first or last of these depending
237          * on which they want, and we make sure our module is *at least* before or after
238          * the first or last of this subset, depending again on the type of priority.
239          */
240         size_t my_pos = 0;
241
242         /* Locate our module. This is O(n) but it only occurs on module load so we're
243          * not too bothered about it
244          */
245         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
246         {
247                 if (EventHandlers[i][x] == mod)
248                 {
249                         my_pos = x;
250                         goto found_src;
251                 }
252         }
253
254         /* Eh? this module doesnt exist, probably trying to set priority on an event
255          * theyre not attached to.
256          */
257         return false;
258
259 found_src:
260         // The modules registered for a hook are called in reverse order (to allow for easier removal
261         // of list entries while looping), meaning that the Priority given to us has the exact opposite effect
262         // on the list, e.g.: PRIORITY_BEFORE will actually put 'mod' after 'which', etc.
263         size_t swap_pos = my_pos;
264         switch (s)
265         {
266                 case PRIORITY_LAST:
267                         if (prioritizationState != PRIO_STATE_FIRST)
268                                 return true;
269                         else
270                                 swap_pos = 0;
271                         break;
272                 case PRIORITY_FIRST:
273                         if (prioritizationState != PRIO_STATE_FIRST)
274                                 return true;
275                         else
276                                 swap_pos = EventHandlers[i].size() - 1;
277                         break;
278                 case PRIORITY_BEFORE:
279                 {
280                         /* Find the latest possible position, only searching AFTER our position */
281                         for (size_t x = EventHandlers[i].size() - 1; x > my_pos; --x)
282                         {
283                                 if (EventHandlers[i][x] == which)
284                                 {
285                                         swap_pos = x;
286                                         goto swap_now;
287                                 }
288                         }
289                         // didn't find it - either not loaded or we're already after
290                         return true;
291                 }
292                 /* Place this module before a set of other modules */
293                 case PRIORITY_AFTER:
294                 {
295                         for (size_t x = 0; x < my_pos; ++x)
296                         {
297                                 if (EventHandlers[i][x] == which)
298                                 {
299                                         swap_pos = x;
300                                         goto swap_now;
301                                 }
302                         }
303                         // didn't find it - either not loaded or we're already before
304                         return true;
305                 }
306         }
307
308 swap_now:
309         /* Do we need to swap? */
310         if (swap_pos != my_pos)
311         {
312                 // We are going to change positions; we'll need to run again to verify all requirements
313                 if (prioritizationState == PRIO_STATE_LAST)
314                         prioritizationState = PRIO_STATE_AGAIN;
315                 /* Suggestion from Phoenix, "shuffle" the modules to better retain call order */
316                 int incrmnt = 1;
317
318                 if (my_pos > swap_pos)
319                         incrmnt = -1;
320
321                 for (unsigned int j = my_pos; j != swap_pos; j += incrmnt)
322                 {
323                         if ((j + incrmnt > EventHandlers[i].size() - 1) || ((incrmnt == -1) && (j == 0)))
324                                 continue;
325
326                         std::swap(EventHandlers[i][j], EventHandlers[i][j+incrmnt]);
327                 }
328         }
329
330         return true;
331 }
332
333 bool ModuleManager::PrioritizeHooks()
334 {
335         /* We give every module a chance to re-prioritize when we introduce a new one,
336          * not just the one thats loading, as the new module could affect the preference
337          * of others
338          */
339         for (int tries = 0; tries < 20; tries++)
340         {
341                 prioritizationState = tries > 0 ? PRIO_STATE_LAST : PRIO_STATE_FIRST;
342                 for (std::map<std::string, Module*>::iterator n = Modules.begin(); n != Modules.end(); ++n)
343                         n->second->Prioritize();
344
345                 if (prioritizationState == PRIO_STATE_LAST)
346                         break;
347                 if (tries == 19)
348                 {
349                         ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, "Hook priority dependency loop detected");
350                         return false;
351                 }
352         }
353         return true;
354 }
355
356 bool ModuleManager::CanUnload(Module* mod)
357 {
358         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
359
360         if ((modfind == Modules.end()) || (modfind->second != mod) || (mod->dying))
361         {
362                 LastModuleError = "Module " + mod->ModuleSourceFile + " is not loaded, cannot unload it!";
363                 ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, LastModuleError);
364                 return false;
365         }
366         if (mod->GetVersion().Flags & VF_STATIC)
367         {
368                 LastModuleError = "Module " + mod->ModuleSourceFile + " not unloadable (marked static)";
369                 ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, LastModuleError);
370                 return false;
371         }
372
373         mod->dying = true;
374         return true;
375 }
376
377 void ModuleManager::DoSafeUnload(Module* mod)
378 {
379         // First, notify all modules that a module is about to be unloaded, so in case
380         // they pass execution to the soon to be unloaded module, it will happen now,
381         // i.e. before we unregister the services of the module being unloaded
382         FOREACH_MOD(OnUnloadModule, (mod));
383
384         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
385
386         std::vector<reference<ExtensionItem> > items;
387         ServerInstance->Extensions.BeginUnregister(modfind->second, items);
388         /* Give the module a chance to tidy out all its metadata */
389         const chan_hash& chans = ServerInstance->GetChans();
390         for (chan_hash::const_iterator c = chans.begin(); c != chans.end(); )
391         {
392                 Channel* chan = c->second;
393                 ++c;
394                 mod->OnCleanup(TYPE_CHANNEL, chan);
395                 chan->doUnhookExtensions(items);
396                 const UserMembList* users = chan->GetUsers();
397                 for(UserMembCIter mi = users->begin(); mi != users->end(); mi++)
398                         mi->second->doUnhookExtensions(items);
399         }
400
401         const user_hash& users = ServerInstance->Users->GetUsers();
402         for (user_hash::const_iterator u = users.begin(); u != users.end(); )
403         {
404                 User* user = u->second;
405                 // The module may quit the user (e.g. SSL mod unloading) and that will remove it from the container
406                 ++u;
407                 mod->OnCleanup(TYPE_USER, user);
408                 user->doUnhookExtensions(items);
409         }
410
411         const ModeParser::ModeHandlerMap& usermodes = ServerInstance->Modes->GetModes(MODETYPE_USER);
412         for (ModeParser::ModeHandlerMap::const_iterator i = usermodes.begin(); i != usermodes.end(); )
413         {
414                 ModeHandler* mh = i->second;
415                 ++i;
416                 if (mh->creator == mod)
417                         this->DelService(*mh);
418         }
419
420         const ModeParser::ModeHandlerMap& chanmodes = ServerInstance->Modes->GetModes(MODETYPE_CHANNEL);
421         for (ModeParser::ModeHandlerMap::const_iterator i = chanmodes.begin(); i != chanmodes.end(); )
422         {
423                 ModeHandler* mh = i->second;
424                 ++i;
425                 if (mh->creator == mod)
426                         this->DelService(*mh);
427         }
428
429         for(std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.begin(); i != DataProviders.end(); )
430         {
431                 std::multimap<std::string, ServiceProvider*>::iterator curr = i++;
432                 if (curr->second->creator == mod)
433                         DataProviders.erase(curr);
434         }
435
436         dynamic_reference_base::reset_all();
437
438         DetachAll(mod);
439
440         Modules.erase(modfind);
441         ServerInstance->GlobalCulls.AddItem(mod);
442
443         ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, "Module %s unloaded",mod->ModuleSourceFile.c_str());
444         ServerInstance->ISupport.Build();
445 }
446
447 void ModuleManager::UnloadAll()
448 {
449         /* We do this more than once, so that any service providers get a
450          * chance to be unhooked by the modules using them, but then get
451          * a chance to be removed themsleves.
452          *
453          * Note: this deliberately does NOT delete the DLLManager objects
454          */
455         for (int tries = 0; tries < 4; tries++)
456         {
457                 std::map<std::string, Module*>::iterator i = Modules.begin();
458                 while (i != Modules.end())
459                 {
460                         std::map<std::string, Module*>::iterator me = i++;
461                         if (CanUnload(me->second))
462                         {
463                                 DoSafeUnload(me->second);
464                         }
465                 }
466                 ServerInstance->GlobalCulls.Apply();
467         }
468 }
469
470 namespace
471 {
472         struct UnloadAction : public HandlerBase0<void>
473         {
474                 Module* const mod;
475                 UnloadAction(Module* m) : mod(m) {}
476                 void Call()
477                 {
478                         DLLManager* dll = mod->ModuleDLLManager;
479                         ServerInstance->Modules->DoSafeUnload(mod);
480                         ServerInstance->GlobalCulls.Apply();
481                         // In pure static mode this is always NULL
482                         delete dll;
483                         ServerInstance->GlobalCulls.AddItem(this);
484                 }
485         };
486
487         struct ReloadAction : public HandlerBase0<void>
488         {
489                 Module* const mod;
490                 HandlerBase1<void, bool>* const callback;
491                 ReloadAction(Module* m, HandlerBase1<void, bool>* c)
492                         : mod(m), callback(c) {}
493                 void Call()
494                 {
495                         DLLManager* dll = mod->ModuleDLLManager;
496                         std::string name = mod->ModuleSourceFile;
497                         ServerInstance->Modules->DoSafeUnload(mod);
498                         ServerInstance->GlobalCulls.Apply();
499                         delete dll;
500                         bool rv = ServerInstance->Modules->Load(name);
501                         if (callback)
502                                 callback->Call(rv);
503                         ServerInstance->GlobalCulls.AddItem(this);
504                 }
505         };
506 }
507
508 bool ModuleManager::Unload(Module* mod)
509 {
510         if (!CanUnload(mod))
511                 return false;
512         ServerInstance->AtomicActions.AddAction(new UnloadAction(mod));
513         return true;
514 }
515
516 void ModuleManager::Reload(Module* mod, HandlerBase1<void, bool>* callback)
517 {
518         if (CanUnload(mod))
519                 ServerInstance->AtomicActions.AddAction(new ReloadAction(mod, callback));
520         else
521                 callback->Call(false);
522 }
523
524 void ModuleManager::LoadAll()
525 {
526         std::map<std::string, ServiceList> servicemap;
527         LoadCoreModules(servicemap);
528
529         ConfigTagList tags = ServerInstance->Config->ConfTags("module");
530         for (ConfigIter i = tags.first; i != tags.second; ++i)
531         {
532                 ConfigTag* tag = i->second;
533                 std::string name = tag->getString("name");
534                 this->NewServices = &servicemap[name];
535                 std::cout << "[" << con_green << "*" << con_reset << "] Loading module:\t" << con_green << name << con_reset << std::endl;
536
537                 if (!this->Load(name, true))
538                 {
539                         ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, this->LastError());
540                         std::cout << std::endl << "[" << con_red << "*" << con_reset << "] " << this->LastError() << std::endl << std::endl;
541                         ServerInstance->Exit(EXIT_STATUS_MODULE);
542                 }
543         }
544
545         ConfigStatus confstatus;
546
547         for (ModuleMap::const_iterator i = Modules.begin(); i != Modules.end(); ++i)
548         {
549                 Module* mod = i->second;
550                 try
551                 {
552                         ServerInstance->Logs->Log("MODULE", LOG_DEBUG, "Initializing %s", i->first.c_str());
553                         AttachAll(mod);
554                         AddServices(servicemap[i->first]);
555                         mod->init();
556                         mod->ReadConfig(confstatus);
557                 }
558                 catch (CoreException& modexcept)
559                 {
560                         LastModuleError = "Unable to initialize " + mod->ModuleSourceFile + ": " + modexcept.GetReason();
561                         ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, LastModuleError);
562                         std::cout << std::endl << "[" << con_red << "*" << con_reset << "] " << LastModuleError << std::endl << std::endl;
563                         ServerInstance->Exit(EXIT_STATUS_MODULE);
564                 }
565         }
566
567         this->NewServices = NULL;
568
569         if (!PrioritizeHooks())
570                 ServerInstance->Exit(EXIT_STATUS_MODULE);
571 }
572
573 std::string& ModuleManager::LastError()
574 {
575         return LastModuleError;
576 }
577
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
587 void ModuleManager::AddService(ServiceProvider& item)
588 {
589         switch (item.service)
590         {
591                 case SERVICE_COMMAND:
592                         if (!ServerInstance->Parser.AddCommand(static_cast<Command*>(&item)))
593                                 throw ModuleException("Command "+std::string(item.name)+" already exists.");
594                         return;
595                 case SERVICE_MODE:
596                 {
597                         ModeHandler* mh = static_cast<ModeHandler*>(&item);
598                         ServerInstance->Modes->AddMode(mh);
599                         DataProviders.insert(std::make_pair((mh->GetModeType() == MODETYPE_CHANNEL ? "mode/" : "umode/") + item.name, &item));
600                         dynamic_reference_base::reset_all();
601                         return;
602                 }
603                 case SERVICE_METADATA:
604                         if (!ServerInstance->Extensions.Register(static_cast<ExtensionItem*>(&item)))
605                                 throw ModuleException("Extension " + std::string(item.name) + " already exists.");
606                         return;
607                 case SERVICE_DATA:
608                 case SERVICE_IOHOOK:
609                 {
610                         if ((!item.name.compare(0, 5, "mode/", 5)) || (!item.name.compare(0, 6, "umode/", 6)))
611                                 throw ModuleException("The \"mode/\" and the \"umode\" service name prefixes are reserved.");
612
613                         DataProviders.insert(std::make_pair(item.name, &item));
614                         std::string::size_type slash = item.name.find('/');
615                         if (slash != std::string::npos)
616                         {
617                                 DataProviders.insert(std::make_pair(item.name.substr(0, slash), &item));
618                                 DataProviders.insert(std::make_pair(item.name.substr(slash + 1), &item));
619                         }
620                         dynamic_reference_base::reset_all();
621                         return;
622                 }
623                 default:
624                         throw ModuleException("Cannot add unknown service type");
625         }
626 }
627
628 void ModuleManager::DelService(ServiceProvider& item)
629 {
630         switch (item.service)
631         {
632                 case SERVICE_MODE:
633                         if (!ServerInstance->Modes->DelMode(static_cast<ModeHandler*>(&item)))
634                                 throw ModuleException("Mode "+std::string(item.name)+" does not exist.");
635                         // Fall through
636                 case SERVICE_DATA:
637                 case SERVICE_IOHOOK:
638                 {
639                         for(std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.begin(); i != DataProviders.end(); )
640                         {
641                                 std::multimap<std::string, ServiceProvider*>::iterator curr = i++;
642                                 if (curr->second == &item)
643                                         DataProviders.erase(curr);
644                         }
645                         dynamic_reference_base::reset_all();
646                         return;
647                 }
648                 default:
649                         throw ModuleException("Cannot delete unknown service type");
650         }
651 }
652
653 ServiceProvider* ModuleManager::FindService(ServiceType type, const std::string& name)
654 {
655         switch (type)
656         {
657                 case SERVICE_DATA:
658                 case SERVICE_IOHOOK:
659                 {
660                         std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.find(name);
661                         if (i != DataProviders.end() && i->second->service == type)
662                                 return i->second;
663                         return NULL;
664                 }
665                 // TODO implement finding of the other types
666                 default:
667                         throw ModuleException("Cannot find unknown service type");
668         }
669 }
670
671 dynamic_reference_base::dynamic_reference_base(Module* Creator, const std::string& Name)
672         : name(Name), value(NULL), creator(Creator)
673 {
674         if (!dynrefs)
675                 dynrefs = new intrusive_list<dynamic_reference_base>;
676         dynrefs->push_front(this);
677         if (dynref_init_complete)
678                 resolve();
679 }
680
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
691 void dynamic_reference_base::SetProvider(const std::string& newname)
692 {
693         name = newname;
694         resolve();
695 }
696
697 void dynamic_reference_base::resolve()
698 {
699         std::multimap<std::string, ServiceProvider*>::iterator i = ServerInstance->Modules->DataProviders.find(name);
700         if (i != ServerInstance->Modules->DataProviders.end())
701                 value = static_cast<DataProvider*>(i->second);
702         else
703                 value = NULL;
704 }
705
706 Module* ModuleManager::Find(const std::string &name)
707 {
708         std::map<std::string, Module*>::iterator modfind = Modules.find(name);
709
710         if (modfind == Modules.end())
711                 return NULL;
712         else
713                 return modfind->second;
714 }