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