]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules.cpp
57790cd1b5b227c3d7aad4a6780a186cd7718a50
[user/henk/code/inspircd.git] / src / modules.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Core: libIRCDmodules */
15
16 #include "inspircd.h"
17 #include "wildcard.h"
18 #include "xline.h"
19 #include "socket.h"
20 #include "socketengine.h"
21 #include "command_parse.h"
22 #include "dns.h"
23 #include "exitcodes.h"
24
25 #ifndef WIN32
26         #include <dirent.h>
27 #endif
28
29 // version is a simple class for holding a modules version number
30 Version::Version(int major, int minor, int revision, int build, int flags, int api_ver)
31 : Major(major), Minor(minor), Revision(revision), Build(build), Flags(flags), API(api_ver)
32 {
33 }
34
35 Request::Request(char* anydata, Module* src, Module* dst)
36 : data(anydata), source(src), dest(dst)
37 {
38         /* Ensure that because this module doesnt support ID strings, it doesnt break modules that do
39          * by passing them uninitialized pointers (could happen)
40          */
41         id = '\0';
42 }
43
44 Request::Request(Module* src, Module* dst, const char* idstr)
45 : id(idstr), source(src), dest(dst)
46 {
47 }
48
49 char* Request::GetData()
50 {
51         return this->data;
52 }
53
54 const char* Request::GetId()
55 {
56         return this->id;
57 }
58
59 Module* Request::GetSource()
60 {
61         return this->source;
62 }
63
64 Module* Request::GetDest()
65 {
66         return this->dest;
67 }
68
69 const char* Request::Send()
70 {
71         if (this->dest)
72         {
73                 return dest->OnRequest(this);
74         }
75         else
76         {
77                 return NULL;
78         }
79 }
80
81 Event::Event(char* anydata, Module* src, const std::string &eventid) : data(anydata), source(src), id(eventid) { }
82
83 char* Event::GetData()
84 {
85         return (char*)this->data;
86 }
87
88 Module* Event::GetSource()
89 {
90         return this->source;
91 }
92
93 char* Event::Send(InspIRCd* ServerInstance)
94 {
95         FOREACH_MOD(I_OnEvent,OnEvent(this));
96         return NULL;
97 }
98
99 std::string Event::GetEventID()
100 {
101         return this->id;
102 }
103
104
105 // These declarations define the behavours of the base class Module (which does nothing at all)
106
107                 Module::Module(InspIRCd* Me) : ServerInstance(Me) { }
108                 Module::~Module() { }
109 void            Module::OnUserConnect(User*) { }
110 void            Module::OnUserQuit(User*, const std::string&, const std::string&) { }
111 void            Module::OnUserDisconnect(User*) { }
112 void            Module::OnUserJoin(User*, Channel*, bool, bool&) { }
113 void            Module::OnPostJoin(User*, Channel*) { }
114 void            Module::OnUserPart(User*, Channel*, const std::string&, bool&) { }
115 void            Module::OnRehash(User*, const std::string&) { }
116 void            Module::OnServerRaw(std::string&, bool, User*) { }
117 int             Module::OnUserPreJoin(User*, Channel*, const char*, std::string&, const std::string&) { return 0; }
118 void            Module::OnMode(User*, void*, int, const std::string&) { }
119 Version         Module::GetVersion() { return Version(1,0,0,0,VF_VENDOR,-1); }
120 void            Module::OnOper(User*, const std::string&) { }
121 void            Module::OnPostOper(User*, const std::string&, const std::string &) { }
122 void            Module::OnInfo(User*) { }
123 void            Module::OnWhois(User*, User*) { }
124 int             Module::OnUserPreInvite(User*, User*, Channel*, time_t) { return 0; }
125 int             Module::OnUserPreMessage(User*, void*, int, std::string&, char, CUList&) { return 0; }
126 int             Module::OnUserPreNotice(User*, void*, int, std::string&, char, CUList&) { return 0; }
127 int             Module::OnUserPreNick(User*, const std::string&) { return 0; }
128 void            Module::OnUserPostNick(User*, const std::string&) { }
129 int             Module::OnAccessCheck(User*, User*, Channel*, int) { return ACR_DEFAULT; }
130 void            Module::On005Numeric(std::string&) { }
131 int             Module::OnKill(User*, User*, const std::string&) { return 0; }
132 void            Module::OnLoadModule(Module*, const std::string&) { }
133 void            Module::OnUnloadModule(Module*, const std::string&) { }
134 void            Module::OnBackgroundTimer(time_t) { }
135 int             Module::OnPreCommand(std::string&, std::vector<std::string>&, User *, bool, const std::string&) { return 0; }
136 void            Module::OnPostCommand(const std::string&, const std::vector<std::string>&, User *, CmdResult, const std::string&) { }
137 bool            Module::OnCheckReady(User*) { return true; }
138 int             Module::OnUserRegister(User*) { return 0; }
139 int             Module::OnUserPreKick(User*, User*, Channel*, const std::string&) { return 0; }
140 void            Module::OnUserKick(User*, User*, Channel*, const std::string&, bool&) { }
141 int             Module::OnRawMode(User*, Channel*, const char, const std::string &, bool, int, bool) { return 0; }
142 int             Module::OnCheckInvite(User*, Channel*) { return 0; }
143 int             Module::OnCheckKey(User*, Channel*, const std::string&) { return 0; }
144 int             Module::OnCheckLimit(User*, Channel*) { return 0; }
145 int             Module::OnCheckBan(User*, Channel*) { return 0; }
146 int             Module::OnStats(char, User*, string_list&) { return 0; }
147 int             Module::OnChangeLocalUserHost(User*, const std::string&) { return 0; }
148 int             Module::OnChangeLocalUserGECOS(User*, const std::string&) { return 0; }
149 int             Module::OnLocalTopicChange(User*, Channel*, const std::string&) { return 0; }
150 void            Module::OnEvent(Event*) { return; }
151 const char*             Module::OnRequest(Request*) { return NULL; }
152 int             Module::OnPassCompare(Extensible* ex, const std::string &password, const std::string &input, const std::string& hashtype) { return 0; }
153 void            Module::OnGlobalOper(User*) { }
154 void            Module::OnPostConnect(User*) { }
155 int             Module::OnAddBan(User*, Channel*, const std::string &) { return 0; }
156 int             Module::OnDelBan(User*, Channel*, const std::string &) { return 0; }
157 void            Module::OnRawSocketAccept(int, const std::string&, int) { }
158 int             Module::OnRawSocketWrite(int, const char*, int) { return 0; }
159 void            Module::OnRawSocketClose(int) { }
160 void            Module::OnRawSocketConnect(int) { }
161 int             Module::OnRawSocketRead(int, char*, unsigned int, int&) { return 0; }
162 void            Module::OnUserMessage(User*, void*, int, const std::string&, char, const CUList&) { }
163 void            Module::OnUserNotice(User*, void*, int, const std::string&, char, const CUList&) { }
164 void            Module::OnRemoteKill(User*, User*, const std::string&, const std::string&) { }
165 void            Module::OnUserInvite(User*, User*, Channel*, time_t) { }
166 void            Module::OnPostLocalTopicChange(User*, Channel*, const std::string&) { }
167 void            Module::OnGetServerDescription(const std::string&, std::string&) { }
168 void            Module::OnSyncUser(User*, Module*, void*) { }
169 void            Module::OnSyncChannel(Channel*, Module*, void*) { }
170 void            Module::ProtoSendMode(void*, int, void*, const std::string&) { }
171 void            Module::OnSyncChannelMetaData(Channel*, Module*, void*, const std::string&, bool) { }
172 void            Module::OnSyncUserMetaData(User*, Module*, void*, const std::string&, bool) { }
173 void            Module::OnSyncOtherMetaData(Module*, void*, bool) { }
174 void            Module::OnDecodeMetaData(int, void*, const std::string&, const std::string&) { }
175 void            Module::ProtoSendMetaData(void*, int, void*, const std::string&, const std::string&) { }
176 void            Module::OnWallops(User*, const std::string&) { }
177 void            Module::OnChangeHost(User*, const std::string&) { }
178 void            Module::OnChangeName(User*, const std::string&) { }
179 void            Module::OnAddLine(User*, XLine*) { }
180 void            Module::OnDelLine(User*, XLine*) { }
181 void            Module::OnExpireLine(XLine*) { }
182 void            Module::OnCleanup(int, void*) { }
183 int             Module::OnChannelPreDelete(Channel*) { return 0; }
184 void            Module::OnChannelDelete(Channel*) { }
185 int             Module::OnSetAway(User*, const std::string &) { return 0; }
186 int             Module::OnUserList(User*, Channel*, CUList*&) { return 0; }
187 int             Module::OnWhoisLine(User*, User*, int&, std::string&) { return 0; }
188 void            Module::OnBuildExemptList(MessageType, Channel*, User*, char, CUList&, const std::string&) { }
189 void            Module::OnGarbageCollect() { }
190 void            Module::OnBufferFlushed(User*) { }
191 void            Module::OnText(User*, void*, int, const std::string&, char, CUList&) { }
192 void            Module::OnRunTestSuite() { }
193 void            Module::OnNamesListItem(User*, User*, Channel*, std::string&, std::string&) { }
194 int             Module::OnNumeric(User*, unsigned int, const std::string&) { return 0; }
195 void            Module::OnHookUserIO(User*, const std::string&) { }
196
197 ModuleManager::ModuleManager(InspIRCd* Ins) : ModCount(0), Instance(Ins)
198 {
199 }
200
201 ModuleManager::~ModuleManager()
202 {
203 }
204
205 bool ModuleManager::Attach(Implementation i, Module* mod)
206 {
207         if (std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod) != EventHandlers[i].end())
208                 return false;
209
210         EventHandlers[i].push_back(mod);
211         return true;
212 }
213
214 bool ModuleManager::Detach(Implementation i, Module* mod)
215 {
216         EventHandlerIter x = std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod);
217
218         if (x == EventHandlers[i].end())
219                 return false;
220
221         EventHandlers[i].erase(x);
222         return true;
223 }
224
225 void ModuleManager::Attach(Implementation* i, Module* mod, size_t sz)
226 {
227         for (size_t n = 0; n < sz; ++n)
228                 Attach(i[n], mod);
229 }
230
231 void ModuleManager::DetachAll(Module* mod)
232 {
233         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
234                 Detach((Implementation)n, mod);
235 }
236
237 bool ModuleManager::SetPriority(Module* mod, PriorityState s)
238 {
239         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
240                 SetPriority(mod, (Implementation)n, s);
241
242         return true;
243 }
244
245 bool ModuleManager::SetPriority(Module* mod, Implementation i, PriorityState s, Module** modules, size_t sz)
246 {
247         /** To change the priority of a module, we first find its position in the vector,
248          * then we find the position of the other modules in the vector that this module
249          * wants to be before/after. We pick off either the first or last of these depending
250          * on which they want, and we make sure our module is *at least* before or after
251          * the first or last of this subset, depending again on the type of priority.
252          */
253         size_t swap_pos = 0;
254         size_t source = 0;
255         bool swap = true;
256         bool found = false;
257
258         /* Locate our module. This is O(n) but it only occurs on module load so we're
259          * not too bothered about it
260          */
261         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
262         {
263                 if (EventHandlers[i][x] == mod)
264                 {
265                         source = x;
266                         found = true;
267                         break;
268                 }
269         }
270
271         /* Eh? this module doesnt exist, probably trying to set priority on an event
272          * theyre not attached to.
273          */
274         if (!found)
275                 return false;
276
277         switch (s)
278         {
279                 /* Dummy value */
280                 case PRIO_DONTCARE:
281                         swap = false;
282                 break;
283                 /* Module wants to be first, sod everything else */
284                 case PRIO_FIRST:
285                         swap_pos = 0;
286                 break;
287                 /* Module is submissive and wants to be last... awww. */
288                 case PRIO_LAST:
289                         if (EventHandlers[i].empty())
290                                 swap_pos = 0;
291                         else
292                                 swap_pos = EventHandlers[i].size() - 1;
293                 break;
294                 /* Place this module after a set of other modules */
295                 case PRIO_AFTER:
296                 {
297                         /* Find the latest possible position */
298                         swap_pos = 0;
299                         swap = false;
300                         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
301                         {
302                                 for (size_t n = 0; n < sz; ++n)
303                                 {
304                                         if ((modules[n]) && (EventHandlers[i][x] == modules[n]) && (x >= swap_pos) && (source <= swap_pos))
305                                         {
306                                                 swap_pos = x;
307                                                 swap = true;
308                                         }
309                                 }
310                         }
311                 }
312                 break;
313                 /* Place this module before a set of other modules */
314                 case PRIO_BEFORE:
315                 {
316                         swap_pos = EventHandlers[i].size() - 1;
317                         swap = false;
318                         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
319                         {
320                                 for (size_t n = 0; n < sz; ++n)
321                                 {
322                                         if ((modules[n]) && (EventHandlers[i][x] == modules[n]) && (x <= swap_pos) && (source >= swap_pos))
323                                         {
324                                                 swap = true;
325                                                 swap_pos = x;
326                                         }
327                                 }
328                         }
329                 }
330                 break;
331         }
332
333         /* Do we need to swap? */
334         if (swap && (swap_pos != source))
335         {
336                 /* Suggestion from Phoenix, "shuffle" the modules to better retain call order */
337                 int incrmnt = 1;
338
339                 if (source > swap_pos)
340                         incrmnt = -1;
341
342                 for (unsigned int j = source; j != swap_pos; j += incrmnt)
343                 {
344                         if (( j + incrmnt > EventHandlers[i].size() - 1) || (j - incrmnt < 0))
345                                 continue;
346
347                         std::swap(EventHandlers[i][j], EventHandlers[i][j+incrmnt]);
348                 }
349         }
350
351         return true;
352 }
353
354 std::string& ModuleManager::LastError()
355 {
356         return LastModuleError;
357 }
358
359 bool ModuleManager::Load(const char* filename)
360 {
361         /* Do we have a glob pattern in the filename?
362          * The user wants to load multiple modules which
363          * match the pattern.
364          */
365         if (strchr(filename,'*') || (strchr(filename,'?')))
366         {
367                 int n_match = 0;
368                 DIR* library = opendir(Instance->Config->ModPath);
369                 if (library)
370                 {
371                         /* Try and locate and load all modules matching the pattern */
372                         dirent* entry = NULL;
373                         while (0 != (entry = readdir(library)))
374                         {
375                                 if (Instance->MatchText(entry->d_name, filename))
376                                 {
377                                         if (!this->Load(entry->d_name))
378                                                 n_match++;
379                                 }
380                         }
381                         closedir(library);
382                 }
383                 /* Loadmodule will now return false if any one of the modules failed
384                  * to load (but wont abort when it encounters a bad one) and when 1 or
385                  * more modules were actually loaded.
386                  */
387                 return (n_match > 0);
388         }
389
390         char modfile[MAXBUF];
391         snprintf(modfile,MAXBUF,"%s/%s",Instance->Config->ModPath,filename);
392         std::string filename_str = filename;
393
394         if (!ServerConfig::DirValid(modfile))
395         {
396                 LastModuleError = "Module " + std::string(filename) + " is not in the module directory that i am configured to look in (is "+Instance->Config->ModPath+" really a symlink?)";
397                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
398                 return false;
399         }
400         
401         if (!ServerConfig::FileExists(modfile))
402         {
403                 LastModuleError = "Module file could not be found: " + filename_str;
404                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
405                 return false;
406         }
407         
408         if (Modules.find(filename_str) != Modules.end())
409         {       
410                 LastModuleError = "Module " + filename_str + " is already loaded, cannot load a module twice!";
411                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
412                 return false;
413         }
414                 
415         Module* newmod = NULL;
416         ircd_module* newhandle = NULL;
417
418         try
419         {
420                 /* This will throw a CoreException if there's a problem loading
421                  * the module file or getting a pointer to the init_module symbol.
422                  */
423                 newhandle = new ircd_module(Instance, modfile, "init_module");
424                 newmod = newhandle->CallInit();
425
426                 if (newmod)
427                 {
428                         Version v = newmod->GetVersion();
429
430                         if (v.API != API_VERSION)
431                         {
432                                 DetachAll(newmod);
433                                 delete newmod;
434                                 delete newhandle;
435                                 LastModuleError = "Unable to load " + filename_str + ": Incorrect module API version: " + ConvToStr(v.API) + " (our version: " + ConvToStr(API_VERSION) + ")";
436                                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
437                                 return false;
438                         }
439                         else
440                         {
441                                 Instance->Logs->Log("MODULE", DEFAULT,"New module introduced: %s (API version %d, Module version %d.%d.%d.%d)%s", filename, v.API, v.Major, v.Minor, v.Revision, v.Build, (!(v.Flags & VF_VENDOR) ? " [3rd Party]" : " [Vendor]"));
442                         }
443
444                         Modules[filename_str] = std::make_pair(newhandle, newmod);
445                 }
446                 else
447                 {
448                         delete newhandle;
449                         LastModuleError = "Unable to load " + filename_str + ": Probably missing init_module() entrypoint, but dlsym() didn't notice a problem";
450                         Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
451                         return false;
452                 }
453         }
454         /** XXX: Is there anything we can do about this mess? -- Brain */
455         catch (LoadModuleException& modexcept)
456         {
457                 DetachAll(newmod);
458                 if (newmod)
459                         delete newmod;
460                 if (newhandle)
461                         delete newhandle;
462                 LastModuleError = "Unable to load " + filename_str + ": Error when loading: " + modexcept.GetReason();
463                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
464                 return false;
465         }
466         catch (FindSymbolException& modexcept)
467         {
468                 DetachAll(newmod);
469                 if (newmod)
470                         delete newmod;
471                 if (newhandle)
472                         delete newhandle;
473                 LastModuleError = "Unable to load " + filename_str + ": Error finding symbol: " + modexcept.GetReason();
474                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
475                 return false;
476         }
477         catch (CoreException& modexcept)
478         {
479                 DetachAll(newmod);
480                 if (newmod)
481                         delete newmod;
482                 if (newhandle)
483                         delete newhandle;
484                 LastModuleError = "Unable to load " + filename_str + ": " + modexcept.GetReason();
485                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
486                 return false;
487         }
488
489         this->ModCount++;
490         FOREACH_MOD_I(Instance,I_OnLoadModule,OnLoadModule(newmod, filename_str));
491
492         /* We give every module a chance to re-prioritize when we introduce a new one,
493          * not just the one thats loading, as the new module could affect the preference
494          * of others
495          */
496         for (std::map<std::string, std::pair<ircd_module*, Module*> >::iterator n = Modules.begin(); n != Modules.end(); ++n)
497                 n->second.second->Prioritize();
498
499         Instance->BuildISupport();
500         return true;
501 }
502
503 bool ModuleManager::Unload(const char* filename)
504 {
505         std::string filename_str(filename);
506         std::map<std::string, std::pair<ircd_module*, Module*> >::iterator modfind = Modules.find(filename);
507
508         if (modfind != Modules.end())
509         {
510                 if (modfind->second.second->GetVersion().Flags & VF_STATIC)
511                 {
512                         LastModuleError = "Module " + filename_str + " not unloadable (marked static)";
513                         Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
514                         return false;
515                 }
516                 std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modfind->second.second);
517                 if (intercount.first > 0)
518                 {
519                         LastModuleError = "Failed to unload module " + filename_str + ", being used by " + ConvToStr(intercount.first) + " other(s) via interface '" + intercount.second + "'";
520                         Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
521                         return false;
522                 }
523
524                 /* Give the module a chance to tidy out all its metadata */
525                 for (chan_hash::iterator c = Instance->chanlist->begin(); c != Instance->chanlist->end(); c++)
526                 {
527                         modfind->second.second->OnCleanup(TYPE_CHANNEL,c->second);
528                 }
529                 for (user_hash::iterator u = Instance->Users->clientlist->begin(); u != Instance->Users->clientlist->end(); u++)
530                 {
531                         modfind->second.second->OnCleanup(TYPE_USER,u->second);
532                 }
533
534                 /* Tidy up any dangling resolvers */
535                 Instance->Res->CleanResolvers(modfind->second.second);
536
537
538                 FOREACH_MOD_I(Instance,I_OnUnloadModule,OnUnloadModule(modfind->second.second, modfind->first));
539
540                 this->DetachAll(modfind->second.second);
541
542                 Instance->Parser->RemoveCommands(filename);
543
544                 delete modfind->second.second;
545                 delete modfind->second.first;
546                 Modules.erase(modfind);
547
548                 Instance->Logs->Log("MODULE", DEFAULT,"Module %s unloaded",filename);
549                 this->ModCount--;
550                 Instance->BuildISupport();
551                 return true;
552         }
553
554         LastModuleError = "Module " + filename_str + " is not loaded, cannot unload it!";
555         Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
556         return false;
557 }
558
559 /* We must load the modules AFTER initializing the socket engine, now */
560 void ModuleManager::LoadAll()
561 {
562         char configToken[MAXBUF];
563         ModCount = -1;
564
565         for(int count = 0; count < Instance->Config->ConfValueEnum(Instance->Config->config_data, "module"); count++)
566         {
567                 Instance->Config->ConfValue(Instance->Config->config_data, "module", "name", count, configToken, MAXBUF);
568                 printf_c("[\033[1;32m*\033[0m] Loading module:\t\033[1;32m%s\033[0m\n",configToken);
569                 
570                 if (!this->Load(configToken))           
571                 {
572                         Instance->Logs->Log("MODULE", DEFAULT, this->LastError());
573                         printf_c("\n[\033[1;31m*\033[0m] %s\n\n", this->LastError().c_str());
574                         Instance->Exit(EXIT_STATUS_MODULE);
575                 }
576         }
577 }
578
579 bool ModuleManager::PublishFeature(const std::string &FeatureName, Module* Mod)
580 {
581         if (Features.find(FeatureName) == Features.end())
582         {
583                 Features[FeatureName] = Mod;
584                 return true;
585         }
586         return false;
587 }
588
589 bool ModuleManager::UnpublishFeature(const std::string &FeatureName)
590 {
591         featurelist::iterator iter = Features.find(FeatureName);
592         
593         if (iter == Features.end())
594                 return false;
595
596         Features.erase(iter);
597         return true;
598 }
599
600 Module* ModuleManager::FindFeature(const std::string &FeatureName)
601 {
602         featurelist::iterator iter = Features.find(FeatureName);
603
604         if (iter == Features.end())
605                 return NULL;
606
607         return iter->second;
608 }
609
610 bool ModuleManager::PublishInterface(const std::string &InterfaceName, Module* Mod)
611 {
612         interfacelist::iterator iter = Interfaces.find(InterfaceName);
613
614         if (iter == Interfaces.end())
615         {
616                 modulelist ml;
617                 ml.push_back(Mod);
618                 Interfaces[InterfaceName] = std::make_pair(0, ml);
619         }
620         else
621         {
622                 iter->second.second.push_back(Mod);
623         }
624         return true;
625 }
626
627 bool ModuleManager::UnpublishInterface(const std::string &InterfaceName, Module* Mod)
628 {
629         interfacelist::iterator iter = Interfaces.find(InterfaceName);
630
631         if (iter == Interfaces.end())
632                 return false;
633
634         for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
635         {
636                 if (*x == Mod)
637                 {
638                         iter->second.second.erase(x);
639                         if (iter->second.second.empty())
640                                 Interfaces.erase(InterfaceName);
641                         return true;
642                 }
643         }
644         return false;
645 }
646
647 modulelist* ModuleManager::FindInterface(const std::string &InterfaceName)
648 {
649         interfacelist::iterator iter = Interfaces.find(InterfaceName);
650         if (iter == Interfaces.end())
651                 return NULL;
652         else
653                 return &(iter->second.second);
654 }
655
656 bool ModuleManager::ModuleHasInterface(Module* mod, const std::string& InterfaceName)
657 {
658         interfacelist::iterator iter = Interfaces.find(InterfaceName);
659         if (iter == Interfaces.end())
660                 return false;
661         else
662         {
663                 modulelist& ml = iter->second.second;
664                 modulelist::iterator mi = std::find(ml.begin(), ml.end(), mod);
665                 return (mi != ml.end());
666         }
667 }
668
669 void ModuleManager::UseInterface(const std::string &InterfaceName)
670 {
671         interfacelist::iterator iter = Interfaces.find(InterfaceName);
672         if (iter != Interfaces.end())
673                 iter->second.first++;
674
675 }
676
677 void ModuleManager::DoneWithInterface(const std::string &InterfaceName)
678 {
679         interfacelist::iterator iter = Interfaces.find(InterfaceName);
680         if (iter != Interfaces.end())
681                 iter->second.first--;
682 }
683
684 std::pair<int,std::string> ModuleManager::GetInterfaceInstanceCount(Module* m)
685 {
686         for (interfacelist::iterator iter = Interfaces.begin(); iter != Interfaces.end(); iter++)
687         {
688                 for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
689                 {
690                         if (*x == m)
691                         {
692                                 return std::make_pair(iter->second.first, iter->first);
693                         }
694                 }
695         }
696         return std::make_pair(0, "");
697 }
698
699 const std::string& ModuleManager::GetModuleName(Module* m)
700 {
701         static std::string nothing;
702
703         for (std::map<std::string, std::pair<ircd_module*, Module*> >::iterator n = Modules.begin(); n != Modules.end(); ++n)
704         {
705                 if (n->second.second == m)
706                         return n->first;
707         }
708
709         return nothing;
710 }
711
712 /* This is ugly, yes, but hash_map's arent designed to be
713  * addressed in this manner, and this is a bit of a kludge.
714  * Luckily its a specialist function and rarely used by
715  * many modules (in fact, it was specially created to make
716  * m_safelist possible, initially).
717  */
718
719 Channel* InspIRCd::GetChannelIndex(long index)
720 {
721         int target = 0;
722         for (chan_hash::iterator n = this->chanlist->begin(); n != this->chanlist->end(); n++, target++)
723         {
724                 if (index == target)
725                         return n->second;
726         }
727         return NULL;
728 }
729
730 bool InspIRCd::MatchText(const std::string &sliteral, const std::string &spattern)
731 {
732         return match(sliteral, spattern);
733 }
734
735 CmdResult InspIRCd::CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user)
736 {
737         return this->Parser->CallHandler(commandname, parameters, user);
738 }
739
740 bool InspIRCd::IsValidModuleCommand(const std::string &commandname, int pcnt, User* user)
741 {
742         return this->Parser->IsValidCommand(commandname, pcnt, user);
743 }
744
745 void InspIRCd::AddCommand(Command *f)
746 {
747         if (!this->Parser->CreateCommand(f))
748         {
749                 ModuleException err("Command "+std::string(f->command)+" already exists.");
750                 throw (err);
751         }
752 }
753
754 void InspIRCd::SendMode(const std::vector<std::string>& parameters, User *user)
755 {
756         this->Modes->Process(parameters, user, true);
757 }
758
759 void InspIRCd::DumpText(User* User, const std::string &LinePrefix, std::stringstream &TextStream)
760 {
761         std::string CompleteLine = LinePrefix;
762         std::string Word;
763         while (TextStream >> Word)
764         {
765                 if (CompleteLine.length() + Word.length() + 3 > 500)
766                 {
767                         User->WriteServ(CompleteLine);
768                         CompleteLine = LinePrefix;
769                 }
770                 CompleteLine = CompleteLine + Word + " ";
771         }
772         User->WriteServ(CompleteLine);
773 }
774
775 User* FindDescriptorHandler::Call(int socket)
776 {
777         return reinterpret_cast<User*>(Server->SE->GetRef(socket));
778 }
779
780 bool InspIRCd::AddResolver(Resolver* r, bool cached)
781 {
782         if (!cached)
783                 return this->Res->AddResolverClass(r);
784         else
785         {
786                 r->TriggerCachedResult();
787                 delete r;
788                 return true;
789         }
790 }
791
792 Module* ModuleManager::Find(const std::string &name)
793 {
794         std::map<std::string, std::pair<ircd_module*, Module*> >::iterator modfind = Modules.find(name);
795
796         if (modfind == Modules.end())
797                 return NULL;
798         else
799                 return modfind->second.second;
800 }
801
802 const std::vector<std::string> ModuleManager::GetAllModuleNames(int filter)
803 {
804         std::vector<std::string> retval;
805         for (std::map<std::string, std::pair<ircd_module*, Module*> >::iterator x = Modules.begin(); x != Modules.end(); ++x)
806                 if (!filter || (x->second.second->GetVersion().Flags & filter))
807                         retval.push_back(x->first);
808         return retval;
809 }
810
811 ConfigReader::ConfigReader(InspIRCd* Instance) : ServerInstance(Instance)
812 {
813         this->errorlog = new std::ostringstream(std::stringstream::in | std::stringstream::out);
814         this->error = CONF_NO_ERROR;
815         this->data = &ServerInstance->Config->config_data;
816         this->privatehash = false;
817 }
818
819
820 ConfigReader::~ConfigReader()
821 {
822         if (this->errorlog)
823                 delete this->errorlog;
824         if(this->privatehash)
825                 delete this->data;
826 }
827
828
829 ConfigReader::ConfigReader(InspIRCd* Instance, const std::string &filename) : ServerInstance(Instance)
830 {
831         ServerInstance->Config->ClearStack();
832
833         this->error = CONF_NO_ERROR;
834         this->data = new ConfigDataHash;
835         this->privatehash = true;
836         this->errorlog = new std::ostringstream(std::stringstream::in | std::stringstream::out);
837         /*** XXX: This might block! */
838         this->readerror = ServerInstance->Config->DoInclude(*this->data, filename, *this->errorlog);
839         if (!this->readerror)
840                 this->error = CONF_FILE_NOT_FOUND;
841 }
842
843
844 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool allow_linefeeds)
845 {
846         /* Don't need to strlcpy() tag and name anymore, ReadConf() takes const char* */ 
847         std::string result;
848         
849         if (!ServerInstance->Config->ConfValue(*this->data, tag, name, default_value, index, result, allow_linefeeds))
850         {
851                 this->error = CONF_VALUE_NOT_FOUND;
852         }
853         return result;
854 }
855
856 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, int index, bool allow_linefeeds)
857 {
858         return ReadValue(tag, name, "", index, allow_linefeeds);
859 }
860
861 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, const std::string &default_value, int index)
862 {
863         return ServerInstance->Config->ConfValueBool(*this->data, tag, name, default_value, index);
864 }
865
866 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, int index)
867 {
868         return ReadFlag(tag, name, "", index);
869 }
870
871
872 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool need_positive)
873 {
874         int result;
875         
876         if(!ServerInstance->Config->ConfValueInteger(*this->data, tag, name, default_value, index, result))
877         {
878                 this->error = CONF_VALUE_NOT_FOUND;
879                 return 0;
880         }
881         
882         if ((need_positive) && (result < 0))
883         {
884                 this->error = CONF_INT_NEGATIVE;
885                 return 0;
886         }
887         
888         return result;
889 }
890
891 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, int index, bool need_positive)
892 {
893         return ReadInteger(tag, name, "", index, need_positive);
894 }
895
896 long ConfigReader::GetError()
897 {
898         long olderr = this->error;
899         this->error = 0;
900         return olderr;
901 }
902
903 void ConfigReader::DumpErrors(bool bail, User* user)
904 {
905         ServerInstance->Config->ReportConfigError(this->errorlog->str(), bail, user);
906 }
907
908
909 int ConfigReader::Enumerate(const std::string &tag)
910 {
911         return ServerInstance->Config->ConfValueEnum(*this->data, tag);
912 }
913
914 int ConfigReader::EnumerateValues(const std::string &tag, int index)
915 {
916         return ServerInstance->Config->ConfVarEnum(*this->data, tag, index);
917 }
918
919 bool ConfigReader::Verify()
920 {
921         return this->readerror;
922 }
923
924
925 FileReader::FileReader(InspIRCd* Instance, const std::string &filename) : ServerInstance(Instance)
926 {
927         LoadFile(filename);
928 }
929
930 FileReader::FileReader(InspIRCd* Instance) : ServerInstance(Instance)
931 {
932 }
933
934 std::string FileReader::Contents()
935 {
936         std::string x;
937         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
938         {
939                 x.append(*a);
940                 x.append("\r\n");
941         }
942         return x;
943 }
944
945 unsigned long FileReader::ContentSize()
946 {
947         return this->contentsize;
948 }
949
950 void FileReader::CalcSize()
951 {
952         unsigned long n = 0;
953         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
954                 n += (a->length() + 2);
955         this->contentsize = n;
956 }
957
958 void FileReader::LoadFile(const std::string &filename)
959 {
960         file_cache c;
961         c.clear();
962         if (ServerInstance->Config->ReadFile(c,filename.c_str()))
963         {
964                 this->fc = c;
965                 this->CalcSize();
966         }
967 }
968
969
970 FileReader::~FileReader()
971 {
972 }
973
974 bool FileReader::Exists()
975 {
976         return (!(fc.size() == 0));
977 }
978
979 std::string FileReader::GetLine(int x)
980 {
981         if ((x<0) || ((unsigned)x>fc.size()))
982                 return "";
983         return fc[x];
984 }
985
986 int FileReader::FileSize()
987 {
988         return fc.size();
989 }