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