]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/modules.h
Document ModResult and switch the underlying type to char.
[user/henk/code/inspircd.git] / include / modules.h
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2020 Matt Schatz <genius3000@g3k.solutions>
5  *   Copyright (C) 2019 iwalkalone <iwalkalone69@gmail.com>
6  *   Copyright (C) 2013 Adam <Adam@anope.org>
7  *   Copyright (C) 2012-2016, 2018 Attila Molnar <attilamolnar@hush.com>
8  *   Copyright (C) 2012-2013, 2017-2020 Sadie Powell <sadie@witchery.services>
9  *   Copyright (C) 2012 Robby <robby@chatbelgie.be>
10  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
11  *   Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
12  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
13  *   Copyright (C) 2007-2009 Robin Burchell <robin+git@viroteck.net>
14  *   Copyright (C) 2007-2008, 2010 Craig Edwards <brain@inspircd.org>
15  *   Copyright (C) 2007 Oliver Lupton <om@inspircd.org>
16  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
17  *
18  * This file is part of InspIRCd.  InspIRCd is free software: you can
19  * redistribute it and/or modify it under the terms of the GNU General Public
20  * License as published by the Free Software Foundation, version 2.
21  *
22  * This program is distributed in the hope that it will be useful, but WITHOUT
23  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
24  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
25  * details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
29  */
30
31
32 #pragma once
33
34 #include "moduledefs.h"
35 #include "dynamic.h"
36 #include "base.h"
37 #include "ctables.h"
38 #include "inspsocket.h"
39 #include "timer.h"
40 #include "mode.h"
41
42 /** Used to specify the behaviour of a module. */
43 enum ModuleFlags
44 {
45         /** The module has no special attributes. */
46         VF_NONE = 0,
47
48         /** The module is a coremod and can be assumed to be loaded on all servers. */
49         VF_CORE = 1,
50
51         /* The module is included with InspIRCd. */
52         VF_VENDOR = 2,
53
54         /** The module MUST be loaded on all servers on a network to link. */
55         VF_COMMON = 4,
56
57         /** The module SHOULD be loaded on all servers on a network for consistency. */
58         VF_OPTCOMMON = 8
59 };
60
61 /** The event was explicitly allowed. */
62 #define MOD_RES_ALLOW (ModResult(1))
63
64 /** The event was not explicitly allowed or denied. */
65 #define MOD_RES_PASSTHRU (ModResult(0))
66
67 /** The event was explicitly denied. */
68 #define MOD_RES_DENY (ModResult(-1))
69
70 /** Represents the result of a module event. */
71 class ModResult
72 {
73  private:
74         /** The underlying result value. */
75         char result;
76
77  public:
78         /** Creates a new instance of the ModResult class which defaults to MOD_RES_PASSTHRU. */
79         ModResult()
80                 : result(0)
81         {
82         }
83
84         /** Creates a new instance of the ModResult class with the specified value. */
85         explicit ModResult(char res)
86                 : result(res)
87         {
88         }
89
90         /** Determines whether this ModResult has.the same value as \p res */
91         inline bool operator==(const ModResult& res) const
92         {
93                 return result == res.result;
94         }
95
96         /** Determines whether this ModResult has.a different value to \p res */
97         inline bool operator!=(const ModResult& res) const
98         {
99                 return result != res.result;
100         }
101
102         /** Determines whether a non-MOD_RES_PASSTHRU result has been set. */
103         inline bool operator!() const
104         {
105                 return !result;
106         }
107
108         /** Checks whether the result is an MOD_RES_ALLOW or MOD_RES_PASSTHRU when the default is to allow. */
109         inline bool check(bool def) const
110         {
111                 return (result == 1 || (result == 0 && def));
112         }
113
114         /* Merges two results preferring MOD_RES_ALLOW to MOD_RES_DENY. */
115         inline ModResult operator+(const ModResult& res) const
116         {
117                 // If the results are identical or the other result is MOD_RES_PASSTHRU
118                 // then return this result.
119                 if (result == res.result || res.result == 0)
120                         return *this;
121
122                 // If this result is MOD_RES_PASSTHRU then return the other result.
123                 if (result == 0)
124                         return res;
125
126                 // Otherwise,
127
128                 // they are different, and neither is passthru
129                 return MOD_RES_ALLOW;
130         }
131 };
132
133 /**
134  * This #define allows us to call a method in all
135  * loaded modules in a readable simple way, e.g.:
136  * 'FOREACH_MOD(OnConnect,(user));'
137  */
138 #define FOREACH_MOD(y,x) do { \
139         const Module::List& _handlers = ServerInstance->Modules->EventHandlers[I_ ## y]; \
140         for (Module::List::const_reverse_iterator _i = _handlers.rbegin(), _next; _i != _handlers.rend(); _i = _next) \
141         { \
142                 _next = _i+1; \
143                 try \
144                 { \
145                         if (!(*_i)->dying) \
146                                 (*_i)->y x ; \
147                 } \
148                 catch (CoreException& modexcept) \
149                 { \
150                         ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, "Exception caught: " + modexcept.GetReason()); \
151                 } \
152         } \
153 } while (0);
154
155 /**
156  * Custom module result handling loop. This is a paired macro, and should only
157  * be used with while_each_hook.
158  *
159  * See src/channels.cpp for an example of use.
160  */
161 #define DO_EACH_HOOK(n,v,args) \
162 do { \
163         const Module::List& _handlers = ServerInstance->Modules->EventHandlers[I_ ## n]; \
164         for (Module::List::const_reverse_iterator _i = _handlers.rbegin(), _next; _i != _handlers.rend(); _i = _next) \
165         { \
166                 _next = _i+1; \
167                 try \
168                 { \
169                         if (!(*_i)->dying) \
170                                 v = (*_i)->n args;
171
172 #define WHILE_EACH_HOOK(n) \
173                 } \
174                 catch (CoreException& except_ ## n) \
175                 { \
176                         ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, "Exception caught: " + (except_ ## n).GetReason()); \
177                 } \
178         } \
179 } while(0)
180
181 /**
182  * Module result iterator
183  * Runs the given hook until some module returns a useful result.
184  *
185  * Example: ModResult result;
186  * FIRST_MOD_RESULT(OnUserPreNick, result, (user, newnick))
187  */
188 #define FIRST_MOD_RESULT(n,v,args) do { \
189         v = MOD_RES_PASSTHRU; \
190         DO_EACH_HOOK(n,v,args) \
191         { \
192                 if (v != MOD_RES_PASSTHRU) \
193                         break; \
194         } \
195         WHILE_EACH_HOOK(n); \
196 } while (0)
197
198 /** Holds a module's Version information.
199  * The members (set by the constructor only) indicate details as to the version number
200  * of a module. A class of type Version is returned by the GetVersion method of the Module class.
201  */
202 class CoreExport Version
203 {
204  public:
205         /** Module description
206          */
207         const std::string description;
208
209         /** Flags
210          */
211         const int Flags;
212
213         /** Server linking description string */
214         const std::string link_data;
215
216         /** Simple module version */
217         Version(const std::string &desc, int flags = VF_NONE);
218
219         /** Complex version information, including linking compatibility data */
220         Version(const std::string &desc, int flags, const std::string& linkdata);
221 };
222
223 class CoreExport DataProvider : public ServiceProvider
224 {
225  public:
226         DataProvider(Module* Creator, const std::string& Name)
227                 : ServiceProvider(Creator, Name, SERVICE_DATA) {}
228 };
229
230 /** Priority types which can be used by Module::Prioritize()
231  */
232 enum Priority { PRIORITY_FIRST, PRIORITY_LAST, PRIORITY_BEFORE, PRIORITY_AFTER };
233
234 /** Implementation-specific flags which may be set in Module::Implements()
235  */
236 enum Implementation
237 {
238         I_OnUserConnect, I_OnUserPreQuit, I_OnUserQuit, I_OnUserDisconnect, I_OnUserJoin, I_OnUserPart,
239         I_OnSendSnotice, I_OnUserPreJoin, I_OnUserPreKick, I_OnUserKick, I_OnOper,
240         I_OnUserPreInvite, I_OnUserInvite, I_OnUserPreMessage, I_OnUserPreNick,
241         I_OnUserPostMessage, I_OnUserMessageBlocked, I_OnMode, I_OnShutdown,
242         I_OnDecodeMetaData, I_OnAcceptConnection, I_OnUserInit, I_OnUserPostInit,
243         I_OnChangeHost, I_OnChangeRealName, I_OnAddLine, I_OnDelLine, I_OnExpireLine,
244         I_OnUserPostNick, I_OnPreMode, I_On005Numeric, I_OnKill, I_OnLoadModule,
245         I_OnUnloadModule, I_OnBackgroundTimer, I_OnPreCommand, I_OnCheckReady, I_OnCheckInvite,
246         I_OnRawMode, I_OnCheckKey, I_OnCheckLimit, I_OnCheckBan, I_OnCheckChannelBan, I_OnExtBanCheck,
247         I_OnPreChangeHost, I_OnPreTopicChange, I_OnConnectionFail,
248         I_OnPostTopicChange, I_OnPostConnect, I_OnPostDeoper,
249         I_OnPreChangeRealName, I_OnUserRegister, I_OnChannelPreDelete, I_OnChannelDelete,
250         I_OnPostOper, I_OnPostCommand, I_OnCommandBlocked, I_OnPostJoin,
251         I_OnBuildNeighborList, I_OnGarbageCollect, I_OnSetConnectClass,
252         I_OnUserMessage, I_OnPassCompare, I_OnNumeric,
253         I_OnPreRehash, I_OnModuleRehash, I_OnChangeIdent, I_OnSetUserIP,
254         I_OnServiceAdd, I_OnServiceDel, I_OnUserWrite,
255         I_END
256 };
257
258 /** Base class for all InspIRCd modules
259  *  This class is the base class for InspIRCd modules. All modules must inherit from this class,
260  *  its methods will be called when irc server events occur. class inherited from module must be
261  *  instantiated by the ModuleFactory class (see relevant section) for the module to be initialised.
262  */
263 class CoreExport Module : public classbase, public usecountbase
264 {
265         /** Detach an event from this module
266          * @param i Event type to detach
267          */
268         void DetachEvent(Implementation i);
269
270  public:
271         /** A list of modules. */
272         typedef std::vector<Module*> List;
273
274         /** File that this module was loaded from
275          */
276         std::string ModuleSourceFile;
277
278         /** Reference to the dlopen() value
279          */
280         DLLManager* ModuleDLLManager;
281
282         /** If true, this module will be unloaded soon, further unload attempts will fail
283          * Value is used by the ModuleManager internally, you should not modify it
284          */
285         bool dying;
286
287         /** Default constructor.
288          * Creates a module class. Don't do any type of hook registration or checks
289          * for other modules here; do that in init().
290          */
291         Module();
292
293         /** Module setup
294          * \exception ModuleException Throwing this class, or any class derived from ModuleException, causes loading of the module to abort.
295          */
296         virtual void init() { }
297
298         /** Clean up prior to destruction
299          * If you override, you must call this AFTER your module's cleanup
300          */
301         CullResult cull() CXX11_OVERRIDE;
302
303         /** Default destructor.
304          * destroys a module class
305          */
306         virtual ~Module();
307
308         /** Called when the hooks provided by a module need to be prioritised. */
309         virtual void Prioritize() { }
310
311         /** This method is called when you should reload module specific configuration:
312          * on boot, on a /REHASH and on module load.
313          * @param status The current status, can be inspected for more information;
314          * also used for reporting configuration errors and warnings.
315          */
316         virtual void ReadConfig(ConfigStatus& status);
317
318         /** Returns the version number of a Module.
319          * The method should return a Version object with its version information assigned via
320          * Version::Version
321          */
322         virtual Version GetVersion() = 0;
323
324         /** Called when a user connects.
325          * The details of the connecting user are available to you in the parameter User *user
326          * @param user The user who is connecting
327          */
328         virtual void OnUserConnect(LocalUser* user);
329
330         /** Called when before a user quits.
331          * The details of the exiting user are available to you in the parameter User *user
332          * This event is only called when the user is fully registered when they quit. To catch
333          * raw disconnections, use the OnUserDisconnect method.
334          * @param user The user who is quitting
335          * @param message The user's quit message (as seen by non-opers)
336          * @param oper_message The user's quit message (as seen by opers)
337          */
338         virtual ModResult OnUserPreQuit(LocalUser* user, std::string& message, std::string& oper_message);
339
340         /** Called when a user quits.
341          * The details of the exiting user are available to you in the parameter User *user
342          * This event is only called when the user is fully registered when they quit. To catch
343          * raw disconnections, use the OnUserDisconnect method.
344          * @param user The user who is quitting
345          * @param message The user's quit message (as seen by non-opers)
346          * @param oper_message The user's quit message (as seen by opers)
347          */
348         virtual void OnUserQuit(User* user, const std::string &message, const std::string &oper_message);
349
350         /** Called whenever a user's socket is closed.
351          * The details of the exiting user are available to you in the parameter User *user
352          * This event is called for all users, registered or not, as a cleanup method for modules
353          * which might assign resources to user, such as dns lookups, objects and sockets.
354          * @param user The user who is disconnecting
355          */
356         virtual void OnUserDisconnect(LocalUser* user);
357
358         /** Called whenever a channel is about to be deleted
359          * @param chan The channel being deleted
360          * @return An integer specifying whether or not the channel may be deleted. 0 for yes, 1 for no.
361          */
362         virtual ModResult OnChannelPreDelete(Channel *chan);
363
364         /** Called whenever a channel is deleted, either by QUIT, KICK or PART.
365          * @param chan The channel being deleted
366          */
367         virtual void OnChannelDelete(Channel* chan);
368
369         /** Called when a user joins a channel.
370          * The details of the joining user are available to you in the parameter User *user,
371          * and the details of the channel they have joined is available in the variable Channel *channel
372          * @param memb The channel membership being created
373          * @param sync This is set to true if the JOIN is the result of a network sync and the remote user is being introduced
374          * to a channel due to the network sync.
375          * @param created This is true if the join created the channel
376          * @param except_list A list of users not to send to.
377          */
378         virtual void OnUserJoin(Membership* memb, bool sync, bool created, CUList& except_list);
379
380         /** Called after a user joins a channel
381          * Identical to OnUserJoin, but called immediately afterwards, when any linking module has
382          * seen the join.
383          * @param memb The channel membership created
384          */
385         virtual void OnPostJoin(Membership* memb);
386
387         /** Called when a user parts a channel.
388          * The details of the leaving user are available to you in the parameter User *user,
389          * and the details of the channel they have left is available in the variable Channel *channel
390          * @param memb The channel membership being destroyed
391          * @param partmessage The part message, or an empty string (may be modified)
392          * @param except_list A list of users to not send to.
393          */
394         virtual void OnUserPart(Membership* memb, std::string &partmessage, CUList& except_list);
395
396         /** Called on rehash.
397          * This method is called prior to a /REHASH or when a SIGHUP is received from the operating
398          * system. This is called in all cases -- including when this server will not execute the
399          * rehash because it is directed at a remote server.
400          *
401          * @param user The user performing the rehash, if any. If this is server initiated, the value of
402          * this variable will be NULL.
403          * @param parameter The (optional) parameter given to REHASH from the user. Empty when server
404          * initiated.
405          */
406         virtual void OnPreRehash(User* user, const std::string &parameter);
407
408         /** Called on rehash.
409          * This method is called when a user initiates a module-specific rehash. This can be used to do
410          * expensive operations (such as reloading TLS (SSL) certificates) that are not executed on a normal
411          * rehash for efficiency. A rehash of this type does not reload the core configuration.
412          *
413          * @param user The user performing the rehash.
414          * @param parameter The parameter given to REHASH
415          */
416         virtual void OnModuleRehash(User* user, const std::string &parameter);
417
418         /** Called whenever a snotice is about to be sent to a snomask.
419          * snomask and type may both be modified; the message may not.
420          * @param snomask The snomask the message is going to (e.g. 'A')
421          * @param type The textual description the snomask will go to (e.g. 'OPER')
422          * @param message The text message to be sent via snotice
423          * @return 1 to block the snotice from being sent entirely, 0 else.
424          */
425         virtual ModResult OnSendSnotice(char &snomask, std::string &type, const std::string &message);
426
427         /** Called whenever a user is about to join a channel, before any processing is done.
428          * Returning a value of 1 from this function stops the process immediately, causing no
429          * output to be sent to the user by the core. If you do this you must produce your own numerics,
430          * notices etc. This is useful for modules which may want to mimic +b, +k, +l etc. Returning -1 from
431          * this function forces the join to be allowed, bypassing restrictions such as banlists, invite, keys etc.
432          *
433          * IMPORTANT NOTE!
434          *
435          * If the user joins a NEW channel which does not exist yet, OnUserPreJoin will be called BEFORE the channel
436          * record is created. This will cause Channel* chan to be NULL. There is very little you can do in form of
437          * processing on the actual channel record at this point, however the channel NAME will still be passed in
438          * char* cname, so that you could for example implement a channel blacklist or whitelist, etc.
439          * @param user The user joining the channel
440          * @param chan If the  channel is a new channel, this will be NULL, otherwise it will be a pointer to the channel being joined
441          * @param cname The channel name being joined. For new channels this is valid where chan is not.
442          * @param privs A string containing the users privilages when joining the channel. For new channels this will contain "o".
443          * You may alter this string to alter the user's modes on the channel.
444          * @param keygiven The key given to join the channel, or an empty string if none was provided
445          * @return 1 To prevent the join, 0 to allow it.
446          */
447         virtual ModResult OnUserPreJoin(LocalUser* user, Channel* chan, const std::string& cname, std::string& privs, const std::string& keygiven);
448
449         /** Called whenever a user is about to be kicked.
450          * Returning a value of 1 from this function stops the process immediately, causing no
451          * output to be sent to the user by the core. If you do this you must produce your own numerics,
452          * notices etc.
453          * @param source The user issuing the kick
454          * @param memb The channel membership of the user who is being kicked.
455          * @param reason The kick reason
456          * @return 1 to prevent the kick, 0 to continue normally, -1 to explicitly allow the kick regardless of normal operation
457          */
458         virtual ModResult OnUserPreKick(User* source, Membership* memb, const std::string &reason);
459
460         /** Called whenever a user is kicked.
461          * If this method is called, the kick is already underway and cannot be prevented, so
462          * to prevent a kick, please use Module::OnUserPreKick instead of this method.
463          * @param source The user issuing the kick
464          * @param memb The channel membership of the user who was kicked.
465          * @param reason The kick reason
466          * @param except_list A list of users to not send to.
467          */
468         virtual void OnUserKick(User* source, Membership* memb, const std::string &reason, CUList& except_list);
469
470         /** Called whenever a user opers locally.
471          * The User will contain the oper mode 'o' as this function is called after any modifications
472          * are made to the user's structure by the core.
473          * @param user The user who is opering up
474          * @param opertype The opers type name
475          */
476         virtual void OnOper(User* user, const std::string &opertype);
477
478         /** Called after a user opers locally.
479          * This is identical to Module::OnOper(), except it is called after OnOper so that other modules
480          * can be guaranteed to already have processed the oper-up, for example m_spanningtree has sent
481          * out the OPERTYPE, etc.
482          * @param user The user who is opering up
483          * @param opername The name of the oper that the user is opering up to. Only valid locally. Empty string otherwise.
484          * @param opertype The opers type name
485          */
486         virtual void OnPostOper(User* user, const std::string &opername, const std::string &opertype);
487
488         /** Called after a user deopers locally.
489          * @param user The user who has deopered.
490          */
491         virtual void OnPostDeoper(User* user);
492
493         /** Called whenever a user is about to invite another user into a channel, before any processing is done.
494          * Returning 1 from this function stops the process immediately, causing no
495          * output to be sent to the user by the core. If you do this you must produce your own numerics,
496          * notices etc. This is useful for modules which may want to filter invites to channels.
497          * @param source The user who is issuing the INVITE
498          * @param dest The user being invited
499          * @param channel The channel the user is being invited to
500          * @param timeout The time the invite will expire (0 == never)
501          * @return 1 to deny the invite, 0 to check whether or not the user has permission to invite, -1 to explicitly allow the invite
502          */
503         virtual ModResult OnUserPreInvite(User* source,User* dest,Channel* channel, time_t timeout);
504
505         /** Called after a user has been successfully invited to a channel.
506          * You cannot prevent the invite from occurring using this function, to do that,
507          * use OnUserPreInvite instead.
508          * @param source The user who is issuing the INVITE
509          * @param dest The user being invited
510          * @param channel The channel the user is being invited to
511          * @param timeout The time the invite will expire (0 == never)
512          * @param notifyrank Rank required to get an invite announcement (if enabled)
513          * @param notifyexcepts List of users to not send the default NOTICE invite announcement to
514          */
515         virtual void OnUserInvite(User* source, User* dest, Channel* channel, time_t timeout, unsigned int notifyrank, CUList& notifyexcepts);
516
517         /** Called before a user sends a message to a channel, a user, or a server glob mask.
518          * @param user The user sending the message.
519          * @param target The target of the message. This can either be a channel, a user, or a server
520          *               glob mask.
521          * @param details Details about the message such as the message text and type. See the
522          *                MessageDetails class for more information.
523          * @return MOD_RES_ALLOW to explicitly allow the message, MOD_RES_DENY to explicitly deny the
524          *         message, or MOD_RES_PASSTHRU to let another module handle the event.
525          */
526         virtual ModResult OnUserPreMessage(User* user, const MessageTarget& target, MessageDetails& details);
527
528         /** Called when sending a message to all "neighbors" of a given user -
529          * that is, all users that share a common channel. This is used in
530          * commands such as NICK, QUIT, etc.
531          * @param source The source of the message
532          * @param include_c Channels to scan for users to include
533          * @param exceptions Map of user->bool that overrides the inclusion decision
534          *
535          * Set exceptions[user] = true to include, exceptions[user] = false to exclude
536          */
537         virtual void OnBuildNeighborList(User* source, IncludeChanList& include_c, std::map<User*, bool>& exceptions);
538
539         /** Called before local nickname changes. This can be used to implement Q-lines etc.
540          * If your method returns nonzero, the nickchange is silently forbidden, and it is down to your
541          * module to generate some meaninful output.
542          * @param user The username changing their nick
543          * @param newnick Their new nickname
544          * @return 1 to deny the change, 0 to allow
545          */
546         virtual ModResult OnUserPreNick(LocalUser* user, const std::string& newnick);
547
548         /** Called immediately after a user sends a message to a channel, a user, or a server glob mask.
549          * @param user The user sending the message.
550          * @param target The target of the message. This can either be a channel, a user, or a server
551          *               glob mask.
552          * @param details Details about the message such as the message text and type. See the
553          *                MessageDetails class for more information.
554          */
555         virtual void OnUserPostMessage(User* user, const MessageTarget& target, const MessageDetails& details);
556
557         /** Called immediately before a user sends a message to a channel, a user, or a server glob mask.
558          * @param user The user sending the message.
559          * @param target The target of the message. This can either be a channel, a user, or a server
560          *               glob mask.
561          * @param details Details about the message such as the message text and type. See the
562          *                MessageDetails class for more information.
563          */
564         virtual void OnUserMessage(User* user, const MessageTarget& target, const MessageDetails& details);
565
566         /** Called when a message sent by a user to a channel, a user, or a server glob mask is blocked.
567          * @param user The user sending the message.
568          * @param target The target of the message. This can either be a channel, a user, or a server
569          *               glob mask.
570          * @param details Details about the message such as the message text and type. See the
571          *                MessageDetails class for more information.
572          */
573         virtual void OnUserMessageBlocked(User* user, const MessageTarget& target, const MessageDetails& details);
574
575         /** Called after every MODE command sent from a user
576          * Either the usertarget or the chantarget variable contains the target of the modes,
577          * the actual target will have a non-NULL pointer.
578          * All changed modes are available in the changelist object.
579          * @param user The user sending the MODEs
580          * @param usertarget The target user of the modes, NULL if the target is a channel
581          * @param chantarget The target channel of the modes, NULL if the target is a user
582          * @param changelist The changed modes.
583          * @param processflags Flags passed to ModeParser::Process(), see ModeParser::ModeProcessFlags
584          * for the possible flags.
585          */
586         virtual void OnMode(User* user, User* usertarget, Channel* chantarget, const Modes::ChangeList& changelist, ModeParser::ModeProcessFlag processflags);
587
588         /** Allows module data, sent via ProtoSendMetaData, to be decoded again by a receiving module.
589          * Please see src/modules/m_swhois.cpp for a working example of how to use this method call.
590          * @param target The Channel* or User* that data should be added to
591          * @param extname The extension name which is being sent
592          * @param extdata The extension data, encoded at the other end by an identical module
593          */
594         virtual void OnDecodeMetaData(Extensible* target, const std::string &extname, const std::string &extdata);
595
596         /** Called whenever a user's hostname is changed.
597          * This event triggers after the host has been set.
598          * @param user The user whos host is being changed
599          * @param newhost The new hostname being set
600          */
601         virtual void OnChangeHost(User* user, const std::string &newhost);
602
603         /** Called whenever a user's real name is changed.
604          * This event triggers after the name has been set.
605          * @param user The user who's real name is being changed
606          * @param real The new real name being set on the user
607          */
608         virtual void OnChangeRealName(User* user, const std::string& real);
609
610         /** Called whenever a user's IDENT is changed.
611          * This event triggers after the name has been set.
612          * @param user The user who's IDENT is being changed
613          * @param ident The new IDENT being set on the user
614          */
615         virtual void OnChangeIdent(User* user, const std::string &ident);
616
617         /** Called whenever an xline is added by a local user.
618          * This method is triggered after the line is added.
619          * @param source The sender of the line or NULL for local server
620          * @param line The xline being added
621          */
622         virtual void OnAddLine(User* source, XLine* line);
623
624         /** Called whenever an xline is deleted MANUALLY. See OnExpireLine for expiry.
625          * This method is triggered after the line is deleted.
626          * @param source The user removing the line or NULL for local server
627          * @param line the line being deleted
628          */
629         virtual void OnDelLine(User* source, XLine* line);
630
631         /** Called whenever an xline expires.
632          * This method is triggered after the line is deleted.
633          * @param line The line being deleted.
634          */
635         virtual void OnExpireLine(XLine *line);
636
637         /** Called before the module is unloaded to clean up extensibles.
638          * This method is called once for every channel, membership, and user.
639          * so that you can clear up any data relating to the specified extensible.
640          * @param type The type of extensible being cleaned up. If this is EXT_CHANNEL
641          *             then item is a Channel*, EXT_MEMBERSHIP then item is a Membership*,
642          *             and EXT_USER then item is a User*.
643          * @param item A pointer to the extensible which is being cleaned up.
644          */
645         virtual void OnCleanup(ExtensionItem::ExtensibleType type, Extensible* item);
646
647         /** Called after any nickchange, local or remote. This can be used to track users after nickchanges
648          * have been applied. Please note that although you can see remote nickchanges through this function, you should
649          * NOT make any changes to the User if the user is a remote user as this may cause a desnyc.
650          * check user->server before taking any action (including returning nonzero from the method).
651          * Because this method is called after the nickchange is taken place, no return values are possible
652          * to indicate forbidding of the nick change. Use OnUserPreNick for this.
653          * @param user The user changing their nick
654          * @param oldnick The old nickname of the user before the nickchange
655          */
656         virtual void OnUserPostNick(User* user, const std::string &oldnick);
657
658         /** Called before a mode change via the MODE command, to allow a single access check for
659          * a full mode change (use OnRawMode to check individual modes)
660          *
661          * Returning MOD_RES_ALLOW will skip prefix level checks, but can be overridden by
662          * OnRawMode for each individual mode
663          *
664          * @param source the user making the mode change
665          * @param dest the user destination of the umode change (NULL if a channel mode)
666          * @param channel the channel destination of the mode change
667          * @param modes Modes being changed, can be edited
668          */
669         virtual ModResult OnPreMode(User* source, User* dest, Channel* channel, Modes::ChangeList& modes);
670
671         /** Called when a 005 numeric is about to be output.
672          * The module should modify the 005 numeric if needed to indicate its features.
673         * @param tokens The 005 map to be modified if necessary.
674         */
675         virtual void On005Numeric(std::map<std::string, std::string>& tokens);
676
677         /** Called when a client is disconnected by KILL.
678          * If a client is killed by a server, e.g. a nickname collision or protocol error,
679          * source is NULL.
680          * Return 1 from this function to prevent the kill, and 0 from this function to allow
681          * it as normal. If you prevent the kill no output will be sent to the client, it is
682          * down to your module to generate this information.
683          * NOTE: It is NOT advisable to stop kills which originate from servers or remote users.
684          * If you do so youre risking race conditions, desyncs and worse!
685          * @param source The user sending the KILL
686          * @param dest The user being killed
687          * @param reason The kill reason
688          * @return 1 to prevent the kill, 0 to allow
689          */
690         virtual ModResult OnKill(User* source, User* dest, const std::string &reason);
691
692         /** Called whenever a module is loaded.
693          * mod will contain a pointer to the module, and string will contain its name,
694          * for example m_widgets.so. This function is primary for dependency checking,
695          * your module may decide to enable some extra features if it sees that you have
696          * for example loaded "m_killwidgets.so" with "m_makewidgets.so". It is highly
697          * recommended that modules do *NOT* bail if they cannot satisfy dependencies,
698          * but instead operate under reduced functionality, unless the dependency is
699          * absolutely necessary (e.g. a module that extends the features of another
700          * module).
701          * @param mod A pointer to the new module
702          */
703         virtual void OnLoadModule(Module* mod);
704
705         /** Called whenever a module is unloaded.
706          * mod will contain a pointer to the module, and string will contain its name,
707          * for example m_widgets.so. This function is primary for dependency checking,
708          * your module may decide to enable some extra features if it sees that you have
709          * for example loaded "m_killwidgets.so" with "m_makewidgets.so". It is highly
710          * recommended that modules do *NOT* bail if they cannot satisfy dependencies,
711          * but instead operate under reduced functionality, unless the dependency is
712          * absolutely necessary (e.g. a module that extends the features of another
713          * module).
714          * @param mod Pointer to the module being unloaded (still valid)
715          */
716         virtual void OnUnloadModule(Module* mod);
717
718         /** Called once every five seconds for background processing.
719          * This timer can be used to control timed features. Its period is not accurate
720          * enough to be used as a clock, but it is guaranteed to be called at least once in
721          * any five second period, directly from the main loop of the server.
722          * @param curtime The current timer derived from time(2)
723          */
724         virtual void OnBackgroundTimer(time_t curtime);
725
726         /** Called whenever any command is about to be executed.
727          * This event occurs for all registered commands, whether they are registered in the core,
728          * or another module, and for invalid commands. Invalid commands may only be sent to this
729          * function when the value of validated is false. By returning 1 from this method you may prevent the
730          * command being executed. If you do this, no output is created by the core, and it is
731          * down to your module to produce any output necessary.
732          * Note that unless you return 1, you should not destroy any structures (e.g. by using
733          * InspIRCd::QuitUser) otherwise when the command's handler function executes after your
734          * method returns, it will be passed an invalid pointer to the user object and crash!)
735          * @param command The command being executed
736          * @param parameters An array of array of characters containing the parameters for the command
737          * @param user the user issuing the command
738          * @param validated True if the command has passed all checks, e.g. it is recognised, has enough parameters, the user has permission to execute it, etc.
739          * You should only change the parameter list and command string if validated == false (e.g. before the command lookup occurs).
740          * @return 1 to block the command, 0 to allow
741          */
742         virtual ModResult OnPreCommand(std::string& command, CommandBase::Params& parameters, LocalUser* user, bool validated);
743
744         /** Called after any command has been executed.
745          * This event occurs for all registered commands, whether they are registered in the core,
746          * or another module, but it will not occur for invalid commands (e.g. ones which do not
747          * exist within the command table). The result code returned by the command handler is
748          * provided.
749          * @param command The command being executed
750          * @param parameters An array of array of characters containing the parameters for the command
751          * @param user the user issuing the command
752          * @param result The return code given by the command handler, one of CMD_SUCCESS or CMD_FAILURE
753          * @param loop Whether the command is being called from LoopCall or directly.
754          */
755         virtual void OnPostCommand(Command* command, const CommandBase::Params& parameters, LocalUser* user, CmdResult result, bool loop);
756
757         /** Called when a command was blocked before it could be executed.
758          * @param command The command being executed.
759          * @param parameters The parameters for the command.
760          * @param user The user issuing the command.
761          */
762         virtual void OnCommandBlocked(const std::string& command, const CommandBase::Params& parameters, LocalUser* user);
763
764         /** Called after a user object is initialised and added to the user list.
765          * When this is called the user has not had their I/O hooks checked or had their initial
766          * connect class assigned and may not yet have a serialiser. You probably want to use
767          * the OnUserPostInit or OnUserSetIP hooks instead of this one.
768          * @param user The connecting user.
769          */
770         virtual void OnUserInit(LocalUser* user);
771
772         /** Called after a user object has had their I/O hooks checked, their initial connection
773          * class assigned, and had a serialiser set.
774          * @param user The connecting user.
775          */
776         virtual void OnUserPostInit(LocalUser* user);
777
778         /** Called to check if a user who is connecting can now be allowed to register
779          * If any modules return false for this function, the user is held in the waiting
780          * state until all modules return true. For example a module which implements ident
781          * lookups will continue to return false for a user until their ident lookup is completed.
782          * Note that the registration timeout for a user overrides these checks, if the registration
783          * timeout is reached, the user is disconnected even if modules report that the user is
784          * not ready to connect.
785          * @param user The user to check
786          * @return true to indicate readiness, false if otherwise
787          */
788         virtual ModResult OnCheckReady(LocalUser* user);
789
790         /** Called whenever a user is about to register their connection (e.g. before the user
791          * is sent the MOTD etc). Modules can use this method if they are performing a function
792          * which must be done before the actual connection is completed (e.g. ident lookups,
793          * dnsbl lookups, etc).
794          * Note that you should NOT delete the user record here by causing a disconnection!
795          * Use OnUserConnect for that instead.
796          * @param user The user registering
797          * @return 1 to indicate user quit, 0 to continue
798          */
799         virtual ModResult OnUserRegister(LocalUser* user);
800
801         /** Called whenever a user joins a channel, to determine if invite checks should go ahead or not.
802          * This method will always be called for each join, whether or not the channel is actually +i, and
803          * determines the outcome of an if statement around the whole section of invite checking code.
804          * return 1 to explicitly allow the join to go ahead or 0 to ignore the event.
805          * @param user The user joining the channel
806          * @param chan The channel being joined
807          * @return 1 to explicitly allow the join, 0 to proceed as normal
808          */
809         virtual ModResult OnCheckInvite(User* user, Channel* chan);
810
811         /** Called whenever a mode character is processed.
812          * Return 1 from this function to block the mode character from being processed entirely.
813          * @param user The user who is sending the mode
814          * @param chan The channel the mode is being sent to (or NULL if a usermode)
815          * @param mh The mode handler for the mode being changed
816          * @param param The parameter for the mode or an empty string
817          * @param adding true of the mode is being added, false if it is being removed
818          * @return ACR_DENY to deny the mode, ACR_DEFAULT to do standard mode checking, and ACR_ALLOW
819          * to skip all permission checking. Please note that for remote mode changes, your return value
820          * will be ignored!
821          */
822         virtual ModResult OnRawMode(User* user, Channel* chan, ModeHandler* mh, const std::string& param, bool adding);
823
824         /** Called whenever a user joins a channel, to determine if key checks should go ahead or not.
825          * This method will always be called for each join, whether or not the channel is actually +k, and
826          * determines the outcome of an if statement around the whole section of key checking code.
827          * if the user specified no key, the keygiven string will be a valid but empty value.
828          * return 1 to explicitly allow the join to go ahead or 0 to ignore the event.
829          * @param user The user joining the channel
830          * @param chan The channel being joined
831          * @param keygiven The key given on joining the channel.
832          * @return 1 to explicitly allow the join, 0 to proceed as normal
833          */
834         virtual ModResult OnCheckKey(User* user, Channel* chan, const std::string &keygiven);
835
836         /** Called whenever a user joins a channel, to determine if channel limit checks should go ahead or not.
837          * This method will always be called for each join, whether or not the channel is actually +l, and
838          * determines the outcome of an if statement around the whole section of channel limit checking code.
839          * return 1 to explicitly allow the join to go ahead or 0 to ignore the event.
840          * @param user The user joining the channel
841          * @param chan The channel being joined
842          * @return 1 to explicitly allow the join, 0 to proceed as normal
843          */
844         virtual ModResult OnCheckLimit(User* user, Channel* chan);
845
846         /**
847          * Checks for a user's ban from the channel
848          * @param user The user to check
849          * @param chan The channel to check in
850          * @return MOD_RES_DENY to mark as banned, MOD_RES_ALLOW to skip the
851          * ban check, or MOD_RES_PASSTHRU to check bans normally
852          */
853         virtual ModResult OnCheckChannelBan(User* user, Channel* chan);
854
855         /**
856          * Checks for a user's match of a single ban
857          * @param user The user to check for match
858          * @param chan The channel on which the match is being checked
859          * @param mask The mask being checked
860          * @return MOD_RES_DENY to mark as banned, MOD_RES_ALLOW to skip the
861          * ban check, or MOD_RES_PASSTHRU to check bans normally
862          */
863         virtual ModResult OnCheckBan(User* user, Channel* chan, const std::string& mask);
864
865         /** Checks for a match on a given extban type
866          * @return MOD_RES_DENY to mark as banned, MOD_RES_ALLOW to skip the
867          * ban check, or MOD_RES_PASSTHRU to check bans normally
868          */
869         virtual ModResult OnExtBanCheck(User* user, Channel* chan, char type);
870
871         /** Called whenever a change of a local users displayed host is attempted.
872          * Return 1 to deny the host change, or 0 to allow it.
873          * @param user The user whos host will be changed
874          * @param newhost The new hostname
875          * @return 1 to deny the host change, 0 to allow
876          */
877         virtual ModResult OnPreChangeHost(LocalUser* user, const std::string &newhost);
878
879         /** Called whenever a change of a local users real name is attempted.
880          * return MOD_RES_DENY to deny the name change, or MOD_RES_ALLOW to allow it.
881          * @param user The user whos real name will be changed
882          * @param newhost The new real name.
883          * @return MOD_RES_DENY to deny the real name change, MOD_RES_ALLOW to allow
884          */
885         virtual ModResult OnPreChangeRealName(LocalUser* user, const std::string &newhost);
886
887         /** Called before a topic is changed.
888          * Return 1 to deny the topic change, 0 to check details on the change, -1 to let it through with no checks
889          * As with other 'pre' events, you should only ever block a local event.
890          * @param user The user changing the topic
891          * @param chan The channels who's topic is being changed
892          * @param topic The actual topic text
893          * @return 1 to block the topic change, 0 to allow
894          */
895         virtual ModResult OnPreTopicChange(User* user, Channel* chan, const std::string &topic);
896
897         /** Called whenever a topic has been changed.
898          * To block topic changes you must use OnPreTopicChange instead.
899          * @param user The user changing the topic
900          * @param chan The channels who's topic is being changed
901          * @param topic The actual topic text
902          */
903         virtual void OnPostTopicChange(User* user, Channel* chan, const std::string &topic);
904
905         /** Called whenever a password check is to be made. Replaces the old OldOperCompare API.
906          * The password field (from the config file) is in 'password' and is to be compared against
907          * 'input'. This method allows for encryption of passwords (oper, connect:allow, die/restart, etc).
908          * You should return a nonzero value to override the normal comparison, or zero to pass it on.
909          * @param ex The object that's causing the authentication (User* for \<oper> \<connect:allow> etc, Server* for \<link>).
910          * @param password The password from the configuration file (the password="" value).
911          * @param input The password entered by the user or whoever.
912          * @param hashtype The hash value from the config
913          * @return 0 to do nothing (pass on to next module/default), 1 == password is OK, -1 == password is not OK
914          */
915         virtual ModResult OnPassCompare(Extensible* ex, const std::string &password, const std::string &input, const std::string& hashtype);
916
917         /** Called after a user has fully connected and all modules have executed OnUserConnect
918          * This event is informational only. You should not change any user information in this
919          * event. To do so, use the OnUserConnect method to change the state of local users.
920          * This is called for both local and remote users.
921          * @param user The user who is connecting
922          */
923         virtual void OnPostConnect(User* user);
924
925         /** Called when a port accepts a connection
926          * Return MOD_RES_ACCEPT if you have used the file descriptor.
927          * @param fd The file descriptor returned from accept()
928          * @param sock The socket connection for the new user
929          * @param client The client IP address and port
930          * @param server The server IP address and port
931          */
932         virtual ModResult OnAcceptConnection(int fd, ListenSocket* sock, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server);
933
934         /** Called at intervals for modules to garbage-collect any hashes etc.
935          * Certain data types such as hash_map 'leak' buckets, which must be
936          * tidied up and freed by copying into a new item every so often. This
937          * method is called when it is time to do that.
938          */
939         virtual void OnGarbageCollect();
940
941         /** Called when a user's connect class is being matched
942          * @return MOD_RES_ALLOW to force the class to match, MOD_RES_DENY to forbid it, or
943          * MOD_RES_PASSTHRU to allow normal matching (by host/port).
944          */
945         virtual ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass);
946
947         virtual ModResult OnNumeric(User* user, const Numeric::Numeric& numeric);
948
949         /** Called whenever a local user's IP is set for the first time, or when a local user's IP changes due to
950          * a module like m_cgiirc changing it.
951          * @param user The user whose IP is being set
952          */
953         virtual void OnSetUserIP(LocalUser* user);
954
955         /** Called whenever a ServiceProvider is registered.
956          * @param service ServiceProvider being registered.
957          */
958         virtual void OnServiceAdd(ServiceProvider& service);
959
960         /** Called whenever a ServiceProvider is unregistered.
961          * @param service ServiceProvider being unregistered.
962          */
963         virtual void OnServiceDel(ServiceProvider& service);
964
965         /** Called whenever a message is about to be written to a user.
966          * @param user The user who is having a message sent to them.
967          * @param msg The message which is being written to the user.
968          * @return MOD_RES_ALLOW to explicitly allow the message to be sent, MOD_RES_DENY to explicitly
969          * deny the message from being sent, or MOD_RES_PASSTHRU to let another module handle the event.
970          */
971         virtual ModResult OnUserWrite(LocalUser* user, ClientProtocol::Message& msg);
972
973         /** Called when a user connection has been unexpectedly disconnected.
974          * @param user The user who has been unexpectedly disconnected.
975          * @param error The type of error which caused this connection failure.
976          * @return MOD_RES_ALLOW to explicitly retain the user as a zombie, MOD_RES_DENY to explicitly
977          * disconnect the user, or MOD_RES_PASSTHRU to let another module handle the event.
978          */
979         virtual ModResult OnConnectionFail(LocalUser* user, BufferedSocketError error);
980
981         /** Called before a server shuts down.
982          * @param reason The reason the server is shutting down.
983          */
984         virtual void OnShutdown(const std::string& reason);
985 };
986
987 /** ModuleManager takes care of all things module-related
988  * in the core.
989  */
990 class CoreExport ModuleManager : public fakederef<ModuleManager>
991 {
992  public:
993         typedef std::vector<ServiceProvider*> ServiceList;
994
995  private:
996         /** Holds a string describing the last module error to occur
997          */
998         std::string LastModuleError;
999
1000         /** List of loaded modules and shared object/dll handles
1001          * keyed by module name
1002          */
1003         std::map<std::string, Module*> Modules;
1004
1005         enum {
1006                 PRIO_STATE_FIRST,
1007                 PRIO_STATE_AGAIN,
1008                 PRIO_STATE_LAST
1009         } prioritizationState;
1010
1011         /** Loads all core modules (core_*)
1012          */
1013         void LoadCoreModules(std::map<std::string, ServiceList>& servicemap);
1014
1015         /** Calls the Prioritize() method in all loaded modules
1016          * @return True if all went well, false if a dependency loop was detected
1017          */
1018         bool PrioritizeHooks();
1019
1020         /** Unregister all user modes or all channel modes owned by a module
1021          * @param mod Module whose modes to unregister
1022          * @param modetype MODETYPE_USER to unregister user modes, MODETYPE_CHANNEL to unregister channel modes
1023          */
1024         void UnregisterModes(Module* mod, ModeType modetype);
1025
1026  public:
1027         typedef std::map<std::string, Module*> ModuleMap;
1028
1029         /** Event handler hooks.
1030          * This needs to be public to be used by FOREACH_MOD and friends.
1031          */
1032         Module::List EventHandlers[I_END];
1033
1034         /** List of data services keyed by name */
1035         std::multimap<std::string, ServiceProvider*, irc::insensitive_swo> DataProviders;
1036
1037         /** A list of ServiceProviders waiting to be registered.
1038          * Non-NULL when constructing a Module, NULL otherwise.
1039          * When non-NULL ServiceProviders add themselves to this list on creation and the core
1040          * automatically registers them (that is, call AddService()) after the Module is constructed,
1041          * and before Module::init() is called.
1042          * If a service is created after the construction of the Module (for example in init()) it
1043          * has to be registered manually.
1044          */
1045         ServiceList* NewServices;
1046
1047         /** Expands the name of a module by prepending "m_" and appending ".so".
1048          * No-op if the name already has the ".so" extension.
1049          * @param modname Module name to expand
1050          * @return Module name starting with "m_" and ending with ".so"
1051          */
1052         static std::string ExpandModName(const std::string& modname);
1053
1054         /** Simple, bog-standard, boring constructor.
1055          */
1056         ModuleManager();
1057
1058         /** Destructor
1059          */
1060         ~ModuleManager();
1061
1062         /** Change the priority of one event in a module.
1063          * Each module event has a list of modules which are attached to that event type.
1064          * If you wish to be called before or after other specific modules, you may use this
1065          * method (usually within void Module::Prioritize()) to set your events priority.
1066          * You may use this call in other methods too, however, this is not supported behaviour
1067          * for a module.
1068          * @param mod The module to change the priority of
1069          * @param i The event to change the priority of
1070          * @param s The state you wish to use for this event. Use one of
1071          * PRIO_FIRST to set the event to be first called, PRIO_LAST to
1072          * set it to be the last called, or PRIO_BEFORE and PRIORITY_AFTER
1073          * to set it to be before or after one or more other modules.
1074          * @param which If PRIO_BEFORE or PRIORITY_AFTER is set in parameter 's',
1075          * then this contains a the module that your module must be placed before
1076          * or after.
1077          */
1078         bool SetPriority(Module* mod, Implementation i, Priority s, Module* which = NULL);
1079
1080         /** Change the priority of all events in a module.
1081          * @param mod The module to set the priority of
1082          * @param s The priority of all events in the module.
1083          * Note that with this method, it is not possible to effectively use
1084          * PRIO_BEFORE or PRIORITY_AFTER, you should use the more fine tuned
1085          * SetPriority method for this, where you may specify other modules to
1086          * be prioritized against.
1087          */
1088         void SetPriority(Module* mod, Priority s);
1089
1090         /** Attach an event to a module.
1091          * You may later detach the event with ModuleManager::Detach().
1092          * If your module is unloaded, all events are automatically detached.
1093          * @param i Event type to attach
1094          * @param mod Module to attach event to
1095          * @return True if the event was attached
1096          */
1097         bool Attach(Implementation i, Module* mod);
1098
1099         /** Detach an event from a module.
1100          * This is not required when your module unloads, as the core will
1101          * automatically detach your module from all events it is attached to.
1102          * @param i Event type to detach
1103          * @param mod Module to detach event from
1104          * @return True if the event was detached
1105          */
1106         bool Detach(Implementation i, Module* mod);
1107
1108         /** Attach an array of events to a module
1109          * @param i Event types (array) to attach
1110          * @param mod Module to attach events to
1111          * @param sz The size of the implementation array
1112          */
1113         void Attach(Implementation* i, Module* mod, size_t sz);
1114
1115         /** Detach all events from a module (used on unload)
1116          * @param mod Module to detach from
1117          */
1118         void DetachAll(Module* mod);
1119
1120         /** Attach all events to a module (used on module load)
1121          * @param mod Module to attach to all events
1122          */
1123         void AttachAll(Module* mod);
1124
1125         /** Returns text describing the last module error
1126          * @return The last error message to occur
1127          */
1128         std::string& LastError();
1129
1130         /** Load a given module file
1131          * @param filename The file to load
1132          * @param defer Defer module init (loading many modules)
1133          * @return True if the module was found and loaded
1134          */
1135         bool Load(const std::string& filename, bool defer = false);
1136
1137         /** Unload a given module file. Note that the module will not be
1138          * completely gone until the cull list has finished processing.
1139          *
1140          * @return true on success; if false, LastError will give a reason
1141          */
1142         bool Unload(Module* module);
1143
1144         /** Called by the InspIRCd constructor to load all modules from the config file.
1145          */
1146         void LoadAll();
1147         void UnloadAll();
1148         void DoSafeUnload(Module*);
1149
1150         /** Check if a module can be unloaded and if yes, prepare it for unload
1151          * @param mod Module to be unloaded
1152          * @return True if the module is unloadable, false otherwise.
1153          * If true the module must be unloaded in the current main loop iteration.
1154          */
1155         bool CanUnload(Module* mod);
1156
1157         /** Find a module by name, and return a Module* to it.
1158          * This is preferred over iterating the module lists yourself.
1159          * @param name The module name to look up
1160          * @return A pointer to the module, or NULL if the module cannot be found
1161          */
1162         Module* Find(const std::string &name);
1163
1164         /** Register a service provided by a module */
1165         void AddService(ServiceProvider&);
1166
1167         /** Unregister a service provided by a module */
1168         void DelService(ServiceProvider&);
1169
1170         /** Register all services in a given ServiceList
1171          * @param list The list containing the services to register
1172          */
1173         void AddServices(const ServiceList& list);
1174
1175         inline void AddServices(ServiceProvider** list, int count)
1176         {
1177                 for(int i=0; i < count; i++)
1178                         AddService(*list[i]);
1179         }
1180
1181         /** Find a service by name.
1182          * If multiple modules provide a given service, the first one loaded will be chosen.
1183          */
1184         ServiceProvider* FindService(ServiceType Type, const std::string& name);
1185
1186         template<typename T> inline T* FindDataService(const std::string& name)
1187         {
1188                 return static_cast<T*>(FindService(SERVICE_DATA, name));
1189         }
1190
1191         /** Get a map of all loaded modules keyed by their name
1192          * @return A ModuleMap containing all loaded modules
1193          */
1194         const ModuleMap& GetModules() const { return Modules; }
1195
1196         /** Make a service referenceable by dynamic_references
1197          * @param name Name that will be used by dynamic_references to find the object
1198          * @param service Service to make referenceable by dynamic_references
1199          */
1200         void AddReferent(const std::string& name, ServiceProvider* service);
1201
1202         /** Make a service no longer referenceable by dynamic_references
1203          * @param service Service to make no longer referenceable by dynamic_references
1204          */
1205         void DelReferent(ServiceProvider* service);
1206 };