2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2016 Attila Molnar <attilamolnar@hush.com>
6 * This file is part of InspIRCd. InspIRCd is free software: you can
7 * redistribute it and/or modify it under the terms of the GNU General Public
8 * License as published by the Free Software Foundation, version 2.
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 namespace ClientProtocol
33 /** Contains a message parsed from wire format.
34 * Used by Serializer::Parse().
36 struct ClientProtocol::ParseOutput
38 /** Command name, must not be empty.
42 /** Parameter list, may be empty.
44 ClientProtocol::ParamList params;
46 /** Message tags, may be empty.
48 ClientProtocol::TagMap tags;
51 /** A selection of zero or more tags in a TagMap.
53 class ClientProtocol::TagSelection
55 std::bitset<64> selection;
58 /** Check if a tag is selected.
59 * @param tags TagMap the tag is in. The TagMap must contain the same tags as it had when the tag
60 * was selected with Select(), otherwise the result is not meaningful.
61 * @param it Iterator to the tag to check.
62 * @return True if the tag is selected, false otherwise.
64 bool IsSelected(const TagMap& tags, TagMap::const_iterator it) const
66 const size_t index = std::distance(tags.begin(), it);
67 return ((index < selection.size()) && (selection[index]));
71 * @param tags TagMap the tag is in. This parameter must be the same every time the method is called.
72 * The TagMap must not be altered otherwise the results of IsSelected() is not meaningful.
73 * @param it Iterator to the tag to mark as selected.
75 void Select(const TagMap& tags, TagMap::const_iterator it)
77 const size_t index = std::distance(tags.begin(), it);
78 if (index < selection.size())
79 selection[index] = true;
82 /** Check if a TagSelection is equivalent to this object.
83 * @param other Other TagSelection object to compare this with.
84 * @return True if the objects are equivalent, false if they aren't.
86 bool operator==(const TagSelection& other) const
88 return (this->selection == other.selection);
92 class ClientProtocol::MessageSource
95 const std::string* sourcestr;
98 /** Constructor, sets the source to be the full host of a user or sets it to be nothing.
99 * The actual source string when serializing will be obtained from User::GetFullHost() if the user is non-NULL.
100 * @param Sourceuser User to set as source of the message. If NULL, the message won't have a source when serialized.
101 * Optional, defaults to NULL.
103 MessageSource(User* Sourceuser = NULL)
105 SetSourceUser(Sourceuser);
108 /** Constructor, sets the source to the supplied string and optionally sets the source user.
109 * @param Sourcestr String to use as message source for serialization purposes. Must remain valid
110 * as long as this object is alive.
111 * @param Sourceuser User to set as source. Optional, defaults to NULL. It will not be used for serialization but
112 * if provided it may be used internally, for example to create message tags.
113 * Useful when the source string is synthesized but it is still related to a User.
115 MessageSource(const std::string& Sourcestr, User* Sourceuser = NULL)
117 SetSource(Sourcestr, Sourceuser);
120 /** Get the source of this message as a string.
121 * @return Pointer to the message source string or NULL if there is no source.
123 const std::string* GetSource() const
125 // Return string if there's one explicitly set
129 return &sourceuser->GetFullHost();
133 /** Get the source User.
134 * This shouldn't be used for serialization, use GetSource() for that.
135 * @return User pointer if the message has a source user, NULL otherwise.
137 User* GetSourceUser() const { return sourceuser; }
139 /** Set the source of this message to a User.
140 * See the one parameter constructor for a more detailed description.
141 * @param Sourceuser User to set as source.
143 void SetSourceUser(User* Sourceuser)
145 sourceuser = Sourceuser;
149 /** Set the source string and optionally source user.
150 * See the two parameter constructor for a more detailed description.
151 * @param Sourcestr String source, to be used for serialization purposes. Must remain valid as long
152 * as this object is alive.
153 * @param Sourceuser Source user to set, optional.
155 void SetSource(const std::string& Sourcestr, User* Sourceuser = NULL)
157 sourcestr = &Sourcestr;
158 sourceuser = Sourceuser;
161 /** Copy the source from a MessageSource object.
162 * @param other MessageSource object to copy from.
164 void SetSource(const MessageSource& other)
166 sourcestr = other.sourcestr;
167 sourceuser = other.sourceuser;
171 /** Outgoing client protocol message.
172 * Represents a high level client protocol message which is turned into raw or wire format
173 * by a Serializer. Messages can be serialized into different format by different serializers.
175 * Messages are created on demand and are disposed of after they have been sent.
177 * All messages have a command name, a list of parameters and a map of tags, the last two can be empty.
178 * They also always have a source, see class MessageSource.
180 class ClientProtocol::Message : public ClientProtocol::MessageSource
183 /** Contains information required to identify a specific version of a serialized message.
185 struct SerializedInfo
187 const Serializer* serializer;
191 * @param Ser Serializer used to serialize the message.
192 * @param Tagwl Tag whitelist used to serialize the message.
194 SerializedInfo(const Serializer* Ser, const TagSelection& Tagwl)
200 /** Check if a SerializedInfo object is equivalent to this object.
201 * @param other Other SerializedInfo object.
202 * @return True if other is equivalent to this object, false otherwise.
204 bool operator==(const SerializedInfo& other) const
206 return ((serializer == other.serializer) && (tagwl == other.tagwl));
212 const std::string* ptr;
213 insp::aligned_storage<std::string> str;
216 void InitFrom(const Param& other)
220 new(str) std::string(*other.str);
226 operator const std::string&() const { return (owned ? *str : *ptr); }
234 Param(const std::string& s)
240 Param(int, const char* s)
243 new(str) std::string(s);
246 Param(int, const std::string& s)
249 new(str) std::string(s);
252 Param(const Param& other)
264 Param& operator=(const Param& other)
276 bool IsOwned() const { return owned; }
279 typedef std::vector<Param> ParamList;
282 typedef std::vector<std::pair<SerializedInfo, SerializedMessage> > SerializedList;
288 mutable SerializedList serlist;
292 /** Set command string.
293 * @param cmd Command string to set.
295 void SetCommand(const char* cmd)
304 * @param cmd Command name, e.g. "JOIN", "NICK". May be NULL. If NULL, the command must be set
305 * with SetCommand() before the message is serialized.
306 * @param Sourceuser See the one parameter constructor of MessageSource for description.
308 Message(const char* cmd, User* Sourceuser = NULL)
309 : ClientProtocol::MessageSource(Sourceuser)
310 , command(cmd ? cmd : std::string())
311 , msginit_done(false)
319 * @param cmd Command name, e.g. "JOIN", "NICK". May be NULL. If NULL, the command must be set
320 * with SetCommand() before the message is serialized.
321 * @param Sourcestr See the two parameter constructor of MessageSource for description.
322 * Must remain valid as long as this object is alive.
323 * @param Sourceuser See the two parameter constructor of MessageSource for description.
325 Message(const char* cmd, const std::string& Sourcestr, User* Sourceuser = NULL)
326 : ClientProtocol::MessageSource(Sourcestr, Sourceuser)
327 , command(cmd ? cmd : std::string())
328 , msginit_done(false)
335 /** Get the parameters of this message.
336 * @return List of parameters.
338 const ParamList& GetParams() const { return params; }
340 /** Get a map of tags attached to this message.
341 * The map contains the tag providers that attached the tag to the message.
342 * @return Map of tags.
344 const TagMap& GetTags() const { return tags; }
346 /** Get the command string.
347 * @return Command string, e.g. "NICK", "001".
349 const char* GetCommand() const { return command.c_str(); }
351 /** Add a parameter to the parameter list.
352 * @param str String to add, will be copied.
354 void PushParam(const char* str) { params.push_back(Param(0, str)); }
356 /** Add a parameter to the parameter list.
357 * @param str String to add, will be copied.
359 void PushParam(const std::string& str) { params.push_back(Param(0, str)); }
361 /** Add a parameter to the parameter list.
362 * @param str String to add.
363 * The string will NOT be copied, it must remain alive until ClearParams() is called or until the object is destroyed.
365 void PushParamRef(const std::string& str) { params.push_back(str); }
367 /** Add a placeholder parameter to the parameter list.
368 * Placeholder parameters must be filled in later with actual parameters using ReplaceParam() or ReplaceParamRef().
370 void PushParamPlaceholder() { params.push_back(Param()); }
372 /** Replace a parameter or a placeholder that is already in the parameter list.
373 * @param index Index of the parameter to replace. Must be less than GetParams().size().
374 * @param str String to replace the parameter or placeholder with, will be copied.
376 void ReplaceParam(unsigned int index, const char* str) { params[index] = Param(0, str); }
378 /** Replace a parameter or a placeholder that is already in the parameter list.
379 * @param index Index of the parameter to replace. Must be less than GetParams().size().
380 * @param str String to replace the parameter or placeholder with, will be copied.
382 void ReplaceParam(unsigned int index, const std::string& str) { params[index] = Param(0, str); }
384 /** Replace a parameter or a placeholder that is already in the parameter list.
385 * @param index Index of the parameter to replace. Must be less than GetParams().size().
386 * @param str String to replace the parameter or placeholder with.
387 * The string will NOT be copied, it must remain alive until ClearParams() is called or until the object is destroyed.
389 void ReplaceParamRef(unsigned int index, const std::string& str) { params[index] = Param(str); }
392 * @param tagname Raw name of the tag to use in the protocol.
393 * @param tagprov Provider of the tag.
394 * @param val Tag value. If empty no value will be sent with the tag.
395 * @param tagdata Tag provider specific data, will be passed to MessageTagProvider::ShouldSendTag(). Optional, defaults to NULL.
397 void AddTag(const std::string& tagname, MessageTagProvider* tagprov, const std::string& val, void* tagdata = NULL)
399 tags.insert(std::make_pair(tagname, MessageTagData(tagprov, val, tagdata)));
402 /** Add all tags in a TagMap to the tags in this message. Existing tags will not be overwritten.
403 * @param newtags New tags to add.
405 void AddTags(const ClientProtocol::TagMap& newtags)
407 tags.insert(newtags.begin(), newtags.end());
410 /** Get the message in a serialized form.
411 * @param serializeinfo Information about which exact serialized form of the message is the caller asking for
412 * (which serializer to use and which tags to include).
413 * @return Serialized message according to serializeinfo. The returned reference remains valid until the
414 * next call to this method.
416 const SerializedMessage& GetSerialized(const SerializedInfo& serializeinfo) const;
418 /** Clear the parameter list and tags.
422 msginit_done = false;
428 /** Remove all serialized messages.
429 * If a parameter is changed after the message has been sent at least once, this method must be called before
430 * serializing the message again to ensure the cache won't contain stale data.
432 void InvalidateCache()
440 for (ParamList::iterator i = params.begin(); i != params.end(); ++i, j++)
444 ReplaceParam(j, curr);
448 void SetSideEffect(bool Sideeffect) { sideeffect = Sideeffect; }
449 bool IsSideEffect() const { return sideeffect; }
451 friend class Serializer;
454 /** Client protocol event class.
455 * All messages sent to a user must be part of an event. A single event may result in more than one protocol message
456 * being sent, for example a join event may result in a JOIN and a MODE protocol message sent to members of the channel
457 * if the joining user has some prefix modes set.
459 * Event hooks attached to a specific event can alter the messages sent for that event.
461 class ClientProtocol::Event
463 EventProvider* event;
465 const MessageList* initialmsglist;
470 * @param protoeventprov Protocol event provider the event is an instance of.
472 Event(EventProvider& protoeventprov)
473 : event(&protoeventprov)
475 , initialmsglist(NULL)
476 , eventinit_done(false)
481 * @param protoeventprov Protocol event provider the event is an instance of.
482 * @param msg Message to include in this event by default.
484 Event(EventProvider& protoeventprov, ClientProtocol::Message& msg)
485 : event(&protoeventprov)
487 , initialmsglist(NULL)
488 , eventinit_done(false)
492 /** Set a single message as the initial message in the event.
493 * Modules may alter this later.
495 void SetMessage(Message* msg)
498 initialmsglist = NULL;
501 /** Set a list of messages as the initial messages in the event.
502 * Modules may alter this later.
504 void SetMessageList(const MessageList& msglist)
507 initialmsglist = &msglist;
510 /** Get a list of messages to send to a user.
511 * The exact messages sent to a user are determined by the initial message(s) set and hooks.
512 * @param user User to get the messages for.
513 * @param messagelist List to fill in with messages to send to the user for the event
515 void GetMessagesForUser(LocalUser* user, MessageList& messagelist);
518 /** Base class for message tag providers.
519 * All message tags belong to a message tag provider. Message tag providers can populate messages
520 * with tags before the message is sent and they have the job of determining whether a user should
521 * get a message tag or be allowed to send one.
523 class ClientProtocol::MessageTagProvider : public Events::ModuleEventListener
527 * @param mod Module owning the provider.
529 MessageTagProvider(Module* mod)
530 : Events::ModuleEventListener(mod, "event/messagetag")
534 /** Called when a message is ready to be sent to give the tag provider a chance to add tags to the message.
535 * To add tags call Message::AddTag(). If the provided tag or tags have been added already elsewhere or if the
536 * provider doesn't want its tag(s) to be on the message, the implementation doesn't have to do anything special.
537 * The default implementation does nothing.
538 * @param msg Message to be populated with tags.
540 virtual void OnPopulateTags(ClientProtocol::Message& msg)
544 /** Called for each tag that the server receives from a client in a message.
545 * @param user User that sent the tag.
546 * @param tagname Name of the tag.
547 * @param tagvalue Value of the tag, empty string if the tag has no value. May be modified.
548 * @return MOD_RES_ALLOW to accept the tag with the value in 'value', MOD_RES_DENY to reject the tag and act as if it wasn't sent,
549 * MOD_RES_PASSTHRU to make no decision. If no hooks accept a tag, the tag is rejected.
550 * The default implementation returns MOD_RES_PASSTHRU.
552 virtual ModResult OnProcessTag(User* user, const std::string& tagname, std::string& tagvalue)
554 return MOD_RES_PASSTHRU;
557 /** Called whenever a user is about to receive a message that has a tag attached which is provided by this provider
558 * to determine whether or not the user should get the tag.
559 * @param user User in question.
560 * @param tagdata Tag in question.
561 * @return True if the tag should be sent to the user, false otherwise.
563 virtual bool ShouldSendTag(LocalUser* user, const MessageTagData& tagdata) = 0;
566 /** Base class for client protocol event hooks.
567 * A protocol event hook is attached to a single event type. It has the ability to alter or block messages
568 * sent to users which belong to the event the hook is attached to.
570 class ClientProtocol::EventHook : public Events::ModuleEventListener
573 static std::string GetEventName(const std::string& name)
575 return "event/protoevent_" + name;
579 * @param mod Owner of the hook.
580 * @param name Name of the event to hook.
581 * @param priority Priority of the hook. Determines the order in which hooks for the same event get called.
584 EventHook(Module* mod, const std::string& name, unsigned int priority = Events::ModuleEventListener::DefaultPriority)
585 : Events::ModuleEventListener(mod, GetEventName(name), priority)
589 /** Called exactly once before an event is sent to any user.
590 * The default implementation doesn't do anything.
591 * @param ev Event being sent to one or more users.
593 virtual void OnEventInit(const ClientProtocol::Event& ev)
597 /** Called for each user that may receive the event.
598 * The hook may alter the messages sent to the user and decide whether further hooks should be executed.
599 * @param user User the message list is being prepared to be sent to.
600 * @param ev Event associated with the messages.
601 * @param messagelist List of messages to send to the user. The hook can alter this in any way it sees fit, for example it can replace messages,
602 * add new messages, etc. The list must not be empty when the method returns.
603 * @return MOD_RES_PASSTHRU to run hooks after the called hook or if no hooks are after the called hook, send the messages in messagelist to the user.
604 * MOD_RES_DENY to not send any messages to the user and to not run other hooks,
605 * MOD_RES_ALLOW to send the messages in messagelist to the user and to not run other hooks.
607 virtual ModResult OnPreEventSend(LocalUser* user, const ClientProtocol::Event& ev, ClientProtocol::MessageList& messagelist) = 0;
610 /** Event provider for client protocol events.
611 * Protocol event hooks can be attached to the instances of these providers. The core has event
612 * providers for most common IRC events defined in RFC1459.
614 class ClientProtocol::EventProvider : public Events::ModuleEventProvider
618 * @param Mod Module that owns the event provider.
619 * @param eventname Name of the event this provider is for, e.g. "JOIN", "PART", "NUMERIC".
620 * Should match command name if applicable.
622 EventProvider(Module* Mod, const std::string& eventname)
623 : Events::ModuleEventProvider(Mod, ClientProtocol::EventHook::GetEventName(eventname))
628 /** Commonly used client protocol events.
629 * Available via InspIRCd::GetRFCEvents().
631 struct ClientProtocol::RFCEvents
633 EventProvider numeric;
641 EventProvider privmsg;
642 EventProvider invite;
648 : numeric(NULL, "NUMERIC")
655 , topic(NULL, "TOPIC")
656 , privmsg(NULL, "PRIVMSG")
657 , invite(NULL, "INVITE")
660 , error(NULL, "ERROR")
665 /** Base class for client protocol serializers.
666 * A serializer has to implement serialization and parsing of protocol messages to/from wire format.
668 class CoreExport ClientProtocol::Serializer : public DataProvider
670 Events::ModuleEventProvider evprov;
672 /** Make a white list containing which tags a user should get.
673 * @param user User in question.
674 * @param tagmap Tag map that contains all possible tags.
675 * @return Whitelist of tags to send to the user.
677 TagSelection MakeTagWhitelist(LocalUser* user, const TagMap& tagmap) const;
681 * @param mod Module owning the serializer.
682 * @param Name Name of the serializer, e.g. "rfc".
684 Serializer(Module* mod, const char* Name);
686 /** Handle a tag in a message being parsed. Call this method for each parsed tag.
687 * @param user User sending the tag.
688 * @param tagname Name of the tag.
689 * @param tagvalue Tag value, may be empty.
690 * @param tags TagMap to place the tag into, if it gets accepted.
691 * @return True if no error occured, false if the tag name is invalid or if this tag already exists.
693 bool HandleTag(LocalUser* user, const std::string& tagname, std::string& tagvalue, TagMap& tags) const;
695 /** Serialize a message for a user.
696 * @param user User to serialize the message for.
697 * @param msg Message to serialize.
698 * @return Raw serialized message, only containing the appropriate tags for the user.
699 * The reference is guaranteed to be valid as long as the Message object is alive and until the same
700 * Message is serialized for another user.
702 const SerializedMessage& SerializeForUser(LocalUser* user, Message& msg);
704 /** Serialize a high level protocol message into wire format.
705 * @param msg High level message to serialize. Contains all necessary information about the message, including all possible tags.
706 * @param tagwl Message tags to include in the serialized message. Tags attached to the message but not included in the whitelist must not
707 * appear in the output. This is because each user may get a different set of tags for the same message.
708 * @return Protocol message in wire format. Must contain message delimiter as well, if any (e.g. CRLF for RFC1459).
710 virtual std::string Serialize(const Message& msg, const TagSelection& tagwl) const = 0;
712 /** Parse a protocol message from wire format.
713 * @param user Source of the message.
714 * @param line Raw protocol message.
715 * @param parseoutput Output of the parser.
716 * @return True if the message was parsed successfully into parseoutput and should be processed, false to drop the message.
718 virtual bool Parse(LocalUser* user, const std::string& line, ParseOutput& parseoutput) = 0;
721 inline ClientProtocol::MessageTagData::MessageTagData(MessageTagProvider* prov, const std::string& val, void* data)