]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules.cpp
Fix for bug #376 - FEATURE - (sorry w00t) - not backporting to stable.
[user/henk/code/inspircd.git] / src / modules.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/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 "configreader.h"
16 #include "users.h"
17 #include "modules.h"
18 #include "wildcard.h"
19 #include "mode.h"
20 #include "xline.h"
21 #include "socket.h"
22 #include "socketengine.h"
23 #include "command_parse.h"
24 #include "dns.h"
25
26
27 #ifndef WIN32
28         #include <dirent.h>
29 #endif
30
31 // version is a simple class for holding a modules version number
32 Version::Version(int major, int minor, int revision, int build, int flags, int api_ver)
33 : Major(major), Minor(minor), Revision(revision), Build(build), Flags(flags), API(api_ver)
34 {
35 }
36
37 Request::Request(char* anydata, Module* src, Module* dst)
38 : data(anydata), source(src), dest(dst)
39 {
40         /* Ensure that because this module doesnt support ID strings, it doesnt break modules that do
41          * by passing them uninitialized pointers (could happen)
42          */
43         id = '\0';
44 }
45
46 Request::Request(Module* src, Module* dst, const char* idstr)
47 : id(idstr), source(src), dest(dst)
48 {
49 }
50
51 char* Request::GetData()
52 {
53         return this->data;
54 }
55
56 const char* Request::GetId()
57 {
58         return this->id;
59 }
60
61 Module* Request::GetSource()
62 {
63         return this->source;
64 }
65
66 Module* Request::GetDest()
67 {
68         return this->dest;
69 }
70
71 char* Request::Send()
72 {
73         if (this->dest)
74         {
75                 return dest->OnRequest(this);
76         }
77         else
78         {
79                 return NULL;
80         }
81 }
82
83 Event::Event(char* anydata, Module* src, const std::string &eventid) : data(anydata), source(src), id(eventid) { }
84
85 char* Event::GetData()
86 {
87         return (char*)this->data;
88 }
89
90 Module* Event::GetSource()
91 {
92         return this->source;
93 }
94
95 char* Event::Send(InspIRCd* ServerInstance)
96 {
97         FOREACH_MOD(I_OnEvent,OnEvent(this));
98         return NULL;
99 }
100
101 std::string Event::GetEventID()
102 {
103         return this->id;
104 }
105
106
107 // These declarations define the behavours of the base class Module (which does nothing at all)
108
109                 Module::Module(InspIRCd* Me) : ServerInstance(Me) { }
110                 Module::~Module() { }
111 void            Module::OnUserConnect(userrec* user) { }
112 void            Module::OnUserQuit(userrec* user, const std::string& message, const std::string &oper_message) { }
113 void            Module::OnUserDisconnect(userrec* user) { }
114 void            Module::OnUserJoin(userrec* user, chanrec* channel, bool &silent) { }
115 void            Module::OnPostJoin(userrec* user, chanrec* channel) { }
116 void            Module::OnUserPart(userrec* user, chanrec* channel, const std::string &partmessage, bool &silent) { }
117 void            Module::OnRehash(userrec* user, const std::string &parameter) { }
118 void            Module::OnServerRaw(std::string &raw, bool inbound, userrec* user) { }
119 int             Module::OnUserPreJoin(userrec* user, chanrec* chan, const char* cname, std::string &privs) { return 0; }
120 void            Module::OnMode(userrec* user, void* dest, int target_type, const std::string &text) { }
121 Version         Module::GetVersion() { return Version(1,0,0,0,VF_VENDOR,-1); }
122 void            Module::OnOper(userrec* user, const std::string &opertype) { }
123 void            Module::OnPostOper(userrec* user, const std::string &opertype) { }
124 void            Module::OnInfo(userrec* user) { }
125 void            Module::OnWhois(userrec* source, userrec* dest) { }
126 int             Module::OnUserPreInvite(userrec* source,userrec* dest,chanrec* channel) { return 0; }
127 int             Module::OnUserPreMessage(userrec* user,void* dest,int target_type, std::string &text,char status, CUList &exempt_list) { return 0; }
128 int             Module::OnUserPreNotice(userrec* user,void* dest,int target_type, std::string &text,char status, CUList &exempt_list) { return 0; }
129 int             Module::OnUserPreNick(userrec* user, const std::string &newnick) { return 0; }
130 void            Module::OnUserPostNick(userrec* user, const std::string &oldnick) { }
131 int             Module::OnAccessCheck(userrec* source,userrec* dest,chanrec* channel,int access_type) { return ACR_DEFAULT; }
132 void            Module::On005Numeric(std::string &output) { }
133 int             Module::OnKill(userrec* source, userrec* dest, const std::string &reason) { return 0; }
134 void            Module::OnLoadModule(Module* mod,const std::string &name) { }
135 void            Module::OnUnloadModule(Module* mod,const std::string &name) { }
136 void            Module::OnBackgroundTimer(time_t curtime) { }
137 int             Module::OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line) { return 0; }
138 void            Module::OnPostCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, CmdResult result, const std::string &original_line) { }
139 bool            Module::OnCheckReady(userrec* user) { return true; }
140 int             Module::OnUserRegister(userrec* user) { return 0; }
141 int             Module::OnUserPreKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason) { return 0; }
142 void            Module::OnUserKick(userrec* source, userrec* user, chanrec* chan, const std::string &reason, bool &silent) { }
143 int             Module::OnCheckInvite(userrec* user, chanrec* chan) { return 0; }
144 int             Module::OnCheckKey(userrec* user, chanrec* chan, const std::string &keygiven) { return 0; }
145 int             Module::OnCheckLimit(userrec* user, chanrec* chan) { return 0; }
146 int             Module::OnCheckBan(userrec* user, chanrec* chan) { return 0; }
147 int             Module::OnStats(char symbol, userrec* user, string_list &results) { return 0; }
148 int             Module::OnChangeLocalUserHost(userrec* user, const std::string &newhost) { return 0; }
149 int             Module::OnChangeLocalUserGECOS(userrec* user, const std::string &newhost) { return 0; }
150 int             Module::OnLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic) { return 0; }
151 void            Module::OnEvent(Event* event) { return; }
152 char*           Module::OnRequest(Request* request) { return NULL; }
153 int             Module::OnOperCompare(const std::string &password, const std::string &input, int tagnumber) { return 0; }
154 void            Module::OnGlobalOper(userrec* user) { }
155 void            Module::OnPostConnect(userrec* user) { }
156 int             Module::OnAddBan(userrec* source, chanrec* channel,const std::string &banmask) { return 0; }
157 int             Module::OnDelBan(userrec* source, chanrec* channel,const std::string &banmask) { return 0; }
158 void            Module::OnRawSocketAccept(int fd, const std::string &ip, int localport) { }
159 int             Module::OnRawSocketWrite(int fd, const char* buffer, int count) { return 0; }
160 void            Module::OnRawSocketClose(int fd) { }
161 void            Module::OnRawSocketConnect(int fd) { }
162 int             Module::OnRawSocketRead(int fd, char* buffer, unsigned int count, int &readresult) { return 0; }
163 void            Module::OnUserMessage(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list) { }
164 void            Module::OnUserNotice(userrec* user, void* dest, int target_type, const std::string &text, char status, const CUList &exempt_list) { }
165 void            Module::OnRemoteKill(userrec* source, userrec* dest, const std::string &reason, const std::string &operreason) { }
166 void            Module::OnUserInvite(userrec* source,userrec* dest,chanrec* channel) { }
167 void            Module::OnPostLocalTopicChange(userrec* user, chanrec* chan, const std::string &topic) { }
168 void            Module::OnGetServerDescription(const std::string &servername,std::string &description) { }
169 void            Module::OnSyncUser(userrec* user, Module* proto, void* opaque) { }
170 void            Module::OnSyncChannel(chanrec* chan, Module* proto, void* opaque) { }
171 void            Module::ProtoSendMode(void* opaque, int target_type, void* target, const std::string &modeline) { }
172 void            Module::OnSyncChannelMetaData(chanrec* chan, Module* proto,void* opaque, const std::string &extname, bool displayable) { }
173 void            Module::OnSyncUserMetaData(userrec* user, Module* proto,void* opaque, const std::string &extname, bool displayable) { }
174 void            Module::OnSyncOtherMetaData(Module* proto, void* opaque, bool displayable) { }
175 void            Module::OnDecodeMetaData(int target_type, void* target, const std::string &extname, const std::string &extdata) { }
176 void            Module::ProtoSendMetaData(void* opaque, int target_type, void* target, const std::string &extname, const std::string &extdata) { }
177 void            Module::OnWallops(userrec* user, const std::string &text) { }
178 void            Module::OnChangeHost(userrec* user, const std::string &newhost) { }
179 void            Module::OnChangeName(userrec* user, const std::string &gecos) { }
180 void            Module::OnAddGLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask) { }
181 void            Module::OnAddZLine(long duration, userrec* source, const std::string &reason, const std::string &ipmask) { }
182 void            Module::OnAddKLine(long duration, userrec* source, const std::string &reason, const std::string &hostmask) { }
183 void            Module::OnAddQLine(long duration, userrec* source, const std::string &reason, const std::string &nickmask) { }
184 void            Module::OnAddELine(long duration, userrec* source, const std::string &reason, const std::string &hostmask) { }
185 void            Module::OnDelGLine(userrec* source, const std::string &hostmask) { }
186 void            Module::OnDelZLine(userrec* source, const std::string &ipmask) { }
187 void            Module::OnDelKLine(userrec* source, const std::string &hostmask) { }
188 void            Module::OnDelQLine(userrec* source, const std::string &nickmask) { }
189 void            Module::OnDelELine(userrec* source, const std::string &hostmask) { }
190 void            Module::OnCleanup(int target_type, void* item) { }
191 void            Module::Implements(char* Implements) { for (int j = 0; j < 255; j++) Implements[j] = 0; }
192 void            Module::OnChannelDelete(chanrec* chan) { }
193 Priority        Module::Prioritize() { return PRIORITY_DONTCARE; }
194 void            Module::OnSetAway(userrec* user) { }
195 void            Module::OnCancelAway(userrec* user) { }
196 int             Module::OnUserList(userrec* user, chanrec* Ptr, CUList* &userlist) { return 0; }
197 int             Module::OnWhoisLine(userrec* user, userrec* dest, int &numeric, std::string &text) { return 0; }
198 void            Module::OnBuildExemptList(MessageType message_type, chanrec* chan, userrec* sender, char status, CUList &exempt_list) { }
199 void            Module::OnGarbageCollect() { }
200 void            Module::OnBufferFlushed(userrec* user) { }
201
202
203 char* InspIRCd::ModuleError()
204 {
205         return MODERR;
206 }
207
208 void InspIRCd::EraseFactory(int j)
209 {
210         int v = 0;
211         for (std::vector<ircd_module*>::iterator t = factory.begin(); t != factory.end(); t++)
212         {
213                 if (v == j)
214                 {
215                         delete *t;
216                         factory.erase(t);
217                         factory.push_back(NULL);
218                         return;
219                 }
220                 v++;
221         }
222 }
223
224 void InspIRCd::EraseModule(int j)
225 {
226         int v1 = 0;
227         for (ModuleList::iterator m = modules.begin(); m!= modules.end(); m++)
228         {
229                 if (v1 == j)
230                 {
231                         DELETE(*m);
232                         modules.erase(m);
233                         modules.push_back(NULL);
234                         break;
235                 }
236                 v1++;
237         }
238         int v2 = 0;
239         for (std::vector<std::string>::iterator v = Config->module_names.begin(); v != Config->module_names.end(); v++)
240         {
241                 if (v2 == j)
242                 {
243                         Config->module_names.erase(v);
244                         break;
245                 }
246                 v2++;
247         }
248
249 }
250
251 void InspIRCd::MoveTo(std::string modulename,int slot)
252 {
253         unsigned int v2 = 256;
254         for (unsigned int v = 0; v < Config->module_names.size(); v++)
255         {
256                 if (Config->module_names[v] == modulename)
257                 {
258                         // found an instance, swap it with the item at the end
259                         v2 = v;
260                         break;
261                 }
262         }
263         if ((v2 != (unsigned int)slot) && (v2 < 256))
264         {
265                 // Swap the module names over
266                 Config->module_names[v2] = Config->module_names[slot];
267                 Config->module_names[slot] = modulename;
268                 // now swap the module factories
269                 ircd_module* temp = factory[v2];
270                 factory[v2] = factory[slot];
271                 factory[slot] = temp;
272                 // now swap the module objects
273                 Module* temp_module = modules[v2];
274                 modules[v2] = modules[slot];
275                 modules[slot] = temp_module;
276                 // now swap the implement lists (we dont
277                 // need to swap the global or recount it)
278                 for (int n = 0; n < 255; n++)
279                 {
280                         char x = Config->implement_lists[v2][n];
281                         Config->implement_lists[v2][n] = Config->implement_lists[slot][n];
282                         Config->implement_lists[slot][n] = x;
283                 }
284         }
285 }
286
287 void InspIRCd::MoveAfter(std::string modulename, std::string after)
288 {
289         for (unsigned int v = 0; v < Config->module_names.size(); v++)
290         {
291                 if (Config->module_names[v] == after)
292                 {
293                         MoveTo(modulename, v);
294                         return;
295                 }
296         }
297 }
298
299 void InspIRCd::MoveBefore(std::string modulename, std::string before)
300 {
301         for (unsigned int v = 0; v < Config->module_names.size(); v++)
302         {
303                 if (Config->module_names[v] == before)
304                 {
305                         if (v > 0)
306                         {
307                                 MoveTo(modulename, v-1);
308                         }
309                         else
310                         {
311                                 MoveTo(modulename, v);
312                         }
313                         return;
314                 }
315         }
316 }
317
318 void InspIRCd::MoveToFirst(std::string modulename)
319 {
320         MoveTo(modulename,0);
321 }
322
323 void InspIRCd::MoveToLast(std::string modulename)
324 {
325         MoveTo(modulename,this->GetModuleCount());
326 }
327
328 bool InspIRCd::UnloadModule(const char* filename)
329 {
330         std::string filename_str = filename;
331         for (unsigned int j = 0; j != Config->module_names.size(); j++)
332         {
333                 if (Config->module_names[j] == filename_str)
334                 {
335                         if (modules[j]->GetVersion().Flags & VF_STATIC)
336                         {
337                                 this->Log(DEFAULT,"Failed to unload STATIC module %s",filename);
338                                 snprintf(MODERR,MAXBUF,"Module not unloadable (marked static)");
339                                 return false;
340                         }
341                         std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modules[j]);
342                         if (intercount.first > 0)
343                         {
344                                 this->Log(DEFAULT,"Failed to unload module %s, being used by %d other(s) via interface '%s'",filename, intercount.first, intercount.second.c_str());
345                                 snprintf(MODERR,MAXBUF,"Module not unloadable (Still in use by %d other module%s which %s using its interface '%s') -- unload dependent modules first!",
346                                                 intercount.first,
347                                                 intercount.first > 1 ? "s" : "",
348                                                 intercount.first > 1 ? "are" : "is",
349                                                 intercount.second.c_str());
350                                 return false;
351                         }
352                         /* Give the module a chance to tidy out all its metadata */
353                         for (chan_hash::iterator c = this->chanlist->begin(); c != this->chanlist->end(); c++)
354                         {
355                                 modules[j]->OnCleanup(TYPE_CHANNEL,c->second);
356                         }
357                         for (user_hash::iterator u = this->clientlist->begin(); u != this->clientlist->end(); u++)
358                         {
359                                 modules[j]->OnCleanup(TYPE_USER,u->second);
360                         }
361
362                         /* Tidy up any dangling resolvers */
363                         this->Res->CleanResolvers(modules[j]);
364
365                         FOREACH_MOD_I(this,I_OnUnloadModule,OnUnloadModule(modules[j],Config->module_names[j]));
366
367                         for(int t = 0; t < 255; t++)
368                         {
369                                 Config->global_implementation[t] -= Config->implement_lists[j][t];
370                         }
371
372                         /* We have to renumber implement_lists after unload because the module numbers change!
373                          */
374                         for(int j2 = j; j2 < 254; j2++)
375                         {
376                                 for(int t = 0; t < 255; t++)
377                                 {
378                                         Config->implement_lists[j2][t] = Config->implement_lists[j2+1][t];
379                                 }
380                         }
381
382                         // found the module
383                         Parser->RemoveCommands(filename);
384                         this->EraseModule(j);
385                         this->EraseFactory(j);
386                         this->Log(DEFAULT,"Module %s unloaded",filename);
387                         this->ModCount--;
388                         BuildISupport();
389                         return true;
390                 }
391         }
392         this->Log(DEFAULT,"Module %s is not loaded, cannot unload it!",filename);
393         snprintf(MODERR,MAXBUF,"Module not loaded");
394         return false;
395 }
396
397 bool InspIRCd::LoadModule(const char* filename)
398 {
399         /* Do we have a glob pattern in the filename?
400          * The user wants to load multiple modules which
401          * match the pattern.
402          */
403         if (strchr(filename,'*') || (strchr(filename,'?')))
404         {
405                 int n_match = 0;
406                 DIR* library = opendir(Config->ModPath);
407                 if (library)
408                 {
409                         /* Try and locate and load all modules matching the pattern */
410                         dirent* entry = NULL;
411                         while ((entry = readdir(library)))
412                         {
413                                 if (this->MatchText(entry->d_name, filename))
414                                 {
415                                         if (!this->LoadModule(entry->d_name))
416                                                 n_match++;
417                                 }
418                         }
419                         closedir(library);
420                 }
421                 /* Loadmodule will now return false if any one of the modules failed
422                  * to load (but wont abort when it encounters a bad one) and when 1 or
423                  * more modules were actually loaded.
424                  */
425                 return (n_match > 0);
426         }
427
428         char modfile[MAXBUF];
429         snprintf(modfile,MAXBUF,"%s/%s",Config->ModPath,filename);
430         std::string filename_str = filename;
431
432         if (!ServerConfig::DirValid(modfile))
433         {
434                 this->Log(DEFAULT,"Module %s is not within the modules directory.",modfile);
435                 snprintf(MODERR,MAXBUF,"Module %s is not within the modules directory.",modfile);
436                 return false;
437         }
438         if (ServerConfig::FileExists(modfile))
439         {
440
441                 for (unsigned int j = 0; j < Config->module_names.size(); j++)
442                 {
443                         if (Config->module_names[j] == filename_str)
444                         {
445                                 this->Log(DEFAULT,"Module %s is already loaded, cannot load a module twice!",modfile);
446                                 snprintf(MODERR,MAXBUF,"Module already loaded");
447                                 return false;
448                         }
449                 }
450                 Module* m = NULL;
451                 ircd_module* a = NULL;
452                 try
453                 {
454                         a = new ircd_module(this, modfile);
455                         factory[this->ModCount+1] = a;
456                         if (factory[this->ModCount+1]->LastError())
457                         {
458                                 this->Log(DEFAULT,"Unable to load %s: %s",modfile,factory[this->ModCount+1]->LastError());
459                                 snprintf(MODERR,MAXBUF,"Loader/Linker error: %s",factory[this->ModCount+1]->LastError());
460                                 return false;
461                         }
462                         if ((long)factory[this->ModCount+1]->factory != -1)
463                         {
464                                 m = factory[this->ModCount+1]->factory->CreateModule(this);
465
466                                 Version v = m->GetVersion();
467
468                                 if (v.API != API_VERSION)
469                                 {
470                                         delete m;
471                                         this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
472                                         snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
473                                         return false;
474                                 }
475                                 else
476                                 {
477                                         this->Log(DEFAULT,"New module introduced: %s (API version %d, Module version %d.%d.%d.%d)%s", filename, v.API, v.Major, v.Minor, v.Revision, v.Build, (!(v.Flags & VF_VENDOR) ? " [3rd Party]" : " [Vendor]"));
478                                 }
479
480                                 modules[this->ModCount+1] = m;
481                                 /* save the module and the module's classfactory, if
482                                  * this isnt done, random crashes can occur :/ */
483                                 Config->module_names.push_back(filename);
484
485                                 char* x = &Config->implement_lists[this->ModCount+1][0];
486                                 for(int t = 0; t < 255; t++)
487                                         x[t] = 0;
488
489                                 modules[this->ModCount+1]->Implements(x);
490
491                                 for(int t = 0; t < 255; t++)
492                                         Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
493                         }
494                         else
495                         {
496                                 this->Log(DEFAULT,"Unable to load %s",modfile);
497                                 snprintf(MODERR,MAXBUF,"Factory function failed: Probably missing init_module() entrypoint.");
498                                 return false;
499                         }
500                 }
501                 catch (CoreException& modexcept)
502                 {
503                         this->Log(DEFAULT,"Unable to load %s: %s",modfile,modexcept.GetReason());
504                         snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
505                         return false;
506                 }
507         }
508         else
509         {
510                 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
511                 snprintf(MODERR,MAXBUF,"Module file could not be found");
512                 return false;
513         }
514         this->ModCount++;
515         FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
516         // now work out which modules, if any, want to move to the back of the queue,
517         // and if they do, move them there.
518         std::vector<std::string> put_to_back;
519         std::vector<std::string> put_to_front;
520         std::map<std::string,std::string> put_before;
521         std::map<std::string,std::string> put_after;
522         for (unsigned int j = 0; j < Config->module_names.size(); j++)
523         {
524                 if (modules[j]->Prioritize() == PRIORITY_LAST)
525                         put_to_back.push_back(Config->module_names[j]);
526                 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
527                         put_to_front.push_back(Config->module_names[j]);
528                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
529                         put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
530                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
531                         put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
532         }
533         for (unsigned int j = 0; j < put_to_back.size(); j++)
534                 MoveToLast(put_to_back[j]);
535         for (unsigned int j = 0; j < put_to_front.size(); j++)
536                 MoveToFirst(put_to_front[j]);
537         for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
538                 MoveBefore(j->first,j->second);
539         for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
540                 MoveAfter(j->first,j->second);
541         BuildISupport();
542         return true;
543 }
544
545 long InspIRCd::PriorityAfter(const std::string &modulename)
546 {
547         for (unsigned int j = 0; j < this->Config->module_names.size(); j++)
548         {
549                 if (this->Config->module_names[j] == modulename)
550                 {
551                         return ((j << 8) | PRIORITY_AFTER);
552                 }
553         }
554         return PRIORITY_DONTCARE;
555 }
556
557 long InspIRCd::PriorityBefore(const std::string &modulename)
558 {
559         for (unsigned int j = 0; j < this->Config->module_names.size(); j++)
560         {
561                 if (this->Config->module_names[j] == modulename)
562                 {
563                         return ((j << 8) | PRIORITY_BEFORE);
564                 }
565         }
566         return PRIORITY_DONTCARE;
567 }
568
569 bool InspIRCd::PublishFeature(const std::string &FeatureName, Module* Mod)
570 {
571         if (Features.find(FeatureName) == Features.end())
572         {
573                 Features[FeatureName] = Mod;
574                 return true;
575         }
576         return false;
577 }
578
579 bool InspIRCd::UnpublishFeature(const std::string &FeatureName)
580 {
581         featurelist::iterator iter = Features.find(FeatureName);
582         
583         if (iter == Features.end())
584                 return false;
585
586         Features.erase(iter);
587         return true;
588 }
589
590 Module* InspIRCd::FindFeature(const std::string &FeatureName)
591 {
592         featurelist::iterator iter = Features.find(FeatureName);
593
594         if (iter == Features.end())
595                 return NULL;
596
597         return iter->second;
598 }
599
600 bool InspIRCd::PublishInterface(const std::string &InterfaceName, Module* Mod)
601 {
602         interfacelist::iterator iter = Interfaces.find(InterfaceName);
603
604         if (iter == Interfaces.end())
605         {
606                 modulelist ml;
607                 ml.push_back(Mod);
608                 Interfaces[InterfaceName] = std::make_pair(0, ml);
609                 return true;
610         }
611         else
612         {
613                 iter->second.second.push_back(Mod);
614                 return true;
615         }
616         return false;
617 }
618
619 bool InspIRCd::UnpublishInterface(const std::string &InterfaceName, Module* Mod)
620 {
621         interfacelist::iterator iter = Interfaces.find(InterfaceName);
622
623         if (iter == Interfaces.end())
624                 return false;
625
626         for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
627         {
628                 if (*x == Mod)
629                 {
630                         iter->second.second.erase(x);
631                         if (iter->second.second.empty())
632                                 Interfaces.erase(InterfaceName);
633                         return true;
634                 }
635         }
636         return false;
637 }
638
639 modulelist* InspIRCd::FindInterface(const std::string &InterfaceName)
640 {
641         interfacelist::iterator iter = Interfaces.find(InterfaceName);
642         if (iter == Interfaces.end())
643                 return NULL;
644         else
645                 return &(iter->second.second);
646 }
647
648 void InspIRCd::UseInterface(const std::string &InterfaceName)
649 {
650         interfacelist::iterator iter = Interfaces.find(InterfaceName);
651         if (iter != Interfaces.end())
652                 iter->second.first++;
653
654 }
655
656 void InspIRCd::DoneWithInterface(const std::string &InterfaceName)
657 {
658         interfacelist::iterator iter = Interfaces.find(InterfaceName);
659         if (iter != Interfaces.end())
660                 iter->second.first--;
661 }
662
663 std::pair<int,std::string> InspIRCd::GetInterfaceInstanceCount(Module* m)
664 {
665         for (interfacelist::iterator iter = Interfaces.begin(); iter != Interfaces.end(); iter++)
666         {
667                 for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
668                 {
669                         if (*x == m)
670                         {
671                                 return std::make_pair(iter->second.first, iter->first);
672                         }
673                 }
674         }
675         return std::make_pair(0, "");
676 }
677
678 const std::string& InspIRCd::GetModuleName(Module* m)
679 {
680         static std::string nothing; /* Prevent compiler warning */
681
682         if (!this->GetModuleCount())
683                 return nothing;
684
685         for (int i = 0; i <= this->GetModuleCount(); i++)
686         {
687                 if (this->modules[i] == m)
688                 {
689                         return this->Config->module_names[i];
690                 }
691         }
692         return nothing; /* As above */
693 }
694
695 /* This is ugly, yes, but hash_map's arent designed to be
696  * addressed in this manner, and this is a bit of a kludge.
697  * Luckily its a specialist function and rarely used by
698  * many modules (in fact, it was specially created to make
699  * m_safelist possible, initially).
700  */
701
702 chanrec* InspIRCd::GetChannelIndex(long index)
703 {
704         int target = 0;
705         for (chan_hash::iterator n = this->chanlist->begin(); n != this->chanlist->end(); n++, target++)
706         {
707                 if (index == target)
708                         return n->second;
709         }
710         return NULL;
711 }
712
713 bool InspIRCd::MatchText(const std::string &sliteral, const std::string &spattern)
714 {
715         return match(sliteral.c_str(),spattern.c_str());
716 }
717
718 CmdResult InspIRCd::CallCommandHandler(const std::string &commandname, const char** parameters, int pcnt, userrec* user)
719 {
720         return this->Parser->CallHandler(commandname,parameters,pcnt,user);
721 }
722
723 bool InspIRCd::IsValidModuleCommand(const std::string &commandname, int pcnt, userrec* user)
724 {
725         return this->Parser->IsValidCommand(commandname, pcnt, user);
726 }
727
728 void InspIRCd::AddCommand(command_t *f)
729 {
730         if (!this->Parser->CreateCommand(f))
731         {
732                 ModuleException err("Command "+std::string(f->command)+" already exists.");
733                 throw (err);
734         }
735 }
736
737 void InspIRCd::SendMode(const char** parameters, int pcnt, userrec *user)
738 {
739         this->Modes->Process(parameters,pcnt,user,true);
740 }
741
742 void InspIRCd::DumpText(userrec* User, const std::string &LinePrefix, stringstream &TextStream)
743 {
744         std::string CompleteLine = LinePrefix;
745         std::string Word;
746         while (TextStream >> Word)
747         {
748                 if (CompleteLine.length() + Word.length() + 3 > 500)
749                 {
750                         User->WriteServ(CompleteLine);
751                         CompleteLine = LinePrefix;
752                 }
753                 CompleteLine = CompleteLine + Word + " ";
754         }
755         User->WriteServ(CompleteLine);
756 }
757
758 userrec* FindDescriptorHandler::Call(int socket)
759 {
760         return reinterpret_cast<userrec*>(Server->SE->GetRef(socket));
761 }
762
763 bool InspIRCd::AddMode(ModeHandler* mh, const unsigned char mode)
764 {
765         return this->Modes->AddMode(mh,mode);
766 }
767
768 bool InspIRCd::AddModeWatcher(ModeWatcher* mw)
769 {
770         return this->Modes->AddModeWatcher(mw);
771 }
772
773 bool InspIRCd::DelModeWatcher(ModeWatcher* mw)
774 {
775         return this->Modes->DelModeWatcher(mw);
776 }
777
778 bool InspIRCd::AddResolver(Resolver* r, bool cached)
779 {
780         if (!cached)
781                 return this->Res->AddResolverClass(r);
782         else
783         {
784                 r->TriggerCachedResult();
785                 delete r;
786                 return true;
787         }
788 }
789
790 void InspIRCd::AddGLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask)
791 {
792         XLines->add_gline(duration, source.c_str(), reason.c_str(), hostmask.c_str());
793         XLines->apply_lines(APPLY_GLINES);
794 }
795
796 void InspIRCd::AddQLine(long duration, const std::string &source, const std::string &reason, const std::string &nickname)
797 {
798         XLines->add_qline(duration, source.c_str(), reason.c_str(), nickname.c_str());
799         XLines->apply_lines(APPLY_QLINES);
800 }
801
802 void InspIRCd::AddZLine(long duration, const std::string &source, const std::string &reason, const std::string &ipaddr)
803 {
804         XLines->add_zline(duration, source.c_str(), reason.c_str(), ipaddr.c_str());
805         XLines->apply_lines(APPLY_ZLINES);
806 }
807
808 void InspIRCd::AddKLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask)
809 {
810         XLines->add_kline(duration, source.c_str(), reason.c_str(), hostmask.c_str());
811         XLines->apply_lines(APPLY_KLINES);
812 }
813
814 void InspIRCd::AddELine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask)
815 {
816         XLines->add_eline(duration, source.c_str(), reason.c_str(), hostmask.c_str());
817 }
818
819 bool InspIRCd::DelGLine(const std::string &hostmask)
820 {
821         return XLines->del_gline(hostmask.c_str());
822 }
823
824 bool InspIRCd::DelQLine(const std::string &nickname)
825 {
826         return XLines->del_qline(nickname.c_str());
827 }
828
829 bool InspIRCd::DelZLine(const std::string &ipaddr)
830 {
831         return XLines->del_zline(ipaddr.c_str());
832 }
833
834 bool InspIRCd::DelKLine(const std::string &hostmask)
835 {
836         return XLines->del_kline(hostmask.c_str());
837 }
838
839 bool InspIRCd::DelELine(const std::string &hostmask)
840 {
841         return XLines->del_eline(hostmask.c_str());
842 }
843
844 /*
845  * XXX why on *earth* is this in modules.cpp...? I think
846  * perhaps we need a server.cpp for InspIRCd:: stuff where possible. -- w00t
847  */
848 bool InspIRCd::IsValidMask(const std::string &mask)
849 {
850         char* dest = (char*)mask.c_str();
851         int exclamation = 0;
852         int atsign = 0;
853
854         for (char* i = dest; *i; i++)
855         {
856                 /* out of range character, bad mask */
857                 if (*i < 32 || *i > 126)
858                 {
859                         return false;
860                 }
861
862                 switch (*i)
863                 {
864                         case '!':
865                                 exclamation++;
866                                 break;
867                         case '@':
868                                 atsign++;
869                                 break;
870                 }
871         }
872
873         /* valid masks only have 1 ! and @ */
874         if (exclamation != 1 || atsign != 1)
875                 return false;
876
877         return true;
878 }
879
880 Module* InspIRCd::FindModule(const std::string &name)
881 {
882         for (int i = 0; i <= this->GetModuleCount(); i++)
883         {
884                 if (this->Config->module_names[i] == name)
885                 {
886                         return this->modules[i];
887                 }
888         }
889         return NULL;
890 }
891
892 ConfigReader::ConfigReader(InspIRCd* Instance) : ServerInstance(Instance)
893 {
894         /* Is there any reason to load the entire config file again here?
895          * it's needed if they specify another config file, but using the
896          * default one we can just use the global config data - pre-parsed!
897          */
898         this->errorlog = new std::ostringstream(std::stringstream::in | std::stringstream::out);
899         
900         this->data = &ServerInstance->Config->config_data;
901         this->privatehash = false;
902 }
903
904
905 ConfigReader::~ConfigReader()
906 {
907         if (this->errorlog)
908                 DELETE(this->errorlog);
909         if(this->privatehash)
910                 DELETE(this->data);
911 }
912
913
914 ConfigReader::ConfigReader(InspIRCd* Instance, const std::string &filename) : ServerInstance(Instance)
915 {
916         ServerInstance->Config->ClearStack();
917
918         this->data = new ConfigDataHash;
919         this->privatehash = true;
920         this->errorlog = new std::ostringstream(std::stringstream::in | std::stringstream::out);
921         this->readerror = ServerInstance->Config->LoadConf(*this->data, filename, *this->errorlog);
922         if (!this->readerror)
923                 this->error = CONF_FILE_NOT_FOUND;
924 }
925
926
927 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool allow_linefeeds)
928 {
929         /* Don't need to strlcpy() tag and name anymore, ReadConf() takes const char* */ 
930         std::string result;
931         
932         if (!ServerInstance->Config->ConfValue(*this->data, tag, name, default_value, index, result, allow_linefeeds))
933         {
934                 this->error = CONF_VALUE_NOT_FOUND;
935         }
936         return result;
937 }
938
939 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, int index, bool allow_linefeeds)
940 {
941         return ReadValue(tag, name, "", index, allow_linefeeds);
942 }
943
944 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, const std::string &default_value, int index)
945 {
946         return ServerInstance->Config->ConfValueBool(*this->data, tag, name, default_value, index);
947 }
948
949 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, int index)
950 {
951         return ReadFlag(tag, name, "", index);
952 }
953
954
955 long ConfigReader::ReadInteger(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool needs_unsigned)
956 {
957         int result;
958         
959         if(!ServerInstance->Config->ConfValueInteger(*this->data, tag, name, default_value, index, result))
960         {
961                 this->error = CONF_VALUE_NOT_FOUND;
962                 return 0;
963         }
964         
965         if ((needs_unsigned) && (result < 0))
966         {
967                 this->error = CONF_NOT_UNSIGNED;
968                 return 0;
969         }
970         
971         return result;
972 }
973
974 long ConfigReader::ReadInteger(const std::string &tag, const std::string &name, int index, bool needs_unsigned)
975 {
976         return ReadInteger(tag, name, "", index, needs_unsigned);
977 }
978
979 long ConfigReader::GetError()
980 {
981         long olderr = this->error;
982         this->error = 0;
983         return olderr;
984 }
985
986 void ConfigReader::DumpErrors(bool bail, userrec* user)
987 {
988         ServerInstance->Config->ReportConfigError(this->errorlog->str(), bail, user);
989 }
990
991
992 int ConfigReader::Enumerate(const std::string &tag)
993 {
994         return ServerInstance->Config->ConfValueEnum(*this->data, tag);
995 }
996
997 int ConfigReader::EnumerateValues(const std::string &tag, int index)
998 {
999         return ServerInstance->Config->ConfVarEnum(*this->data, tag, index);
1000 }
1001
1002 bool ConfigReader::Verify()
1003 {
1004         return this->readerror;
1005 }
1006
1007
1008 FileReader::FileReader(InspIRCd* Instance, const std::string &filename) : ServerInstance(Instance)
1009 {
1010         LoadFile(filename);
1011 }
1012
1013 FileReader::FileReader(InspIRCd* Instance) : ServerInstance(Instance)
1014 {
1015 }
1016
1017 std::string FileReader::Contents()
1018 {
1019         std::string x;
1020         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
1021         {
1022                 x.append(*a);
1023                 x.append("\r\n");
1024         }
1025         return x;
1026 }
1027
1028 unsigned long FileReader::ContentSize()
1029 {
1030         return this->contentsize;
1031 }
1032
1033 void FileReader::CalcSize()
1034 {
1035         unsigned long n = 0;
1036         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
1037                 n += (a->length() + 2);
1038         this->contentsize = n;
1039 }
1040
1041 void FileReader::LoadFile(const std::string &filename)
1042 {
1043         file_cache c;
1044         c.clear();
1045         if (ServerInstance->Config->ReadFile(c,filename.c_str()))
1046         {
1047                 this->fc = c;
1048                 this->CalcSize();
1049         }
1050 }
1051
1052
1053 FileReader::~FileReader()
1054 {
1055 }
1056
1057 bool FileReader::Exists()
1058 {
1059         return (!(fc.size() == 0));
1060 }
1061
1062 std::string FileReader::GetLine(int x)
1063 {
1064         if ((x<0) || ((unsigned)x>fc.size()))
1065                 return "";
1066         return fc[x];
1067 }
1068
1069 int FileReader::FileSize()
1070 {
1071         return fc.size();
1072 }
1073
1074