1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
18 #include "inspsocket.h"
22 /** connect class types
31 /** RFC1459 channel modes
34 /** +s: Server notice mask */
35 UM_SNOMASK = 's' - 65,
37 UM_WALLOPS = 'w' - 65,
39 UM_INVISIBLE = 'i' - 65,
41 UM_OPERATOR = 'o' - 65
44 /** Registration state of a user, e.g.
45 * have they sent USER, NICK, PASS yet?
47 enum RegistrationState {
49 #ifndef WIN32 // Burlex: This is already defined in win32, luckily it is still 0.
50 REG_NONE = 0, /* Has sent nothing */
53 REG_USER = 1, /* Has sent USER */
54 REG_NICK = 2, /* Has sent NICK */
55 REG_NICKUSER = 3, /* Bitwise combination of REG_NICK and REG_USER */
56 REG_ALL = 7 /* REG_NICKUSER plus next bit along */
59 /* Required forward declaration */
64 /** Holds information relevent to <connect allow> and <connect deny> tags in the config file.
66 struct CoreExport ConnectClass : public refcountbase
68 reference<ConfigTag> config;
69 /** Type of line, either CC_ALLOW or CC_DENY
73 /** Connect class name
77 /** Max time to register the connection in seconds
79 unsigned int registration_timeout;
81 /** Host mask for this line
85 /** Number of seconds between pings for this line
87 unsigned int pingtime;
89 /** (Optional) Password for this line
93 /** (Optional) Hash Method for this line
97 /** Maximum size of sendq for users in this class (bytes)
98 * Users cannot send commands if they go over this limit
100 unsigned long softsendqmax;
102 /** Maximum size of sendq for users in this class (bytes)
103 * Users are killed if they go over this limit
105 unsigned long hardsendqmax;
107 /** Maximum size of recvq for users in this class (bytes)
109 unsigned long recvqmax;
111 /** Local max when connecting by this connection class
113 unsigned long maxlocal;
115 /** Global max when connecting by this connection class
117 unsigned long maxglobal;
119 /** Max channels for this class
121 unsigned int maxchans;
123 /** Port number this connect class applies to
127 /** How many users may be in this connect class before they are refused?
128 * (0 = no limit = default)
132 /** Create a new connect class with no settings.
134 ConnectClass(ConfigTag* tag, char type, const std::string& mask);
135 /** Create a new connect class with inherited settings.
137 ConnectClass(ConfigTag* tag, char type, const std::string& mask, const ConnectClass& parent);
139 /** Update the settings in this block to match the given block */
140 void Update(const ConnectClass* newSettings);
143 const std::string& GetName() { return name; }
144 const std::string& GetPass() { return pass; }
145 const std::string& GetHost() { return host; }
146 const int GetPort() { return port; }
148 /** Returns the registration timeout
150 time_t GetRegTimeout()
152 return (registration_timeout ? registration_timeout : 90);
155 /** Returns the ping frequency
157 unsigned int GetPingTime()
159 return (pingtime ? pingtime : 120);
162 /** Returns the maximum sendq value (soft limit)
163 * Note that this is in addition to internal OS buffers
165 unsigned long GetSendqSoftMax()
167 return (softsendqmax ? softsendqmax : 4096);
170 /** Returns the maximum sendq value (hard limit)
172 unsigned long GetSendqHardMax()
174 return (hardsendqmax ? hardsendqmax : 0x100000);
177 /** Returns the maximum recvq value
179 unsigned long GetRecvqMax()
181 return (recvqmax ? recvqmax : 4096);
184 /** Returusn the maximum number of local sessions
186 unsigned long GetMaxLocal()
191 /** Returns the maximum number of global sessions
193 unsigned long GetMaxGlobal()
199 /** Holds a complete list of all channels to which a user has been invited and has not yet joined, and the time at which they'll expire.
201 CoreExport typedef std::vector< std::pair<irc::string, time_t> > InvitedList;
203 /** Holds a complete list of all allow and deny tags from the configuration file (connection classes)
205 CoreExport typedef std::vector<reference<ConnectClass> > ClassVector;
207 /** Typedef for the list of user-channel records for a user
209 CoreExport typedef std::set<Channel*> UserChanList;
211 /** Shorthand for an iterator into a UserChanList
213 CoreExport typedef UserChanList::iterator UCListIter;
215 /* Required forward declaration
219 /** Holds all information about a user
220 * This class stores all information about a user connected to the irc server. Everything about a
221 * connection is stored here primarily, from the user's socket ID (file descriptor) through to the
222 * user's nickname and hostname.
224 class CoreExport User : public StreamSocket
227 /** A list of channels the user has a pending invite to.
228 * Upon INVITE channels are added, and upon JOIN, the
229 * channels are removed from this list.
233 /** Cached nick!ident@dhost value using the displayed hostname
235 std::string cached_fullhost;
237 /** Cached ident@ip value using the real IP address
239 std::string cached_hostip;
241 /** Cached ident@realhost value using the real hostname
243 std::string cached_makehost;
245 /** Cached nick!ident@realhost value using the real hostname
247 std::string cached_fullrealhost;
249 /** Set by GetIPString() to avoid constantly re-grabbing IP via sockets voodoo.
251 std::string cachedip;
253 /** When we erase the user (in the destructor),
254 * we call this method to subtract one from all
255 * mode characters this user is making use of.
257 void DecrementModes();
259 std::set<std::string> *AllowedOperCommands;
260 std::set<std::string> *AllowedPrivs;
262 /** Allowed user modes from oper classes. */
263 std::bitset<64> AllowedUserModes;
265 /** Allowed channel modes from oper classes. */
266 std::bitset<64> AllowedChanModes;
269 /** Contains a pointer to the connect class a user is on from - this will be NULL for remote connections.
271 reference<ConnectClass> MyClass;
273 /** Hostname of connection.
274 * This should be valid as per RFC1035.
278 /** Stats counter for bytes inbound
282 /** Stats counter for bytes outbound
286 /** Stats counter for commands inbound
290 /** Stats counter for commands outbound
294 /** True if user has authenticated, false if otherwise
298 /** Used by User to indicate the registration status of the connection
299 * It is a bitfield of the REG_NICK, REG_USER and REG_ALL bits to indicate
300 * the connection state.
304 /** Time the connection was last pinged
308 /** Time that the object was instantiated (used for TS calculation etc)
312 /** Time the connection was created, set in the constructor. This
313 * may be different from the time the user's classbase object was
318 /** Time that the connection last sent a message, used to calculate idle time
322 /** Used by PING checking code
326 /** Stored reverse lookup from res_forward. Should not be used after resolution.
328 std::string stored_host;
330 /** Starts a DNS lookup of the user's IP.
331 * This will cause two UserResolver classes to be instantiated.
332 * When complete, these objects set User::dns_done to true.
334 void StartDNSLookup();
336 /** The users nickname.
337 * An invalid nickname indicates an unregistered connection prior to the NICK command.
338 * Use InspIRCd::IsNick() to validate nicknames.
342 /** The user's unique identifier.
343 * This is the unique identifier which the user has across the network.
347 /** The users ident reply.
348 * Two characters are added to the user-defined limit to compensate for the tilde etc.
352 /** The host displayed to non-opers (used for cloaking etc).
353 * This usually matches the value of User::host.
357 /** The users full name (GECOS).
359 std::string fullname;
361 /** The user's mode list.
362 * NOT a null terminated string.
364 * Much love to the STL for giving us an easy to use bitset, saving us RAM.
365 * if (modes[modeletter-65]) is set, then the mode is
366 * set, for example, to work out if mode +s is set, we check the field
367 * User::modes['s'-65] != 0.
368 * The following RFC characters o, w, s, i have constants defined via an
369 * enum, such as UM_SERVERNOTICE and UM_OPETATOR.
371 std::bitset<64> modes;
373 /** What snomasks are set on this user.
374 * This functions the same as the above modes.
376 std::bitset<64> snomasks;
378 /** Channels this user is on, and the permissions they have there
382 /** The server the user is connected to.
386 /** The user's away message.
387 * If this string is empty, the user is not marked as away.
391 /** Time the user last went away.
392 * This is ONLY RELIABLE if user IS_AWAY()!
396 /** The oper type they logged in as, if they are an oper.
397 * This is used to check permissions in operclasses, so that
398 * we can say 'yay' or 'nay' to any commands they issue.
399 * The value of this is the value of a valid 'type name=' tag.
403 /** True when DNS lookups are completed.
404 * The UserResolver classes res_forward and res_reverse will
405 * set this value once they complete.
409 /** Password specified by the user when they registered.
410 * This is stored even if the <connect> block doesnt need a password, so that
411 * modules may check it.
413 std::string password;
415 /** Whether or not to send an snotice about this user's quitting
419 /** If this is set to true, then all socket operations for the user
420 * are dropped into the bit-bucket.
421 * This value is set by QuitUser, and is not needed seperately from that call.
422 * Please note that setting this value alone will NOT cause the user to quit.
426 /** Server address and port that this user is connected to.
427 * If unknown, address family is AF_UNKNOWN
429 irc::sockets::sockaddrs server_sa;
430 /** Client address that the user is connected from.
431 * Port number is only valid if local.
433 * Do not modify this value directly, use SetClientIP() to change it
435 irc::sockets::sockaddrs client_sa;
437 /** Sets the client IP for this user
438 * @return true if the conversion was successful
440 bool SetClientIP(const char* sip);
443 * @return The port number of this user.
447 /** Get client IP string from sockaddr, using static internal buffer
448 * @return The IP string
450 const char* GetIPString();
452 /** Get a CIDR mask from the IP of this user, using a static internal buffer.
453 * e.g., GetCIDRMask(16) for 223.254.214.52 returns 223.254.0.0/16
454 * This may be used for CIDR clone detection, etc.
456 * (XXX, brief note: when we do the sockets rewrite, this should move down a
457 * level so it may be used on more derived objects. -- w00t)
459 const char *GetCIDRMask(int range);
461 /** This is true if the user matched an exception (E:Line). It is used to save time on ban checks.
465 /** This value contains how far into the penalty threshold the user is. Once its over
466 * the penalty threshold then commands are held and processed on-timer.
470 /** Default constructor
471 * @throw CoreException if the UID allocated to the user already exists
472 * @param Instance Creator instance
473 * @param uid User UUID, or empty to allocate one automatically
475 User(const std::string &uid = "");
477 /** Check if the user matches a G or K line, and disconnect them if they do.
478 * @param doZline True if ZLines should be checked (if IP has changed since initial connect)
479 * Returns true if the user matched a ban, false else.
481 bool CheckLines(bool doZline = false);
483 /** Returns the full displayed host of the user
484 * This member function returns the hostname of the user as seen by other users
485 * on the server, in nick!ident&at;host form.
486 * @return The full masked host of the user
488 virtual const std::string GetFullHost();
490 /** Returns the full real host of the user
491 * This member function returns the hostname of the user as seen by other users
492 * on the server, in nick!ident&at;host form. If any form of hostname cloaking is in operation,
493 * e.g. through a module, then this method will ignore it and return the true hostname.
494 * @return The full real host of the user
496 virtual const std::string GetFullRealHost();
498 /** This clears any cached results that are used for GetFullRealHost() etc.
499 * The results of these calls are cached as generating them can be generally expensive.
501 void InvalidateCache();
503 /** Create a displayable mode string for this users snomasks
504 * @return The notice mask character sequence
506 const char* FormatNoticeMasks();
508 /** Process a snomask modifier string, e.g. +abc-de
509 * @param sm A sequence of notice mask characters
510 * @return The cleaned mode sequence which can be output,
511 * e.g. in the above example if masks c and e are not
512 * valid, this function will return +ab-d
514 std::string ProcessNoticeMasks(const char *sm);
516 /** Returns true if a notice mask is set
517 * @param sm A notice mask character to check
518 * @return True if the notice mask is set
520 bool IsNoticeMaskSet(unsigned char sm);
522 /** Changed a specific notice mask value
523 * @param sm The server notice mask to change
524 * @param value An on/off value for this mask
526 void SetNoticeMask(unsigned char sm, bool value);
528 /** Create a displayable mode string for this users umodes
529 * @param The mode string
531 const char* FormatModes(bool showparameters = false);
533 /** Returns true if a specific mode is set
534 * @param m The user mode
535 * @return True if the mode is set
537 bool IsModeSet(unsigned char m);
539 /** Set a specific usermode to on or off
540 * @param m The user mode
541 * @param value On or off setting of the mode
543 void SetMode(unsigned char m, bool value);
545 /** Returns true if a user is invited to a channel.
546 * @param channel A channel name to look up
547 * @return True if the user is invited to the given channel
549 virtual bool IsInvited(const irc::string &channel);
551 /** Adds a channel to a users invite list (invites them to a channel)
552 * @param channel A channel name to add
553 * @param timeout When the invite should expire (0 == never)
555 virtual void InviteTo(const irc::string &channel, time_t timeout);
557 /** Removes a channel from a users invite list.
558 * This member function is called on successfully joining an invite only channel
559 * to which the user has previously been invited, to clear the invitation.
560 * @param channel The channel to remove the invite to
562 virtual void RemoveInvite(const irc::string &channel);
564 /** Returns true or false for if a user can execute a privilaged oper command.
565 * This is done by looking up their oper type from User::oper, then referencing
566 * this to their oper classes and checking the commands they can execute.
567 * @param command A command (should be all CAPS)
568 * @return True if this user can execute the command
570 bool HasPermission(const std::string &command);
572 /** Returns true if a user has a given permission.
573 * This is used to check whether or not users may perform certain actions which admins may not wish to give to
574 * all operators, yet are not commands. An example might be oper override, mass messaging (/notice $*), etc.
576 * @param privstr The priv to chec, e.g. "users/override/topic". These are loaded free-form from the config file.
577 * @param noisy If set to true, the user is notified that they do not have the specified permission where applicable. If false, no notification is sent.
578 * @return True if this user has the permission in question.
580 bool HasPrivPermission(const std::string &privstr, bool noisy = false);
582 /** Returns true or false if a user can set a privileged user or channel mode.
583 * This is done by looking up their oper type from User::oper, then referencing
584 * this to their oper classes, and checking the modes they can set.
585 * @param mode The mode the check
586 * @param type ModeType (MODETYPE_CHANNEL or MODETYPE_USER).
587 * @return True if the user can set or unset this mode.
589 bool HasModePermission(unsigned char mode, ModeType type);
591 /** Adds to the user's write buffer.
592 * You may add any amount of text up to this users sendq value, if you exceed the
593 * sendq value, the user will be removed, and further buffer adds will be dropped.
594 * @param data The data to add to the write buffer
596 void AddWriteBuf(const std::string &data);
598 /** Returns the list of channels this user has been invited to but has not yet joined.
599 * @return A list of channels the user is invited to
601 InvitedList* GetInviteList();
603 /** Creates a wildcard host.
604 * Takes a buffer to use and fills the given buffer with the host in the format *!*@hostname
605 * @return The wildcarded hostname in *!*@host form
607 char* MakeWildHost();
609 /** Creates a usermask with real host.
610 * Takes a buffer to use and fills the given buffer with the hostmask in the format user@host
611 * @return the usermask in the format user@host
613 const std::string& MakeHost();
615 /** Creates a usermask with real ip.
616 * Takes a buffer to use and fills the given buffer with the ipmask in the format user@ip
617 * @return the usermask in the format user@ip
619 const std::string& MakeHostIP();
621 /** Add the user to WHOWAS system
625 /** Oper up the user using the given opertype.
626 * This will also give the +o usermode.
627 * @param opertype The oper type to oper as
629 void Oper(const std::string &opertype, const std::string &opername);
631 /** Call this method to find the matching <connect> for a user, and to check them against it.
635 /** Use this method to fully connect a user.
636 * This will send the message of the day, check G/K/E lines, etc.
640 /** Change this users hash key to a new string.
641 * You should not call this function directly. It is used by the core
642 * to update the users hash entry on a nickchange.
643 * @param New new user_hash key
644 * @return Pointer to User in hash (usually 'this')
646 User* UpdateNickHash(const char* New);
648 /** Force a nickname change.
649 * If the nickname change fails (for example, because the nick in question
650 * already exists) this function will return false, and you must then either
651 * output an error message, or quit the user for nickname collision.
652 * @param newnick The nickname to change to
653 * @return True if the nickchange was successful.
655 bool ForceNickChange(const char* newnick);
658 * This will clear the +o usermode and unset the user's oper type
662 /** Write text to this user, appending CR/LF.
663 * @param text A std::string to send to the user
665 void Write(const std::string &text);
667 /** Write text to this user, appending CR/LF.
668 * @param text The format string for text to send to the user
669 * @param ... POD-type format arguments
671 void Write(const char *text, ...) CUSTOM_PRINTF(2, 3);
673 /** Write text to this user, appending CR/LF and prepending :server.name
674 * @param text A std::string to send to the user
676 void WriteServ(const std::string& text);
678 /** Write text to this user, appending CR/LF and prepending :server.name
679 * @param text The format string for text to send to the user
680 * @param ... POD-type format arguments
682 void WriteServ(const char* text, ...) CUSTOM_PRINTF(2, 3);
684 void WriteNumeric(unsigned int numeric, const char* text, ...) CUSTOM_PRINTF(3, 4);
686 void WriteNumeric(unsigned int numeric, const std::string &text);
688 /** Write text to this user, appending CR/LF and prepending :nick!user@host of the user provided in the first parameter.
689 * @param user The user to prepend the :nick!user@host of
690 * @param text A std::string to send to the user
692 void WriteFrom(User *user, const std::string &text);
694 /** Write text to this user, appending CR/LF and prepending :nick!user@host of the user provided in the first parameter.
695 * @param user The user to prepend the :nick!user@host of
696 * @param text The format string for text to send to the user
697 * @param ... POD-type format arguments
699 void WriteFrom(User *user, const char* text, ...) CUSTOM_PRINTF(3, 4);
701 /** Write text to the user provided in the first parameter, appending CR/LF, and prepending THIS user's :nick!user@host.
702 * @param dest The user to route the message to
703 * @param text A std::string to send to the user
705 void WriteTo(User *dest, const std::string &data);
707 /** Write text to the user provided in the first parameter, appending CR/LF, and prepending THIS user's :nick!user@host.
708 * @param dest The user to route the message to
709 * @param text The format string for text to send to the user
710 * @param ... POD-type format arguments
712 void WriteTo(User *dest, const char *data, ...) CUSTOM_PRINTF(3, 4);
714 /** Write to all users that can see this user (including this user in the list), appending CR/LF
715 * @param text A std::string to send to the users
717 void WriteCommonRaw(const std::string &line, bool include_self = true);
719 /** Write to all users that can see this user (including this user in the list), appending CR/LF
720 * @param text The format string for text to send to the users
721 * @param ... POD-type format arguments
723 void WriteCommon(const char* text, ...) CUSTOM_PRINTF(2, 3);
725 /** Write to all users that can see this user (not including this user in the list), appending CR/LF
726 * @param text The format string for text to send to the users
727 * @param ... POD-type format arguments
729 void WriteCommonExcept(const char* text, ...) CUSTOM_PRINTF(2, 3);
731 /** Write a quit message to all common users, as in User::WriteCommonExcept but with a specific
732 * quit message for opers only.
733 * @param normal_text Normal user quit message
734 * @param oper_text Oper only quit message
736 void WriteCommonQuit(const std::string &normal_text, const std::string &oper_text);
738 /** Write a WALLOPS message from this user to all local opers.
739 * If this user is not opered, the function will return without doing anything.
740 * @param text The format string to send in the WALLOPS message
741 * @param ... Format arguments
743 void WriteWallOps(const char* text, ...) CUSTOM_PRINTF(2, 3);
745 /** Write a WALLOPS message from this user to all local opers.
746 * If this user is not opered, the function will return without doing anything.
747 * @param text The text to send in the WALLOPS message
749 void WriteWallOps(const std::string &text);
751 /** Return true if the user shares at least one channel with another user
752 * @param other The other user to compare the channel list against
753 * @return True if the given user shares at least one channel with this user
755 bool SharesChannelWith(User *other);
757 /** Send fake quit/join messages for host or ident cycle.
758 * Run this after the item in question has changed.
759 * You should not need to use this function, call ChangeDisplayedHost instead
761 * @param The entire QUIT line, including the source using the old value
763 void DoHostCycle(const std::string &quitline);
765 /** Change the displayed host of a user.
766 * ALWAYS use this function, rather than writing User::dhost directly,
767 * as this triggers module events allowing the change to be syncronized to
768 * remote servers. This will also emulate a QUIT and rejoin (where configured)
769 * before setting their host field.
770 * @param host The new hostname to set
771 * @return True if the change succeeded, false if it didn't
773 bool ChangeDisplayedHost(const char* host);
775 /** Change the ident (username) of a user.
776 * ALWAYS use this function, rather than writing User::ident directly,
777 * as this correctly causes the user to seem to quit (where configured)
778 * before setting their ident field.
779 * @param host The new ident to set
780 * @return True if the change succeeded, false if it didn't
782 bool ChangeIdent(const char* newident);
784 /** Change a users realname field.
785 * ALWAYS use this function, rather than writing User::fullname directly,
786 * as this triggers module events allowing the change to be syncronized to
788 * @param gecos The user's new realname
789 * @return True if the change succeeded, false if otherwise
791 bool ChangeName(const char* gecos);
793 /** Send a command to all local users from this user
794 * The command given must be able to send text with the
795 * first parameter as a servermask (e.g. $*), so basically
796 * you should use PRIVMSG or NOTICE.
797 * @param command the command to send
798 * @param text The text format string to send
799 * @param ... Format arguments
801 void SendAll(const char* command, const char* text, ...) CUSTOM_PRINTF(3, 4);
803 /** Compile a channel list for this user. Used internally by WHOIS
804 * @param source The user to prepare the channel list for
805 * @param spy Whether to return the spy channel list rather than the normal one
806 * @return This user's channel list
808 std::string ChannelList(User* source, bool spy);
810 /** Split the channel list in cl which came from dest, and spool it to this user
811 * Used internally by WHOIS
812 * @param dest The user the original channel list came from
813 * @param cl The channel list as a string obtained from User::ChannelList()
815 void SplitChanList(User* dest, const std::string &cl);
817 /** Remove this user from all channels they are on, and delete any that are now empty.
818 * This is used by QUIT, and will not send part messages!
820 void PurgeEmptyChannels();
822 /** Get the connect class which this user belongs to.
823 * @return A pointer to this user's connect class
825 ConnectClass *GetClass();
827 /** Set the connect class to which this user belongs to.
828 * @param explicit_name Set this string to tie the user to a specific class name. Otherwise, the class is fitted by checking <connect> tags from the configuration file.
829 * @return A reference to this user's current connect class.
831 ConnectClass *SetClass(const std::string &explicit_name = "");
833 /** Show the message of the day to this user
837 /** Show the server RULES file to this user
841 /** Increases a user's command penalty by a set amount.
843 void IncreasePenalty(int increase);
845 /** Decreases a user's command penalty by a set amount.
847 void DecreasePenalty(int decrease);
850 void OnError(BufferedSocketError error);
852 /** Default destructor
858 /** Derived from Resolver, and performs user forward/reverse lookups.
860 class CoreExport UserResolver : public Resolver
863 /** User this class is 'attached' to.
866 /** File descriptor teh lookup is bound to
869 /** True if the lookup is forward, false if is a reverse lookup
873 /** Create a resolver.
874 * @param Instance The creating instance
875 * @param user The user to begin lookup on
876 * @param to_resolve The IP or host to resolve
877 * @param qt The query type
878 * @param cache Modified by the constructor if the result was cached
880 UserResolver(User* user, std::string to_resolve, QueryType qt, bool &cache);
882 /** Called on successful lookup
883 * @param result Result string
884 * @param ttl Time to live for result
885 * @param cached True if the result was found in the cache
887 void OnLookupComplete(const std::string &result, unsigned int ttl, bool cached);
889 /** Called on failed lookup
890 * @param e Error code
891 * @param errormessage Error message string
893 void OnError(ResolverError e, const std::string &errormessage);