]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules.cpp
PURE_STATIC improvements: Allow modules to be reloaded, generate linker arguments
[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>&, User *, bool, const std::string&) { return MOD_RES_PASSTHRU; }
103 void            Module::OnPostCommand(const std::string&, const std::vector<std::string>&, User *, 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 void            Module::OnText(User*, void*, int, const std::string&, char, CUList&) { }
159 void            Module::OnRunTestSuite() { }
160 void            Module::OnNamesListItem(User*, Membership*, std::string&, std::string&) { }
161 ModResult       Module::OnNumeric(User*, unsigned int, const std::string&) { return MOD_RES_PASSTHRU; }
162 void            Module::OnHookIO(StreamSocket*, ListenSocket*) { }
163 ModResult   Module::OnAcceptConnection(int, ListenSocket*, irc::sockets::sockaddrs*, irc::sockets::sockaddrs*) { return MOD_RES_PASSTHRU; }
164 void            Module::OnSendWhoLine(User*, User*, Channel*, std::string&) { }
165 ModResult       Module::OnChannelRestrictionApply(User*, Channel*, const char*) { return MOD_RES_PASSTHRU; }
166
167 ModuleManager::ModuleManager() : ModCount(0)
168 {
169 }
170
171 ModuleManager::~ModuleManager()
172 {
173 }
174
175 bool ModuleManager::Attach(Implementation i, Module* mod)
176 {
177         if (std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod) != EventHandlers[i].end())
178                 return false;
179
180         EventHandlers[i].push_back(mod);
181         return true;
182 }
183
184 bool ModuleManager::Detach(Implementation i, Module* mod)
185 {
186         EventHandlerIter x = std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod);
187
188         if (x == EventHandlers[i].end())
189                 return false;
190
191         EventHandlers[i].erase(x);
192         return true;
193 }
194
195 void ModuleManager::Attach(Implementation* i, Module* mod, size_t sz)
196 {
197         for (size_t n = 0; n < sz; ++n)
198                 Attach(i[n], mod);
199 }
200
201 void ModuleManager::DetachAll(Module* mod)
202 {
203         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
204                 Detach((Implementation)n, mod);
205 }
206
207 bool ModuleManager::SetPriority(Module* mod, Priority s)
208 {
209         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
210                 SetPriority(mod, (Implementation)n, s);
211
212         return true;
213 }
214
215 bool ModuleManager::SetPriority(Module* mod, Implementation i, Priority s, Module** modules, size_t sz)
216 {
217         /** To change the priority of a module, we first find its position in the vector,
218          * then we find the position of the other modules in the vector that this module
219          * wants to be before/after. We pick off either the first or last of these depending
220          * on which they want, and we make sure our module is *at least* before or after
221          * the first or last of this subset, depending again on the type of priority.
222          */
223         size_t swap_pos = 0;
224         size_t source = 0;
225         bool swap = true;
226         bool found = false;
227
228         /* Locate our module. This is O(n) but it only occurs on module load so we're
229          * not too bothered about it
230          */
231         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
232         {
233                 if (EventHandlers[i][x] == mod)
234                 {
235                         source = x;
236                         found = true;
237                         break;
238                 }
239         }
240
241         /* Eh? this module doesnt exist, probably trying to set priority on an event
242          * theyre not attached to.
243          */
244         if (!found)
245                 return false;
246
247         switch (s)
248         {
249                 /* Dummy value */
250                 case PRIORITY_DONTCARE:
251                         swap = false;
252                 break;
253                 /* Module wants to be first, sod everything else */
254                 case PRIORITY_FIRST:
255                         if (prioritizationState != PRIO_STATE_FIRST)
256                                 swap = false;
257                         else
258                                 swap_pos = 0;
259                 break;
260                 /* Module wants to be last. */
261                 case PRIORITY_LAST:
262                         if (prioritizationState != PRIO_STATE_FIRST)
263                                 swap = false;
264                         else if (EventHandlers[i].empty())
265                                 swap_pos = 0;
266                         else
267                                 swap_pos = EventHandlers[i].size() - 1;
268                 break;
269                 /* Place this module after a set of other modules */
270                 case PRIORITY_AFTER:
271                 {
272                         /* Find the latest possible position */
273                         swap_pos = 0;
274                         swap = false;
275                         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
276                         {
277                                 for (size_t n = 0; n < sz; ++n)
278                                 {
279                                         if ((modules[n]) && (EventHandlers[i][x] == modules[n]) && (x >= swap_pos) && (source <= swap_pos))
280                                         {
281                                                 swap_pos = x;
282                                                 swap = true;
283                                         }
284                                 }
285                         }
286                 }
287                 break;
288                 /* Place this module before a set of other modules */
289                 case PRIORITY_BEFORE:
290                 {
291                         swap_pos = EventHandlers[i].size() - 1;
292                         swap = false;
293                         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
294                         {
295                                 for (size_t n = 0; n < sz; ++n)
296                                 {
297                                         if ((modules[n]) && (EventHandlers[i][x] == modules[n]) && (x <= swap_pos) && (source >= swap_pos))
298                                         {
299                                                 swap = true;
300                                                 swap_pos = x;
301                                         }
302                                 }
303                         }
304                 }
305                 break;
306         }
307
308         /* Do we need to swap? */
309         if (swap && (swap_pos != source))
310         {
311                 // We are going to change positions; we'll need to run again to verify all requirements
312                 if (prioritizationState == PRIO_STATE_LAST)
313                         prioritizationState = PRIO_STATE_AGAIN;
314                 /* Suggestion from Phoenix, "shuffle" the modules to better retain call order */
315                 int incrmnt = 1;
316
317                 if (source > swap_pos)
318                         incrmnt = -1;
319
320                 for (unsigned int j = source; j != swap_pos; j += incrmnt)
321                 {
322                         if (( j + incrmnt > EventHandlers[i].size() - 1) || (j + incrmnt < 0))
323                                 continue;
324
325                         std::swap(EventHandlers[i][j], EventHandlers[i][j+incrmnt]);
326                 }
327         }
328
329         return true;
330 }
331
332 bool ModuleManager::CanUnload(Module* mod)
333 {
334         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
335
336         if (modfind == Modules.end() || modfind->second != mod)
337         {
338                 LastModuleError = "Module " + mod->ModuleSourceFile + " is not loaded, cannot unload it!";
339                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
340                 return false;
341         }
342         if (mod->GetVersion().Flags & VF_STATIC)
343         {
344                 LastModuleError = "Module " + mod->ModuleSourceFile + " not unloadable (marked static)";
345                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
346                 return false;
347         }
348         return true;
349 }
350
351 void ModuleManager::DoSafeUnload(Module* mod)
352 {
353         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
354
355         std::vector<reference<ExtensionItem> > items;
356         ServerInstance->Extensions.BeginUnregister(modfind->second, items);
357         /* Give the module a chance to tidy out all its metadata */
358         for (chan_hash::iterator c = ServerInstance->chanlist->begin(); c != ServerInstance->chanlist->end(); c++)
359         {
360                 mod->OnCleanup(TYPE_CHANNEL,c->second);
361                 c->second->doUnhookExtensions(items);
362                 const UserMembList* users = c->second->GetUsers();
363                 for(UserMembCIter mi = users->begin(); mi != users->end(); mi++)
364                         mi->second->doUnhookExtensions(items);
365         }
366         for (user_hash::iterator u = ServerInstance->Users->clientlist->begin(); u != ServerInstance->Users->clientlist->end(); u++)
367         {
368                 mod->OnCleanup(TYPE_USER,u->second);
369                 u->second->doUnhookExtensions(items);
370         }
371         for(char m='A'; m <= 'z'; m++)
372         {
373                 ModeHandler* mh;
374                 mh = ServerInstance->Modes->FindMode(m, MODETYPE_USER);
375                 if (mh && mh->creator == mod)
376                         ServerInstance->Modes->DelMode(mh);
377                 mh = ServerInstance->Modes->FindMode(m, MODETYPE_CHANNEL);
378                 if (mh && mh->creator == mod)
379                         ServerInstance->Modes->DelMode(mh);
380         }
381         for(std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.begin(); i != DataProviders.end(); )
382         {
383                 std::multimap<std::string, ServiceProvider*>::iterator curr = i++;
384                 if (curr->second->creator == mod)
385                         DataProviders.erase(curr);
386         }
387         for(unsigned int i = 0; i < ServerInstance->Modules->ActiveDynrefs.size(); i++)
388                 ServerInstance->Modules->ActiveDynrefs[i]->ClearCache();
389
390         /* Tidy up any dangling resolvers */
391         ServerInstance->Res->CleanResolvers(mod);
392
393         FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(mod));
394
395         DetachAll(mod);
396
397         Modules.erase(modfind);
398         ServerInstance->GlobalCulls.AddItem(mod);
399
400         ServerInstance->Logs->Log("MODULE", DEFAULT,"Module %s unloaded",mod->ModuleSourceFile.c_str());
401         this->ModCount--;
402         ServerInstance->BuildISupport();
403 }
404
405 std::string& ModuleManager::LastError()
406 {
407         return LastModuleError;
408 }
409
410 CmdResult InspIRCd::CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user)
411 {
412         return this->Parser->CallHandler(commandname, parameters, user);
413 }
414
415 bool InspIRCd::IsValidModuleCommand(const std::string &commandname, int pcnt, User* user)
416 {
417         return this->Parser->IsValidCommand(commandname, pcnt, user);
418 }
419
420 void InspIRCd::AddCommand(Command *f)
421 {
422         if (!this->Parser->AddCommand(f))
423         {
424                 throw ModuleException("Command "+std::string(f->name)+" already exists.");
425         }
426 }
427
428 void ModuleManager::AddService(ServiceProvider& item)
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_CMODE:
437                 case SERVICE_UMODE:
438                         if (!ServerInstance->Modes->AddMode(static_cast<ModeHandler*>(&item)))
439                                 throw ModuleException("Mode "+std::string(item.name)+" already exists.");
440                         return;
441                 case SERVICE_METADATA:
442                         ServerInstance->Extensions.Register(static_cast<ExtensionItem*>(&item));
443                         return;
444                 case SERVICE_DATA:
445                 case SERVICE_IOHOOK:
446                 {
447                         DataProviders.insert(std::make_pair(item.name, &item));
448                         std::string::size_type slash = item.name.find('/');
449                         if (slash != std::string::npos)
450                         {
451                                 DataProviders.insert(std::make_pair(item.name.substr(0, slash), &item));
452                                 DataProviders.insert(std::make_pair(item.name.substr(slash + 1), &item));
453                         }
454                         return;
455                 }
456                 default:
457                         throw ModuleException("Cannot add unknown service type");
458         }
459 }
460
461 ServiceProvider* ModuleManager::FindService(ServiceType type, const std::string& name)
462 {
463         switch (type)
464         {
465                 case SERVICE_DATA:
466                 case SERVICE_IOHOOK:
467                 {
468                         std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.find(name);
469                         if (i != DataProviders.end() && i->second->service == type)
470                                 return i->second;
471                         return NULL;
472                 }
473                 // TODO implement finding of the other types
474                 default:
475                         throw ModuleException("Cannot find unknown service type");
476         }
477 }
478
479 dynamic_reference_base::dynamic_reference_base(Module* Creator, const std::string& Name)
480         : name(Name), value(NULL), creator(Creator)
481 {
482         ServerInstance->Modules->ActiveDynrefs.push_back(this);
483 }
484
485 dynamic_reference_base::~dynamic_reference_base()
486 {
487         for(unsigned int i = 0; i < ServerInstance->Modules->ActiveDynrefs.size(); i++)
488         {
489                 if (ServerInstance->Modules->ActiveDynrefs[i] == this)
490                 {
491                         unsigned int last = ServerInstance->Modules->ActiveDynrefs.size() - 1;
492                         if (i != last)
493                                 ServerInstance->Modules->ActiveDynrefs[i] = ServerInstance->Modules->ActiveDynrefs[last];
494                         ServerInstance->Modules->ActiveDynrefs.erase(ServerInstance->Modules->ActiveDynrefs.begin() + last);
495                         return;
496                 }
497         }
498 }
499
500 void dynamic_reference_base::SetProvider(const std::string& newname)
501 {
502         name = newname;
503         ClearCache();
504 }
505
506 void dynamic_reference_base::lookup()
507 {
508         if (!*this)
509                 throw ModuleException("Dynamic reference to '" + name + "' failed to resolve");
510 }
511
512 dynamic_reference_base::operator bool()
513 {
514         if (!value)
515         {
516                 std::multimap<std::string, ServiceProvider*>::iterator i = ServerInstance->Modules->DataProviders.find(name);
517                 if (i != ServerInstance->Modules->DataProviders.end())
518                         value = static_cast<DataProvider*>(i->second);
519         }
520         return value;
521 }
522
523 void InspIRCd::SendMode(const std::vector<std::string>& parameters, User *user)
524 {
525         this->Modes->Process(parameters, user);
526 }
527
528 bool InspIRCd::AddResolver(Resolver* r, bool cached)
529 {
530         if (!cached)
531                 return this->Res->AddResolverClass(r);
532         else
533         {
534                 r->TriggerCachedResult();
535                 delete r;
536                 return true;
537         }
538 }
539
540 Module* ModuleManager::Find(const std::string &name)
541 {
542         std::map<std::string, Module*>::iterator modfind = Modules.find(name);
543
544         if (modfind == Modules.end())
545                 return NULL;
546         else
547                 return modfind->second;
548 }
549
550 const std::vector<std::string> ModuleManager::GetAllModuleNames(int filter)
551 {
552         std::vector<std::string> retval;
553         for (std::map<std::string, Module*>::iterator x = Modules.begin(); x != Modules.end(); ++x)
554                 if (!filter || (x->second->GetVersion().Flags & filter))
555                         retval.push_back(x->first);
556         return retval;
557 }
558
559 ConfigReader::ConfigReader()
560 {
561         this->error = 0;
562 }
563
564
565 ConfigReader::~ConfigReader()
566 {
567 }
568
569 static ConfigTag* SlowGetTag(const std::string &tag, int index)
570 {
571         ConfigTagList tags = ServerInstance->Config->ConfTags(tag);
572         while (tags.first != tags.second)
573         {
574                 if (!index)
575                         return tags.first->second;
576                 tags.first++;
577                 index--;
578         }
579         return NULL;
580 }
581
582 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool allow_linefeeds)
583 {
584         std::string result = default_value;
585         if (!SlowGetTag(tag, index)->readString(name, result, allow_linefeeds))
586         {
587                 this->error = CONF_VALUE_NOT_FOUND;
588         }
589         return result;
590 }
591
592 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, int index, bool allow_linefeeds)
593 {
594         return ReadValue(tag, name, "", index, allow_linefeeds);
595 }
596
597 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, const std::string &default_value, int index)
598 {
599         bool def = (default_value == "yes");
600         return SlowGetTag(tag, index)->getBool(name, def);
601 }
602
603 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, int index)
604 {
605         return ReadFlag(tag, name, "", index);
606 }
607
608
609 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool need_positive)
610 {
611         int v = atoi(default_value.c_str());
612         int result = SlowGetTag(tag, index)->getInt(name, v);
613
614         if ((need_positive) && (result < 0))
615         {
616                 this->error = CONF_INT_NEGATIVE;
617                 return 0;
618         }
619
620         return result;
621 }
622
623 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, int index, bool need_positive)
624 {
625         return ReadInteger(tag, name, "", index, need_positive);
626 }
627
628 long ConfigReader::GetError()
629 {
630         long olderr = this->error;
631         this->error = 0;
632         return olderr;
633 }
634
635 int ConfigReader::Enumerate(const std::string &tag)
636 {
637         ServerInstance->Logs->Log("MODULE", DEBUG, "Module is using ConfigReader::Enumerate on %s; this is slow!",
638                 tag.c_str());
639         int i=0;
640         while (SlowGetTag(tag, i)) i++;
641         return i;
642 }
643
644 FileReader::FileReader(const std::string &filename)
645 {
646         LoadFile(filename);
647 }
648
649 FileReader::FileReader()
650 {
651 }
652
653 std::string FileReader::Contents()
654 {
655         std::string x;
656         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
657         {
658                 x.append(*a);
659                 x.append("\r\n");
660         }
661         return x;
662 }
663
664 unsigned long FileReader::ContentSize()
665 {
666         return this->contentsize;
667 }
668
669 void FileReader::CalcSize()
670 {
671         unsigned long n = 0;
672         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
673                 n += (a->length() + 2);
674         this->contentsize = n;
675 }
676
677 void FileReader::LoadFile(const std::string &filename)
678 {
679         file_cache c;
680         c.clear();
681         if (ServerInstance->Config->ReadFile(c,filename.c_str()))
682         {
683                 this->fc = c;
684                 this->CalcSize();
685         }
686 }
687
688
689 FileReader::~FileReader()
690 {
691 }
692
693 bool FileReader::Exists()
694 {
695         return (!(fc.size() == 0));
696 }
697
698 std::string FileReader::GetLine(int x)
699 {
700         if ((x<0) || ((unsigned)x>fc.size()))
701                 return "";
702         return fc[x];
703 }
704
705 int FileReader::FileSize()
706 {
707         return fc.size();
708 }