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