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