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