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