]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules.cpp
(Om, this commit is safe): remove references to DELETE() macro, revert back to delete...
[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                 snprintf(MODERR, MAXBUF,"Module %s is not within the modules directory.", modfile);
431                 this->Log(DEFAULT, MODERR);
432                 return false;
433         }
434         
435         if (ServerConfig::FileExists(modfile))
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                 
447                 Module* m = NULL;
448                 ircd_module* a = NULL;
449                 
450                 try
451                 {
452                         /* This will throw a CoreException if there's a problem loading
453                          * the module file or getting a pointer to the init_module symbol.
454                          */
455                         a = new ircd_module(this, modfile, "init_module");
456                         
457                         factory[this->ModCount+1] = a;
458                         
459                         m = factory[this->ModCount+1]->CallInit();
460
461                         if(m)
462                         {
463                                 Version v = m->GetVersion();
464
465                                 if (v.API != API_VERSION)
466                                 {
467                                         delete m;
468                                         this->Log(DEFAULT,"Unable to load %s: Incorrect module API version: %d (our version: %d)",modfile,v.API,API_VERSION);
469                                         snprintf(MODERR,MAXBUF,"Loader/Linker error: Incorrect module API version: %d (our version: %d)",v.API,API_VERSION);
470                                         return false;
471                                 }
472                                 else
473                                 {
474                                         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]"));
475                                 }
476
477                                 modules[this->ModCount+1] = m;
478                                 
479                                 /* save the module and the module's classfactory, if
480                                  * this isnt done, random crashes can occur :/ */
481                                 Config->module_names.push_back(filename);
482
483                                 char* x = &Config->implement_lists[this->ModCount+1][0];
484                                 for(int t = 0; t < 255; t++)
485                                         x[t] = 0;
486
487                                 modules[this->ModCount+1]->Implements(x);
488
489                                 for(int t = 0; t < 255; t++)
490                                         Config->global_implementation[t] += Config->implement_lists[this->ModCount+1][t];
491                         }
492                         else
493                         {
494                                 this->Log(DEFAULT, "Unable to load %s",modfile);
495                                 snprintf(MODERR,MAXBUF, "Probably missing init_module() entrypoint, but dlsym() didn't notice a problem");
496                                 return false;
497                         }
498                 }
499                 catch (LoadModuleException& modexcept)
500                 {
501                         this->Log(DEFAULT,"Unable to load %s: %s", modfile, modexcept.GetReason());
502                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s", modexcept.GetReason());
503                         return false;
504                 }
505                 catch (FindSymbolException& modexcept)
506                 {
507                         this->Log(DEFAULT,"Unable to load %s: %s", modfile, modexcept.GetReason());
508                         snprintf(MODERR,MAXBUF,"Loader/Linker error: %s", modexcept.GetReason());
509                         return false;
510                 }
511                 catch (CoreException& modexcept)
512                 {
513                         this->Log(DEFAULT,"Unable to load %s: %s",modfile,modexcept.GetReason());
514                         snprintf(MODERR,MAXBUF,"Factory function of %s threw an exception: %s", modexcept.GetSource(), modexcept.GetReason());
515                         return false;
516                 }
517         }
518         else
519         {
520                 this->Log(DEFAULT,"InspIRCd: startup: Module Not Found %s",modfile);
521                 snprintf(MODERR,MAXBUF,"Module file could not be found");
522                 return false;
523         }
524         
525         this->ModCount++;
526         FOREACH_MOD_I(this,I_OnLoadModule,OnLoadModule(modules[this->ModCount],filename_str));
527         // now work out which modules, if any, want to move to the back of the queue,
528         // and if they do, move them there.
529         std::vector<std::string> put_to_back;
530         std::vector<std::string> put_to_front;
531         std::map<std::string,std::string> put_before;
532         std::map<std::string,std::string> put_after;
533         for (unsigned int j = 0; j < Config->module_names.size(); j++)
534         {
535                 if (modules[j]->Prioritize() == PRIORITY_LAST)
536                         put_to_back.push_back(Config->module_names[j]);
537                 else if (modules[j]->Prioritize() == PRIORITY_FIRST)
538                         put_to_front.push_back(Config->module_names[j]);
539                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_BEFORE)
540                         put_before[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
541                 else if ((modules[j]->Prioritize() & 0xFF) == PRIORITY_AFTER)
542                         put_after[Config->module_names[j]] = Config->module_names[modules[j]->Prioritize() >> 8];
543         }
544         for (unsigned int j = 0; j < put_to_back.size(); j++)
545                 MoveToLast(put_to_back[j]);
546         for (unsigned int j = 0; j < put_to_front.size(); j++)
547                 MoveToFirst(put_to_front[j]);
548         for (std::map<std::string,std::string>::iterator j = put_before.begin(); j != put_before.end(); j++)
549                 MoveBefore(j->first,j->second);
550         for (std::map<std::string,std::string>::iterator j = put_after.begin(); j != put_after.end(); j++)
551                 MoveAfter(j->first,j->second);
552         BuildISupport();
553         return true;
554 }
555
556 long InspIRCd::PriorityAfter(const std::string &modulename)
557 {
558         for (unsigned int j = 0; j < this->Config->module_names.size(); j++)
559         {
560                 if (this->Config->module_names[j] == modulename)
561                 {
562                         return ((j << 8) | PRIORITY_AFTER);
563                 }
564         }
565         return PRIORITY_DONTCARE;
566 }
567
568 long InspIRCd::PriorityBefore(const std::string &modulename)
569 {
570         for (unsigned int j = 0; j < this->Config->module_names.size(); j++)
571         {
572                 if (this->Config->module_names[j] == modulename)
573                 {
574                         return ((j << 8) | PRIORITY_BEFORE);
575                 }
576         }
577         return PRIORITY_DONTCARE;
578 }
579
580 bool InspIRCd::PublishFeature(const std::string &FeatureName, Module* Mod)
581 {
582         if (Features.find(FeatureName) == Features.end())
583         {
584                 Features[FeatureName] = Mod;
585                 return true;
586         }
587         return false;
588 }
589
590 bool InspIRCd::UnpublishFeature(const std::string &FeatureName)
591 {
592         featurelist::iterator iter = Features.find(FeatureName);
593         
594         if (iter == Features.end())
595                 return false;
596
597         Features.erase(iter);
598         return true;
599 }
600
601 Module* InspIRCd::FindFeature(const std::string &FeatureName)
602 {
603         featurelist::iterator iter = Features.find(FeatureName);
604
605         if (iter == Features.end())
606                 return NULL;
607
608         return iter->second;
609 }
610
611 bool InspIRCd::PublishInterface(const std::string &InterfaceName, Module* Mod)
612 {
613         interfacelist::iterator iter = Interfaces.find(InterfaceName);
614
615         if (iter == Interfaces.end())
616         {
617                 modulelist ml;
618                 ml.push_back(Mod);
619                 Interfaces[InterfaceName] = std::make_pair(0, ml);
620                 return true;
621         }
622         else
623         {
624                 iter->second.second.push_back(Mod);
625                 return true;
626         }
627         return false;
628 }
629
630 bool InspIRCd::UnpublishInterface(const std::string &InterfaceName, Module* Mod)
631 {
632         interfacelist::iterator iter = Interfaces.find(InterfaceName);
633
634         if (iter == Interfaces.end())
635                 return false;
636
637         for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
638         {
639                 if (*x == Mod)
640                 {
641                         iter->second.second.erase(x);
642                         if (iter->second.second.empty())
643                                 Interfaces.erase(InterfaceName);
644                         return true;
645                 }
646         }
647         return false;
648 }
649
650 modulelist* InspIRCd::FindInterface(const std::string &InterfaceName)
651 {
652         interfacelist::iterator iter = Interfaces.find(InterfaceName);
653         if (iter == Interfaces.end())
654                 return NULL;
655         else
656                 return &(iter->second.second);
657 }
658
659 void InspIRCd::UseInterface(const std::string &InterfaceName)
660 {
661         interfacelist::iterator iter = Interfaces.find(InterfaceName);
662         if (iter != Interfaces.end())
663                 iter->second.first++;
664
665 }
666
667 void InspIRCd::DoneWithInterface(const std::string &InterfaceName)
668 {
669         interfacelist::iterator iter = Interfaces.find(InterfaceName);
670         if (iter != Interfaces.end())
671                 iter->second.first--;
672 }
673
674 std::pair<int,std::string> InspIRCd::GetInterfaceInstanceCount(Module* m)
675 {
676         for (interfacelist::iterator iter = Interfaces.begin(); iter != Interfaces.end(); iter++)
677         {
678                 for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
679                 {
680                         if (*x == m)
681                         {
682                                 return std::make_pair(iter->second.first, iter->first);
683                         }
684                 }
685         }
686         return std::make_pair(0, "");
687 }
688
689 const std::string& InspIRCd::GetModuleName(Module* m)
690 {
691         static std::string nothing; /* Prevent compiler warning */
692
693         if (!this->GetModuleCount())
694                 return nothing;
695
696         for (int i = 0; i <= this->GetModuleCount(); i++)
697         {
698                 if (this->modules[i] == m)
699                 {
700                         return this->Config->module_names[i];
701                 }
702         }
703         return nothing; /* As above */
704 }
705
706 /* This is ugly, yes, but hash_map's arent designed to be
707  * addressed in this manner, and this is a bit of a kludge.
708  * Luckily its a specialist function and rarely used by
709  * many modules (in fact, it was specially created to make
710  * m_safelist possible, initially).
711  */
712
713 chanrec* InspIRCd::GetChannelIndex(long index)
714 {
715         int target = 0;
716         for (chan_hash::iterator n = this->chanlist->begin(); n != this->chanlist->end(); n++, target++)
717         {
718                 if (index == target)
719                         return n->second;
720         }
721         return NULL;
722 }
723
724 bool InspIRCd::MatchText(const std::string &sliteral, const std::string &spattern)
725 {
726         return match(sliteral.c_str(),spattern.c_str());
727 }
728
729 CmdResult InspIRCd::CallCommandHandler(const std::string &commandname, const char** parameters, int pcnt, userrec* user)
730 {
731         return this->Parser->CallHandler(commandname,parameters,pcnt,user);
732 }
733
734 bool InspIRCd::IsValidModuleCommand(const std::string &commandname, int pcnt, userrec* user)
735 {
736         return this->Parser->IsValidCommand(commandname, pcnt, user);
737 }
738
739 void InspIRCd::AddCommand(command_t *f)
740 {
741         if (!this->Parser->CreateCommand(f))
742         {
743                 ModuleException err("Command "+std::string(f->command)+" already exists.");
744                 throw (err);
745         }
746 }
747
748 void InspIRCd::SendMode(const char** parameters, int pcnt, userrec *user)
749 {
750         this->Modes->Process(parameters,pcnt,user,true);
751 }
752
753 void InspIRCd::DumpText(userrec* User, const std::string &LinePrefix, stringstream &TextStream)
754 {
755         std::string CompleteLine = LinePrefix;
756         std::string Word;
757         while (TextStream >> Word)
758         {
759                 if (CompleteLine.length() + Word.length() + 3 > 500)
760                 {
761                         User->WriteServ(CompleteLine);
762                         CompleteLine = LinePrefix;
763                 }
764                 CompleteLine = CompleteLine + Word + " ";
765         }
766         User->WriteServ(CompleteLine);
767 }
768
769 userrec* FindDescriptorHandler::Call(int socket)
770 {
771         return reinterpret_cast<userrec*>(Server->SE->GetRef(socket));
772 }
773
774 bool InspIRCd::AddMode(ModeHandler* mh, const unsigned char mode)
775 {
776         return this->Modes->AddMode(mh,mode);
777 }
778
779 bool InspIRCd::AddModeWatcher(ModeWatcher* mw)
780 {
781         return this->Modes->AddModeWatcher(mw);
782 }
783
784 bool InspIRCd::DelModeWatcher(ModeWatcher* mw)
785 {
786         return this->Modes->DelModeWatcher(mw);
787 }
788
789 bool InspIRCd::AddResolver(Resolver* r, bool cached)
790 {
791         if (!cached)
792                 return this->Res->AddResolverClass(r);
793         else
794         {
795                 r->TriggerCachedResult();
796                 delete r;
797                 return true;
798         }
799 }
800
801 void InspIRCd::AddGLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask)
802 {
803         XLines->add_gline(duration, source.c_str(), reason.c_str(), hostmask.c_str());
804         XLines->apply_lines(APPLY_GLINES);
805 }
806
807 void InspIRCd::AddQLine(long duration, const std::string &source, const std::string &reason, const std::string &nickname)
808 {
809         XLines->add_qline(duration, source.c_str(), reason.c_str(), nickname.c_str());
810         XLines->apply_lines(APPLY_QLINES);
811 }
812
813 void InspIRCd::AddZLine(long duration, const std::string &source, const std::string &reason, const std::string &ipaddr)
814 {
815         XLines->add_zline(duration, source.c_str(), reason.c_str(), ipaddr.c_str());
816         XLines->apply_lines(APPLY_ZLINES);
817 }
818
819 void InspIRCd::AddKLine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask)
820 {
821         XLines->add_kline(duration, source.c_str(), reason.c_str(), hostmask.c_str());
822         XLines->apply_lines(APPLY_KLINES);
823 }
824
825 void InspIRCd::AddELine(long duration, const std::string &source, const std::string &reason, const std::string &hostmask)
826 {
827         XLines->add_eline(duration, source.c_str(), reason.c_str(), hostmask.c_str());
828 }
829
830 bool InspIRCd::DelGLine(const std::string &hostmask)
831 {
832         return XLines->del_gline(hostmask.c_str());
833 }
834
835 bool InspIRCd::DelQLine(const std::string &nickname)
836 {
837         return XLines->del_qline(nickname.c_str());
838 }
839
840 bool InspIRCd::DelZLine(const std::string &ipaddr)
841 {
842         return XLines->del_zline(ipaddr.c_str());
843 }
844
845 bool InspIRCd::DelKLine(const std::string &hostmask)
846 {
847         return XLines->del_kline(hostmask.c_str());
848 }
849
850 bool InspIRCd::DelELine(const std::string &hostmask)
851 {
852         return XLines->del_eline(hostmask.c_str());
853 }
854
855 /*
856  * XXX why on *earth* is this in modules.cpp...? I think
857  * perhaps we need a server.cpp for InspIRCd:: stuff where possible. -- w00t
858  */
859 bool InspIRCd::IsValidMask(const std::string &mask)
860 {
861         char* dest = (char*)mask.c_str();
862         int exclamation = 0;
863         int atsign = 0;
864
865         for (char* i = dest; *i; i++)
866         {
867                 /* out of range character, bad mask */
868                 if (*i < 32 || *i > 126)
869                 {
870                         return false;
871                 }
872
873                 switch (*i)
874                 {
875                         case '!':
876                                 exclamation++;
877                                 break;
878                         case '@':
879                                 atsign++;
880                                 break;
881                 }
882         }
883
884         /* valid masks only have 1 ! and @ */
885         if (exclamation != 1 || atsign != 1)
886                 return false;
887
888         return true;
889 }
890
891 Module* InspIRCd::FindModule(const std::string &name)
892 {
893         for (int i = 0; i <= this->GetModuleCount(); i++)
894         {
895                 if (this->Config->module_names[i] == name)
896                 {
897                         return this->modules[i];
898                 }
899         }
900         return NULL;
901 }
902
903 ConfigReader::ConfigReader(InspIRCd* Instance) : ServerInstance(Instance)
904 {
905         /* Is there any reason to load the entire config file again here?
906          * it's needed if they specify another config file, but using the
907          * default one we can just use the global config data - pre-parsed!
908          */
909         this->errorlog = new std::ostringstream(std::stringstream::in | std::stringstream::out);
910         
911         this->data = &ServerInstance->Config->config_data;
912         this->privatehash = false;
913 }
914
915
916 ConfigReader::~ConfigReader()
917 {
918         if (this->errorlog)
919                 delete this->errorlog;
920         if(this->privatehash)
921                 delete this->data;
922 }
923
924
925 ConfigReader::ConfigReader(InspIRCd* Instance, const std::string &filename) : ServerInstance(Instance)
926 {
927         ServerInstance->Config->ClearStack();
928
929         this->data = new ConfigDataHash;
930         this->privatehash = true;
931         this->errorlog = new std::ostringstream(std::stringstream::in | std::stringstream::out);
932         this->readerror = ServerInstance->Config->LoadConf(*this->data, filename, *this->errorlog);
933         if (!this->readerror)
934                 this->error = CONF_FILE_NOT_FOUND;
935 }
936
937
938 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool allow_linefeeds)
939 {
940         /* Don't need to strlcpy() tag and name anymore, ReadConf() takes const char* */ 
941         std::string result;
942         
943         if (!ServerInstance->Config->ConfValue(*this->data, tag, name, default_value, index, result, allow_linefeeds))
944         {
945                 this->error = CONF_VALUE_NOT_FOUND;
946         }
947         return result;
948 }
949
950 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, int index, bool allow_linefeeds)
951 {
952         return ReadValue(tag, name, "", index, allow_linefeeds);
953 }
954
955 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, const std::string &default_value, int index)
956 {
957         return ServerInstance->Config->ConfValueBool(*this->data, tag, name, default_value, index);
958 }
959
960 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, int index)
961 {
962         return ReadFlag(tag, name, "", index);
963 }
964
965
966 long ConfigReader::ReadInteger(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool needs_unsigned)
967 {
968         int result;
969         
970         if(!ServerInstance->Config->ConfValueInteger(*this->data, tag, name, default_value, index, result))
971         {
972                 this->error = CONF_VALUE_NOT_FOUND;
973                 return 0;
974         }
975         
976         if ((needs_unsigned) && (result < 0))
977         {
978                 this->error = CONF_NOT_UNSIGNED;
979                 return 0;
980         }
981         
982         return result;
983 }
984
985 long ConfigReader::ReadInteger(const std::string &tag, const std::string &name, int index, bool needs_unsigned)
986 {
987         return ReadInteger(tag, name, "", index, needs_unsigned);
988 }
989
990 long ConfigReader::GetError()
991 {
992         long olderr = this->error;
993         this->error = 0;
994         return olderr;
995 }
996
997 void ConfigReader::DumpErrors(bool bail, userrec* user)
998 {
999         ServerInstance->Config->ReportConfigError(this->errorlog->str(), bail, user);
1000 }
1001
1002
1003 int ConfigReader::Enumerate(const std::string &tag)
1004 {
1005         return ServerInstance->Config->ConfValueEnum(*this->data, tag);
1006 }
1007
1008 int ConfigReader::EnumerateValues(const std::string &tag, int index)
1009 {
1010         return ServerInstance->Config->ConfVarEnum(*this->data, tag, index);
1011 }
1012
1013 bool ConfigReader::Verify()
1014 {
1015         return this->readerror;
1016 }
1017
1018
1019 FileReader::FileReader(InspIRCd* Instance, const std::string &filename) : ServerInstance(Instance)
1020 {
1021         LoadFile(filename);
1022 }
1023
1024 FileReader::FileReader(InspIRCd* Instance) : ServerInstance(Instance)
1025 {
1026 }
1027
1028 std::string FileReader::Contents()
1029 {
1030         std::string x;
1031         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
1032         {
1033                 x.append(*a);
1034                 x.append("\r\n");
1035         }
1036         return x;
1037 }
1038
1039 unsigned long FileReader::ContentSize()
1040 {
1041         return this->contentsize;
1042 }
1043
1044 void FileReader::CalcSize()
1045 {
1046         unsigned long n = 0;
1047         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
1048                 n += (a->length() + 2);
1049         this->contentsize = n;
1050 }
1051
1052 void FileReader::LoadFile(const std::string &filename)
1053 {
1054         file_cache c;
1055         c.clear();
1056         if (ServerInstance->Config->ReadFile(c,filename.c_str()))
1057         {
1058                 this->fc = c;
1059                 this->CalcSize();
1060         }
1061 }
1062
1063
1064 FileReader::~FileReader()
1065 {
1066 }
1067
1068 bool FileReader::Exists()
1069 {
1070         return (!(fc.size() == 0));
1071 }
1072
1073 std::string FileReader::GetLine(int x)
1074 {
1075         if ((x<0) || ((unsigned)x>fc.size()))
1076                 return "";
1077         return fc[x];
1078 }
1079
1080 int FileReader::FileSize()
1081 {
1082         return fc.size();
1083 }