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