]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules.cpp
ee18112a1597dfaecad4a2bf42883be5af470df4
[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 template<>
31 VersionBase<API_VERSION>::VersionBase(const std::string &modv, int flags, int, const std::string& rev)
32 : description(modv), version(rev), Flags(flags)
33 {
34 }
35
36 Request::Request(char* anydata, Module* src, Module* dst)
37 : data(anydata), source(src), dest(dst)
38 {
39         /* Ensure that because this module doesnt support ID strings, it doesnt break modules that do
40          * by passing them uninitialized pointers (could happen)
41          */
42         id = '\0';
43 }
44
45 Request::Request(Module* src, Module* dst, const char* idstr)
46 : id(idstr), source(src), dest(dst)
47 {
48 }
49
50 char* Request::GetData()
51 {
52         return this->data;
53 }
54
55 const char* Request::GetId()
56 {
57         return this->id;
58 }
59
60 Module* Request::GetSource()
61 {
62         return this->source;
63 }
64
65 Module* Request::GetDest()
66 {
67         return this->dest;
68 }
69
70 const char* Request::Send()
71 {
72         if (this->dest)
73         {
74                 return dest->OnRequest(this);
75         }
76         else
77         {
78                 return NULL;
79         }
80 }
81
82 Event::Event(char* anydata, Module* src, const std::string &eventid) : data(anydata), source(src), id(eventid) { }
83
84 char* Event::GetData()
85 {
86         return this->data;
87 }
88
89 Module* Event::GetSource()
90 {
91         return this->source;
92 }
93
94 char* Event::Send()
95 {
96         FOREACH_MOD(I_OnEvent,OnEvent(this));
97         return NULL;
98 }
99
100 std::string Event::GetEventID()
101 {
102         return this->id;
103 }
104
105
106 // These declarations define the behavours of the base class Module (which does nothing at all)
107
108 Module::Module() { }
109 bool Module::cull()
110 {
111         ServerInstance->GlobalCulls.AddItem(ModuleDLLFactory);
112         return true;
113 }
114 Module::~Module() { }
115
116 ModResult       Module::OnSendSnotice(char &snomask, std::string &type, const std::string &message) { return MOD_RES_PASSTHRU; }
117 void            Module::OnUserConnect(User*) { }
118 void            Module::OnUserQuit(User*, const std::string&, const std::string&) { }
119 void            Module::OnUserDisconnect(User*) { }
120 void            Module::OnUserJoin(Membership*, bool, bool, CUList&) { }
121 void            Module::OnPostJoin(Membership*) { }
122 void            Module::OnUserPart(Membership*, std::string&, CUList&) { }
123 void            Module::OnPreRehash(User*, const std::string&) { }
124 void            Module::OnModuleRehash(User*, const std::string&) { }
125 void            Module::OnRehash(User*) { }
126 ModResult       Module::OnUserPreJoin(User*, Channel*, const char*, std::string&, const std::string&) { return MOD_RES_PASSTHRU; }
127 void            Module::OnMode(User*, void*, int, const std::vector<std::string>&, const std::vector<TranslateType>&) { }
128 void            Module::OnOper(User*, const std::string&) { }
129 void            Module::OnPostOper(User*, const std::string&, const std::string &) { }
130 void            Module::OnInfo(User*) { }
131 void            Module::OnWhois(User*, User*) { }
132 ModResult       Module::OnUserPreInvite(User*, User*, Channel*, time_t) { return MOD_RES_PASSTHRU; }
133 ModResult       Module::OnUserPreMessage(User*, void*, int, std::string&, char, CUList&) { return MOD_RES_PASSTHRU; }
134 ModResult       Module::OnUserPreNotice(User*, void*, int, std::string&, char, CUList&) { return MOD_RES_PASSTHRU; }
135 ModResult       Module::OnUserPreNick(User*, const std::string&) { return MOD_RES_PASSTHRU; }
136 void            Module::OnUserPostNick(User*, const std::string&) { }
137 ModResult       Module::OnPreMode(User*, User*, Channel*, const std::vector<std::string>&) { return MOD_RES_PASSTHRU; }
138 void            Module::On005Numeric(std::string&) { }
139 ModResult       Module::OnKill(User*, User*, const std::string&) { return MOD_RES_PASSTHRU; }
140 void            Module::OnLoadModule(Module*, const std::string&) { }
141 void            Module::OnUnloadModule(Module*, const std::string&) { }
142 void            Module::OnBackgroundTimer(time_t) { }
143 ModResult       Module::OnPreCommand(std::string&, std::vector<std::string>&, User *, bool, const std::string&) { return MOD_RES_PASSTHRU; }
144 void            Module::OnPostCommand(const std::string&, const std::vector<std::string>&, User *, CmdResult, const std::string&) { }
145 ModResult       Module::OnCheckReady(User*) { return MOD_RES_PASSTHRU; }
146 ModResult       Module::OnUserRegister(User*) { return MOD_RES_PASSTHRU; }
147 ModResult       Module::OnUserPreKick(User*, Membership*, const std::string&) { return MOD_RES_PASSTHRU; }
148 void            Module::OnUserKick(User*, Membership*, const std::string&, CUList&) { }
149 ModResult       Module::OnRawMode(User*, Channel*, const char, const std::string &, bool, int) { return MOD_RES_PASSTHRU; }
150 ModResult       Module::OnCheckInvite(User*, Channel*) { return MOD_RES_PASSTHRU; }
151 ModResult       Module::OnCheckKey(User*, Channel*, const std::string&) { return MOD_RES_PASSTHRU; }
152 ModResult       Module::OnCheckLimit(User*, Channel*) { return MOD_RES_PASSTHRU; }
153 ModResult       Module::OnCheckChannelBan(User*, Channel*) { return MOD_RES_PASSTHRU; }
154 ModResult       Module::OnCheckBan(User*, Channel*, const std::string&) { return MOD_RES_PASSTHRU; }
155 ModResult       Module::OnExtBanCheck(User*, Channel*, char) { return MOD_RES_PASSTHRU; }
156 ModResult       Module::OnStats(char, User*, string_list&) { return MOD_RES_PASSTHRU; }
157 ModResult       Module::OnChangeLocalUserHost(User*, const std::string&) { return MOD_RES_PASSTHRU; }
158 ModResult       Module::OnChangeLocalUserGECOS(User*, const std::string&) { return MOD_RES_PASSTHRU; }
159 ModResult       Module::OnPreTopicChange(User*, Channel*, const std::string&) { return MOD_RES_PASSTHRU; }
160 void            Module::OnEvent(Event*) { return; }
161 const char*             Module::OnRequest(Request*) { return NULL; }
162 ModResult       Module::OnPassCompare(Extensible* ex, const std::string &password, const std::string &input, const std::string& hashtype) { return MOD_RES_PASSTHRU; }
163 void            Module::OnGlobalOper(User*) { }
164 void            Module::OnPostConnect(User*) { }
165 ModResult       Module::OnAddBan(User*, Channel*, const std::string &) { return MOD_RES_PASSTHRU; }
166 ModResult       Module::OnDelBan(User*, Channel*, const std::string &) { return MOD_RES_PASSTHRU; }
167 void            Module::OnStreamSocketAccept(StreamSocket*, irc::sockets::sockaddrs*, irc::sockets::sockaddrs*) { }
168 int             Module::OnStreamSocketWrite(StreamSocket*, std::string&) { return -1; }
169 void            Module::OnStreamSocketClose(StreamSocket*) { }
170 void            Module::OnStreamSocketConnect(StreamSocket*) { }
171 int             Module::OnStreamSocketRead(StreamSocket*, std::string&) { return -1; }
172 void            Module::OnUserMessage(User*, void*, int, const std::string&, char, const CUList&) { }
173 void            Module::OnUserNotice(User*, void*, int, const std::string&, char, const CUList&) { }
174 void            Module::OnRemoteKill(User*, User*, const std::string&, const std::string&) { }
175 void            Module::OnUserInvite(User*, User*, Channel*, time_t) { }
176 void            Module::OnPostTopicChange(User*, Channel*, const std::string&) { }
177 void            Module::OnGetServerDescription(const std::string&, std::string&) { }
178 void            Module::OnSyncUser(User*, Module*, void*) { }
179 void            Module::OnSyncChannel(Channel*, Module*, void*) { }
180 void            Module::OnSyncNetwork(Module*, void*) { }
181 void            Module::ProtoSendMode(void*, TargetTypeFlags, void*, const std::vector<std::string>&, const std::vector<TranslateType>&) { }
182 void            Module::OnDecodeMetaData(Extensible*, const std::string&, const std::string&) { }
183 void            Module::ProtoSendMetaData(void*, Extensible*, const std::string&, const std::string&) { }
184 void            Module::OnWallops(User*, const std::string&) { }
185 void            Module::OnChangeHost(User*, const std::string&) { }
186 void            Module::OnChangeName(User*, const std::string&) { }
187 void            Module::OnChangeIdent(User*, const std::string&) { }
188 void            Module::OnAddLine(User*, XLine*) { }
189 void            Module::OnDelLine(User*, XLine*) { }
190 void            Module::OnExpireLine(XLine*) { }
191 void            Module::OnCleanup(int, void*) { }
192 ModResult       Module::OnChannelPreDelete(Channel*) { return MOD_RES_PASSTHRU; }
193 void            Module::OnChannelDelete(Channel*) { }
194 ModResult       Module::OnSetAway(User*, const std::string &) { return MOD_RES_PASSTHRU; }
195 ModResult       Module::OnUserList(User*, Channel*) { return MOD_RES_PASSTHRU; }
196 ModResult       Module::OnWhoisLine(User*, User*, int&, std::string&) { return MOD_RES_PASSTHRU; }
197 void            Module::OnBuildNeighborList(User*, UserChanList&, std::map<User*,bool>&) { }
198 void            Module::OnGarbageCollect() { }
199 void            Module::OnText(User*, void*, int, const std::string&, char, CUList&) { }
200 void            Module::OnRunTestSuite() { }
201 void            Module::OnNamesListItem(User*, Membership*, std::string&, std::string&) { }
202 ModResult       Module::OnNumeric(User*, unsigned int, const std::string&) { return MOD_RES_PASSTHRU; }
203 void            Module::OnHookIO(StreamSocket*, ListenSocketBase*) { }
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                         ServerInstance->Logs->Log("MODULE", DEFAULT,"New module introduced: %s (Module version %s)%s", filename, v.version.c_str(), (!(v.Flags & VF_VENDOR) ? " [3rd Party]" : " [Vendor]"));
444
445                         Modules[filename_str] = newmod;
446                 }
447                 else
448                 {
449                         delete newhandle;
450                         LastModuleError = "Unable to load " + filename_str + ": Probably missing init_module() entrypoint, but dlsym() didn't notice a problem";
451                         ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
452                         return false;
453                 }
454         }
455         /** XXX: Is there anything we can do about this mess? -- Brain
456          * Yeah, don't use exceptions without RAII. -- Daniel
457          */
458         catch (LoadModuleException& modexcept)
459         {
460                 DetachAll(newmod);
461                 if (newmod)
462                         delete newmod;
463                 if (newhandle)
464                         delete newhandle;
465                 LastModuleError = "Unable to load " + filename_str + ": Error when loading: " + modexcept.GetReason();
466                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
467                 return false;
468         }
469         catch (FindSymbolException& modexcept)
470         {
471                 DetachAll(newmod);
472                 if (newmod)
473                         delete newmod;
474                 if (newhandle)
475                         delete newhandle;
476                 LastModuleError = "Unable to load " + filename_str + ": Error finding symbol: " + modexcept.GetReason();
477                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
478                 return false;
479         }
480         catch (CoreException& modexcept)
481         {
482                 DetachAll(newmod);
483                 if (newmod)
484                         delete newmod;
485                 if (newhandle)
486                         delete newhandle;
487                 LastModuleError = "Unable to load " + filename_str + ": " + modexcept.GetReason();
488                 ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
489                 return false;
490         }
491
492         this->ModCount++;
493         FOREACH_MOD(I_OnLoadModule,OnLoadModule(newmod, filename_str));
494
495         /* We give every module a chance to re-prioritize when we introduce a new one,
496          * not just the one thats loading, as the new module could affect the preference
497          * of others
498          */
499         for(int tries = 0; tries < 20; tries++)
500         {
501                 prioritizationState = tries > 0 ? PRIO_STATE_LAST : PRIO_STATE_FIRST;
502                 for (std::map<std::string, Module*>::iterator n = Modules.begin(); n != Modules.end(); ++n)
503                         n->second->Prioritize();
504
505                 if (prioritizationState == PRIO_STATE_LAST)
506                         break;
507                 if (tries == 19)
508                         ServerInstance->Logs->Log("MODULE", DEFAULT, "Hook priority dependency loop detected while loading " + filename_str);
509         }
510
511         ServerInstance->BuildISupport();
512         return true;
513 }
514
515 bool ModuleManager::Unload(const char* filename)
516 {
517         std::string filename_str(filename);
518         std::map<std::string, Module*>::iterator modfind = Modules.find(filename);
519
520         if (modfind != Modules.end())
521         {
522                 if (modfind->second->GetVersion().Flags & VF_STATIC)
523                 {
524                         LastModuleError = "Module " + filename_str + " not unloadable (marked static)";
525                         ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
526                         return false;
527                 }
528                 std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modfind->second);
529                 if (intercount.first > 0)
530                 {
531                         LastModuleError = "Failed to unload module " + filename_str + ", being used by " + ConvToStr(intercount.first) + " other(s) via interface '" + intercount.second + "'";
532                         ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
533                         return false;
534                 }
535
536                 std::vector<ExtensionItem*> items = Extensible::BeginUnregister(modfind->second);
537                 /* Give the module a chance to tidy out all its metadata */
538                 for (chan_hash::iterator c = ServerInstance->chanlist->begin(); c != ServerInstance->chanlist->end(); c++)
539                 {
540                         modfind->second->OnCleanup(TYPE_CHANNEL,c->second);
541                         c->second->doUnhookExtensions(items);
542                         const UserMembList* users = c->second->GetUsers();
543                         for(UserMembCIter mi = users->begin(); mi != users->end(); mi++)
544                                 mi->second->doUnhookExtensions(items);
545                 }
546                 for (user_hash::iterator u = ServerInstance->Users->clientlist->begin(); u != ServerInstance->Users->clientlist->end(); u++)
547                 {
548                         modfind->second->OnCleanup(TYPE_USER,u->second);
549                         u->second->doUnhookExtensions(items);
550                 }
551
552                 /* Tidy up any dangling resolvers */
553                 ServerInstance->Res->CleanResolvers(modfind->second);
554
555                 FOREACH_MOD(I_OnUnloadModule,OnUnloadModule(modfind->second, modfind->first));
556
557                 this->DetachAll(modfind->second);
558
559                 ServerInstance->Parser->RemoveCommands(modfind->second);
560                 ServerInstance->Modes->RemoveModes(modfind->second);
561
562                 ServerInstance->GlobalCulls.AddItem(modfind->second);
563                 Modules.erase(modfind);
564
565                 ServerInstance->Logs->Log("MODULE", DEFAULT,"Module %s unloaded",filename);
566                 this->ModCount--;
567                 ServerInstance->BuildISupport();
568                 return true;
569         }
570
571         LastModuleError = "Module " + filename_str + " is not loaded, cannot unload it!";
572         ServerInstance->Logs->Log("MODULE", DEFAULT, LastModuleError);
573         return false;
574 }
575
576 /* We must load the modules AFTER initializing the socket engine, now */
577 void ModuleManager::LoadAll()
578 {
579         char configToken[MAXBUF];
580         ModCount = -1;
581
582         printf("\nLoading core commands");
583         fflush(stdout);
584
585         DIR* library = opendir(ServerInstance->Config->ModPath.c_str());
586         if (library)
587         {
588                 dirent* entry = NULL;
589                 while (0 != (entry = readdir(library)))
590                 {
591                         if (InspIRCd::Match(entry->d_name, "cmd_*.so", ascii_case_insensitive_map))
592                         {
593                                 printf(".");
594                                 fflush(stdout);
595
596                                 if (!Load(entry->d_name))
597                                 {
598                                         ServerInstance->Logs->Log("MODULE", DEFAULT, this->LastError());
599                                         printf_c("\n[\033[1;31m*\033[0m] %s\n\n", this->LastError().c_str());
600                                         ServerInstance->Exit(EXIT_STATUS_MODULE);
601                                 }
602                         }
603                 }
604                 closedir(library);
605                 printf("\n");
606         }
607
608         for(int count = 0; count < ServerInstance->Config->ConfValueEnum("module"); count++)
609         {
610                 ServerInstance->Config->ConfValue("module", "name", count, configToken, MAXBUF);
611                 printf_c("[\033[1;32m*\033[0m] Loading module:\t\033[1;32m%s\033[0m\n",configToken);
612
613                 if (!this->Load(configToken))
614                 {
615                         ServerInstance->Logs->Log("MODULE", DEFAULT, this->LastError());
616                         printf_c("\n[\033[1;31m*\033[0m] %s\n\n", this->LastError().c_str());
617                         ServerInstance->Exit(EXIT_STATUS_MODULE);
618                 }
619         }
620 }
621
622 bool ModuleManager::PublishFeature(const std::string &FeatureName, Module* Mod)
623 {
624         if (Features.find(FeatureName) == Features.end())
625         {
626                 Features[FeatureName] = Mod;
627                 return true;
628         }
629         return false;
630 }
631
632 bool ModuleManager::UnpublishFeature(const std::string &FeatureName)
633 {
634         featurelist::iterator iter = Features.find(FeatureName);
635
636         if (iter == Features.end())
637                 return false;
638
639         Features.erase(iter);
640         return true;
641 }
642
643 Module* ModuleManager::FindFeature(const std::string &FeatureName)
644 {
645         featurelist::iterator iter = Features.find(FeatureName);
646
647         if (iter == Features.end())
648                 return NULL;
649
650         return iter->second;
651 }
652
653 bool ModuleManager::PublishInterface(const std::string &InterfaceName, Module* Mod)
654 {
655         interfacelist::iterator iter = Interfaces.find(InterfaceName);
656
657         if (iter == Interfaces.end())
658         {
659                 modulelist ml;
660                 ml.push_back(Mod);
661                 Interfaces[InterfaceName] = std::make_pair(0, ml);
662         }
663         else
664         {
665                 iter->second.second.push_back(Mod);
666         }
667         return true;
668 }
669
670 bool ModuleManager::UnpublishInterface(const std::string &InterfaceName, Module* Mod)
671 {
672         interfacelist::iterator iter = Interfaces.find(InterfaceName);
673
674         if (iter == Interfaces.end())
675                 return false;
676
677         for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
678         {
679                 if (*x == Mod)
680                 {
681                         iter->second.second.erase(x);
682                         if (iter->second.second.empty())
683                                 Interfaces.erase(InterfaceName);
684                         return true;
685                 }
686         }
687         return false;
688 }
689
690 modulelist* ModuleManager::FindInterface(const std::string &InterfaceName)
691 {
692         interfacelist::iterator iter = Interfaces.find(InterfaceName);
693         if (iter == Interfaces.end())
694                 return NULL;
695         else
696                 return &(iter->second.second);
697 }
698
699 bool ModuleManager::ModuleHasInterface(Module* mod, const std::string& InterfaceName)
700 {
701         interfacelist::iterator iter = Interfaces.find(InterfaceName);
702         if (iter == Interfaces.end())
703                 return false;
704         else
705         {
706                 modulelist& ml = iter->second.second;
707                 modulelist::iterator mi = std::find(ml.begin(), ml.end(), mod);
708                 return (mi != ml.end());
709         }
710 }
711
712 void ModuleManager::UseInterface(const std::string &InterfaceName)
713 {
714         interfacelist::iterator iter = Interfaces.find(InterfaceName);
715         if (iter != Interfaces.end())
716                 iter->second.first++;
717
718 }
719
720 void ModuleManager::DoneWithInterface(const std::string &InterfaceName)
721 {
722         interfacelist::iterator iter = Interfaces.find(InterfaceName);
723         if (iter != Interfaces.end())
724                 iter->second.first--;
725 }
726
727 std::pair<int,std::string> ModuleManager::GetInterfaceInstanceCount(Module* m)
728 {
729         for (interfacelist::iterator iter = Interfaces.begin(); iter != Interfaces.end(); iter++)
730         {
731                 for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
732                 {
733                         if (*x == m)
734                         {
735                                 return std::make_pair(iter->second.first, iter->first);
736                         }
737                 }
738         }
739         return std::make_pair(0, "");
740 }
741
742 const std::string& ModuleManager::GetModuleName(Module* m)
743 {
744         static std::string nothing;
745
746         for (std::map<std::string, Module*>::iterator n = Modules.begin(); n != Modules.end(); ++n)
747         {
748                 if (n->second == m)
749                         return n->first;
750         }
751
752         return nothing;
753 }
754
755 /* This is ugly, yes, but hash_map's arent designed to be
756  * addressed in this manner, and this is a bit of a kludge.
757  * Luckily its a specialist function and rarely used by
758  * many modules (in fact, it was specially created to make
759  * m_safelist possible, initially).
760  */
761
762 Channel* InspIRCd::GetChannelIndex(long index)
763 {
764         int target = 0;
765         for (chan_hash::iterator n = this->chanlist->begin(); n != this->chanlist->end(); n++, target++)
766         {
767                 if (index == target)
768                         return n->second;
769         }
770         return NULL;
771 }
772
773 CmdResult InspIRCd::CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user)
774 {
775         return this->Parser->CallHandler(commandname, parameters, user);
776 }
777
778 bool InspIRCd::IsValidModuleCommand(const std::string &commandname, int pcnt, User* user)
779 {
780         return this->Parser->IsValidCommand(commandname, pcnt, user);
781 }
782
783 void InspIRCd::AddCommand(Command *f)
784 {
785         if (!this->Parser->CreateCommand(f))
786         {
787                 ModuleException err("Command "+std::string(f->command)+" already exists.");
788                 throw (err);
789         }
790 }
791
792 void InspIRCd::SendMode(const std::vector<std::string>& parameters, User *user)
793 {
794         this->Modes->Process(parameters, user);
795 }
796
797 void InspIRCd::DumpText(User* user, const std::string &text)
798 {
799         if (IS_LOCAL(user))
800         {
801                 user->Write(text);
802         }
803         else
804         {
805                 PI->PushToClient(user, text);
806         }
807 }
808
809 void InspIRCd::DumpText(User* user, const char *text, ...)
810 {
811         va_list argsPtr;
812         char line[MAXBUF];
813
814         va_start(argsPtr, text);
815         vsnprintf(line, MAXBUF, text, argsPtr);
816         va_end(argsPtr);
817
818         DumpText(user, std::string(line));
819 }
820
821 void InspIRCd::DumpText(User* user, const std::string &LinePrefix, std::stringstream &TextStream)
822 {
823         char line[MAXBUF];
824         int start_pos = LinePrefix.length();
825         int pos = start_pos;
826         memcpy(line, LinePrefix.data(), pos);
827         std::string Word;
828         while (TextStream >> Word)
829         {
830                 int len = Word.length();
831                 if (pos + len + 12 > MAXBUF)
832                 {
833                         line[pos] = '\0';
834                         DumpText(user, std::string(line));
835                         pos = start_pos;
836                 }
837                 line[pos] = ' ';
838                 memcpy(line + pos + 1, Word.data(), len);
839                 pos += len + 1;
840         }
841         line[pos] = '\0';
842         DumpText(user, std::string(line));
843 }
844
845 bool InspIRCd::AddResolver(Resolver* r, bool cached)
846 {
847         if (!cached)
848                 return this->Res->AddResolverClass(r);
849         else
850         {
851                 r->TriggerCachedResult();
852                 delete r;
853                 return true;
854         }
855 }
856
857 Module* ModuleManager::Find(const std::string &name)
858 {
859         std::map<std::string, Module*>::iterator modfind = Modules.find(name);
860
861         if (modfind == Modules.end())
862                 return NULL;
863         else
864                 return modfind->second;
865 }
866
867 const std::vector<std::string> ModuleManager::GetAllModuleNames(int filter)
868 {
869         std::vector<std::string> retval;
870         for (std::map<std::string, Module*>::iterator x = Modules.begin(); x != Modules.end(); ++x)
871                 if (!filter || (x->second->GetVersion().Flags & filter))
872                         retval.push_back(x->first);
873         return retval;
874 }
875
876 ConfigReader::ConfigReader()
877 {
878         this->error = 0;
879 }
880
881
882 ConfigReader::~ConfigReader()
883 {
884 }
885
886
887 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool allow_linefeeds)
888 {
889         /* Don't need to strlcpy() tag and name anymore, ReadConf() takes const char* */
890         std::string result;
891
892         if (!ServerInstance->Config->ConfValue(tag, name, default_value, index, result, allow_linefeeds))
893         {
894                 this->error = CONF_VALUE_NOT_FOUND;
895         }
896         return result;
897 }
898
899 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, int index, bool allow_linefeeds)
900 {
901         return ReadValue(tag, name, "", index, allow_linefeeds);
902 }
903
904 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, const std::string &default_value, int index)
905 {
906         return ServerInstance->Config->ConfValueBool(tag, name, default_value, index);
907 }
908
909 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, int index)
910 {
911         return ReadFlag(tag, name, "", index);
912 }
913
914
915 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool need_positive)
916 {
917         int result;
918
919         if(!ServerInstance->Config->ConfValueInteger(tag, name, default_value, index, result))
920         {
921                 this->error = CONF_VALUE_NOT_FOUND;
922                 return 0;
923         }
924
925         if ((need_positive) && (result < 0))
926         {
927                 this->error = CONF_INT_NEGATIVE;
928                 return 0;
929         }
930
931         return result;
932 }
933
934 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, int index, bool need_positive)
935 {
936         return ReadInteger(tag, name, "", index, need_positive);
937 }
938
939 long ConfigReader::GetError()
940 {
941         long olderr = this->error;
942         this->error = 0;
943         return olderr;
944 }
945
946 int ConfigReader::Enumerate(const std::string &tag)
947 {
948         return ServerInstance->Config->ConfValueEnum(tag);
949 }
950
951 int ConfigReader::EnumerateValues(const std::string &tag, int index)
952 {
953         return ServerInstance->Config->ConfVarEnum(tag, index);
954 }
955
956 FileReader::FileReader(const std::string &filename)
957 {
958         LoadFile(filename);
959 }
960
961 FileReader::FileReader()
962 {
963 }
964
965 std::string FileReader::Contents()
966 {
967         std::string x;
968         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
969         {
970                 x.append(*a);
971                 x.append("\r\n");
972         }
973         return x;
974 }
975
976 unsigned long FileReader::ContentSize()
977 {
978         return this->contentsize;
979 }
980
981 void FileReader::CalcSize()
982 {
983         unsigned long n = 0;
984         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
985                 n += (a->length() + 2);
986         this->contentsize = n;
987 }
988
989 void FileReader::LoadFile(const std::string &filename)
990 {
991         file_cache c;
992         c.clear();
993         if (ServerInstance->Config->ReadFile(c,filename.c_str()))
994         {
995                 this->fc = c;
996                 this->CalcSize();
997         }
998 }
999
1000
1001 FileReader::~FileReader()
1002 {
1003 }
1004
1005 bool FileReader::Exists()
1006 {
1007         return (!(fc.size() == 0));
1008 }
1009
1010 std::string FileReader::GetLine(int x)
1011 {
1012         if ((x<0) || ((unsigned)x>fc.size()))
1013                 return "";
1014         return fc[x];
1015 }
1016
1017 int FileReader::FileSize()
1018 {
1019         return fc.size();
1020 }