2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
6 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
7 * Copyright (C) 2003-2007 Craig Edwards <craigedwards@brainbox.cc>
8 * Copyright (C) 2007 Burlex <???@???>
9 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
11 * This file is part of InspIRCd. InspIRCd is free software: you can
12 * redistribute it and/or modify it under the terms of the GNU General Public
13 * License as published by the Free Software Foundation, version 2.
15 * This program is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
28 #include "inspsocket.h"
30 #include "membership.h"
32 /** connect class types
39 /** named connect block (for opers, etc) */
43 /** Registration state of a user, e.g.
44 * have they sent USER, NICK, PASS yet?
46 enum RegistrationState {
48 #ifndef _WIN32 // Burlex: This is already defined in win32, luckily it is still 0.
49 REG_NONE = 0, /* Has sent nothing */
52 REG_USER = 1, /* Has sent USER */
53 REG_NICK = 2, /* Has sent NICK */
54 REG_NICKUSER = 3, /* Bitwise combination of REG_NICK and REG_USER */
55 REG_ALL = 7 /* REG_NICKUSER plus next bit along */
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 /** True if this class uses fake lag to manage flood, false if it kills */
76 /** Connect class name
80 /** Max time to register the connection in seconds
82 unsigned int registration_timeout;
84 /** Host mask for this line
88 /** Number of seconds between pings for this line
90 unsigned int pingtime;
92 /** Maximum size of sendq for users in this class (bytes)
93 * Users cannot send commands if they go over this limit
95 unsigned long softsendqmax;
97 /** Maximum size of sendq for users in this class (bytes)
98 * Users are killed if they go over this limit
100 unsigned long hardsendqmax;
102 /** Maximum size of recvq for users in this class (bytes)
104 unsigned long recvqmax;
106 /** Seconds worth of penalty before penalty system activates
108 unsigned int penaltythreshold;
110 /** Maximum rate of commands (units: millicommands per second) */
111 unsigned int commandrate;
113 /** Local max when connecting by this connection class
115 unsigned long maxlocal;
117 /** Global max when connecting by this connection class
119 unsigned long maxglobal;
121 /** True if max connections for this class is hit and a warning is wanted
125 /** Max channels for this class
127 unsigned int maxchans;
129 /** How many users may be in this connect class before they are refused?
130 * (0 = no limit = default)
134 /** If set to true, no user DNS lookups are to be performed
136 bool resolvehostnames;
138 /** Create a new connect class with no settings.
140 ConnectClass(ConfigTag* tag, char type, const std::string& mask);
141 /** Create a new connect class with inherited settings.
143 ConnectClass(ConfigTag* tag, char type, const std::string& mask, const ConnectClass& parent);
145 /** Update the settings in this block to match the given block */
146 void Update(const ConnectClass* newSettings);
148 const std::string& GetName() { return name; }
149 const std::string& GetHost() { return host; }
151 /** Returns the registration timeout
153 time_t GetRegTimeout()
155 return (registration_timeout ? registration_timeout : 90);
158 /** Returns the ping frequency
160 unsigned int GetPingTime()
162 return (pingtime ? pingtime : 120);
165 /** Returns the maximum sendq value (soft limit)
166 * Note that this is in addition to internal OS buffers
168 unsigned long GetSendqSoftMax()
170 return (softsendqmax ? softsendqmax : 4096);
173 /** Returns the maximum sendq value (hard limit)
175 unsigned long GetSendqHardMax()
177 return (hardsendqmax ? hardsendqmax : 0x100000);
180 /** Returns the maximum recvq value
182 unsigned long GetRecvqMax()
184 return (recvqmax ? recvqmax : 4096);
187 /** Returns the penalty threshold value
189 unsigned int GetPenaltyThreshold()
191 return penaltythreshold ? penaltythreshold : (fakelag ? 10 : 20);
194 unsigned int GetCommandRate()
196 return commandrate ? commandrate : 1000;
199 /** Return the maximum number of local sessions
201 unsigned long GetMaxLocal()
206 /** Returns the maximum number of global sessions
208 unsigned long GetMaxGlobal()
214 /** Holds all information about a user
215 * This class stores all information about a user connected to the irc server. Everything about a
216 * connection is stored here primarily, from the user's socket ID (file descriptor) through to the
217 * user's nickname and hostname.
219 class CoreExport User : public Extensible
222 /** Cached nick!ident@dhost value using the displayed hostname
224 std::string cached_fullhost;
226 /** Cached ident@ip value using the real IP address
228 std::string cached_hostip;
230 /** Cached ident@realhost value using the real hostname
232 std::string cached_makehost;
234 /** Cached nick!ident@realhost value using the real hostname
236 std::string cached_fullrealhost;
238 /** Set by GetIPString() to avoid constantly re-grabbing IP via sockets voodoo.
240 std::string cachedip;
242 /** The user's mode list.
243 * Much love to the STL for giving us an easy to use bitset, saving us RAM.
244 * if (modes[modeid]) is set, then the mode is set.
245 * For example, to work out if mode +i is set, we check the field
246 * User::modes[invisiblemode->modeid] == true.
248 std::bitset<ModeParser::MODEID_MAX> modes;
251 /** List of Memberships for this user
253 typedef insp::intrusive_list<Membership> ChanList;
255 /** Hostname of connection.
256 * This should be valid as per RFC1035.
260 /** Time that the object was instantiated (used for TS calculation etc)
264 /** Time the connection was created, set in the constructor. This
265 * may be different from the time the user's classbase object was
270 /** Client address that the user is connected from.
271 * Do not modify this value directly, use SetClientIP() to change it.
272 * Port is not valid for remote users.
274 irc::sockets::sockaddrs client_sa;
276 /** The users nickname.
277 * An invalid nickname indicates an unregistered connection prior to the NICK command.
278 * Use InspIRCd::IsNick() to validate nicknames.
282 /** The user's unique identifier.
283 * This is the unique identifier which the user has across the network.
285 const std::string uuid;
287 /** The users ident reply.
288 * Two characters are added to the user-defined limit to compensate for the tilde etc.
292 /** The host displayed to non-opers (used for cloaking etc).
293 * This usually matches the value of User::host.
297 /** The users full name (GECOS).
299 std::string fullname;
301 /** What snomasks are set on this user.
302 * This functions the same as the above modes.
304 std::bitset<64> snomasks;
306 /** Channels this user is on
310 /** The server the user is connected to.
314 /** The user's away message.
315 * If this string is empty, the user is not marked as away.
319 /** Time the user last went away.
320 * This is ONLY RELIABLE if user IsAway()!
324 /** The oper type they logged in as, if they are an oper.
326 reference<OperInfo> oper;
328 /** Used by User to indicate the registration status of the connection
329 * It is a bitfield of the REG_NICK, REG_USER and REG_ALL bits to indicate
330 * the connection state.
332 unsigned int registered:3;
334 /** If this is set to true, then all socket operations for the user
335 * are dropped into the bit-bucket.
336 * This value is set by QuitUser, and is not needed seperately from that call.
337 * Please note that setting this value alone will NOT cause the user to quit.
339 unsigned int quitting:1;
341 /** What type of user is this? */
342 const unsigned int usertype:2;
344 /** Get client IP string from sockaddr, using static internal buffer
345 * @return The IP string
347 const std::string& GetIPString();
349 /** Get CIDR mask, using default range, for this user
351 irc::sockets::cidr_mask GetCIDRMask();
353 /** Sets the client IP for this user
354 * @return true if the conversion was successful
356 virtual bool SetClientIP(const char* sip, bool recheck_eline = true);
358 virtual void SetClientIP(const irc::sockets::sockaddrs& sa, bool recheck_eline = true);
361 * @throw CoreException if the UID allocated to the user already exists
363 User(const std::string& uid, Server* srv, int objtype);
365 /** Returns the full displayed host of the user
366 * This member function returns the hostname of the user as seen by other users
367 * on the server, in nick!ident\@host form.
368 * @return The full masked host of the user
370 virtual const std::string& GetFullHost();
372 /** Returns the full real host of the user
373 * This member function returns the hostname of the user as seen by other users
374 * on the server, in nick!ident\@host form. If any form of hostname cloaking is in operation,
375 * e.g. through a module, then this method will ignore it and return the true hostname.
376 * @return The full real host of the user
378 virtual const std::string& GetFullRealHost();
380 /** This clears any cached results that are used for GetFullRealHost() etc.
381 * The results of these calls are cached as generating them can be generally expensive.
383 void InvalidateCache();
385 /** Returns whether this user is currently away or not. If true,
386 * further information can be found in User::awaymsg and User::awaytime
387 * @return True if the user is away, false otherwise
389 bool IsAway() const { return (!awaymsg.empty()); }
391 /** Returns whether this user is an oper or not. If true,
392 * oper information can be obtained from User::oper
393 * @return True if the user is an oper, false otherwise
395 bool IsOper() const { return oper; }
397 /** Returns true if a notice mask is set
398 * @param sm A notice mask character to check
399 * @return True if the notice mask is set
401 bool IsNoticeMaskSet(unsigned char sm);
403 /** Create a displayable mode string for this users umodes
404 * @param showparameters The mode string
406 const char* FormatModes(bool showparameters = false);
408 /** Returns true if a specific mode is set
409 * @param m The user mode
410 * @return True if the mode is set
412 bool IsModeSet(unsigned char m);
413 bool IsModeSet(ModeHandler* mh);
414 bool IsModeSet(ModeHandler& mh) { return IsModeSet(&mh); }
415 bool IsModeSet(UserModeReference& moderef);
417 /** Set a specific usermode to on or off
418 * @param m The user mode
419 * @param value On or off setting of the mode
421 void SetMode(ModeHandler* mh, bool value);
422 void SetMode(ModeHandler& mh, bool value) { SetMode(&mh, value); }
424 /** Returns true or false for if a user can execute a privilaged oper command.
425 * This is done by looking up their oper type from User::oper, then referencing
426 * this to their oper classes and checking the commands they can execute.
427 * @param command A command (should be all CAPS)
428 * @return True if this user can execute the command
430 virtual bool HasPermission(const std::string &command);
432 /** Returns true if a user has a given permission.
433 * This is used to check whether or not users may perform certain actions which admins may not wish to give to
434 * all operators, yet are not commands. An example might be oper override, mass messaging (/notice $*), etc.
436 * @param privstr The priv to chec, e.g. "users/override/topic". These are loaded free-form from the config file.
437 * @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.
438 * @return True if this user has the permission in question.
440 virtual bool HasPrivPermission(const std::string &privstr, bool noisy = false);
442 /** Returns true or false if a user can set a privileged user or channel mode.
443 * This is done by looking up their oper type from User::oper, then referencing
444 * this to their oper classes, and checking the modes they can set.
445 * @param mode The mode the check
446 * @param type ModeType (MODETYPE_CHANNEL or MODETYPE_USER).
447 * @return True if the user can set or unset this mode.
449 virtual bool HasModePermission(unsigned char mode, ModeType type);
451 /** Creates a usermask with real host.
452 * Takes a buffer to use and fills the given buffer with the hostmask in the format user\@host
453 * @return the usermask in the format user\@host
455 const std::string& MakeHost();
457 /** Creates a usermask with real ip.
458 * Takes a buffer to use and fills the given buffer with the ipmask in the format user\@ip
459 * @return the usermask in the format user\@ip
461 const std::string& MakeHostIP();
463 /** Oper up the user using the given opertype.
464 * This will also give the +o usermode.
466 void Oper(OperInfo* info);
469 * This will clear the +o usermode and unset the user's oper type
473 /** Write text to this user, appending CR/LF. Works on local users only.
474 * @param text A std::string to send to the user
476 virtual void Write(const std::string &text);
478 /** Write text to this user, appending CR/LF.
479 * Works on local users only.
480 * @param text The format string for text to send to the user
481 * @param ... POD-type format arguments
483 virtual void Write(const char *text, ...) CUSTOM_PRINTF(2, 3);
485 /** Write text to this user, appending CR/LF and prepending :server.name
486 * Works on local users only.
487 * @param text A std::string to send to the user
489 void WriteServ(const std::string& text);
491 /** Write text to this user, appending CR/LF and prepending :server.name
492 * Works on local users only.
493 * @param text The format string for text to send to the user
494 * @param ... POD-type format arguments
496 void WriteServ(const char* text, ...) CUSTOM_PRINTF(2, 3);
498 /** Sends a command to this user.
499 * @param command The command to be sent.
500 * @param text The message to send.
502 void WriteCommand(const char* command, const std::string& text);
504 /** Sends a server notice to this user.
505 * @param text The contents of the message to send.
507 void WriteNotice(const std::string& text) { this->WriteCommand("NOTICE", ":" + text); }
509 void WriteNumeric(unsigned int numeric, const char* text, ...) CUSTOM_PRINTF(3, 4);
511 void WriteNumeric(unsigned int numeric, const std::string &text);
513 /** Write text to this user, appending CR/LF and prepending :nick!user\@host of the user provided in the first parameter.
514 * @param user The user to prepend the :nick!user\@host of
515 * @param text A std::string to send to the user
517 void WriteFrom(User *user, const std::string &text);
519 /** Write text to this user, appending CR/LF and prepending :nick!user\@host of the user provided in the first parameter.
520 * @param user The user to prepend the :nick!user\@host of
521 * @param text The format string for text to send to the user
522 * @param ... POD-type format arguments
524 void WriteFrom(User *user, const char* text, ...) CUSTOM_PRINTF(3, 4);
526 /** Write to all users that can see this user (including this user in the list if include_self is true), appending CR/LF
527 * @param line A std::string to send to the users
528 * @param include_self Should the message be sent back to the author?
530 void WriteCommonRaw(const std::string &line, bool include_self = true);
532 /** Write to all users that can see this user (including this user in the list), appending CR/LF
533 * @param text The format string for text to send to the users
534 * @param ... POD-type format arguments
536 void WriteCommon(const char* text, ...) CUSTOM_PRINTF(2, 3);
538 /** Write a quit message to all common users, as in User::WriteCommonExcept but with a specific
539 * quit message for opers only.
540 * @param normal_text Normal user quit message
541 * @param oper_text Oper only quit message
543 void WriteCommonQuit(const std::string &normal_text, const std::string &oper_text);
545 /** Dump text to a user target, splitting it appropriately to fit
546 * @param linePrefix text to prefix each complete line with
547 * @param textStream the text to send to the user
549 void SendText(const std::string& linePrefix, std::stringstream& textStream);
551 /** Write to the user, routing the line if the user is remote.
553 virtual void SendText(const std::string& line) = 0;
555 /** Write to the user, routing the line if the user is remote.
557 void SendText(const char* text, ...) CUSTOM_PRINTF(2, 3);
559 /** Return true if the user shares at least one channel with another user
560 * @param other The other user to compare the channel list against
561 * @return True if the given user shares at least one channel with this user
563 bool SharesChannelWith(User *other);
565 /** Change the displayed host of a user.
566 * ALWAYS use this function, rather than writing User::dhost directly,
567 * as this triggers module events allowing the change to be syncronized to
569 * @param host The new hostname to set
570 * @return True if the change succeeded, false if it didn't
571 * (a module vetoed the change).
573 bool ChangeDisplayedHost(const std::string& host);
575 /** Change the ident (username) of a user.
576 * ALWAYS use this function, rather than writing User::ident directly,
577 * as this triggers module events allowing the change to be syncronized to
579 * @param newident The new ident to set
580 * @return True if the change succeeded, false if it didn't
582 bool ChangeIdent(const std::string& newident);
584 /** Change a users realname field.
585 * ALWAYS use this function, rather than writing User::fullname directly,
586 * as this triggers module events allowing the change to be syncronized to
588 * @param gecos The user's new realname
589 * @return True if the change succeeded, false if otherwise
591 bool ChangeName(const std::string& gecos);
593 /** Change a user's nick
594 * @param newnick The new nick. If equal to the users uuid, the nick change always succeeds.
595 * @return True if the change succeeded
597 bool ChangeNick(const std::string& newnick, time_t newts = 0);
599 /** Remove this user from all channels they are on, and delete any that are now empty.
600 * This is used by QUIT, and will not send part messages!
602 void PurgeEmptyChannels();
604 /** Default destructor
607 virtual CullResult cull();
610 class CoreExport UserIOHandler : public StreamSocket
613 LocalUser* const user;
614 UserIOHandler(LocalUser* me) : user(me) {}
616 void OnError(BufferedSocketError error);
618 /** Adds to the user's write buffer.
619 * You may add any amount of text up to this users sendq value, if you exceed the
620 * sendq value, the user will be removed, and further buffer adds will be dropped.
621 * @param data The data to add to the write buffer
623 void AddWriteBuf(const std::string &data);
626 typedef unsigned int already_sent_t;
628 class CoreExport LocalUser : public User, public InviteBase<LocalUser>, public insp::intrusive_list_node<LocalUser>
631 LocalUser(int fd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server);
636 /** Stats counter for bytes inbound
638 unsigned int bytes_in;
640 /** Stats counter for bytes outbound
642 unsigned int bytes_out;
644 /** Stats counter for commands inbound
646 unsigned int cmds_in;
648 /** Stats counter for commands outbound
650 unsigned int cmds_out;
652 /** Password specified by the user when they registered (if any).
653 * This is stored even if the \<connect> block doesnt need a password, so that
654 * modules may check it.
656 std::string password;
658 /** Contains a pointer to the connect class a user is on from
660 reference<ConnectClass> MyClass;
662 /** Get the connect class which this user belongs to.
663 * @return A pointer to this user's connect class.
665 ConnectClass* GetClass() const { return MyClass; }
667 /** Call this method to find the matching \<connect> for a user, and to check them against it.
669 void CheckClass(bool clone_count = true);
671 /** Server address and port that this user is connected to.
673 irc::sockets::sockaddrs server_sa;
676 * @return The port number of this user.
680 /** Recursion fix: user is out of SendQ and will be quit as soon as possible.
681 * This can't be handled normally because QuitUser itself calls Write on other
682 * users, which could trigger their SendQ to overrun.
684 unsigned int quitting_sendq:1;
686 /** has the user responded to their previous ping?
688 unsigned int lastping:1;
690 /** This is true if the user matched an exception (E:Line). It is used to save time on ban checks.
692 unsigned int exempt:1;
694 /** Used by PING checking code
698 /** Time that the connection last sent a message, used to calculate idle time
702 /** This value contains how far into the penalty threshold the user is.
703 * This is used either to enable fake lag or for excess flood quits
705 unsigned int CommandFloodPenalty;
707 static already_sent_t already_sent_id;
708 already_sent_t already_sent;
710 /** Check if the user matches a G or K line, and disconnect them if they do.
711 * @param doZline True if ZLines should be checked (if IP has changed since initial connect)
712 * Returns true if the user matched a ban, false else.
714 bool CheckLines(bool doZline = false);
716 /** Use this method to fully connect a user.
717 * This will send the message of the day, check G/K/E lines, etc.
721 /** Set the connect class to which this user belongs to.
722 * @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.
723 * @return A reference to this user's current connect class.
725 void SetClass(const std::string &explicit_name = "");
727 bool SetClientIP(const char* sip, bool recheck_eline = true);
729 void SetClientIP(const irc::sockets::sockaddrs& sa, bool recheck_eline = true);
731 void SendText(const std::string& line);
732 void Write(const std::string& text);
733 void Write(const char*, ...) CUSTOM_PRINTF(2, 3);
735 /** Returns the list of channels this user has been invited to but has not yet joined.
736 * @return A list of channels the user is invited to
738 InviteList& GetInviteList();
740 /** Returns true if a user is invited to a channel.
741 * @param chan A channel to look up
742 * @return True if the user is invited to the given channel
744 bool IsInvited(Channel* chan) { return (Invitation::Find(chan, this) != NULL); }
746 /** Removes a channel from a users invite list.
747 * This member function is called on successfully joining an invite only channel
748 * to which the user has previously been invited, to clear the invitation.
749 * @param chan The channel to remove the invite to
750 * @return True if the user was invited to the channel and the invite was erased, false if the user wasn't invited
752 bool RemoveInvite(Channel* chan);
754 void RemoveExpiredInvites();
756 /** Returns true or false for if a user can execute a privilaged oper command.
757 * This is done by looking up their oper type from User::oper, then referencing
758 * this to their oper classes and checking the commands they can execute.
759 * @param command A command (should be all CAPS)
760 * @return True if this user can execute the command
762 bool HasPermission(const std::string &command);
764 /** Returns true if a user has a given permission.
765 * This is used to check whether or not users may perform certain actions which admins may not wish to give to
766 * all operators, yet are not commands. An example might be oper override, mass messaging (/notice $*), etc.
768 * @param privstr The priv to chec, e.g. "users/override/topic". These are loaded free-form from the config file.
769 * @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.
770 * @return True if this user has the permission in question.
772 bool HasPrivPermission(const std::string &privstr, bool noisy = false);
774 /** Returns true or false if a user can set a privileged user or channel mode.
775 * This is done by looking up their oper type from User::oper, then referencing
776 * this to their oper classes, and checking the modes they can set.
777 * @param mode The mode the check
778 * @param type ModeType (MODETYPE_CHANNEL or MODETYPE_USER).
779 * @return True if the user can set or unset this mode.
781 bool HasModePermission(unsigned char mode, ModeType type);
784 class CoreExport RemoteUser : public User
787 RemoteUser(const std::string& uid, Server* srv) : User(uid, srv, USERTYPE_REMOTE)
790 virtual void SendText(const std::string& line);
793 class CoreExport FakeUser : public User
796 FakeUser(const std::string& uid, Server* srv) : User(uid, srv, USERTYPE_SERVER)
798 nick = srv->GetName();
801 FakeUser(const std::string& uid, const std::string& sname, const std::string& sdesc)
802 : User(uid, new Server(sname, sdesc), USERTYPE_SERVER)
807 virtual CullResult cull();
808 virtual void SendText(const std::string& line);
809 virtual const std::string& GetFullHost();
810 virtual const std::string& GetFullRealHost();
813 /* Faster than dynamic_cast */
814 /** Is a local user */
815 inline LocalUser* IS_LOCAL(User* u)
817 return u->usertype == USERTYPE_LOCAL ? static_cast<LocalUser*>(u) : NULL;
819 /** Is a remote user */
820 inline RemoteUser* IS_REMOTE(User* u)
822 return u->usertype == USERTYPE_REMOTE ? static_cast<RemoteUser*>(u) : NULL;
824 /** Is a server fakeuser */
825 inline FakeUser* IS_SERVER(User* u)
827 return u->usertype == USERTYPE_SERVER ? static_cast<FakeUser*>(u) : NULL;
830 inline bool User::IsModeSet(ModeHandler* mh)
832 return (modes[mh->GetId()]);
835 inline bool User::IsModeSet(UserModeReference& moderef)
839 return IsModeSet(*moderef);
842 inline void User::SetMode(ModeHandler* mh, bool value)
844 modes[mh->GetId()] = value;