]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules.cpp
87d25ac428d7ef7b8df3ae82bd5fc415653e1345
[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<reference<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         for(char m='A'; m < 'z'; m++)
480         {
481                 ModeHandler* mh;
482                 mh = ServerInstance->Modes->FindMode(m, MODETYPE_USER);
483                 if (mh && mh->creator == mod)
484                         ServerInstance->Modes->DelMode(mh);
485                 mh = ServerInstance->Modes->FindMode(m, MODETYPE_CHANNEL);
486                 if (mh && mh->creator == mod)
487                         ServerInstance->Modes->DelMode(mh);
488         }
489
490         /* Tidy up any dangling resolvers */
491         ServerInstance->Res->CleanResolvers(mod);
492
493         FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(mod));
494
495         DetachAll(mod);
496
497         Modules.erase(modfind);
498         ServerInstance->GlobalCulls.AddItem(mod);
499
500         ServerInstance->Logs->Log("MODULE", DEFAULT,"Module %s unloaded",mod->ModuleSourceFile.c_str());
501         this->ModCount--;
502         ServerInstance->BuildISupport();
503 }
504
505 namespace {
506         struct UnloadAction : public HandlerBase0<void>
507         {
508                 Module* const mod;
509                 UnloadAction(Module* m) : mod(m) {}
510                 void Call()
511                 {
512                         DLLManager* dll = mod->ModuleDLLManager;
513                         ServerInstance->Modules->DoSafeUnload(mod);
514                         ServerInstance->GlobalCulls.Apply();
515                         delete dll;
516                         ServerInstance->GlobalCulls.AddItem(this);
517                 }
518         };
519
520         struct ReloadAction : public HandlerBase0<void>
521         {
522                 Module* const mod;
523                 HandlerBase1<void, bool>* const callback;
524                 ReloadAction(Module* m, HandlerBase1<void, bool>* c)
525                         : mod(m), callback(c) {}
526                 void Call()
527                 {
528                         DLLManager* dll = mod->ModuleDLLManager;
529                         std::string name = mod->ModuleSourceFile;
530                         ServerInstance->Modules->DoSafeUnload(mod);
531                         ServerInstance->GlobalCulls.Apply();
532                         delete dll;
533                         bool rv = ServerInstance->Modules->Load(name.c_str());
534                         callback->Call(rv);
535                         ServerInstance->GlobalCulls.AddItem(this);
536                 }
537         };
538 }
539
540 bool ModuleManager::Unload(Module* mod)
541 {
542         if (!CanUnload(mod))
543                 return false;
544         ServerInstance->AtomicActions.AddAction(new UnloadAction(mod));
545         return true;
546 }
547
548 void ModuleManager::Reload(Module* mod, HandlerBase1<void, bool>* callback)
549 {
550         if (CanUnload(mod))
551                 ServerInstance->AtomicActions.AddAction(new ReloadAction(mod, callback));
552         else
553                 callback->Call(false);
554 }
555
556 /* We must load the modules AFTER initializing the socket engine, now */
557 void ModuleManager::LoadAll()
558 {
559         ModCount = 0;
560
561         printf("\nLoading core commands");
562         fflush(stdout);
563
564         DIR* library = opendir(ServerInstance->Config->ModPath.c_str());
565         if (library)
566         {
567                 dirent* entry = NULL;
568                 while (0 != (entry = readdir(library)))
569                 {
570                         if (InspIRCd::Match(entry->d_name, "cmd_*.so", ascii_case_insensitive_map))
571                         {
572                                 printf(".");
573                                 fflush(stdout);
574
575                                 if (!Load(entry->d_name))
576                                 {
577                                         ServerInstance->Logs->Log("MODULE", DEFAULT, this->LastError());
578                                         printf_c("\n[\033[1;31m*\033[0m] %s\n\n", this->LastError().c_str());
579                                         ServerInstance->Exit(EXIT_STATUS_MODULE);
580                                 }
581                         }
582                 }
583                 closedir(library);
584                 printf("\n");
585         }
586
587         for(int count = 0;; count++)
588         {
589                 ConfigTag* tag = ServerInstance->Config->ConfValue("module", count);
590                 if (!tag)
591                         break;
592                 std::string name = tag->getString("name");
593                 printf_c("[\033[1;32m*\033[0m] Loading module:\t\033[1;32m%s\033[0m\n",name.c_str());
594
595                 if (!this->Load(name.c_str()))
596                 {
597                         ServerInstance->Logs->Log("MODULE", DEFAULT, this->LastError());
598                         printf_c("\n[\033[1;31m*\033[0m] %s\n\n", this->LastError().c_str());
599                         ServerInstance->Exit(EXIT_STATUS_MODULE);
600                 }
601         }
602 }
603
604 void ModuleManager::UnloadAll()
605 {
606         /* We do this more than once, so that any service providers get a
607          * chance to be unhooked by the modules using them, but then get
608          * a chance to be removed themsleves.
609          *
610          * Note: this deliberately does NOT delete the DLLManager objects
611          */
612         for (int tries = 0; tries < 4; tries++)
613         {
614                 std::map<std::string, Module*>::iterator i = Modules.begin();
615                 while (i != Modules.end())
616                 {
617                         std::map<std::string, Module*>::iterator me = i++;
618                         if (CanUnload(me->second))
619                         {
620                                 DoSafeUnload(me->second);
621                         }
622                 }
623                 ServerInstance->GlobalCulls.Apply();
624         }
625 }
626
627 bool ModuleManager::PublishFeature(const std::string &FeatureName, Module* Mod)
628 {
629         if (Features.find(FeatureName) == Features.end())
630         {
631                 Features[FeatureName] = Mod;
632                 return true;
633         }
634         return false;
635 }
636
637 bool ModuleManager::UnpublishFeature(const std::string &FeatureName)
638 {
639         featurelist::iterator iter = Features.find(FeatureName);
640
641         if (iter == Features.end())
642                 return false;
643
644         Features.erase(iter);
645         return true;
646 }
647
648 Module* ModuleManager::FindFeature(const std::string &FeatureName)
649 {
650         featurelist::iterator iter = Features.find(FeatureName);
651
652         if (iter == Features.end())
653                 return NULL;
654
655         return iter->second;
656 }
657
658 bool ModuleManager::PublishInterface(const std::string &InterfaceName, Module* Mod)
659 {
660         interfacelist::iterator iter = Interfaces.find(InterfaceName);
661
662         if (iter == Interfaces.end())
663         {
664                 modulelist ml;
665                 ml.push_back(Mod);
666                 Interfaces[InterfaceName] = std::make_pair(0, ml);
667         }
668         else
669         {
670                 iter->second.second.push_back(Mod);
671         }
672         return true;
673 }
674
675 bool ModuleManager::UnpublishInterface(const std::string &InterfaceName, Module* Mod)
676 {
677         interfacelist::iterator iter = Interfaces.find(InterfaceName);
678
679         if (iter == Interfaces.end())
680                 return false;
681
682         for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
683         {
684                 if (*x == Mod)
685                 {
686                         iter->second.second.erase(x);
687                         if (iter->second.second.empty())
688                                 Interfaces.erase(InterfaceName);
689                         return true;
690                 }
691         }
692         return false;
693 }
694
695 modulelist* ModuleManager::FindInterface(const std::string &InterfaceName)
696 {
697         interfacelist::iterator iter = Interfaces.find(InterfaceName);
698         if (iter == Interfaces.end())
699                 return NULL;
700         else
701                 return &(iter->second.second);
702 }
703
704 bool ModuleManager::ModuleHasInterface(Module* mod, const std::string& InterfaceName)
705 {
706         interfacelist::iterator iter = Interfaces.find(InterfaceName);
707         if (iter == Interfaces.end())
708                 return false;
709         else
710         {
711                 modulelist& ml = iter->second.second;
712                 modulelist::iterator mi = std::find(ml.begin(), ml.end(), mod);
713                 return (mi != ml.end());
714         }
715 }
716
717 void ModuleManager::UseInterface(const std::string &InterfaceName)
718 {
719         interfacelist::iterator iter = Interfaces.find(InterfaceName);
720         if (iter != Interfaces.end())
721                 iter->second.first++;
722
723 }
724
725 void ModuleManager::DoneWithInterface(const std::string &InterfaceName)
726 {
727         interfacelist::iterator iter = Interfaces.find(InterfaceName);
728         if (iter != Interfaces.end())
729                 iter->second.first--;
730 }
731
732 std::pair<int,std::string> ModuleManager::GetInterfaceInstanceCount(Module* m)
733 {
734         for (interfacelist::iterator iter = Interfaces.begin(); iter != Interfaces.end(); iter++)
735         {
736                 for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
737                 {
738                         if (*x == m)
739                         {
740                                 return std::make_pair(iter->second.first, iter->first);
741                         }
742                 }
743         }
744         return std::make_pair(0, "");
745 }
746
747 const std::string& ModuleManager::GetModuleName(Module* m)
748 {
749         static std::string nothing;
750
751         for (std::map<std::string, Module*>::iterator n = Modules.begin(); n != Modules.end(); ++n)
752         {
753                 if (n->second == m)
754                         return n->first;
755         }
756
757         return nothing;
758 }
759
760 CmdResult InspIRCd::CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user)
761 {
762         return this->Parser->CallHandler(commandname, parameters, user);
763 }
764
765 bool InspIRCd::IsValidModuleCommand(const std::string &commandname, int pcnt, User* user)
766 {
767         return this->Parser->IsValidCommand(commandname, pcnt, user);
768 }
769
770 void InspIRCd::AddCommand(Command *f)
771 {
772         if (!this->Parser->AddCommand(f))
773         {
774                 throw ModuleException("Command "+std::string(f->command)+" already exists.");
775         }
776 }
777
778 void InspIRCd::SendMode(const std::vector<std::string>& parameters, User *user)
779 {
780         this->Modes->Process(parameters, user);
781 }
782
783 void InspIRCd::DumpText(User* user, const std::string &text)
784 {
785         if (IS_LOCAL(user))
786         {
787                 user->Write(text);
788         }
789         else
790         {
791                 PI->PushToClient(user, text);
792         }
793 }
794
795 void InspIRCd::DumpText(User* user, const char *text, ...)
796 {
797         va_list argsPtr;
798         char line[MAXBUF];
799
800         va_start(argsPtr, text);
801         vsnprintf(line, MAXBUF, text, argsPtr);
802         va_end(argsPtr);
803
804         DumpText(user, std::string(line));
805 }
806
807 void InspIRCd::DumpText(User* user, const std::string &LinePrefix, std::stringstream &TextStream)
808 {
809         char line[MAXBUF];
810         int start_pos = LinePrefix.length();
811         int pos = start_pos;
812         memcpy(line, LinePrefix.data(), pos);
813         std::string Word;
814         while (TextStream >> Word)
815         {
816                 int len = Word.length();
817                 if (pos + len + 12 > MAXBUF)
818                 {
819                         line[pos] = '\0';
820                         DumpText(user, std::string(line));
821                         pos = start_pos;
822                 }
823                 line[pos] = ' ';
824                 memcpy(line + pos + 1, Word.data(), len);
825                 pos += len + 1;
826         }
827         line[pos] = '\0';
828         DumpText(user, std::string(line));
829 }
830
831 bool InspIRCd::AddResolver(Resolver* r, bool cached)
832 {
833         if (!cached)
834                 return this->Res->AddResolverClass(r);
835         else
836         {
837                 r->TriggerCachedResult();
838                 delete r;
839                 return true;
840         }
841 }
842
843 Module* ModuleManager::Find(const std::string &name)
844 {
845         std::map<std::string, Module*>::iterator modfind = Modules.find(name);
846
847         if (modfind == Modules.end())
848                 return NULL;
849         else
850                 return modfind->second;
851 }
852
853 const std::vector<std::string> ModuleManager::GetAllModuleNames(int filter)
854 {
855         std::vector<std::string> retval;
856         for (std::map<std::string, Module*>::iterator x = Modules.begin(); x != Modules.end(); ++x)
857                 if (!filter || (x->second->GetVersion().Flags & filter))
858                         retval.push_back(x->first);
859         return retval;
860 }
861
862 ConfigReader::ConfigReader()
863 {
864         this->error = 0;
865 }
866
867
868 ConfigReader::~ConfigReader()
869 {
870 }
871
872
873 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool allow_linefeeds)
874 {
875         /* Don't need to strlcpy() tag and name anymore, ReadConf() takes const char* */
876         std::string result = default_value;
877         if (!ServerInstance->Config->ConfValue(tag, index)->readString(name, result, allow_linefeeds))
878         {
879                 this->error = CONF_VALUE_NOT_FOUND;
880         }
881         return result;
882 }
883
884 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, int index, bool allow_linefeeds)
885 {
886         return ReadValue(tag, name, "", index, allow_linefeeds);
887 }
888
889 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, const std::string &default_value, int index)
890 {
891         bool def = (default_value == "yes");
892         return ServerInstance->Config->ConfValue(tag, index)->getBool(name, def);
893 }
894
895 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, int index)
896 {
897         return ReadFlag(tag, name, "", index);
898 }
899
900
901 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool need_positive)
902 {
903         int v = atoi(default_value.c_str());
904         int result = ServerInstance->Config->ConfValue(tag, index)->getInt(name, v);
905
906         if ((need_positive) && (result < 0))
907         {
908                 this->error = CONF_INT_NEGATIVE;
909                 return 0;
910         }
911
912         return result;
913 }
914
915 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, int index, bool need_positive)
916 {
917         return ReadInteger(tag, name, "", index, need_positive);
918 }
919
920 long ConfigReader::GetError()
921 {
922         long olderr = this->error;
923         this->error = 0;
924         return olderr;
925 }
926
927 int ConfigReader::Enumerate(const std::string &tag)
928 {
929         ServerInstance->Logs->Log("MODULE", DEBUG, "Module is using ConfigReader::Enumerate on %s; this is slow!",
930                 tag.c_str());
931         int i=0;
932         while (ServerInstance->Config->ConfValue(tag, i)) i++;
933         return i;
934 }
935
936 FileReader::FileReader(const std::string &filename)
937 {
938         LoadFile(filename);
939 }
940
941 FileReader::FileReader()
942 {
943 }
944
945 std::string FileReader::Contents()
946 {
947         std::string x;
948         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
949         {
950                 x.append(*a);
951                 x.append("\r\n");
952         }
953         return x;
954 }
955
956 unsigned long FileReader::ContentSize()
957 {
958         return this->contentsize;
959 }
960
961 void FileReader::CalcSize()
962 {
963         unsigned long n = 0;
964         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
965                 n += (a->length() + 2);
966         this->contentsize = n;
967 }
968
969 void FileReader::LoadFile(const std::string &filename)
970 {
971         file_cache c;
972         c.clear();
973         if (ServerInstance->Config->ReadFile(c,filename.c_str()))
974         {
975                 this->fc = c;
976                 this->CalcSize();
977         }
978 }
979
980
981 FileReader::~FileReader()
982 {
983 }
984
985 bool FileReader::Exists()
986 {
987         return (!(fc.size() == 0));
988 }
989
990 std::string FileReader::GetLine(int x)
991 {
992         if ((x<0) || ((unsigned)x>fc.size()))
993                 return "";
994         return fc[x];
995 }
996
997 int FileReader::FileSize()
998 {
999         return fc.size();
1000 }