]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules.cpp
Change cmd_*.so to use the Module object API
[user/henk/code/inspircd.git] / src / modules.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Core */
15
16 #include "inspircd.h"
17 #include "xline.h"
18 #include "socket.h"
19 #include "socketengine.h"
20 #include "command_parse.h"
21 #include "dns.h"
22 #include "exitcodes.h"
23
24 #ifndef WIN32
25         #include <dirent.h>
26 #endif
27
28
29 // version is a simple class for holding a modules version number
30 Version::Version(const std::string &modv, int flags, int api_ver, const std::string& rev)
31 : version(modv + " " + rev), Flags(flags), API(api_ver)
32 {
33 }
34
35 Request::Request(char* anydata, Module* src, Module* dst)
36 : data(anydata), source(src), dest(dst)
37 {
38         /* Ensure that because this module doesnt support ID strings, it doesnt break modules that do
39          * by passing them uninitialized pointers (could happen)
40          */
41         id = '\0';
42 }
43
44 Request::Request(Module* src, Module* dst, const char* idstr)
45 : id(idstr), source(src), dest(dst)
46 {
47 }
48
49 char* Request::GetData()
50 {
51         return this->data;
52 }
53
54 const char* Request::GetId()
55 {
56         return this->id;
57 }
58
59 Module* Request::GetSource()
60 {
61         return this->source;
62 }
63
64 Module* Request::GetDest()
65 {
66         return this->dest;
67 }
68
69 const char* Request::Send()
70 {
71         if (this->dest)
72         {
73                 return dest->OnRequest(this);
74         }
75         else
76         {
77                 return NULL;
78         }
79 }
80
81 Event::Event(char* anydata, Module* src, const std::string &eventid) : data(anydata), source(src), id(eventid) { }
82
83 char* Event::GetData()
84 {
85         return this->data;
86 }
87
88 Module* Event::GetSource()
89 {
90         return this->source;
91 }
92
93 char* Event::Send(InspIRCd* ServerInstance)
94 {
95         FOREACH_MOD(I_OnEvent,OnEvent(this));
96         return NULL;
97 }
98
99 std::string Event::GetEventID()
100 {
101         return this->id;
102 }
103
104
105 // These declarations define the behavours of the base class Module (which does nothing at all)
106
107 Module::Module(InspIRCd* Me) : ServerInstance(Me) { }
108 Module::~Module() { }
109
110 ModResult       Module::OnSendSnotice(char &snomask, std::string &type, const std::string &message) { return MOD_RES_PASSTHRU; }
111 void            Module::OnUserConnect(User*) { }
112 void            Module::OnUserQuit(User*, const std::string&, const std::string&) { }
113 void            Module::OnUserDisconnect(User*) { }
114 void            Module::OnUserJoin(User*, Channel*, bool, bool&, bool) { }
115 void            Module::OnPostJoin(User*, Channel*) { }
116 void            Module::OnUserPart(User*, Channel*, std::string&, bool&) { }
117 void            Module::OnPreRehash(User*, const std::string&) { }
118 void            Module::OnModuleRehash(User*, const std::string&) { }
119 void            Module::OnRehash(User*) { }
120 ModResult       Module::OnUserPreJoin(User*, Channel*, const char*, std::string&, const std::string&) { return MOD_RES_PASSTHRU; }
121 void            Module::OnMode(User*, void*, int, const std::vector<std::string>&, const std::vector<TranslateType>&) { }
122 Version         Module::GetVersion() { return Version("Misconfigured", VF_VENDOR, -1); }
123 void            Module::OnOper(User*, const std::string&) { }
124 void            Module::OnPostOper(User*, const std::string&, const std::string &) { }
125 void            Module::OnInfo(User*) { }
126 void            Module::OnWhois(User*, User*) { }
127 ModResult       Module::OnUserPreInvite(User*, User*, Channel*, time_t) { return MOD_RES_PASSTHRU; }
128 ModResult       Module::OnUserPreMessage(User*, void*, int, std::string&, char, CUList&) { return MOD_RES_PASSTHRU; }
129 ModResult       Module::OnUserPreNotice(User*, void*, int, std::string&, char, CUList&) { return MOD_RES_PASSTHRU; }
130 ModResult       Module::OnUserPreNick(User*, const std::string&) { return MOD_RES_PASSTHRU; }
131 void            Module::OnUserPostNick(User*, const std::string&) { }
132 ModResult       Module::OnAccessCheck(User*, User*, Channel*, int) { return MOD_RES_PASSTHRU; }
133 void            Module::On005Numeric(std::string&) { }
134 ModResult       Module::OnKill(User*, User*, const std::string&) { return MOD_RES_PASSTHRU; }
135 void            Module::OnLoadModule(Module*, const std::string&) { }
136 void            Module::OnUnloadModule(Module*, const std::string&) { }
137 void            Module::OnBackgroundTimer(time_t) { }
138 ModResult       Module::OnPreCommand(std::string&, std::vector<std::string>&, User *, bool, const std::string&) { return MOD_RES_PASSTHRU; }
139 void            Module::OnPostCommand(const std::string&, const std::vector<std::string>&, User *, CmdResult, const std::string&) { }
140 ModResult       Module::OnCheckReady(User*) { return MOD_RES_PASSTHRU; }
141 ModResult       Module::OnUserRegister(User*) { return MOD_RES_PASSTHRU; }
142 ModResult       Module::OnUserPreKick(User*, User*, Channel*, const std::string&) { return MOD_RES_PASSTHRU; }
143 void            Module::OnUserKick(User*, User*, Channel*, const std::string&, bool&) { }
144 ModResult       Module::OnRawMode(User*, Channel*, const char, const std::string &, bool, int) { return MOD_RES_PASSTHRU; }
145 ModResult       Module::OnCheckInvite(User*, Channel*) { return MOD_RES_PASSTHRU; }
146 ModResult       Module::OnCheckKey(User*, Channel*, const std::string&) { return MOD_RES_PASSTHRU; }
147 ModResult       Module::OnCheckLimit(User*, Channel*) { return MOD_RES_PASSTHRU; }
148 ModResult       Module::OnCheckBan(User*, Channel*) { return MOD_RES_PASSTHRU; }
149 ModResult       Module::OnCheckExtBan(User *, Channel *, char) { return MOD_RES_PASSTHRU; }
150 ModResult       Module::OnCheckStringExtBan(const std::string &s, Channel *c, char type) { return MOD_RES_PASSTHRU; }
151 ModResult       Module::OnStats(char, User*, string_list&) { return MOD_RES_PASSTHRU; }
152 ModResult       Module::OnChangeLocalUserHost(User*, const std::string&) { return MOD_RES_PASSTHRU; }
153 ModResult       Module::OnChangeLocalUserGECOS(User*, const std::string&) { return MOD_RES_PASSTHRU; }
154 ModResult       Module::OnLocalTopicChange(User*, Channel*, const std::string&) { return MOD_RES_PASSTHRU; }
155 void            Module::OnEvent(Event*) { return; }
156 const char*             Module::OnRequest(Request*) { return NULL; }
157 ModResult       Module::OnPassCompare(Extensible* ex, const std::string &password, const std::string &input, const std::string& hashtype) { return MOD_RES_PASSTHRU; }
158 void            Module::OnGlobalOper(User*) { }
159 void            Module::OnPostConnect(User*) { }
160 ModResult       Module::OnAddBan(User*, Channel*, const std::string &) { return MOD_RES_PASSTHRU; }
161 ModResult       Module::OnDelBan(User*, Channel*, const std::string &) { return MOD_RES_PASSTHRU; }
162 void            Module::OnRawSocketAccept(int, irc::sockets::sockaddrs*, irc::sockets::sockaddrs*) { }
163 int             Module::OnRawSocketWrite(int, const char*, int) { return 0; }
164 void            Module::OnRawSocketClose(int) { }
165 void            Module::OnRawSocketConnect(int) { }
166 int             Module::OnRawSocketRead(int, char*, unsigned int, int&) { return 0; }
167 void            Module::OnUserMessage(User*, void*, int, const std::string&, char, const CUList&) { }
168 void            Module::OnUserNotice(User*, void*, int, const std::string&, char, const CUList&) { }
169 void            Module::OnRemoteKill(User*, User*, const std::string&, const std::string&) { }
170 void            Module::OnUserInvite(User*, User*, Channel*, time_t) { }
171 void            Module::OnPostLocalTopicChange(User*, Channel*, const std::string&) { }
172 void            Module::OnGetServerDescription(const std::string&, std::string&) { }
173 void            Module::OnSyncUser(User*, Module*, void*) { }
174 void            Module::OnSyncChannel(Channel*, Module*, void*) { }
175 void            Module::OnSyncNetwork(Module*, void*) { }
176 void            Module::ProtoSendMode(void*, TargetTypeFlags, void*, const std::vector<std::string>&, const std::vector<TranslateType>&) { }
177 void            Module::OnDecodeMetaData(Extensible*, const std::string&, const std::string&) { }
178 void            Module::ProtoSendMetaData(void*, Extensible*, const std::string&, const std::string&) { }
179 std::string     Module::ProtoTranslate(Extensible*) { return "?"; }
180 void            Module::OnWallops(User*, const std::string&) { }
181 void            Module::OnChangeHost(User*, const std::string&) { }
182 void            Module::OnChangeName(User*, const std::string&) { }
183 void            Module::OnChangeIdent(User*, const std::string&) { }
184 void            Module::OnAddLine(User*, XLine*) { }
185 void            Module::OnDelLine(User*, XLine*) { }
186 void            Module::OnExpireLine(XLine*) { }
187 void            Module::OnCleanup(int, void*) { }
188 ModResult       Module::OnChannelPreDelete(Channel*) { return MOD_RES_PASSTHRU; }
189 void            Module::OnChannelDelete(Channel*) { }
190 ModResult       Module::OnSetAway(User*, const std::string &) { return MOD_RES_PASSTHRU; }
191 ModResult       Module::OnUserList(User*, Channel*, CUList*&) { return MOD_RES_PASSTHRU; }
192 ModResult       Module::OnWhoisLine(User*, User*, int&, std::string&) { return MOD_RES_PASSTHRU; }
193 void            Module::OnBuildExemptList(MessageType, Channel*, User*, char, CUList&, const std::string&) { }
194 void            Module::OnGarbageCollect() { }
195 void            Module::OnBufferFlushed(User*) { }
196 void            Module::OnText(User*, void*, int, const std::string&, char, CUList&) { }
197 void            Module::OnRunTestSuite() { }
198 void            Module::OnNamesListItem(User*, User*, Channel*, std::string&, std::string&) { }
199 ModResult       Module::OnNumeric(User*, unsigned int, const std::string&) { return MOD_RES_PASSTHRU; }
200 void            Module::OnHookIO(EventHandler*, ListenSocketBase*) { }
201 ModResult       Module::OnHostCycle(User*) { return MOD_RES_PASSTHRU; }
202 void            Module::OnSendWhoLine(User*, User*, Channel*, std::string&) { }
203
204 ModuleManager::ModuleManager(InspIRCd* Ins) : ModCount(0), Instance(Ins)
205 {
206 }
207
208 ModuleManager::~ModuleManager()
209 {
210 }
211
212 bool ModuleManager::Attach(Implementation i, Module* mod)
213 {
214         if (std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod) != EventHandlers[i].end())
215                 return false;
216
217         EventHandlers[i].push_back(mod);
218         return true;
219 }
220
221 bool ModuleManager::Detach(Implementation i, Module* mod)
222 {
223         EventHandlerIter x = std::find(EventHandlers[i].begin(), EventHandlers[i].end(), mod);
224
225         if (x == EventHandlers[i].end())
226                 return false;
227
228         EventHandlers[i].erase(x);
229         return true;
230 }
231
232 void ModuleManager::Attach(Implementation* i, Module* mod, size_t sz)
233 {
234         for (size_t n = 0; n < sz; ++n)
235                 Attach(i[n], mod);
236 }
237
238 void ModuleManager::DetachAll(Module* mod)
239 {
240         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
241                 Detach((Implementation)n, mod);
242 }
243
244 bool ModuleManager::SetPriority(Module* mod, Priority s)
245 {
246         for (size_t n = I_BEGIN + 1; n != I_END; ++n)
247                 SetPriority(mod, (Implementation)n, s);
248
249         return true;
250 }
251
252 bool ModuleManager::SetPriority(Module* mod, Implementation i, Priority s, Module** modules, size_t sz)
253 {
254         /** To change the priority of a module, we first find its position in the vector,
255          * then we find the position of the other modules in the vector that this module
256          * wants to be before/after. We pick off either the first or last of these depending
257          * on which they want, and we make sure our module is *at least* before or after
258          * the first or last of this subset, depending again on the type of priority.
259          */
260         size_t swap_pos = 0;
261         size_t source = 0;
262         bool swap = true;
263         bool found = false;
264
265         /* Locate our module. This is O(n) but it only occurs on module load so we're
266          * not too bothered about it
267          */
268         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
269         {
270                 if (EventHandlers[i][x] == mod)
271                 {
272                         source = x;
273                         found = true;
274                         break;
275                 }
276         }
277
278         /* Eh? this module doesnt exist, probably trying to set priority on an event
279          * theyre not attached to.
280          */
281         if (!found)
282                 return false;
283
284         switch (s)
285         {
286                 /* Dummy value */
287                 case PRIORITY_DONTCARE:
288                         swap = false;
289                 break;
290                 /* Module wants to be first, sod everything else */
291                 case PRIORITY_FIRST:
292                         if (prioritizationState != PRIO_STATE_FIRST)
293                                 swap = false;
294                         else
295                                 swap_pos = 0;
296                 break;
297                 /* Module wants to be last. */
298                 case PRIORITY_LAST:
299                         if (prioritizationState != PRIO_STATE_FIRST)
300                                 swap = false;
301                         else if (EventHandlers[i].empty())
302                                 swap_pos = 0;
303                         else
304                                 swap_pos = EventHandlers[i].size() - 1;
305                 break;
306                 /* Place this module after a set of other modules */
307                 case PRIORITY_AFTER:
308                 {
309                         /* Find the latest possible position */
310                         swap_pos = 0;
311                         swap = false;
312                         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
313                         {
314                                 for (size_t n = 0; n < sz; ++n)
315                                 {
316                                         if ((modules[n]) && (EventHandlers[i][x] == modules[n]) && (x >= swap_pos) && (source <= swap_pos))
317                                         {
318                                                 swap_pos = x;
319                                                 swap = true;
320                                         }
321                                 }
322                         }
323                 }
324                 break;
325                 /* Place this module before a set of other modules */
326                 case PRIORITY_BEFORE:
327                 {
328                         swap_pos = EventHandlers[i].size() - 1;
329                         swap = false;
330                         for (size_t x = 0; x != EventHandlers[i].size(); ++x)
331                         {
332                                 for (size_t n = 0; n < sz; ++n)
333                                 {
334                                         if ((modules[n]) && (EventHandlers[i][x] == modules[n]) && (x <= swap_pos) && (source >= swap_pos))
335                                         {
336                                                 swap = true;
337                                                 swap_pos = x;
338                                         }
339                                 }
340                         }
341                 }
342                 break;
343         }
344
345         /* Do we need to swap? */
346         if (swap && (swap_pos != source))
347         {
348                 // We are going to change positions; we'll need to run again to verify all requirements
349                 if (prioritizationState == PRIO_STATE_LAST)
350                         prioritizationState = PRIO_STATE_AGAIN;
351                 /* Suggestion from Phoenix, "shuffle" the modules to better retain call order */
352                 int incrmnt = 1;
353
354                 if (source > swap_pos)
355                         incrmnt = -1;
356
357                 for (unsigned int j = source; j != swap_pos; j += incrmnt)
358                 {
359                         if (( j + incrmnt > EventHandlers[i].size() - 1) || (j + incrmnt < 0))
360                                 continue;
361
362                         std::swap(EventHandlers[i][j], EventHandlers[i][j+incrmnt]);
363                 }
364         }
365
366         return true;
367 }
368
369 std::string& ModuleManager::LastError()
370 {
371         return LastModuleError;
372 }
373
374 bool ModuleManager::Load(const char* filename)
375 {
376         /* Do we have a glob pattern in the filename?
377          * The user wants to load multiple modules which
378          * match the pattern.
379          */
380         if (strchr(filename,'*') || (strchr(filename,'?')))
381         {
382                 int n_match = 0;
383                 DIR* library = opendir(Instance->Config->ModPath.c_str());
384                 if (library)
385                 {
386                         /* Try and locate and load all modules matching the pattern */
387                         dirent* entry = NULL;
388                         while (0 != (entry = readdir(library)))
389                         {
390                                 if (InspIRCd::Match(entry->d_name, filename, ascii_case_insensitive_map))
391                                 {
392                                         if (!this->Load(entry->d_name))
393                                                 n_match++;
394                                 }
395                         }
396                         closedir(library);
397                 }
398                 /* Loadmodule will now return false if any one of the modules failed
399                  * to load (but wont abort when it encounters a bad one) and when 1 or
400                  * more modules were actually loaded.
401                  */
402                 return (n_match > 0 ? false : true);
403         }
404
405         char modfile[MAXBUF];
406         snprintf(modfile,MAXBUF,"%s/%s",Instance->Config->ModPath.c_str(),filename);
407         std::string filename_str = filename;
408
409         if (!ServerConfig::FileExists(modfile))
410         {
411                 LastModuleError = "Module file could not be found: " + filename_str;
412                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
413                 return false;
414         }
415
416         if (Modules.find(filename_str) != Modules.end())
417         {
418                 LastModuleError = "Module " + filename_str + " is already loaded, cannot load a module twice!";
419                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
420                 return false;
421         }
422
423         Module* newmod = NULL;
424         ircd_module* newhandle = NULL;
425
426         try
427         {
428                 /* This will throw a CoreException if there's a problem loading
429                  * the module file or getting a pointer to the init_module symbol.
430                  */
431                 newhandle = new ircd_module(Instance, modfile, "init_module");
432                 newmod = newhandle->CallInit();
433
434                 if (newmod)
435                 {
436                         newmod->ModuleSourceFile = filename_str;
437                         Version v = newmod->GetVersion();
438
439                         if (v.API != API_VERSION)
440                         {
441                                 DetachAll(newmod);
442                                 delete newmod;
443                                 delete newhandle;
444                                 LastModuleError = "Unable to load " + filename_str + ": Incorrect module API version: " + ConvToStr(v.API) + " (our version: " + ConvToStr(API_VERSION) + ")";
445                                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
446                                 return false;
447                         }
448                         else
449                         {
450                                 Instance->Logs->Log("MODULE", DEFAULT,"New module introduced: %s (API version %d, Module version %s)%s", filename, v.API, v.version.c_str(), (!(v.Flags & VF_VENDOR) ? " [3rd Party]" : " [Vendor]"));
451                         }
452
453                         Modules[filename_str] = std::make_pair(newhandle, newmod);
454                 }
455                 else
456                 {
457                         delete newhandle;
458                         LastModuleError = "Unable to load " + filename_str + ": Probably missing init_module() entrypoint, but dlsym() didn't notice a problem";
459                         Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
460                         return false;
461                 }
462         }
463         /** XXX: Is there anything we can do about this mess? -- Brain */
464         catch (LoadModuleException& modexcept)
465         {
466                 DetachAll(newmod);
467                 if (newmod)
468                         delete newmod;
469                 if (newhandle)
470                         delete newhandle;
471                 LastModuleError = "Unable to load " + filename_str + ": Error when loading: " + modexcept.GetReason();
472                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
473                 return false;
474         }
475         catch (FindSymbolException& modexcept)
476         {
477                 DetachAll(newmod);
478                 if (newmod)
479                         delete newmod;
480                 if (newhandle)
481                         delete newhandle;
482                 LastModuleError = "Unable to load " + filename_str + ": Error finding symbol: " + modexcept.GetReason();
483                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
484                 return false;
485         }
486         catch (CoreException& modexcept)
487         {
488                 DetachAll(newmod);
489                 if (newmod)
490                         delete newmod;
491                 if (newhandle)
492                         delete newhandle;
493                 LastModuleError = "Unable to load " + filename_str + ": " + modexcept.GetReason();
494                 Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
495                 return false;
496         }
497
498         this->ModCount++;
499         FOREACH_MOD_I(Instance,I_OnLoadModule,OnLoadModule(newmod, filename_str));
500
501         /* We give every module a chance to re-prioritize when we introduce a new one,
502          * not just the one thats loading, as the new module could affect the preference
503          * of others
504          */
505         for(int tries = 0; tries < 20; tries++)
506         {
507                 prioritizationState = tries > 0 ? PRIO_STATE_LAST : PRIO_STATE_FIRST;
508                 for (std::map<std::string, std::pair<ircd_module*, Module*> >::iterator n = Modules.begin(); n != Modules.end(); ++n)
509                         n->second.second->Prioritize();
510
511                 if (prioritizationState == PRIO_STATE_LAST)
512                         break;
513                 if (tries == 19)
514                         Instance->Logs->Log("MODULE", DEFAULT, "Hook priority dependency loop detected while loading " + filename_str);
515         }
516
517         Instance->BuildISupport();
518         return true;
519 }
520
521 bool ModuleManager::Unload(const char* filename)
522 {
523         std::string filename_str(filename);
524         std::map<std::string, std::pair<ircd_module*, Module*> >::iterator modfind = Modules.find(filename);
525
526         if (modfind != Modules.end())
527         {
528                 if (modfind->second.second->GetVersion().Flags & VF_STATIC)
529                 {
530                         LastModuleError = "Module " + filename_str + " not unloadable (marked static)";
531                         Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
532                         return false;
533                 }
534                 std::pair<int,std::string> intercount = GetInterfaceInstanceCount(modfind->second.second);
535                 if (intercount.first > 0)
536                 {
537                         LastModuleError = "Failed to unload module " + filename_str + ", being used by " + ConvToStr(intercount.first) + " other(s) via interface '" + intercount.second + "'";
538                         Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
539                         return false;
540                 }
541
542                 /* Give the module a chance to tidy out all its metadata */
543                 for (chan_hash::iterator c = Instance->chanlist->begin(); c != Instance->chanlist->end(); c++)
544                 {
545                         modfind->second.second->OnCleanup(TYPE_CHANNEL,c->second);
546                 }
547                 for (user_hash::iterator u = Instance->Users->clientlist->begin(); u != Instance->Users->clientlist->end(); u++)
548                 {
549                         modfind->second.second->OnCleanup(TYPE_USER,u->second);
550                 }
551
552                 /* Tidy up any dangling resolvers */
553                 Instance->Res->CleanResolvers(modfind->second.second);
554
555
556                 FOREACH_MOD_I(Instance,I_OnUnloadModule,OnUnloadModule(modfind->second.second, modfind->first));
557
558                 this->DetachAll(modfind->second.second);
559
560                 Instance->Parser->RemoveCommands(modfind->second.second);
561
562                 delete modfind->second.second;
563                 delete modfind->second.first;
564                 Modules.erase(modfind);
565
566                 Instance->Logs->Log("MODULE", DEFAULT,"Module %s unloaded",filename);
567                 this->ModCount--;
568                 Instance->BuildISupport();
569                 return true;
570         }
571
572         LastModuleError = "Module " + filename_str + " is not loaded, cannot unload it!";
573         Instance->Logs->Log("MODULE", DEFAULT, LastModuleError);
574         return false;
575 }
576
577 /* We must load the modules AFTER initializing the socket engine, now */
578 void ModuleManager::LoadAll()
579 {
580         char configToken[MAXBUF];
581         ModCount = -1;
582
583         printf("\nLoading core commands");
584         fflush(stdout);
585
586         DIR* library = opendir(Instance->Config->ModPath.c_str());
587         if (library)
588         {
589                 dirent* entry = NULL;
590                 while (0 != (entry = readdir(library)))
591                 {
592                         if (InspIRCd::Match(entry->d_name, "cmd_*.so", ascii_case_insensitive_map))
593                         {
594                                 printf(".");
595                                 fflush(stdout);
596
597                                 if (!Load(entry->d_name))
598                                 {
599                                         Instance->Logs->Log("MODULE", DEFAULT, this->LastError());
600                                         printf_c("\n[\033[1;31m*\033[0m] %s\n\n", this->LastError().c_str());
601                                         Instance->Exit(EXIT_STATUS_MODULE);
602                                 }
603                         }
604                 }
605                 closedir(library);
606                 printf("\n");
607         }
608
609         for(int count = 0; count < Instance->Config->ConfValueEnum("module"); count++)
610         {
611                 Instance->Config->ConfValue("module", "name", count, configToken, MAXBUF);
612                 printf_c("[\033[1;32m*\033[0m] Loading module:\t\033[1;32m%s\033[0m\n",configToken);
613
614                 if (!this->Load(configToken))
615                 {
616                         Instance->Logs->Log("MODULE", DEFAULT, this->LastError());
617                         printf_c("\n[\033[1;31m*\033[0m] %s\n\n", this->LastError().c_str());
618                         Instance->Exit(EXIT_STATUS_MODULE);
619                 }
620         }
621 }
622
623 bool ModuleManager::PublishFeature(const std::string &FeatureName, Module* Mod)
624 {
625         if (Features.find(FeatureName) == Features.end())
626         {
627                 Features[FeatureName] = Mod;
628                 return true;
629         }
630         return false;
631 }
632
633 bool ModuleManager::UnpublishFeature(const std::string &FeatureName)
634 {
635         featurelist::iterator iter = Features.find(FeatureName);
636
637         if (iter == Features.end())
638                 return false;
639
640         Features.erase(iter);
641         return true;
642 }
643
644 Module* ModuleManager::FindFeature(const std::string &FeatureName)
645 {
646         featurelist::iterator iter = Features.find(FeatureName);
647
648         if (iter == Features.end())
649                 return NULL;
650
651         return iter->second;
652 }
653
654 bool ModuleManager::PublishInterface(const std::string &InterfaceName, Module* Mod)
655 {
656         interfacelist::iterator iter = Interfaces.find(InterfaceName);
657
658         if (iter == Interfaces.end())
659         {
660                 modulelist ml;
661                 ml.push_back(Mod);
662                 Interfaces[InterfaceName] = std::make_pair(0, ml);
663         }
664         else
665         {
666                 iter->second.second.push_back(Mod);
667         }
668         return true;
669 }
670
671 bool ModuleManager::UnpublishInterface(const std::string &InterfaceName, Module* Mod)
672 {
673         interfacelist::iterator iter = Interfaces.find(InterfaceName);
674
675         if (iter == Interfaces.end())
676                 return false;
677
678         for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
679         {
680                 if (*x == Mod)
681                 {
682                         iter->second.second.erase(x);
683                         if (iter->second.second.empty())
684                                 Interfaces.erase(InterfaceName);
685                         return true;
686                 }
687         }
688         return false;
689 }
690
691 modulelist* ModuleManager::FindInterface(const std::string &InterfaceName)
692 {
693         interfacelist::iterator iter = Interfaces.find(InterfaceName);
694         if (iter == Interfaces.end())
695                 return NULL;
696         else
697                 return &(iter->second.second);
698 }
699
700 bool ModuleManager::ModuleHasInterface(Module* mod, const std::string& InterfaceName)
701 {
702         interfacelist::iterator iter = Interfaces.find(InterfaceName);
703         if (iter == Interfaces.end())
704                 return false;
705         else
706         {
707                 modulelist& ml = iter->second.second;
708                 modulelist::iterator mi = std::find(ml.begin(), ml.end(), mod);
709                 return (mi != ml.end());
710         }
711 }
712
713 void ModuleManager::UseInterface(const std::string &InterfaceName)
714 {
715         interfacelist::iterator iter = Interfaces.find(InterfaceName);
716         if (iter != Interfaces.end())
717                 iter->second.first++;
718
719 }
720
721 void ModuleManager::DoneWithInterface(const std::string &InterfaceName)
722 {
723         interfacelist::iterator iter = Interfaces.find(InterfaceName);
724         if (iter != Interfaces.end())
725                 iter->second.first--;
726 }
727
728 std::pair<int,std::string> ModuleManager::GetInterfaceInstanceCount(Module* m)
729 {
730         for (interfacelist::iterator iter = Interfaces.begin(); iter != Interfaces.end(); iter++)
731         {
732                 for (modulelist::iterator x = iter->second.second.begin(); x != iter->second.second.end(); x++)
733                 {
734                         if (*x == m)
735                         {
736                                 return std::make_pair(iter->second.first, iter->first);
737                         }
738                 }
739         }
740         return std::make_pair(0, "");
741 }
742
743 const std::string& ModuleManager::GetModuleName(Module* m)
744 {
745         static std::string nothing;
746
747         for (std::map<std::string, std::pair<ircd_module*, Module*> >::iterator n = Modules.begin(); n != Modules.end(); ++n)
748         {
749                 if (n->second.second == m)
750                         return n->first;
751         }
752
753         return nothing;
754 }
755
756 /* This is ugly, yes, but hash_map's arent designed to be
757  * addressed in this manner, and this is a bit of a kludge.
758  * Luckily its a specialist function and rarely used by
759  * many modules (in fact, it was specially created to make
760  * m_safelist possible, initially).
761  */
762
763 Channel* InspIRCd::GetChannelIndex(long index)
764 {
765         int target = 0;
766         for (chan_hash::iterator n = this->chanlist->begin(); n != this->chanlist->end(); n++, target++)
767         {
768                 if (index == target)
769                         return n->second;
770         }
771         return NULL;
772 }
773
774 CmdResult InspIRCd::CallCommandHandler(const std::string &commandname, const std::vector<std::string>& parameters, User* user)
775 {
776         return this->Parser->CallHandler(commandname, parameters, user);
777 }
778
779 bool InspIRCd::IsValidModuleCommand(const std::string &commandname, int pcnt, User* user)
780 {
781         return this->Parser->IsValidCommand(commandname, pcnt, user);
782 }
783
784 void InspIRCd::AddCommand(Command *f)
785 {
786         if (!this->Parser->CreateCommand(f))
787         {
788                 ModuleException err("Command "+std::string(f->command)+" already exists.");
789                 throw (err);
790         }
791 }
792
793 void InspIRCd::SendMode(const std::vector<std::string>& parameters, User *user)
794 {
795         this->Modes->Process(parameters, user);
796 }
797
798 void InspIRCd::DumpText(User* user, const std::string &text)
799 {
800         if (IS_LOCAL(user))
801         {
802                 user->Write(text);
803         }
804         else
805         {
806                 PI->PushToClient(user, text);
807         }
808 }
809
810 void InspIRCd::DumpText(User* user, const char *text, ...)
811 {
812         va_list argsPtr;
813         char line[MAXBUF];
814
815         va_start(argsPtr, text);
816         vsnprintf(line, MAXBUF, text, argsPtr);
817         va_end(argsPtr);
818
819         DumpText(user, std::string(line));
820 }
821
822 void InspIRCd::DumpText(User* user, const std::string &LinePrefix, std::stringstream &TextStream)
823 {
824         char line[MAXBUF];
825         int start_pos = LinePrefix.length();
826         int pos = start_pos;
827         memcpy(line, LinePrefix.data(), pos);
828         std::string Word;
829         while (TextStream >> Word)
830         {
831                 int len = Word.length();
832                 if (pos + len + 12 > MAXBUF)
833                 {
834                         line[pos] = '\0';
835                         DumpText(user, std::string(line));
836                         pos = start_pos;
837                 }
838                 line[pos] = ' ';
839                 memcpy(line + pos + 1, Word.data(), len);
840                 pos += len + 1;
841         }
842         line[pos] = '\0';
843         DumpText(user, std::string(line));
844 }
845
846 bool InspIRCd::AddResolver(Resolver* r, bool cached)
847 {
848         if (!cached)
849                 return this->Res->AddResolverClass(r);
850         else
851         {
852                 r->TriggerCachedResult();
853                 delete r;
854                 return true;
855         }
856 }
857
858 Module* ModuleManager::Find(const std::string &name)
859 {
860         std::map<std::string, std::pair<ircd_module*, Module*> >::iterator modfind = Modules.find(name);
861
862         if (modfind == Modules.end())
863                 return NULL;
864         else
865                 return modfind->second.second;
866 }
867
868 const std::vector<std::string> ModuleManager::GetAllModuleNames(int filter)
869 {
870         std::vector<std::string> retval;
871         for (std::map<std::string, std::pair<ircd_module*, Module*> >::iterator x = Modules.begin(); x != Modules.end(); ++x)
872                 if (!filter || (x->second.second->GetVersion().Flags & filter))
873                         retval.push_back(x->first);
874         return retval;
875 }
876
877 ConfigReader::ConfigReader(InspIRCd* Instance) : ServerInstance(Instance)
878 {
879         this->error = 0;
880 }
881
882
883 ConfigReader::~ConfigReader()
884 {
885 }
886
887
888 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool allow_linefeeds)
889 {
890         /* Don't need to strlcpy() tag and name anymore, ReadConf() takes const char* */
891         std::string result;
892
893         if (!ServerInstance->Config->ConfValue(tag, name, default_value, index, result, allow_linefeeds))
894         {
895                 this->error = CONF_VALUE_NOT_FOUND;
896         }
897         return result;
898 }
899
900 std::string ConfigReader::ReadValue(const std::string &tag, const std::string &name, int index, bool allow_linefeeds)
901 {
902         return ReadValue(tag, name, "", index, allow_linefeeds);
903 }
904
905 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, const std::string &default_value, int index)
906 {
907         return ServerInstance->Config->ConfValueBool(tag, name, default_value, index);
908 }
909
910 bool ConfigReader::ReadFlag(const std::string &tag, const std::string &name, int index)
911 {
912         return ReadFlag(tag, name, "", index);
913 }
914
915
916 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, const std::string &default_value, int index, bool need_positive)
917 {
918         int result;
919
920         if(!ServerInstance->Config->ConfValueInteger(tag, name, default_value, index, result))
921         {
922                 this->error = CONF_VALUE_NOT_FOUND;
923                 return 0;
924         }
925
926         if ((need_positive) && (result < 0))
927         {
928                 this->error = CONF_INT_NEGATIVE;
929                 return 0;
930         }
931
932         return result;
933 }
934
935 int ConfigReader::ReadInteger(const std::string &tag, const std::string &name, int index, bool need_positive)
936 {
937         return ReadInteger(tag, name, "", index, need_positive);
938 }
939
940 long ConfigReader::GetError()
941 {
942         long olderr = this->error;
943         this->error = 0;
944         return olderr;
945 }
946
947 int ConfigReader::Enumerate(const std::string &tag)
948 {
949         return ServerInstance->Config->ConfValueEnum(tag);
950 }
951
952 int ConfigReader::EnumerateValues(const std::string &tag, int index)
953 {
954         return ServerInstance->Config->ConfVarEnum(tag, index);
955 }
956
957 FileReader::FileReader(InspIRCd* Instance, const std::string &filename) : ServerInstance(Instance)
958 {
959         LoadFile(filename);
960 }
961
962 FileReader::FileReader(InspIRCd* Instance) : ServerInstance(Instance)
963 {
964 }
965
966 std::string FileReader::Contents()
967 {
968         std::string x;
969         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
970         {
971                 x.append(*a);
972                 x.append("\r\n");
973         }
974         return x;
975 }
976
977 unsigned long FileReader::ContentSize()
978 {
979         return this->contentsize;
980 }
981
982 void FileReader::CalcSize()
983 {
984         unsigned long n = 0;
985         for (file_cache::iterator a = this->fc.begin(); a != this->fc.end(); a++)
986                 n += (a->length() + 2);
987         this->contentsize = n;
988 }
989
990 void FileReader::LoadFile(const std::string &filename)
991 {
992         file_cache c;
993         c.clear();
994         if (ServerInstance->Config->ReadFile(c,filename.c_str()))
995         {
996                 this->fc = c;
997                 this->CalcSize();
998         }
999 }
1000
1001
1002 FileReader::~FileReader()
1003 {
1004 }
1005
1006 bool FileReader::Exists()
1007 {
1008         return (!(fc.size() == 0));
1009 }
1010
1011 std::string FileReader::GetLine(int x)
1012 {
1013         if ((x<0) || ((unsigned)x>fc.size()))
1014                 return "";
1015         return fc[x];
1016 }
1017
1018 int FileReader::FileSize()
1019 {
1020         return fc.size();
1021 }