1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
21 #include "inspircd_config.h"
24 #include "inspstring.h"
25 #include "connection.h"
28 #include "cull_list.h"
42 /** RFC1459 channel modes
45 UM_SERVERNOTICE = 's'-65,
47 UM_INVISIBLE = 'i'-65,
52 enum RegistrationState {
53 REG_NONE = 0, /* Has sent nothing */
54 REG_USER = 1, /* Has sent USER */
55 REG_NICK = 2, /* Has sent NICK */
56 REG_NICKUSER = 3, /* Bitwise combination of REG_NICK and REG_USER */
57 REG_ALL = 7 /* REG_NICKUSER plus next bit along */
62 /** Derived from Resolver, and performs user forward/reverse lookups.
64 class UserResolver : public Resolver
67 /** User this class is 'attached' to.
73 UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, QueryType qt);
75 void OnLookupComplete(const std::string &result);
76 void OnError(ResolverError e, const std::string &errormessage);
80 /** Holds information relevent to <connect allow> and <connect deny> tags in the config file.
82 class ConnectClass : public classbase
85 /** Type of line, either CC_ALLOW or CC_DENY
88 /** Max time to register the connection in seconds
90 int registration_timeout;
91 /** Number of lines in buffer before excess flood is triggered
94 /** Host mask for this line
97 /** Number of seconds between pings for this line
100 /** (Optional) Password for this line
104 /** Threshold value for flood disconnect
108 /** Maximum size of sendq for users in this class (bytes)
112 /** Maximum size of recvq for users in this class (bytes)
116 /** Local max when connecting by this connection class
120 /** Global max when connecting by this connection class
124 ConnectClass() : registration_timeout(0), flood(0), host(""), pingtime(0), pass(""), threshold(0), sendqmax(0), recvqmax(0)
129 /** Holds a complete list of all channels to which a user has been invited and has not yet joined.
131 typedef std::vector<irc::string> InvitedList;
133 /** Holds a complete list of all allow and deny tags from the configuration file (connection classes)
135 typedef std::vector<ConnectClass> ClassVector;
137 /** Typedef for the list of user-channel records for a user
139 typedef std::map<chanrec*, char> UserChanList;
140 typedef UserChanList::iterator UCListIter;
142 /** Holds all information about a user
143 * This class stores all information about a user connected to the irc server. Everything about a
144 * connection is stored here primarily, from the user's socket ID (file descriptor) through to the
145 * user's nickname and hostname. Use the FindNick method of the InspIRCd class to locate a specific user
146 * by nickname, or the FindDescriptor method of the InspIRCd class to find a specific user by their
147 * file descriptor value.
149 class userrec : public connection
152 /** Pointer to creator.
153 * This is required to make use of core functions
154 * from within the userrec class.
156 InspIRCd* ServerInstance;
158 /** A list of channels the user has a pending invite to.
159 * Upon INVITE channels are added, and upon JOIN, the
160 * channels are removed from this list.
164 /** Number of channels this user is currently on
166 unsigned int ChannelCount;
168 /** Resolvers for looking up this users IP address
169 * This will occur if and when res_reverse completes.
170 * When this class completes its lookup, userrec::dns_done
171 * will be set from false to true.
173 UserResolver* res_forward;
175 /** Resolvers for looking up this users hostname
176 * This is instantiated by userrec::StartDNSLookup(),
177 * and on success, instantiates userrec::res_reverse.
179 UserResolver* res_reverse;
181 /** Stored reverse lookup from res_forward
183 std::string stored_host;
185 /** Starts a DNS lookup of the user's IP.
186 * This will cause two UserResolver classes to be instantiated.
187 * When complete, these objects set userrec::dns_done to true.
189 void StartDNSLookup();
191 /** The users nickname.
192 * An invalid nickname indicates an unregistered connection prior to the NICK command.
193 * Use InspIRCd::IsNick() to validate nicknames.
197 /** The users ident reply.
198 * Two characters are added to the user-defined limit to compensate for the tilde etc.
200 char ident[IDENTMAX+2];
202 /** The host displayed to non-opers (used for cloaking etc).
203 * This usually matches the value of userrec::host.
207 /** The users full name (GECOS).
209 char fullname[MAXGECOS+1];
211 /** The user's mode list.
212 * This is NOT a null terminated string! In the 1.1 version of InspIRCd
213 * this is an array of values in a similar way to channel modes.
214 * A value of 1 in field (modeletter-65) indicates that the mode is
215 * set, for example, to work out if mode +s is set, we check the field
216 * userrec::modes['s'-65] != 0.
217 * The following RFC characters o, w, s, i have constants defined via an
218 * enum, such as UM_SERVERNOTICE and UM_OPETATOR.
222 /** What snomasks are set on this user.
223 * This functions the same as the above modes.
227 /** Channels this user is on, and the permissions they have there
231 /** The server the user is connected to.
235 /** The user's away message.
236 * If this string is empty, the user is not marked as away.
238 char awaymsg[MAXAWAY+1];
240 /** Number of lines the user can place into the buffer
241 * (up to the global NetBufferSize bytes) before they
242 * are disconnected for excess flood
246 /** Number of seconds this user is given to send USER/NICK
247 * If they do not send their details in this time limit they
248 * will be disconnected
250 unsigned int timeout;
252 /** The oper type they logged in as, if they are an oper.
253 * This is used to check permissions in operclasses, so that
254 * we can say 'yay' or 'nay' to any commands they issue.
255 * The value of this is the value of a valid 'type name=' tag.
259 /** True when DNS lookups are completed.
260 * The UserResolver classes res_forward and res_reverse will
261 * set this value once they complete.
265 /** Number of seconds between PINGs for this user (set from <connect:allow> tag
267 unsigned int pingmax;
269 /** Password specified by the user when they registered.
270 * This is stored even if the <connect> block doesnt need a password, so that
271 * modules may check it.
275 /** User's receive queue.
276 * Lines from the IRCd awaiting processing are stored here.
277 * Upgraded april 2005, old system a bit hairy.
281 /** User's send queue.
282 * Lines waiting to be sent are stored here until their buffer is flushed.
286 /** Flood counters - lines received
290 /** Flood counters - time lines_in is due to be reset
294 /** Flood counters - Highest value lines_in may reach before the user gets disconnected
298 /** IPV4 or IPV6 ip address
302 /** Initialize the clients sockaddr
303 * @param protocol_family The protocol family of the IP address, AF_INET or AF_INET6
304 * @param ip A human-readable IP address for this user matching the protcol_family
305 * @param port The port number of this user or zero for a remote user
307 void SetSockAddr(int protocol_family, const char* ip, int port);
309 /** Get port number from sockaddr
310 * @return The port number of this user.
314 /** Get protocol family from sockaddr
315 * @return The protocol family of this user, either AF_INET or AF_INET6
317 int GetProtocolFamily();
319 /** Get IP string from sockaddr, using static internal buffer
320 * @return The IP string
322 const char* GetIPString();
324 /** Get IP string from sockaddr, using caller-specified buffer
325 * @param buf A buffer to use
326 * @return The IP string
328 const char* GetIPString(char* buf);
330 /* Write error string
332 std::string WriteError;
334 /** Maximum size this user's sendq can become
338 /** Maximum size this user's recvq can become
342 /** This is true if the user matched an exception when they connected to the ircd.
343 * It isnt valid after this point, and you should not attempt to do anything with it
344 * after this point, because the eline might be removed at a later time, and/or no
345 * longer be applicable to this user. It is only used to save doing the eline lookup
346 * twice (instead we do it once and set this value).
350 /** Default constructor
351 * @throw Nothing at present
353 userrec(InspIRCd* Instance);
355 /** Returns the full displayed host of the user
356 * This member function returns the hostname of the user as seen by other users
357 * on the server, in nick!ident&at;host form.
358 * @return The full masked host of the user
360 virtual char* GetFullHost();
362 /** Returns the full real host of the user
363 * This member function returns the hostname of the user as seen by other users
364 * on the server, in nick!ident&at;host form. If any form of hostname cloaking is in operation,
365 * e.g. through a module, then this method will ignore it and return the true hostname.
366 * @return The full real host of the user
368 virtual char* GetFullRealHost();
370 /** Create a displayable mode string for this users snomasks
371 * @return The notice mask character sequence
373 const char* FormatNoticeMasks();
375 /** Process a snomask modifier string, e.g. +abc-de
376 * @param sm A sequence of notice mask characters
377 * @return The cleaned mode sequence which can be output,
378 * e.g. in the above example if masks c and e are not
379 * valid, this function will return +ab-d
381 std::string ProcessNoticeMasks(const char *sm);
383 /** Returns true if a notice mask is set
384 * @param sm A notice mask character to check
385 * @return True if the notice mask is set
387 bool IsNoticeMaskSet(unsigned char sm);
389 /** Changed a specific notice mask value
390 * @param sm The server notice mask to change
391 * @param value An on/off value for this mask
393 void SetNoticeMask(unsigned char sm, bool value);
395 /** Create a displayable mode string for this users umodes
396 * @param The mode string
398 const char* FormatModes();
400 /** Returns true if a specific mode is set
401 * @param m The user mode
402 * @return True if the mode is set
404 bool IsModeSet(unsigned char m);
406 /** Set a specific usermode to on or off
407 * @param m The user mode
408 * @param value On or off setting of the mode
410 void SetMode(unsigned char m, bool value);
412 /** Returns true if a user is invited to a channel.
413 * @param channel A channel name to look up
414 * @return True if the user is invited to the given channel
416 virtual bool IsInvited(const irc::string &channel);
418 /** Adds a channel to a users invite list (invites them to a channel)
419 * @param channel A channel name to add
421 virtual void InviteTo(const irc::string &channel);
423 /** Removes a channel from a users invite list.
424 * This member function is called on successfully joining an invite only channel
425 * to which the user has previously been invited, to clear the invitation.
426 * @param channel The channel to remove the invite to
428 virtual void RemoveInvite(const irc::string &channel);
430 /** Returns true or false for if a user can execute a privilaged oper command.
431 * This is done by looking up their oper type from userrec::oper, then referencing
432 * this to their oper classes and checking the commands they can execute.
433 * @param command A command (should be all CAPS)
434 * @return True if this user can execute the command
436 bool HasPermission(const std::string &command);
438 /** Calls read() to read some data for this user using their fd.
439 * @param buffer The buffer to read into
440 * @param size The size of data to read
441 * @return The number of bytes read, or -1 if an error occured.
443 int ReadData(void* buffer, size_t size);
445 /** This method adds data to the read buffer of the user.
446 * The buffer can grow to any size within limits of the available memory,
447 * managed by the size of a std::string, however if any individual line in
448 * the buffer grows over 600 bytes in length (which is 88 chars over the
449 * RFC-specified limit per line) then the method will return false and the
450 * text will not be inserted.
451 * @param a The string to add to the users read buffer
452 * @return True if the string was successfully added to the read buffer
454 bool AddBuffer(std::string a);
456 /** This method returns true if the buffer contains at least one carriage return
457 * character (e.g. one complete line may be read)
458 * @return True if there is at least one complete line in the users buffer
460 bool BufferIsReady();
462 /** This function clears the entire buffer by setting it to an empty string.
466 /** This method returns the first available string at the tail end of the buffer
467 * and advances the tail end of the buffer past the string. This means it is
468 * a one way operation in a similar way to strtok(), and multiple calls return
469 * multiple lines if they are available. The results of this function if there
470 * are no lines to be read are unknown, always use BufferIsReady() to check if
471 * it is ok to read the buffer before calling GetBuffer().
472 * @return The string at the tail end of this users buffer
474 std::string GetBuffer();
476 /** Sets the write error for a connection. This is done because the actual disconnect
477 * of a client may occur at an inopportune time such as half way through /LIST output.
478 * The WriteErrors of clients are checked at a more ideal time (in the mainloop) and
479 * errored clients purged.
480 * @param error The error string to set.
482 void SetWriteError(const std::string &error);
484 /** Returns the write error which last occured on this connection or an empty string
486 * @return The error string which has occured for this user
488 const char* GetWriteError();
490 /** Adds to the user's write buffer.
491 * You may add any amount of text up to this users sendq value, if you exceed the
492 * sendq value, SetWriteError() will be called to set the users error string to
493 * "SendQ exceeded", and further buffer adds will be dropped.
494 * @param data The data to add to the write buffer
496 void AddWriteBuf(const std::string &data);
498 /** Flushes as much of the user's buffer to the file descriptor as possible.
499 * This function may not always flush the entire buffer, rather instead as much of it
500 * as it possibly can. If the send() call fails to send the entire buffer, the buffer
501 * position is advanced forwards and the rest of the data sent at the next call to
504 void FlushWriteBuf();
506 /** Returns the list of channels this user has been invited to but has not yet joined.
507 * @return A list of channels the user is invited to
509 InvitedList* GetInviteList();
511 /** Creates a wildcard host.
512 * Takes a buffer to use and fills the given buffer with the host in the format *!*@hostname
513 * @return The wildcarded hostname in *!*@host form
515 char* MakeWildHost();
517 /** Creates a usermask with real host.
518 * Takes a buffer to use and fills the given buffer with the hostmask in the format user@host
519 * @return the usermask in the format user@host
523 /** Creates a usermask with real ip.
524 * Takes a buffer to use and fills the given buffer with the ipmask in the format user@ip
525 * @return the usermask in the format user@ip
529 /** Shuts down and closes the user's socket
530 * This will not cause the user to be deleted. Use InspIRCd::QuitUser for this,
531 * which will call CloseSocket() for you.
535 /** Disconnect a user gracefully
536 * @param user The user to remove
537 * @param r The quit reason
538 * @return Although this function has no return type, on exit the user provided will no longer exist.
540 static void QuitUser(InspIRCd* Instance, userrec *user, const std::string &r);
542 /** Add the user to WHOWAS system
546 /** Oper up the user using the given opertype.
547 * This will also give the +o usermode.
548 * @param opertype The oper type to oper as
550 void Oper(const std::string &opertype);
552 /** Use this method to fully connect a user.
553 * This will send the message of the day, check G/K/E lines, etc.
554 * @param Goners If the user is disconnected by this method call, the
555 * value of 'this' will be pushed onto this CullList. This is used by
556 * the core to connect many users in rapid succession without invalidating
558 * @param Goners a CullList to use for failed connections
560 void FullConnect(CullList* Goners);
562 /** Change this users hash key to a new string.
563 * You should not call this function directly. It is used by the core
564 * to update the users hash entry on a nickchange.
565 * @param New new user_hash key
566 * @return Pointer to userrec in hash (usually 'this')
568 userrec* UpdateNickHash(const char* New);
570 /** Force a nickname change.
571 * If the nickname change fails (for example, because the nick in question
572 * already exists) this function will return false, and you must then either
573 * output an error message, or quit the user for nickname collision.
574 * @param newnick The nickname to change to
575 * @return True if the nickchange was successful.
577 bool ForceNickChange(const char* newnick);
579 /** Add a client to the system.
580 * This will create a new userrec, insert it into the user_hash,
581 * initialize it as not yet registered, and add it to the socket engine.
582 * @param Instance a pointer to the server instance
583 * @param socket The socket id (file descriptor) this user is on
584 * @param port The port number this user connected on
585 * @param iscached This variable is reserved for future use
586 * @param ip The IP address of the user
587 * @return This function has no return value, but a call to AddClient may remove the user.
589 static void AddClient(InspIRCd* Instance, int socket, int port, bool iscached, insp_inaddr ip);
592 * This will clear the +o usermode and unset the user's oper type
596 /** Return the number of global clones of this user
597 * @return The global clone count of this user
599 long GlobalCloneCount();
601 /** Return the number of local clones of this user
602 * @return The local clone count of this user
604 long LocalCloneCount();
606 /** Write text to this user, appending CR/LF.
607 * @param text A std::string to send to the user
609 void Write(std::string text);
611 /** Write text to this user, appending CR/LF.
612 * @param text The format string for text to send to the user
613 * @param ... POD-type format arguments
615 void Write(const char *text, ...);
617 /** Write text to this user, appending CR/LF and prepending :server.name
618 * @param text A std::string to send to the user
620 void WriteServ(const std::string& text);
622 /** Write text to this user, appending CR/LF and prepending :server.name
623 * @param text The format string for text to send to the user
624 * @param ... POD-type format arguments
626 void WriteServ(const char* text, ...);
628 /** Write text to this user, appending CR/LF and prepending :nick!user@host of the user provided in the first parameter.
629 * @param user The user to prepend the :nick!user@host of
630 * @param text A std::string to send to the user
632 void WriteFrom(userrec *user, const std::string &text);
634 /** Write text to this user, appending CR/LF and prepending :nick!user@host of the user provided in the first parameter.
635 * @param user The user to prepend the :nick!user@host of
636 * @param text The format string for text to send to the user
637 * @param ... POD-type format arguments
639 void WriteFrom(userrec *user, const char* text, ...);
641 /** Write text to the user provided in the first parameter, appending CR/LF, and prepending THIS user's :nick!user@host.
642 * @param dest The user to route the message to
643 * @param text A std::string to send to the user
645 void WriteTo(userrec *dest, const std::string &data);
647 /** Write text to the user provided in the first parameter, appending CR/LF, and prepending THIS user's :nick!user@host.
648 * @param dest The user to route the message to
649 * @param text The format string for text to send to the user
650 * @param ... POD-type format arguments
652 void WriteTo(userrec *dest, const char *data, ...);
654 /** Write to all users that can see this user (including this user in the list), appending CR/LF
655 * @param text A std::string to send to the users
657 void WriteCommon(const std::string &text);
659 /** Write to all users that can see this user (including this user in the list), appending CR/LF
660 * @param text The format string for text to send to the users
661 * @param ... POD-type format arguments
663 void WriteCommon(const char* text, ...);
665 /** Write to all users that can see this user (not including this user in the list), appending CR/LF
666 * @param text The format string for text to send to the users
667 * @param ... POD-type format arguments
669 void WriteCommonExcept(const char* text, ...);
671 /** Write to all users that can see this user (not including this user in the list), appending CR/LF
672 * @param text A std::string to send to the users
674 void WriteCommonExcept(const std::string &text);
676 /** Write a WALLOPS message from this user to all local opers.
677 * If this user is not opered, the function will return without doing anything.
678 * @param text The format string to send in the WALLOPS message
679 * @param ... Format arguments
681 void WriteWallOps(const char* text, ...);
683 /** Write a WALLOPS message from this user to all local opers.
684 * If this user is not opered, the function will return without doing anything.
685 * @param text The text to send in the WALLOPS message
687 void WriteWallOps(const std::string &text);
689 /** Return true if the user shares at least one channel with another user
690 * @param other The other user to compare the channel list against
691 * @return True if the given user shares at least one channel with this user
693 bool SharesChannelWith(userrec *other);
695 /** Change the displayed host of a user.
696 * ALWAYS use this function, rather than writing userrec::dhost directly,
697 * as this triggers module events allowing the change to be syncronized to
698 * remote servers. This will also emulate a QUIT and rejoin (where configured)
699 * before setting their host field.
700 * @param host The new hostname to set
701 * @return True if the change succeeded, false if it didn't
703 bool ChangeDisplayedHost(const char* host);
705 /** Change the ident (username) of a user.
706 * ALWAYS use this function, rather than writing userrec::ident directly,
707 * as this correctly causes the user to seem to quit (where configured)
708 * before setting their ident field.
709 * @param host The new ident to set
710 * @return True if the change succeeded, false if it didn't
712 bool ChangeIdent(const char* newident);
714 /** Change a users realname field.
715 * ALWAYS use this function, rather than writing userrec::fullname directly,
716 * as this triggers module events allowing the change to be syncronized to
718 * @param gecos The user's new realname
719 * @return True if the change succeeded, false if otherwise
721 bool ChangeName(const char* gecos);
723 /** Send a notice to all local users from this user
724 * @param text The text format string to send
725 * @param ... Format arguments
727 void NoticeAll(char* text, ...);
729 /** Compile a channel list for this user, and send it to the user 'source'
730 * Used internally by WHOIS
731 * @param The user to send the channel list to if it is not too long
732 * @return This user's channel list
734 std::string ChannelList(userrec* source);
736 /** Split the channel list in cl which came from dest, and spool it to this user
737 * Used internally by WHOIS
738 * @param dest The user the original channel list came from
739 * @param cl The channel list as a string obtained from userrec::ChannelList()
741 void SplitChanList(userrec* dest, const std::string &cl);
743 /** Remove this user from all channels they are on, and delete any that are now empty.
744 * This is used by QUIT, and will not send part messages!
746 void PurgeEmptyChannels();
748 /** Get the connect class which matches this user's host or IP address
749 * @return A reference to this user's connect class
751 ConnectClass& GetClass();
753 /** Show the message of the day to this user
757 /** Show the server RULES file to this user
761 /** Handle socket event.
762 * From EventHandler class.
764 void HandleEvent(EventType et, int errornum = 0);
766 /** Default destructor
774 /** Holds whowas related functions and classes
779 /** Used to hold WHOWAS information
781 class WhoWasGroup : public classbase
803 /** Initialize this WhoQasFroup with a user
805 WhoWasGroup(userrec* user);
811 /** A group of users related by nickname
813 typedef std::deque<WhoWasGroup*> whowas_set;
815 /** Sets of users in the whowas system
817 typedef std::map<irc::string,whowas_set*> whowas_users;
819 /** Sets of time and users in whowas list
821 typedef std::map<time_t,irc::string> whowas_users_fifo;
823 /** Called every hour by the core to remove expired entries
825 void MaintainWhoWas(InspIRCd* ServerInstance, time_t TIME);
827 /** Prune for WhoWasGroupSize, WhoWasMaxGroups and
828 * WhoWasMaxKeep on rehash
830 void PruneWhoWas(InspIRCd* ServerInstance, time_t TIME);
834 /* Configuration callbacks */