]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules.cpp
Make classbase and refcountbase uncopyable; expand comments on their indended uses
[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         /* Do we have a glob pattern in the filename?
325          * The user wants to load multiple modules which
326          * match the pattern.
327          */
328         if (strchr(filename,'*') || (strchr(filename,'?')))
329         {
330                 int n_match = 0;
331                 DIR* library = opendir(ServerInstance->Config->ModPath.c_str());
332                 if (library)
333                 {
334                         /* Try and locate and load all modules matching the pattern */
335                         dirent* entry = NULL;
336                         while (0 != (entry = readdir(library)))
337                         {
338                                 if (InspIRCd::Match(entry->d_name, filename, ascii_case_insensitive_map))
339                                 {
340                                         if (!this->Load(entry->d_name))
341                                                 n_match++;
342                                 }
343                         }
344                         closedir(library);
345                 }
346                 /* Loadmodule will now return false if any one of the modules failed
347                  * to load (but wont abort when it encounters a bad one) and when 1 or
348                  * more modules were actually loaded.
349                  */
350                 return (n_match > 0 ? false : true);
351         }
352
353         char modfile[MAXBUF];
354         snprintf(modfile,MAXBUF,"%s/%s",ServerInstance->Config->ModPath.c_str(),filename);
355         std::string filename_str = filename;
356
357         if (!ServerConfig::FileExists(modfile))
358         {
359                 LastModuleError = "Module file could not be found: " + filename_str;
360                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
361                 return false;
362         }
363
364         if (Modules.find(filename_str) != Modules.end())
365         {
366                 LastModuleError = "Module " + filename_str + " is already loaded, cannot load a module twice!";
367                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
368                 return false;
369         }
370
371         Module* newmod = NULL;
372         DLLManager* newhandle = new DLLManager(modfile);
373
374         try
375         {
376                 newmod = newhandle->callInit();
377
378                 if (newmod)
379                 {
380                         newmod->ModuleSourceFile = filename_str;
381                         newmod->ModuleDLLManager = newhandle;
382                         Version v = newmod->GetVersion();
383
384                         ServerInstance->Logs->Log("MODULE", DEFAULT,"New module introduced: %s (Module version %s)%s",
385                                 filename, v.version.c_str(), (!(v.Flags & VF_VENDOR) ? " [3rd Party]" : " [Vendor]"));
386
387                         Modules[filename_str] = newmod;
388                 }
389                 else
390                 {
391                         LastModuleError = "Unable to load " + filename_str + ": " + newhandle->LastError();
392                         ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
393                         delete newhandle;
394                         return false;
395                 }
396         }
397         catch (CoreException& modexcept)
398         {
399                 // failure in module constructor
400                 delete newmod;
401                 delete newhandle;
402                 LastModuleError = "Unable to load " + filename_str + ": " + modexcept.GetReason();
403                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
404                 return false;
405         }
406
407         this->ModCount++;
408         FOREACH_MOD(I_OnLoadModule,OnLoadModule(newmod));
409
410         /* We give every module a chance to re-prioritize when we introduce a new one,
411          * not just the one thats loading, as the new module could affect the preference
412          * of others
413          */
414         for(int tries = 0; tries < 20; tries++)
415         {
416                 prioritizationState = tries > 0 ? PRIO_STATE_LAST : PRIO_STATE_FIRST;
417                 for (std::map<std::string, Module*>::iterator n = Modules.begin(); n != Modules.end(); ++n)
418                         n->second->Prioritize();
419
420                 if (prioritizationState == PRIO_STATE_LAST)
421                         break;
422                 if (tries == 19)
423                         ServerInstance->Logs->Log("MODULE", DEFAULT, "Hook priority dependency loop detected while loading " + filename_str);
424         }
425
426         ServerInstance->BuildISupport();
427         return true;
428 }
429
430 bool ModuleManager::CanUnload(Module* mod)
431 {
432         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
433
434         if (modfind == Modules.end() || modfind->second != mod)
435         {
436                 LastModuleError = "Module " + mod->ModuleSourceFile + " is not loaded, cannot unload it!";
437                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
438                 return false;
439         }
440         if (mod->GetVersion().Flags & VF_STATIC)
441         {
442                 LastModuleError = "Module " + mod->ModuleSourceFile + " not unloadable (marked static)";
443                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
444                 return false;
445         }
446         std::pair<int,std::string> intercount = GetInterfaceInstanceCount(mod);
447         if (intercount.first > 0)
448         {
449                 LastModuleError = "Failed to unload module " + mod->ModuleSourceFile + ", being used by " + ConvToStr(intercount.first) + " other(s) via interface '" + intercount.second + "'";
450                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
451                 return false;
452         }
453         return true;
454 }
455
456 void ModuleManager::DoSafeUnload(Module* mod)
457 {
458         std::map<std::string, Module*>::iterator modfind = Modules.find(mod->ModuleSourceFile);
459
460         std::vector<ExtensionItem*> items;
461         ServerInstance->Extensions.BeginUnregister(modfind->second, items);
462         /* Give the module a chance to tidy out all its metadata */
463         for (chan_hash::iterator c = ServerInstance->chanlist->begin(); c != ServerInstance->chanlist->end(); c++)
464         {
465                 mod->OnCleanup(TYPE_CHANNEL,c->second);
466                 c->second->doUnhookExtensions(items);
467                 const UserMembList* users = c->second->GetUsers();
468                 for(UserMembCIter mi = users->begin(); mi != users->end(); mi++)
469                         mi->second->doUnhookExtensions(items);
470         }
471         for (user_hash::iterator u = ServerInstance->Users->clientlist->begin(); u != ServerInstance->Users->clientlist->end(); u++)
472         {
473                 mod->OnCleanup(TYPE_USER,u->second);
474                 u->second->doUnhookExtensions(items);
475         }
476
477         /* Tidy up any dangling resolvers */
478         ServerInstance->Res->CleanResolvers(mod);
479
480         FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(mod));
481
482         DetachAll(mod);
483
484         Modules.erase(modfind);
485         ServerInstance->GlobalCulls.AddItem(mod);
486
487         ServerInstance->Logs->Log("MODULE", DEFAULT,"Module %s unloaded",mod->ModuleSourceFile.c_str());
488         this->ModCount--;
489         ServerInstance->BuildISupport();
490 }
491
492 namespace {
493         struct UnloadAction : public HandlerBase0<void>
494         {
495                 Module* const mod;
496                 UnloadAction(Module* m) : mod(m) {}
497                 void Call()
498                 {
499                         DLLManager* dll = mod->ModuleDLLManager;
500                         ServerInstance->Modules->DoSafeUnload(mod);
501                         ServerInstance->GlobalCulls.Apply();
502                         delete dll;
503                         ServerInstance->GlobalCulls.AddItem(this);
504                 }
505         };
506
507         struct ReloadAction : public HandlerBase0<void>
508         {
509                 Module* const mod;
510                 HandlerBase1<void, bool>* const callback;
511                 ReloadAction(Module* m, HandlerBase1<void, bool>* c)
512                         : mod(m), callback(c) {}
513                 void Call()
514                 {
515                         DLLManager* dll = mod->ModuleDLLManager;
516                         std::string name = mod->ModuleSourceFile;
517                         ServerInstance->Modules->DoSafeUnload(mod);
518                         ServerInstance->GlobalCulls.Apply();
519                         delete dll;
520                         bool rv = ServerInstance->Modules->Load(name.c_str());
521                         callback->Call(rv);
522                         ServerInstance->GlobalCulls.AddItem(this);
523                 }
524         };
525 }
526
527 bool ModuleManager::Unload(Module* mod)
528 {
529         if (!CanUnload(mod))
530                 return false;
531         ServerInstance->AtomicActions.AddAction(new UnloadAction(mod));
532         return true;
533 }
534
535 void ModuleManager::Reload(Module* mod, HandlerBase1<void, bool>* callback)
536 {
537         if (CanUnload(mod))
538                 ServerInstance->AtomicActions.AddAction(new ReloadAction(mod, callback));
539         else
540                 callback->Call(false);
541 }
542
543 /* We must load the modules AFTER initializing the socket engine, now */
544 void ModuleManager::LoadAll()
545 {
546         ModCount = 0;
547
548         printf("\nLoading core commands");
549         fflush(stdout);
550
551         DIR* library = opendir(ServerInstance->Config->ModPath.c_str());
552         if (library)
553         {
554                 dirent* entry = NULL;
555                 while (0 != (entry = readdir(library)))
556                 {
557                         if (InspIRCd::Match(entry->d_name, "cmd_*.so", ascii_case_insensitive_map))
558                         {
559                                 printf(".");
560                                 fflush(stdout);
561
562                                 if (!Load(entry->d_name))
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                 closedir(library);
571                 printf("\n");
572         }
573
574         for(int count = 0;; count++)
575         {
576                 ConfigTag* tag = ServerInstance->Config->ConfValue("module", count);
577                 if (!tag)
578                         break;
579                 std::string name = tag->getString("name");
580                 printf_c("[\033[1;32m*\033[0m] Loading module:\t\033[1;32m%s\033[0m\n",name.c_str());
581
582                 if (!this->Load(name.c_str()))
583                 {
584                         ServerInstance->Logs->Log("MODULE", DEFAULT, this->LastError());
585                         printf_c("\n[\033[1;31m*\033[0m] %s\n\n", this->LastError().c_str());
586                         ServerInstance->Exit(EXIT_STATUS_MODULE);
587                 }
588         }
589 }
590
591 void ModuleManager::UnloadAll()
592 {
593         /* We do this more than once, so that any service providers get a
594          * chance to be unhooked by the modules using them, but then get
595          * a chance to be removed themsleves.
596          *
597          * Note: this deliberately does NOT delete the DLLManager objects
598          */
599         for (int tries = 0; tries < 4; tries++)
600         {
601                 std::map<std::string, Module*>::iterator i = Modules.begin();
602                 while (i != Modules.end())
603                 {
604                         std::map<std::string, Module*>::iterator me = i++;
605                         if (CanUnload(me->second))
606                         {
607                                 ServerInstance->GlobalCulls.AddItem(me->second);
608                                 Modules.erase(me);
609                         }
610                 }
611                 ServerInstance->GlobalCulls.Apply();
612         }
613 }
614
615 bool ModuleManager::PublishFeature(const std::string &FeatureName, Module* Mod)
616 {
617         if (Features.find(FeatureName) == Features.end())
618         {
619                 Features[FeatureName] = Mod;
620                 return true;
621         }
622         return false;
623 }
624
625 bool ModuleManager::UnpublishFeature(const std::string &FeatureName)
626 {
627         featurelist::iterator iter = Features.find(FeatureName);
628
629         if (iter == Features.end())
630                 return false;
631
632         Features.erase(iter);
633         return true;
634 }
635
636 Module* ModuleManager::FindFeature(const std::string &FeatureName)
637 {
638         featurelist::iterator iter = Features.find(FeatureName);
639
640         if (iter == Features.end())
641                 return NULL;
642
643         return iter->second;
644 }
645
646 bool ModuleManager::PublishInterface(const std::string &InterfaceName, Module* Mod)
647 {
648         interfacelist::iterator iter = Interfaces.find(InterfaceName);
649
650         if (iter == Interfaces.end())
651         {
652                 modulelist ml;
653                 ml.push_back(Mod);
654                 Interfaces[InterfaceName] = std::make_pair(0, ml);
655         }
656         else
657         {
658                 iter->second.second.push_back(Mod);
659         }
660         return true;
661 }
662
663 bool ModuleManager::UnpublishInterface(const std::string &InterfaceName, Module* Mod)
664 {
665         interfacelist::iterator iter = Interfaces.find(InterfaceName);
666
667         if (iter == Interfaces.end())
668                 return false;
669
670         for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
671         {
672                 if (*x == Mod)
673                 {
674                         iter->second.second.erase(x);
675                         if (iter->second.second.empty())
676                                 Interfaces.erase(InterfaceName);
677                         return true;
678                 }
679         }
680         return false;
681 }
682
683 modulelist* ModuleManager::FindInterface(const std::string &InterfaceName)
684 {
685         interfacelist::iterator iter = Interfaces.find(InterfaceName);
686         if (iter == Interfaces.end())
687                 return NULL;
688         else
689                 return &(iter->second.second);
690 }
691
692 bool ModuleManager::ModuleHasInterface(Module* mod, const std::string& InterfaceName)
693 {
694         interfacelist::iterator iter = Interfaces.find(InterfaceName);
695         if (iter == Interfaces.end())
696                 return false;
697         else
698         {
699                 modulelist& ml = iter->second.second;
700                 modulelist::iterator mi = std::find(ml.begin(), ml.end(), mod);
701                 return (mi != ml.end());
702         }
703 }
704
705 void ModuleManager::UseInterface(const std::string &InterfaceName)
706 {
707         interfacelist::iterator iter = Interfaces.find(InterfaceName);
708         if (iter != Interfaces.end())
709                 iter->second.first++;
710
711 }
712
713 void ModuleManager::DoneWithInterface(const std::string &InterfaceName)
714 {
715         interfacelist::iterator iter = Interfaces.find(InterfaceName);
716         if (iter != Interfaces.end())
717                 iter->second.first--;
718 }
719
720 std::pair<int,std::string> ModuleManager::GetInterfaceInstanceCount(Module* m)
721 {
722         for (interfacelist::iterator iter = Interfaces.begin(); iter != Interfaces.end(); iter++)
723         {
724                 for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
725                 {
726                         if (*x == m)
727                         {
728                                 return std::make_pair(iter->second.first, iter->first);
729                         }
730                 }
731         }
732         return std::make_pair(0, "");
733 }
734
735 const std::string& ModuleManager::GetModuleName(Module* m)
736 {
737         static std::string nothing;
738
739         for (std::map<std::string, Module*>::iterator n = Modules.begin(); n != Modules.end(); ++n)
740         {
741                 if (n->second == m)
742                         return n->first;
743         }
744
745         return nothing;
746 }
747
748 CmdResult InspIRCd::CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user)
749 {
750         return this->Parser->CallHandler(commandname, parameters, user);
751 }
752
753 bool InspIRCd::IsValidModuleCommand(const std::string &commandname, int pcnt, User* user)
754 {
755         return this->Parser->IsValidCommand(commandname, pcnt, user);
756 }
757
758 void InspIRCd::AddCommand(Command *f)
759 {
760         if (!this->Parser->AddCommand(f))
761         {
762                 throw ModuleException("Command "+std::string(f->command)+" already exists.");
763         }
764 }
765
766 void InspIRCd::SendMode(const std::vector<std::string>& parameters, User *user)
767 {
768         this->Modes->Process(parameters, user);
769 }
770
771 void InspIRCd::DumpText(User* user, const std::string &text)
772 {
773         if (IS_LOCAL(user))
774         {
775                 user->Write(text);
776         }
777         else
778         {
779                 PI->PushToClient(user, text);
780         }
781 }
782
783 void InspIRCd::DumpText(User* user, const char *text, ...)
784 {
785         va_list argsPtr;
786         char line[MAXBUF];
787
788         va_start(argsPtr, text);
789         vsnprintf(line, MAXBUF, text, argsPtr);
790         va_end(argsPtr);
791
792         DumpText(user, std::string(line));
793 }
794
795 void InspIRCd::DumpText(User* user, const std::string &LinePrefix, std::stringstream &TextStream)
796 {
797         char line[MAXBUF];
798         int start_pos = LinePrefix.length();
799         int pos = start_pos;
800         memcpy(line, LinePrefix.data(), pos);
801         std::string Word;
802         while (TextStream >> Word)
803         {
804                 int len = Word.length();
805                 if (pos + len + 12 > MAXBUF)
806                 {
807                         line[pos] = '\0';
808                         DumpText(user, std::string(line));
809                         pos = start_pos;
810                 }
811                 line[pos] = ' ';
812                 memcpy(line + pos + 1, Word.data(), len);
813                 pos += len + 1;
814         }
815         line[pos] = '\0';
816         DumpText(user, std::string(line));
817 }
818
819 bool InspIRCd::AddResolver(Resolver* r, bool cached)
820 {
821         if (!cached)
822                 return this->Res->AddResolverClass(r);
823         else
824         {
825                 r->TriggerCachedResult();
826                 delete r;
827                 return true;
828         }
829 }
830
831 Module* ModuleManager::Find(const std::string &name)
832 {
833         std::map<std::string, Module*>::iterator modfind = Modules.find(name);
834
835         if (modfind == Modules.end())
836                 return NULL;
837         else
838                 return modfind->second;
839 }
840
841 const std::vector<std::string> ModuleManager::GetAllModuleNames(int filter)
842 {
843         std::vector<std::string> retval;
844         for (std::map<std::string, Module*>::iterator x = Modules.begin(); x != Modules.end(); ++x)
845                 if (!filter || (x->second->GetVersion().Flags & filter))
846                         retval.push_back(x->first);
847         return retval;
848 }
849
850 ConfigReader::ConfigReader()
851 {
852         this->error = 0;
853 }
854
855
856 ConfigReader::~ConfigReader()
857 {
858 }
859
860
861 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool allow_linefeeds)
862 {
863         /* Don't need to strlcpy() tag and name anymore, ReadConf() takes const char* */
864         std::string result = default_value;
865         if (!ServerInstance->Config->ConfValue(tag, index)->readString(name, result, allow_linefeeds))
866         {
867                 this->error = CONF_VALUE_NOT_FOUND;
868         }
869         return result;
870 }
871
872 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, int index, bool allow_linefeeds)
873 {
874         return ReadValue(tag, name, "", index, allow_linefeeds);
875 }
876
877 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, const std::string &default_value, int index)
878 {
879         bool def = (default_value == "yes");
880         return ServerInstance->Config->ConfValue(tag, index)->getBool(name, def);
881 }
882
883 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, int index)
884 {
885         return ReadFlag(tag, name, "", index);
886 }
887
888
889 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool need_positive)
890 {
891         int v = atoi(default_value.c_str());
892         int result = ServerInstance->Config->ConfValue(tag, index)->getInt(name, v);
893
894         if ((need_positive) && (result < 0))
895         {
896                 this->error = CONF_INT_NEGATIVE;
897                 return 0;
898         }
899
900         return result;
901 }
902
903 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, int index, bool need_positive)
904 {
905         return ReadInteger(tag, name, "", index, need_positive);
906 }
907
908 long ConfigReader::GetError()
909 {
910         long olderr = this->error;
911         this->error = 0;
912         return olderr;
913 }
914
915 int ConfigReader::Enumerate(const std::string &tag)
916 {
917         ServerInstance->Logs->Log("MODULE", DEBUG, "Module is using ConfigReader::Enumerate on %s; this is slow!",
918                 tag.c_str());
919         int i=0;
920         while (ServerInstance->Config->ConfValue(tag, i)) i++;
921         return i;
922 }
923
924 FileReader::FileReader(const std::string &filename)
925 {
926         LoadFile(filename);
927 }
928
929 FileReader::FileReader()
930 {
931 }
932
933 std::string FileReader::Contents()
934 {
935         std::string x;
936         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
937         {
938                 x.append(*a);
939                 x.append("\r\n");
940         }
941         return x;
942 }
943
944 unsigned long FileReader::ContentSize()
945 {
946         return this->contentsize;
947 }
948
949 void FileReader::CalcSize()
950 {
951         unsigned long n = 0;
952         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
953                 n += (a->length() + 2);
954         this->contentsize = n;
955 }
956
957 void FileReader::LoadFile(const std::string &filename)
958 {
959         file_cache c;
960         c.clear();
961         if (ServerInstance->Config->ReadFile(c,filename.c_str()))
962         {
963                 this->fc = c;
964                 this->CalcSize();
965         }
966 }
967
968
969 FileReader::~FileReader()
970 {
971 }
972
973 bool FileReader::Exists()
974 {
975         return (!(fc.size() == 0));
976 }
977
978 std::string FileReader::GetLine(int x)
979 {
980         if ((x<0) || ((unsigned)x>fc.size()))
981                 return "";
982         return fc[x];
983 }
984
985 int FileReader::FileSize()
986 {
987         return fc.size();
988 }