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