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