]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules.cpp
Remove m_sqlv2.h from these modules, they both use v3 now.
[user/henk/code/inspircd.git] / src / modules.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2010 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "xline.h"
16 #include "socket.h"
17 #include "socketengine.h"
18 #include "command_parse.h"
19 #include "dns.h"
20 #include "exitcodes.h"
21
22 #ifndef WIN32
23         #include <dirent.h>
24 #endif
25
26 static std::vector<dynamic_reference_base*>* dynrefs = NULL;
27
28 void dynamic_reference_base::reset_all()
29 {
30         if (!dynrefs)
31                 return;
32         for(unsigned int i = 0; i < dynrefs->size(); i++)
33                 (*dynrefs)[i]->ClearCache();
34 }
35
36 // Version is a simple class for holding a modules version number
37 Version::Version(const std::string &desc, int flags) : description(desc), Flags(flags)
38 {
39 }
40
41 Version::Version(const std::string &desc, int flags, const std::string& linkdata)
42 : description(desc), Flags(flags), link_data(linkdata)
43 {
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*, 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* which)
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 my_pos = 0;
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                         my_pos = x;
236                         goto found_src;
237                 }
238         }
239
240         /* Eh? this module doesnt exist, probably trying to set priority on an event
241          * theyre not attached to.
242          */
243         return false;
244
245 found_src:
246         size_t swap_pos = my_pos;
247         switch (s)
248         {
249                 case PRIORITY_FIRST:
250                         if (prioritizationState != PRIO_STATE_FIRST)
251                                 return true;
252                         else
253                                 swap_pos = 0;
254                         break;
255                 case PRIORITY_LAST:
256                         if (prioritizationState != PRIO_STATE_FIRST)
257                                 return true;
258                         else
259                                 swap_pos = EventHandlers[i].size() - 1;
260                         break;
261                 case PRIORITY_AFTER:
262                 {
263                         /* Find the latest possible position, only searching AFTER our position */
264                         for (size_t x = EventHandlers[i].size() - 1; x > my_pos; --x)
265                         {
266                                 if (EventHandlers[i][x] == which)
267                                 {
268                                         swap_pos = x;
269                                         goto swap_now;
270                                 }
271                         }
272                         // didn't find it - either not loaded or we're already after
273                         return true;
274                 }
275                 /* Place this module before a set of other modules */
276                 case PRIORITY_BEFORE:
277                 {
278                         for (size_t x = 0; x < my_pos; ++x)
279                         {
280                                 if (EventHandlers[i][x] == which)
281                                 {
282                                         swap_pos = x;
283                                         goto swap_now;
284                                 }
285                         }
286                         // didn't find it - either not loaded or we're already before
287                         return true;
288                 }
289         }
290
291 swap_now:
292         /* Do we need to swap? */
293         if (swap_pos != my_pos)
294         {
295                 // We are going to change positions; we'll need to run again to verify all requirements
296                 if (prioritizationState == PRIO_STATE_LAST)
297                         prioritizationState = PRIO_STATE_AGAIN;
298                 /* Suggestion from Phoenix, "shuffle" the modules to better retain call order */
299                 int incrmnt = 1;
300
301                 if (my_pos > swap_pos)
302                         incrmnt = -1;
303
304                 for (unsigned int j = my_pos; j != swap_pos; j += incrmnt)
305                 {
306                         if (( j + incrmnt > EventHandlers[i].size() - 1) || (j + incrmnt < 0))
307                                 continue;
308
309                         std::swap(EventHandlers[i][j], EventHandlers[i][j+incrmnt]);
310                 }
311         }
312
313         return true;
314 }
315
316 bool ModuleManager::CanUnload(Module* mod)
317 {
318         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
319
320         if (modfind == Modules.end() || modfind->second != mod)
321         {
322                 LastModuleError = "Module " + mod->ModuleSourceFile + " is not loaded, cannot unload it!";
323                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
324                 return false;
325         }
326         if (mod->GetVersion().Flags & VF_STATIC)
327         {
328                 LastModuleError = "Module " + mod->ModuleSourceFile + " not unloadable (marked static)";
329                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
330                 return false;
331         }
332         return true;
333 }
334
335 void ModuleManager::DoSafeUnload(Module* mod)
336 {
337         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
338
339         std::vector<reference<ExtensionItem> > items;
340         ServerInstance->Extensions.BeginUnregister(modfind->second, items);
341         /* Give the module a chance to tidy out all its metadata */
342         for (chan_hash::iterator c = ServerInstance->chanlist->begin(); c != ServerInstance->chanlist->end(); c++)
343         {
344                 mod->OnCleanup(TYPE_CHANNEL,c->second);
345                 c->second->doUnhookExtensions(items);
346                 const UserMembList* users = c->second->GetUsers();
347                 for(UserMembCIter mi = users->begin(); mi != users->end(); mi++)
348                         mi->second->doUnhookExtensions(items);
349         }
350         for (user_hash::iterator u = ServerInstance->Users->clientlist->begin(); u != ServerInstance->Users->clientlist->end(); u++)
351         {
352                 mod->OnCleanup(TYPE_USER,u->second);
353                 u->second->doUnhookExtensions(items);
354         }
355         for(char m='A'; m <= 'z'; m++)
356         {
357                 ModeHandler* mh;
358                 mh = ServerInstance->Modes->FindMode(m, MODETYPE_USER);
359                 if (mh && mh->creator == mod)
360                         ServerInstance->Modes->DelMode(mh);
361                 mh = ServerInstance->Modes->FindMode(m, MODETYPE_CHANNEL);
362                 if (mh && mh->creator == mod)
363                         ServerInstance->Modes->DelMode(mh);
364         }
365         for(std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.begin(); i != DataProviders.end(); )
366         {
367                 std::multimap<std::string, ServiceProvider*>::iterator curr = i++;
368                 if (curr->second->creator == mod)
369                         DataProviders.erase(curr);
370         }
371
372         dynamic_reference_base::reset_all();
373
374         /* Tidy up any dangling resolvers */
375         ServerInstance->Res->CleanResolvers(mod);
376
377         FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(mod));
378
379         DetachAll(mod);
380
381         Modules.erase(modfind);
382         ServerInstance->GlobalCulls.AddItem(mod);
383
384         ServerInstance->Logs->Log("MODULE", DEFAULT,"Module %s unloaded",mod->ModuleSourceFile.c_str());
385         this->ModCount--;
386         ServerInstance->BuildISupport();
387 }
388
389 void ModuleManager::UnloadAll()
390 {
391         /* We do this more than once, so that any service providers get a
392          * chance to be unhooked by the modules using them, but then get
393          * a chance to be removed themsleves.
394          *
395          * Note: this deliberately does NOT delete the DLLManager objects
396          */
397         for (int tries = 0; tries < 4; tries++)
398         {
399                 std::map<std::string, Module*>::iterator i = Modules.begin();
400                 while (i != Modules.end())
401                 {
402                         std::map<std::string, Module*>::iterator me = i++;
403                         if (CanUnload(me->second))
404                         {
405                                 DoSafeUnload(me->second);
406                         }
407                 }
408                 ServerInstance->GlobalCulls.Apply();
409         }
410 }
411
412 std::string& ModuleManager::LastError()
413 {
414         return LastModuleError;
415 }
416
417 CmdResult InspIRCd::CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user)
418 {
419         return this->Parser->CallHandler(commandname, parameters, user);
420 }
421
422 bool InspIRCd::IsValidModuleCommand(const std::string &commandname, int pcnt, User* user)
423 {
424         return this->Parser->IsValidCommand(commandname, pcnt, user);
425 }
426
427 void ModuleManager::AddService(ServiceProvider& item)
428 {
429         Module* owner = item.creator;
430         if (Modules.find(owner->ModuleSourceFile) == Modules.end())
431                 ServerInstance->Logs->Log("MODULE", DEFAULT, "Module is registering item %s in constructor; this does not handle exceptions correctly!", item.name.c_str());
432
433         switch (item.service)
434         {
435                 case SERVICE_COMMAND:
436                         if (!ServerInstance->Parser->AddCommand(static_cast<Command*>(&item)))
437                                 throw ModuleException("Command "+std::string(item.name)+" already exists.");
438                         return;
439                 case SERVICE_MODE:
440                         if (!ServerInstance->Modes->AddMode(static_cast<ModeHandler*>(&item)))
441                                 throw ModuleException("Mode "+std::string(item.name)+" already exists.");
442                         return;
443                 case SERVICE_METADATA:
444                         ServerInstance->Extensions.Register(static_cast<ExtensionItem*>(&item));
445                         return;
446                 case SERVICE_DATA:
447                 case SERVICE_IOHOOK:
448                 {
449                         DataProviders.insert(std::make_pair(item.name, &item));
450                         std::string::size_type slash = item.name.find('/');
451                         if (slash != std::string::npos)
452                         {
453                                 DataProviders.insert(std::make_pair(item.name.substr(0, slash), &item));
454                                 DataProviders.insert(std::make_pair(item.name.substr(slash + 1), &item));
455                         }
456                         return;
457                 }
458                 default:
459                         throw ModuleException("Cannot add unknown service type");
460         }
461 }
462
463 void ModuleManager::DelService(ServiceProvider& item)
464 {
465         switch (item.service)
466         {
467                 case SERVICE_MODE:
468                         if (!ServerInstance->Modes->DelMode(static_cast<ModeHandler*>(&item)))
469                                 throw ModuleException("Mode "+std::string(item.name)+" does not exist.");
470                         return;
471                 case SERVICE_DATA:
472                 case SERVICE_IOHOOK:
473                 {
474                         for(std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.begin(); i != DataProviders.end(); )
475                         {
476                                 std::multimap<std::string, ServiceProvider*>::iterator curr = i++;
477                                 if (curr->second == &item)
478                                         DataProviders.erase(curr);
479                         }
480                         dynamic_reference_base::reset_all();
481                         return;
482                 }
483                 default:
484                         throw ModuleException("Cannot delete unknown service type");
485         }
486 }
487
488 ServiceProvider* ModuleManager::FindService(ServiceType type, const std::string& name)
489 {
490         switch (type)
491         {
492                 case SERVICE_DATA:
493                 case SERVICE_IOHOOK:
494                 {
495                         std::multimap<std::string, ServiceProvider*>::iterator i = DataProviders.find(name);
496                         if (i != DataProviders.end() && i->second->service == type)
497                                 return i->second;
498                         return NULL;
499                 }
500                 // TODO implement finding of the other types
501                 default:
502                         throw ModuleException("Cannot find unknown service type");
503         }
504 }
505
506 dynamic_reference_base::dynamic_reference_base(Module* Creator, const std::string& Name)
507         : name(Name), value(NULL), creator(Creator)
508 {
509         if (!dynrefs)
510                 dynrefs = new std::vector<dynamic_reference_base*>;
511         dynrefs->push_back(this);
512 }
513
514 dynamic_reference_base::~dynamic_reference_base()
515 {
516         for(unsigned int i = 0; i < dynrefs->size(); i++)
517         {
518                 if (dynrefs->at(i) == this)
519                 {
520                         unsigned int last = dynrefs->size() - 1;
521                         if (i != last)
522                                 dynrefs->at(i) = dynrefs->at(last);
523                         dynrefs->erase(dynrefs->begin() + last);
524                         if (dynrefs->empty())
525                         {
526                                 delete dynrefs;
527                                 dynrefs = NULL;
528                         }
529                         return;
530                 }
531         }
532 }
533
534 void dynamic_reference_base::SetProvider(const std::string& newname)
535 {
536         name = newname;
537         ClearCache();
538 }
539
540 void dynamic_reference_base::lookup()
541 {
542         if (!*this)
543                 throw ModuleException("Dynamic reference to '" + name + "' failed to resolve");
544 }
545
546 dynamic_reference_base::operator bool()
547 {
548         if (!value)
549         {
550                 std::multimap<std::string, ServiceProvider*>::iterator i = ServerInstance->Modules->DataProviders.find(name);
551                 if (i != ServerInstance->Modules->DataProviders.end())
552                         value = static_cast<DataProvider*>(i->second);
553         }
554         return value;
555 }
556
557 void InspIRCd::SendMode(const std::vector<std::string>& parameters, User *user)
558 {
559         this->Modes->Process(parameters, user);
560 }
561
562
563 void InspIRCd::SendGlobalMode(const std::vector<std::string>& parameters, User *user)
564 {
565         Modes->Process(parameters, user);
566         if (!Modes->GetLastParse().empty())
567                 this->PI->SendMode(parameters[0], Modes->GetLastParseParams(), Modes->GetLastParseTranslate());
568 }
569
570 bool InspIRCd::AddResolver(Resolver* r, bool cached)
571 {
572         if (!cached)
573                 return this->Res->AddResolverClass(r);
574         else
575         {
576                 r->TriggerCachedResult();
577                 delete r;
578                 return true;
579         }
580 }
581
582 Module* ModuleManager::Find(const std::string &name)
583 {
584         std::map<std::string, Module*>::iterator modfind = Modules.find(name);
585
586         if (modfind == Modules.end())
587                 return NULL;
588         else
589                 return modfind->second;
590 }
591
592 const std::vector<std::string> ModuleManager::GetAllModuleNames(int filter)
593 {
594         std::vector<std::string> retval;
595         for (std::map<std::string, Module*>::iterator x = Modules.begin(); x != Modules.end(); ++x)
596                 if (!filter || (x->second->GetVersion().Flags & filter))
597                         retval.push_back(x->first);
598         return retval;
599 }
600
601 ConfigReader::ConfigReader()
602 {
603         this->error = 0;
604         ServerInstance->Logs->Log("MODULE", DEBUG, "ConfigReader is deprecated in 2.0; "
605                 "use ServerInstance->Config->ConfValue(\"key\") or ->ConfTags(\"key\") instead");
606 }
607
608
609 ConfigReader::~ConfigReader()
610 {
611 }
612
613 static ConfigTag* SlowGetTag(const std::string &tag, int index)
614 {
615         ConfigTagList tags = ServerInstance->Config->ConfTags(tag);
616         while (tags.first != tags.second)
617         {
618                 if (!index)
619                         return tags.first->second;
620                 tags.first++;
621                 index--;
622         }
623         return NULL;
624 }
625
626 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool allow_linefeeds)
627 {
628         std::string result = default_value;
629         if (!SlowGetTag(tag, index)->readString(name, result, allow_linefeeds))
630         {
631                 this->error = CONF_VALUE_NOT_FOUND;
632         }
633         return result;
634 }
635
636 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, int index, bool allow_linefeeds)
637 {
638         return ReadValue(tag, name, "", index, allow_linefeeds);
639 }
640
641 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, const std::string &default_value, int index)
642 {
643         bool def = (default_value == "yes");
644         return SlowGetTag(tag, index)->getBool(name, def);
645 }
646
647 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, int index)
648 {
649         return ReadFlag(tag, name, "", index);
650 }
651
652
653 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool need_positive)
654 {
655         int v = atoi(default_value.c_str());
656         int result = SlowGetTag(tag, index)->getInt(name, v);
657
658         if ((need_positive) && (result < 0))
659         {
660                 this->error = CONF_INT_NEGATIVE;
661                 return 0;
662         }
663
664         return result;
665 }
666
667 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, int index, bool need_positive)
668 {
669         return ReadInteger(tag, name, "", index, need_positive);
670 }
671
672 long ConfigReader::GetError()
673 {
674         long olderr = this->error;
675         this->error = 0;
676         return olderr;
677 }
678
679 int ConfigReader::Enumerate(const std::string &tag)
680 {
681         ServerInstance->Logs->Log("MODULE", DEBUG, "Module is using ConfigReader::Enumerate on %s; this is slow!",
682                 tag.c_str());
683         int i=0;
684         while (SlowGetTag(tag, i)) i++;
685         return i;
686 }
687
688 FileReader::FileReader(const std::string &filename)
689 {
690         LoadFile(filename);
691 }
692
693 FileReader::FileReader()
694 {
695 }
696
697 std::string FileReader::Contents()
698 {
699         std::string x;
700         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
701         {
702                 x.append(*a);
703                 x.append("\r\n");
704         }
705         return x;
706 }
707
708 unsigned long FileReader::ContentSize()
709 {
710         return this->contentsize;
711 }
712
713 void FileReader::CalcSize()
714 {
715         unsigned long n = 0;
716         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
717                 n += (a->length() + 2);
718         this->contentsize = n;
719 }
720
721 void FileReader::LoadFile(const std::string &filename)
722 {
723         std::map<std::string, file_cache>::iterator file = ServerInstance->Config->Files.find(filename);
724         if (file != ServerInstance->Config->Files.end())
725         {
726                 this->fc = file->second;
727         }
728         else
729         {
730                 fc.clear();
731                 FILE* f = fopen(filename.c_str(), "r");
732                 if (!f)
733                         return;
734                 char linebuf[MAXBUF*10];
735                 while (fgets(linebuf, sizeof(linebuf), f))
736                 {
737                         int len = strlen(linebuf);
738                         if (len)
739                                 fc.push_back(std::string(linebuf, len - 1));
740                 }
741                 fclose(f);
742         }
743         CalcSize();
744 }
745
746
747 FileReader::~FileReader()
748 {
749 }
750
751 bool FileReader::Exists()
752 {
753         return (!(fc.size() == 0));
754 }
755
756 std::string FileReader::GetLine(int x)
757 {
758         if ((x<0) || ((unsigned)x>fc.size()))
759                 return "";
760         return fc[x];
761 }
762
763 int FileReader::FileSize()
764 {
765         return fc.size();
766 }