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