]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules.cpp
a7b3364ae1c919ba5b075837ea087ef86e75e630
[user/henk/code/inspircd.git] / src / modules.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2007, 2009 Dennis Friis <peavey@inspircd.org>
6  *   Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
7  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
8  *   Copyright (C) 2006-2007 Robin Burchell <robin+git@viroteck.net>
9  *   Copyright (C) 2006-2007 Oliver Lupton <oliverlupton@gmail.com>
10  *   Copyright (C) 2007 Pippijn van Steenhoven <pip88nl@gmail.com>
11  *   Copyright (C) 2003 randomdan <???@???>
12  *
13  * This file is part of InspIRCd.  InspIRCd is free software: you can
14  * redistribute it and/or modify it under the terms of the GNU General Public
15  * License as published by the Free Software Foundation, version 2.
16  *
17  * This program is distributed in the hope that it will be useful, but WITHOUT
18  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
20  * details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24  */
25
26
27 #include "inspircd.h"
28 #include "xline.h"
29 #include "socket.h"
30 #include "socketengine.h"
31 #include "command_parse.h"
32 #include "dns.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
41 void dynamic_reference_base::reset_all()
42 {
43         if (!dynrefs)
44                 return;
45         for(unsigned int i = 0; i < dynrefs->size(); i++)
46                 (*dynrefs)[i]->ClearCache();
47 }
48
49 // Version is a simple class for holding a modules version number
50 Version::Version(const std::string &desc, int flags) : description(desc), Flags(flags)
51 {
52 }
53
54 Version::Version(const std::string &desc, int flags, const std::string& linkdata)
55 : description(desc), Flags(flags), link_data(linkdata)
56 {
57 }
58
59 Request::Request(Module* src, Module* dst, const char* idstr)
60 : id(idstr), source(src), dest(dst)
61 {
62 }
63
64 void Request::Send()
65 {
66         if (dest)
67                 dest->OnRequest(*this);
68 }
69
70 Event::Event(Module* src, const std::string &eventid) : source(src), id(eventid) { }
71
72 void Event::Send()
73 {
74         FOREACH_MOD(I_OnEvent,OnEvent(*this));
75 }
76
77 // These declarations define the behavours of the base class Module (which does nothing at all)
78
79 Module::Module() { }
80 CullResult Module::cull()
81 {
82         return classbase::cull();
83 }
84 Module::~Module()
85 {
86 }
87
88 ModResult       Module::OnSendSnotice(char &snomask, std::string &type, const std::string &message) { return MOD_RES_PASSTHRU; }
89 void            Module::OnUserConnect(LocalUser*) { }
90 void            Module::OnUserQuit(User*, const std::string&, const std::string&) { }
91 void            Module::OnUserDisconnect(LocalUser*) { }
92 void            Module::OnUserJoin(Membership*, bool, bool, CUList&) { }
93 void            Module::OnPostJoin(Membership*) { }
94 void            Module::OnUserPart(Membership*, std::string&, CUList&) { }
95 void            Module::OnPreRehash(User*, const std::string&) { }
96 void            Module::OnModuleRehash(User*, const std::string&) { }
97 void            Module::OnRehash(User*) { }
98 ModResult       Module::OnUserPreJoin(User*, Channel*, const char*, std::string&, const std::string&) { return MOD_RES_PASSTHRU; }
99 void            Module::OnMode(User*, void*, int, const std::vector<std::string>&, const std::vector<TranslateType>&) { }
100 void            Module::OnOper(User*, const std::string&) { }
101 void            Module::OnPostOper(User*, const std::string&, const std::string &) { }
102 void            Module::OnInfo(User*) { }
103 void            Module::OnWhois(User*, User*) { }
104 ModResult       Module::OnUserPreInvite(User*, User*, Channel*, time_t) { return MOD_RES_PASSTHRU; }
105 ModResult       Module::OnUserPreMessage(User*, void*, int, std::string&, char, CUList&) { return MOD_RES_PASSTHRU; }
106 ModResult       Module::OnUserPreNotice(User*, void*, int, std::string&, char, CUList&) { return MOD_RES_PASSTHRU; }
107 ModResult       Module::OnUserPreNick(User*, const std::string&) { return MOD_RES_PASSTHRU; }
108 void            Module::OnUserPostNick(User*, const std::string&) { }
109 ModResult       Module::OnPreMode(User*, User*, Channel*, const std::vector<std::string>&) { return MOD_RES_PASSTHRU; }
110 void            Module::On005Numeric(std::string&) { }
111 ModResult       Module::OnKill(User*, User*, const std::string&) { return MOD_RES_PASSTHRU; }
112 void            Module::OnLoadModule(Module*) { }
113 void            Module::OnUnloadModule(Module*) { }
114 void            Module::OnBackgroundTimer(time_t) { }
115 ModResult       Module::OnPreCommand(std::string&, std::vector<std::string>&, LocalUser*, bool, const std::string&) { return MOD_RES_PASSTHRU; }
116 void            Module::OnPostCommand(const std::string&, const std::vector<std::string>&, LocalUser*, CmdResult, const std::string&) { }
117 void            Module::OnUserInit(LocalUser*) { }
118 ModResult       Module::OnCheckReady(LocalUser*) { return MOD_RES_PASSTHRU; }
119 ModResult       Module::OnUserRegister(LocalUser*) { return MOD_RES_PASSTHRU; }
120 ModResult       Module::OnUserPreKick(User*, Membership*, const std::string&) { return MOD_RES_PASSTHRU; }
121 void            Module::OnUserKick(User*, Membership*, const std::string&, CUList&) { }
122 ModResult       Module::OnRawMode(User*, Channel*, const char, const std::string &, bool, int) { return MOD_RES_PASSTHRU; }
123 ModResult       Module::OnCheckInvite(User*, Channel*) { return MOD_RES_PASSTHRU; }
124 ModResult       Module::OnCheckKey(User*, Channel*, const std::string&) { return MOD_RES_PASSTHRU; }
125 ModResult       Module::OnCheckLimit(User*, Channel*) { return MOD_RES_PASSTHRU; }
126 ModResult       Module::OnCheckChannelBan(User*, Channel*) { return MOD_RES_PASSTHRU; }
127 ModResult       Module::OnCheckBan(User*, Channel*, const std::string&) { return MOD_RES_PASSTHRU; }
128 ModResult       Module::OnExtBanCheck(User*, Channel*, char) { return MOD_RES_PASSTHRU; }
129 ModResult       Module::OnStats(char, User*, string_list&) { return MOD_RES_PASSTHRU; }
130 ModResult       Module::OnChangeLocalUserHost(LocalUser*, const std::string&) { return MOD_RES_PASSTHRU; }
131 ModResult       Module::OnChangeLocalUserGECOS(LocalUser*, const std::string&) { return MOD_RES_PASSTHRU; }
132 ModResult       Module::OnPreTopicChange(User*, Channel*, const std::string&) { return MOD_RES_PASSTHRU; }
133 void            Module::OnEvent(Event&) { }
134 void            Module::OnRequest(Request&) { }
135 ModResult       Module::OnPassCompare(Extensible* ex, const std::string &password, const std::string &input, const std::string& hashtype) { return MOD_RES_PASSTHRU; }
136 void            Module::OnGlobalOper(User*) { }
137 void            Module::OnPostConnect(User*) { }
138 ModResult       Module::OnAddBan(User*, Channel*, const std::string &) { return MOD_RES_PASSTHRU; }
139 ModResult       Module::OnDelBan(User*, Channel*, const std::string &) { return MOD_RES_PASSTHRU; }
140 void            Module::OnStreamSocketAccept(StreamSocket*, irc::sockets::sockaddrs*, irc::sockets::sockaddrs*) { }
141 int             Module::OnStreamSocketWrite(StreamSocket*, std::string&) { return -1; }
142 void            Module::OnStreamSocketClose(StreamSocket*) { }
143 void            Module::OnStreamSocketConnect(StreamSocket*) { }
144 int             Module::OnStreamSocketRead(StreamSocket*, std::string&) { return -1; }
145 void            Module::OnUserMessage(User*, void*, int, const std::string&, char, const CUList&) { }
146 void            Module::OnUserNotice(User*, void*, int, const std::string&, char, const CUList&) { }
147 void            Module::OnRemoteKill(User*, User*, const std::string&, const std::string&) { }
148 void            Module::OnUserInvite(User*, User*, Channel*, time_t) { }
149 void            Module::OnPostTopicChange(User*, Channel*, const std::string&) { }
150 void            Module::OnGetServerDescription(const std::string&, std::string&) { }
151 void            Module::OnSyncUser(User*, Module*, void*) { }
152 void            Module::OnSyncChannel(Channel*, Module*, void*) { }
153 void            Module::OnSyncNetwork(Module*, void*) { }
154 void            Module::ProtoSendMode(void*, TargetTypeFlags, void*, const std::vector<std::string>&, const std::vector<TranslateType>&) { }
155 void            Module::OnDecodeMetaData(Extensible*, const std::string&, const std::string&) { }
156 void            Module::ProtoSendMetaData(void*, Extensible*, const std::string&, const std::string&) { }
157 void            Module::OnWallops(User*, const std::string&) { }
158 void            Module::OnChangeHost(User*, const std::string&) { }
159 void            Module::OnChangeName(User*, const std::string&) { }
160 void            Module::OnChangeIdent(User*, const std::string&) { }
161 void            Module::OnAddLine(User*, XLine*) { }
162 void            Module::OnDelLine(User*, XLine*) { }
163 void            Module::OnExpireLine(XLine*) { }
164 void            Module::OnCleanup(int, void*) { }
165 ModResult       Module::OnChannelPreDelete(Channel*) { return MOD_RES_PASSTHRU; }
166 void            Module::OnChannelDelete(Channel*) { }
167 ModResult       Module::OnSetAway(User*, const std::string &) { return MOD_RES_PASSTHRU; }
168 ModResult       Module::OnWhoisLine(User*, User*, int&, std::string&) { return MOD_RES_PASSTHRU; }
169 void            Module::OnBuildNeighborList(User*, UserChanList&, std::map<User*,bool>&) { }
170 void            Module::OnGarbageCollect() { }
171 ModResult       Module::OnSetConnectClass(LocalUser* user, ConnectClass* myclass) { return MOD_RES_PASSTHRU; }
172 void            Module::OnText(User*, void*, int, const std::string&, char, CUList&) { }
173 void            Module::OnRunTestSuite() { }
174 void            Module::OnNamesListItem(User*, Membership*, std::string&, std::string&) { }
175 ModResult       Module::OnNumeric(User*, unsigned int, const std::string&) { return MOD_RES_PASSTHRU; }
176 void            Module::OnHookIO(StreamSocket*, ListenSocket*) { }
177 ModResult   Module::OnAcceptConnection(int, ListenSocket*, irc::sockets::sockaddrs*, irc::sockets::sockaddrs*) { return MOD_RES_PASSTHRU; }
178 void            Module::OnSendWhoLine(User*, const std::vector<std::string>&, User*, std::string&) { }
179 void            Module::OnSetUserIP(LocalUser*) { }
180
181 ModuleManager::ModuleManager() : ModCount(0)
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::DetachAll(Module* mod)
216 {
217         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
218                 Detach((Implementation)n, mod);
219 }
220
221 bool ModuleManager::SetPriority(Module* mod, Priority s)
222 {
223         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
224                 SetPriority(mod, (Implementation)n, s);
225
226         return true;
227 }
228
229 bool ModuleManager::SetPriority(Module* mod, Implementation i, Priority s, Module* which)
230 {
231         /** To change the priority of a module, we first find its position in the vector,
232          * then we find the position of the other modules in the vector that this module
233          * wants to be before/after. We pick off either the first or last of these depending
234          * on which they want, and we make sure our module is *at least* before or after
235          * the first or last of this subset, depending again on the type of priority.
236          */
237         size_t my_pos = 0;
238
239         /* Locate our module. This is O(n) but it only occurs on module load so we're
240          * not too bothered about it
241          */
242         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
243         {
244                 if (EventHandlers[i][x] == mod)
245                 {
246                         my_pos = x;
247                         goto found_src;
248                 }
249         }
250
251         /* Eh? this module doesnt exist, probably trying to set priority on an event
252          * theyre not attached to.
253          */
254         return false;
255
256 found_src:
257         size_t swap_pos = my_pos;
258         switch (s)
259         {
260                 case PRIORITY_FIRST:
261                         if (prioritizationState != PRIO_STATE_FIRST)
262                                 return true;
263                         else
264                                 swap_pos = 0;
265                         break;
266                 case PRIORITY_LAST:
267                         if (prioritizationState != PRIO_STATE_FIRST)
268                                 return true;
269                         else
270                                 swap_pos = EventHandlers[i].size() - 1;
271                         break;
272                 case PRIORITY_AFTER:
273                 {
274                         /* Find the latest possible position, only searching AFTER our position */
275                         for (size_t x = EventHandlers[i].size() - 1; x > my_pos; --x)
276                         {
277                                 if (EventHandlers[i][x] == which)
278                                 {
279                                         swap_pos = x;
280                                         goto swap_now;
281                                 }
282                         }
283                         // didn't find it - either not loaded or we're already after
284                         return true;
285                 }
286                 /* Place this module before a set of other modules */
287                 case PRIORITY_BEFORE:
288                 {
289                         for (size_t x = 0; x < my_pos; ++x)
290                         {
291                                 if (EventHandlers[i][x] == which)
292                                 {
293                                         swap_pos = x;
294                                         goto swap_now;
295                                 }
296                         }
297                         // didn't find it - either not loaded or we're already before
298                         return true;
299                 }
300         }
301
302 swap_now:
303         /* Do we need to swap? */
304         if (swap_pos != my_pos)
305         {
306                 // We are going to change positions; we'll need to run again to verify all requirements
307                 if (prioritizationState == PRIO_STATE_LAST)
308                         prioritizationState = PRIO_STATE_AGAIN;
309                 /* Suggestion from Phoenix, "shuffle" the modules to better retain call order */
310                 int incrmnt = 1;
311
312                 if (my_pos > swap_pos)
313                         incrmnt = -1;
314
315                 for (unsigned int j = my_pos; j != swap_pos; j += incrmnt)
316                 {
317                         if ((j + incrmnt > EventHandlers[i].size() - 1) || ((incrmnt == -1) && (j == 0)))
318                                 continue;
319
320                         std::swap(EventHandlers[i][j], EventHandlers[i][j+incrmnt]);
321                 }
322         }
323
324         return true;
325 }
326
327 bool ModuleManager::CanUnload(Module* mod)
328 {
329         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
330
331         if ((modfind == Modules.end()) || (modfind->second != mod) || (mod->dying))
332         {
333                 LastModuleError = "Module " + mod->ModuleSourceFile + " is not loaded, cannot unload it!";
334                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
335                 return false;
336         }
337         if (mod->GetVersion().Flags & VF_STATIC)
338         {
339                 LastModuleError = "Module " + mod->ModuleSourceFile + " not unloadable (marked static)";
340                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
341                 return false;
342         }
343
344         mod->dying = true;
345         return true;
346 }
347
348 void ModuleManager::DoSafeUnload(Module* mod)
349 {
350         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
351
352         std::vector<reference<ExtensionItem> > items;
353         ServerInstance->Extensions.BeginUnregister(modfind->second, items);
354         /* Give the module a chance to tidy out all its metadata */
355         for (chan_hash::iterator c = ServerInstance->chanlist->begin(); c != ServerInstance->chanlist->end(); c++)
356         {
357                 mod->OnCleanup(TYPE_CHANNEL,c->second);
358                 c->second->doUnhookExtensions(items);
359                 const UserMembList* users = c->second->GetUsers();
360                 for(UserMembCIter mi = users->begin(); mi != users->end(); mi++)
361                         mi->second->doUnhookExtensions(items);
362         }
363         for (user_hash::iterator u = ServerInstance->Users->clientlist->begin(); u != ServerInstance->Users->clientlist->end(); u++)
364         {
365                 mod->OnCleanup(TYPE_USER,u->second);
366                 u->second->doUnhookExtensions(items);
367         }
368         for(char m='A'; m <= 'z'; m++)
369         {
370                 ModeHandler* mh;
371                 mh = ServerInstance->Modes->FindMode(m, MODETYPE_USER);
372                 if (mh && mh->creator == mod)
373                         ServerInstance->Modes->DelMode(mh);
374                 mh = ServerInstance->Modes->FindMode(m, MODETYPE_CHANNEL);
375                 if (mh && mh->creator == mod)
376                         ServerInstance->Modes->DelMode(mh);
377         }
378         for(std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.begin(); i != DataProviders.end(); )
379         {
380                 std::multimap<std::string, ServiceProvider*>::iterator curr = i++;
381                 if (curr->second->creator == mod)
382                         DataProviders.erase(curr);
383         }
384
385         dynamic_reference_base::reset_all();
386
387         /* Tidy up any dangling resolvers */
388         ServerInstance->Res->CleanResolvers(mod);
389
390         FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(mod));
391
392         DetachAll(mod);
393
394         Modules.erase(modfind);
395         ServerInstance->GlobalCulls.AddItem(mod);
396
397         ServerInstance->Logs->Log("MODULE", DEFAULT,"Module %s unloaded",mod->ModuleSourceFile.c_str());
398         this->ModCount--;
399         ServerInstance->BuildISupport();
400 }
401
402 void ModuleManager::UnloadAll()
403 {
404         /* We do this more than once, so that any service providers get a
405          * chance to be unhooked by the modules using them, but then get
406          * a chance to be removed themsleves.
407          *
408          * Note: this deliberately does NOT delete the DLLManager objects
409          */
410         for (int tries = 0; tries < 4; tries++)
411         {
412                 std::map<std::string, Module*>::iterator i = Modules.begin();
413                 while (i != Modules.end())
414                 {
415                         std::map<std::string, Module*>::iterator me = i++;
416                         if (CanUnload(me->second))
417                         {
418                                 DoSafeUnload(me->second);
419                         }
420                 }
421                 ServerInstance->GlobalCulls.Apply();
422         }
423 }
424
425 std::string& ModuleManager::LastError()
426 {
427         return LastModuleError;
428 }
429
430 CmdResult InspIRCd::CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user)
431 {
432         return this->Parser->CallHandler(commandname, parameters, user);
433 }
434
435 bool InspIRCd::IsValidModuleCommand(const std::string &commandname, int pcnt, User* user)
436 {
437         return this->Parser->IsValidCommand(commandname, pcnt, user);
438 }
439
440 void ModuleManager::AddService(ServiceProvider& item)
441 {
442         switch (item.service)
443         {
444                 case SERVICE_COMMAND:
445                         if (!ServerInstance->Parser->AddCommand(static_cast<Command*>(&item)))
446                                 throw ModuleException("Command "+std::string(item.name)+" already exists.");
447                         return;
448                 case SERVICE_MODE:
449                         if (!ServerInstance->Modes->AddMode(static_cast<ModeHandler*>(&item)))
450                                 throw ModuleException("Mode "+std::string(item.name)+" already exists.");
451                         return;
452                 case SERVICE_METADATA:
453                         if (!ServerInstance->Extensions.Register(static_cast<ExtensionItem*>(&item)))
454                                 throw ModuleException("Extension " + std::string(item.name) + " already exists.");
455                         return;
456                 case SERVICE_DATA:
457                 case SERVICE_IOHOOK:
458                 {
459                         DataProviders.insert(std::make_pair(item.name, &item));
460                         std::string::size_type slash = item.name.find('/');
461                         if (slash != std::string::npos)
462                         {
463                                 DataProviders.insert(std::make_pair(item.name.substr(0, slash), &item));
464                                 DataProviders.insert(std::make_pair(item.name.substr(slash + 1), &item));
465                         }
466                         return;
467                 }
468                 default:
469                         throw ModuleException("Cannot add unknown service type");
470         }
471 }
472
473 void ModuleManager::DelService(ServiceProvider& item)
474 {
475         switch (item.service)
476         {
477                 case SERVICE_MODE:
478                         if (!ServerInstance->Modes->DelMode(static_cast<ModeHandler*>(&item)))
479                                 throw ModuleException("Mode "+std::string(item.name)+" does not exist.");
480                         return;
481                 case SERVICE_DATA:
482                 case SERVICE_IOHOOK:
483                 {
484                         for(std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.begin(); i != DataProviders.end(); )
485                         {
486                                 std::multimap<std::string, ServiceProvider*>::iterator curr = i++;
487                                 if (curr->second == &item)
488                                         DataProviders.erase(curr);
489                         }
490                         dynamic_reference_base::reset_all();
491                         return;
492                 }
493                 default:
494                         throw ModuleException("Cannot delete unknown service type");
495         }
496 }
497
498 ServiceProvider* ModuleManager::FindService(ServiceType type, const std::string& name)
499 {
500         switch (type)
501         {
502                 case SERVICE_DATA:
503                 case SERVICE_IOHOOK:
504                 {
505                         std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.find(name);
506                         if (i != DataProviders.end() && i->second->service == type)
507                                 return i->second;
508                         return NULL;
509                 }
510                 // TODO implement finding of the other types
511                 default:
512                         throw ModuleException("Cannot find unknown service type");
513         }
514 }
515
516 dynamic_reference_base::dynamic_reference_base(Module* Creator, const std::string& Name)
517         : name(Name), value(NULL), creator(Creator)
518 {
519         if (!dynrefs)
520                 dynrefs = new std::vector<dynamic_reference_base*>;
521         dynrefs->push_back(this);
522 }
523
524 dynamic_reference_base::~dynamic_reference_base()
525 {
526         for(unsigned int i = 0; i < dynrefs->size(); i++)
527         {
528                 if (dynrefs->at(i) == this)
529                 {
530                         unsigned int last = dynrefs->size() - 1;
531                         if (i != last)
532                                 dynrefs->at(i) = dynrefs->at(last);
533                         dynrefs->erase(dynrefs->begin() + last);
534                         if (dynrefs->empty())
535                         {
536                                 delete dynrefs;
537                                 dynrefs = NULL;
538                         }
539                         return;
540                 }
541         }
542 }
543
544 void dynamic_reference_base::SetProvider(const std::string& newname)
545 {
546         name = newname;
547         ClearCache();
548 }
549
550 void dynamic_reference_base::lookup()
551 {
552         if (!*this)
553                 throw ModuleException("Dynamic reference to '" + name + "' failed to resolve");
554 }
555
556 dynamic_reference_base::operator bool()
557 {
558         if (!value)
559         {
560                 std::multimap<std::string, ServiceProvider*>::iterator i = ServerInstance->Modules->DataProviders.find(name);
561                 if (i != ServerInstance->Modules->DataProviders.end())
562                         value = static_cast<DataProvider*>(i->second);
563         }
564         return (value != NULL);
565 }
566
567 void InspIRCd::SendMode(const std::vector<std::string>& parameters, User *user)
568 {
569         this->Modes->Process(parameters, user);
570 }
571
572
573 void InspIRCd::SendGlobalMode(const std::vector<std::string>& parameters, User *user)
574 {
575         Modes->Process(parameters, user);
576         if (!Modes->GetLastParse().empty())
577                 this->PI->SendMode(parameters[0], Modes->GetLastParseParams(), Modes->GetLastParseTranslate());
578 }
579
580 bool InspIRCd::AddResolver(Resolver* r, bool cached)
581 {
582         if (!cached)
583                 return this->Res->AddResolverClass(r);
584         else
585         {
586                 r->TriggerCachedResult();
587                 delete r;
588                 return true;
589         }
590 }
591
592 Module* ModuleManager::Find(const std::string &name)
593 {
594         std::map<std::string, Module*>::iterator modfind = Modules.find(name);
595
596         if (modfind == Modules.end())
597                 return NULL;
598         else
599                 return modfind->second;
600 }
601
602 const std::vector<std::string> ModuleManager::GetAllModuleNames(int filter)
603 {
604         std::vector<std::string> retval;
605         for (std::map<std::string, Module*>::iterator x = Modules.begin(); x != Modules.end(); ++x)
606                 if (!filter || (x->second->GetVersion().Flags & filter))
607                         retval.push_back(x->first);
608         return retval;
609 }
610
611 ConfigReader::ConfigReader()
612 {
613         this->error = 0;
614         ServerInstance->Logs->Log("MODULE", DEBUG, "ConfigReader is deprecated in 2.0; "
615                 "use ServerInstance->Config->ConfValue(\"key\") or ->ConfTags(\"key\") instead");
616 }
617
618
619 ConfigReader::~ConfigReader()
620 {
621 }
622
623 static ConfigTag* SlowGetTag(const std::string &tag, int index)
624 {
625         ConfigTagList tags = ServerInstance->Config->ConfTags(tag);
626         while (tags.first != tags.second)
627         {
628                 if (!index)
629                         return tags.first->second;
630                 tags.first++;
631                 index--;
632         }
633         return NULL;
634 }
635
636 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool allow_linefeeds)
637 {
638         std::string result = default_value;
639         if (!SlowGetTag(tag, index)->readString(name, result, allow_linefeeds))
640         {
641                 this->error = CONF_VALUE_NOT_FOUND;
642         }
643         return result;
644 }
645
646 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, int index, bool allow_linefeeds)
647 {
648         return ReadValue(tag, name, "", index, allow_linefeeds);
649 }
650
651 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, const std::string &default_value, int index)
652 {
653         bool def = (default_value == "yes");
654         return SlowGetTag(tag, index)->getBool(name, def);
655 }
656
657 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, int index)
658 {
659         return ReadFlag(tag, name, "", index);
660 }
661
662
663 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool need_positive)
664 {
665         int v = atoi(default_value.c_str());
666         int result = SlowGetTag(tag, index)->getInt(name, v);
667
668         if ((need_positive) && (result < 0))
669         {
670                 this->error = CONF_INT_NEGATIVE;
671                 return 0;
672         }
673
674         return result;
675 }
676
677 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, int index, bool need_positive)
678 {
679         return ReadInteger(tag, name, "", index, need_positive);
680 }
681
682 long ConfigReader::GetError()
683 {
684         long olderr = this->error;
685         this->error = 0;
686         return olderr;
687 }
688
689 int ConfigReader::Enumerate(const std::string &tag)
690 {
691         ServerInstance->Logs->Log("MODULE", DEBUG, "Module is using ConfigReader::Enumerate on %s; this is slow!",
692                 tag.c_str());
693         int i=0;
694         while (SlowGetTag(tag, i)) i++;
695         return i;
696 }
697
698 FileReader::FileReader(const std::string &filename)
699 {
700         LoadFile(filename);
701 }
702
703 FileReader::FileReader()
704 {
705 }
706
707 std::string FileReader::Contents()
708 {
709         std::string x;
710         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
711         {
712                 x.append(*a);
713                 x.append("\r\n");
714         }
715         return x;
716 }
717
718 unsigned long FileReader::ContentSize()
719 {
720         return this->contentsize;
721 }
722
723 void FileReader::CalcSize()
724 {
725         unsigned long n = 0;
726         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
727                 n += (a->length() + 2);
728         this->contentsize = n;
729 }
730
731 void FileReader::LoadFile(const std::string &filename)
732 {
733         std::map<std::string, file_cache>::iterator file = ServerInstance->Config->Files.find(filename);
734         if (file != ServerInstance->Config->Files.end())
735         {
736                 this->fc = file->second;
737         }
738         else
739         {
740                 fc.clear();
741                 FILE* f = fopen(filename.c_str(), "r");
742                 if (!f)
743                         return;
744                 char linebuf[MAXBUF*10];
745                 while (fgets(linebuf, sizeof(linebuf), f))
746                 {
747                         int len = strlen(linebuf);
748                         if (len)
749                                 fc.push_back(std::string(linebuf, len - 1));
750                 }
751                 fclose(f);
752         }
753         CalcSize();
754 }
755
756
757 FileReader::~FileReader()
758 {
759 }
760
761 bool FileReader::Exists()
762 {
763         return (!(fc.size() == 0));
764 }
765
766 std::string FileReader::GetLine(int x)
767 {
768         if ((x<0) || ((unsigned)x>fc.size()))
769                 return "";
770         return fc[x];
771 }
772
773 int FileReader::FileSize()
774 {
775         return fc.size();
776 }