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