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