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,
51 enum RegistrationState {
52 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 /** Holds a channel name to which a user has been invited.
61 class Invited : public classbase
71 /** Derived from Resolver, and performs user forward/reverse lookups.
73 class UserResolver : public Resolver
76 /** User this class is 'attached' to.
82 UserResolver(InspIRCd* Instance, userrec* user, std::string to_resolve, bool forward);
84 void OnLookupComplete(const std::string &result);
85 void OnError(ResolverError e, const std::string &errormessage);
89 /** Holds information relevent to <connect allow> and <connect deny> tags in the config file.
91 class ConnectClass : public classbase
94 /** Type of line, either CC_ALLOW or CC_DENY
97 /** Max time to register the connection in seconds
99 int registration_timeout;
100 /** Number of lines in buffer before excess flood is triggered
103 /** Host mask for this line
106 /** Number of seconds between pings for this line
109 /** (Optional) Password for this line
113 /** Threshold value for flood disconnect
117 /** Maximum size of sendq for users in this class (bytes)
121 /** Maximum size of recvq for users in this class (bytes)
125 /** Local max when connecting by this connection class
129 /** Global max when connecting by this connection class
133 ConnectClass() : registration_timeout(0), flood(0), host(""), pingtime(0), pass(""), threshold(0), sendqmax(0), recvqmax(0)
138 /** Holds a complete list of all channels to which a user has been invited and has not yet joined.
140 typedef std::vector<Invited> InvitedList;
144 /** Holds a complete list of all allow and deny tags from the configuration file (connection classes)
146 typedef std::vector<ConnectClass> ClassVector;
148 /** Typedef for the list of user-channel records for a user
150 typedef std::vector<ucrec*> UserChanList;
152 /** Holds all information about a user
153 * This class stores all information about a user connected to the irc server. Everything about a
154 * connection is stored here primarily, from the user's socket ID (file descriptor) through to the
155 * user's nickname and hostname. Use the FindNick method of the InspIRCd class to locate a specific user
156 * by nickname, or the FindDescriptor method of the InspIRCd class to find a specific user by their
157 * file descriptor value.
159 class userrec : public connection
162 /** Pointer to creator.
163 * This is required to make use of core functions
164 * from within the userrec class.
166 InspIRCd* ServerInstance;
168 /** A list of channels the user has a pending invite to.
169 * Upon INVITE channels are added, and upon JOIN, the
170 * channels are removed from this list.
174 /** Resolvers for looking up this users IP address
175 * This will occur if and when res_reverse completes.
176 * When this class completes its lookup, userrec::dns_done
177 * will be set from false to true.
179 UserResolver* res_forward;
181 /** Resolvers for looking up this users hostname
182 * This is instantiated by userrec::StartDNSLookup(),
183 * and on success, instantiates userrec::res_reverse.
185 UserResolver* res_reverse;
187 /** Stored reverse lookup from res_forward
189 std::string stored_host;
191 /** Starts a DNS lookup of the user's IP.
192 * This will cause two UserResolver classes to be instantiated.
193 * When complete, these objects set userrec::dns_done to true.
195 void StartDNSLookup();
197 /** The users nickname.
198 * An invalid nickname indicates an unregistered connection prior to the NICK command.
199 * Use InspIRCd::IsNick() to validate nicknames.
203 /** The users ident reply.
204 * Two characters are added to the user-defined limit to compensate for the tilde etc.
206 char ident[IDENTMAX+2];
208 /** The host displayed to non-opers (used for cloaking etc).
209 * This usually matches the value of userrec::host.
213 /** The users full name (GECOS).
215 char fullname[MAXGECOS+1];
217 /** The user's mode list.
218 * This is NOT a null terminated string! In the 1.1 version of InspIRCd
219 * this is an array of values in a similar way to channel modes.
220 * A value of 1 in field (modeletter-65) indicates that the mode is
221 * set, for example, to work out if mode +s is set, we check the field
222 * userrec::modes['s'-65] != 0.
223 * The following RFC characters o, w, s, i have constants defined via an
224 * enum, such as UM_SERVERNOTICE and UM_OPETATOR.
228 /** What snomasks are set on this user.
229 * This functions the same as the above modes.
233 /** Channels this user is on, and the permissions they have there
237 /** The server the user is connected to.
241 /** The user's away message.
242 * If this string is empty, the user is not marked as away.
244 char awaymsg[MAXAWAY+1];
246 /** Number of lines the user can place into the buffer
247 * (up to the global NetBufferSize bytes) before they
248 * are disconnected for excess flood
252 /** Number of seconds this user is given to send USER/NICK
253 * If they do not send their details in this time limit they
254 * will be disconnected
256 unsigned int timeout;
258 /** The oper type they logged in as, if they are an oper.
259 * This is used to check permissions in operclasses, so that
260 * we can say 'yay' or 'nay' to any commands they issue.
261 * The value of this is the value of a valid 'type name=' tag.
265 /** True when DNS lookups are completed.
266 * The UserResolver classes res_forward and res_reverse will
267 * set this value once they complete.
271 /** Number of seconds between PINGs for this user (set from <connect:allow> tag
273 unsigned int pingmax;
275 /** Password specified by the user when they registered.
276 * This is stored even if the <connect> block doesnt need a password, so that
277 * modules may check it.
281 /** User's receive queue.
282 * Lines from the IRCd awaiting processing are stored here.
283 * Upgraded april 2005, old system a bit hairy.
287 /** User's send queue.
288 * Lines waiting to be sent are stored here until their buffer is flushed.
292 /** Flood counters - lines received
296 /** Flood counters - time lines_in is due to be reset
300 /** Flood counters - Highest value lines_in may reach before the user gets disconnected
304 /** IPV4 or IPV6 ip address
308 /** Initialize the clients sockaddr
309 * @param protocol_family The protocol family of the IP address, AF_INET or AF_INET6
310 * @param ip A human-readable IP address for this user matching the protcol_family
311 * @param port The port number of this user or zero for a remote user
313 void SetSockAddr(int protocol_family, const char* ip, int port);
315 /** Get port number from sockaddr
316 * @return The port number of this user.
320 /** Get protocol family from sockaddr
321 * @return The protocol family of this user, either AF_INET or AF_INET6
323 int GetProtocolFamily();
325 /** Get IP string from sockaddr, using static internal buffer
326 * @return The IP string
328 const char* GetIPString();
330 /** Get IP string from sockaddr, using caller-specified buffer
331 * @param buf A buffer to use
332 * @return The IP string
334 const char* GetIPString(char* buf);
336 /* Write error string
338 std::string WriteError;
340 /** Maximum size this user's sendq can become
344 /** Maximum size this user's recvq can become
348 /** Default constructor
349 * @throw Nothing at present
351 userrec(InspIRCd* Instance);
353 /** Returns the full displayed host of the user
354 * This member function returns the hostname of the user as seen by other users
355 * on the server, in nick!ident&at;host form.
356 * @return The full masked host of the user
358 virtual char* GetFullHost();
360 /** Returns the full real host of the user
361 * This member function returns the hostname of the user as seen by other users
362 * on the server, in nick!ident&at;host form. If any form of hostname cloaking is in operation,
363 * e.g. through a module, then this method will ignore it and return the true hostname.
364 * @return The full real host of the user
366 virtual char* GetFullRealHost();
368 /** Create a displayable mode string for this users snomasks
369 * @return The notice mask character sequence
371 const char* FormatNoticeMasks();
373 /** Process a snomask modifier string, e.g. +abc-de
374 * @param sm A sequence of notice mask characters
375 * @return True if the notice masks were successfully applied
377 bool userrec::ProcessNoticeMasks(const char *sm);
379 /** Returns true if a notice mask is set
380 * @param sm A notice mask character to check
381 * @return True if the notice mask is set
383 bool IsNoticeMaskSet(unsigned char sm);
385 /** Changed a specific notice mask value
386 * @param sm The server notice mask to change
387 * @param value An on/off value for this mask
389 void SetNoticeMask(unsigned char sm, bool value);
391 /** Create a displayable mode string for this users umodes
392 * @param The mode string
394 const char* FormatModes();
396 /** Returns true if a specific mode is set
397 * @param m The user mode
398 * @return True if the mode is set
400 bool IsModeSet(unsigned char m);
402 /** Set a specific usermode to on or off
403 * @param m The user mode
404 * @param value On or off setting of the mode
406 void SetMode(unsigned char m, bool value);
408 /** Returns true if a user is invited to a channel.
409 * @param channel A channel name to look up
410 * @return True if the user is invited to the given channel
412 virtual bool IsInvited(irc::string &channel);
414 /** Adds a channel to a users invite list (invites them to a channel)
415 * @param channel A channel name to add
417 virtual void InviteTo(irc::string &channel);
419 /** Removes a channel from a users invite list.
420 * This member function is called on successfully joining an invite only channel
421 * to which the user has previously been invited, to clear the invitation.
422 * @param channel The channel to remove the invite to
424 virtual void RemoveInvite(irc::string &channel);
426 /** Returns true or false for if a user can execute a privilaged oper command.
427 * This is done by looking up their oper type from userrec::oper, then referencing
428 * this to their oper classes and checking the commands they can execute.
429 * @param command A command (should be all CAPS)
430 * @return True if this user can execute the command
432 bool HasPermission(const std::string &command);
434 /** Calls read() to read some data for this user using their fd.
435 * @param buffer The buffer to read into
436 * @param size The size of data to read
437 * @return The number of bytes read, or -1 if an error occured.
439 int ReadData(void* buffer, size_t size);
441 /** This method adds data to the read buffer of the user.
442 * The buffer can grow to any size within limits of the available memory,
443 * managed by the size of a std::string, however if any individual line in
444 * the buffer grows over 600 bytes in length (which is 88 chars over the
445 * RFC-specified limit per line) then the method will return false and the
446 * text will not be inserted.
447 * @param a The string to add to the users read buffer
448 * @return True if the string was successfully added to the read buffer
450 bool AddBuffer(std::string a);
452 /** This method returns true if the buffer contains at least one carriage return
453 * character (e.g. one complete line may be read)
454 * @return True if there is at least one complete line in the users buffer
456 bool BufferIsReady();
458 /** This function clears the entire buffer by setting it to an empty string.
462 /** This method returns the first available string at the tail end of the buffer
463 * and advances the tail end of the buffer past the string. This means it is
464 * a one way operation in a similar way to strtok(), and multiple calls return
465 * multiple lines if they are available. The results of this function if there
466 * are no lines to be read are unknown, always use BufferIsReady() to check if
467 * it is ok to read the buffer before calling GetBuffer().
468 * @return The string at the tail end of this users buffer
470 std::string GetBuffer();
472 /** Sets the write error for a connection. This is done because the actual disconnect
473 * of a client may occur at an inopportune time such as half way through /LIST output.
474 * The WriteErrors of clients are checked at a more ideal time (in the mainloop) and
475 * errored clients purged.
476 * @param error The error string to set.
478 void SetWriteError(const std::string &error);
480 /** Returns the write error which last occured on this connection or an empty string
482 * @return The error string which has occured for this user
484 const char* GetWriteError();
486 /** Adds to the user's write buffer.
487 * You may add any amount of text up to this users sendq value, if you exceed the
488 * sendq value, SetWriteError() will be called to set the users error string to
489 * "SendQ exceeded", and further buffer adds will be dropped.
490 * @param data The data to add to the write buffer
492 void AddWriteBuf(const std::string &data);
494 /** Flushes as much of the user's buffer to the file descriptor as possible.
495 * This function may not always flush the entire buffer, rather instead as much of it
496 * as it possibly can. If the send() call fails to send the entire buffer, the buffer
497 * position is advanced forwards and the rest of the data sent at the next call to
500 void FlushWriteBuf();
502 /** Returns the list of channels this user has been invited to but has not yet joined.
503 * @return A list of channels the user is invited to
505 InvitedList* GetInviteList();
507 /** Creates a wildcard host.
508 * Takes a buffer to use and fills the given buffer with the host in the format *!*@hostname
509 * @return The wildcarded hostname in *!*@host form
511 char* MakeWildHost();
514 * Takes a buffer to use and fills the given buffer with the host in the format nick!user@host
515 * @param Buffer to fill with host information
517 void MakeHost(char* nhost);
519 /** Shuts down and closes the user's socket
520 * This will not cause the user to be deleted. Use InspIRCd::QuitUser for this,
521 * which will call CloseSocket() for you.
525 /** Disconnect a user gracefully
526 * @param user The user to remove
527 * @param r The quit reason
528 * @return Although this function has no return type, on exit the user provided will no longer exist.
530 static void QuitUser(InspIRCd* Instance, userrec *user, const std::string &r);
532 /** Add the user to WHOWAS system
536 /** Oper up the user using the given opertype.
537 * This will also give the +o usermode.
538 * @param opertype The oper type to oper as
540 void Oper(const std::string &opertype);
542 /** Use this method to fully connect a user.
543 * This will send the message of the day, check G/K/E lines, etc.
544 * @param Goners If the user is disconnected by this method call, the
545 * value of 'this' will be pushed onto this CullList. This is used by
546 * the core to connect many users in rapid succession without invalidating
548 * @param Goners a CullList to use for failed connections
550 void FullConnect(CullList* Goners);
552 /** Change this users hash key to a new string.
553 * You should not call this function directly. It is used by the core
554 * to update the users hash entry on a nickchange.
555 * @param New new user_hash key
556 * @return Pointer to userrec in hash (usually 'this')
558 userrec* UpdateNickHash(const char* New);
560 /** Force a nickname change.
561 * If the nickname change fails (for example, because the nick in question
562 * already exists) this function will return false, and you must then either
563 * output an error message, or quit the user for nickname collision.
564 * @param newnick The nickname to change to
565 * @return True if the nickchange was successful.
567 bool ForceNickChange(const char* newnick);
569 /** Add a client to the system.
570 * This will create a new userrec, insert it into the user_hash,
571 * initialize it as not yet registered, and add it to the socket engine.
572 * @param Instance a pointer to the server instance
573 * @param socket The socket id (file descriptor) this user is on
574 * @param port The port number this user connected on
575 * @param iscached This variable is reserved for future use
576 * @param ip The IP address of the user
577 * @return This function has no return value, but a call to AddClient may remove the user.
579 static void AddClient(InspIRCd* Instance, int socket, int port, bool iscached, insp_inaddr ip);
582 * This will clear the +o usermode and unset the user's oper type
586 /** Return the number of global clones of this user
587 * @return The global clone count of this user
589 long GlobalCloneCount();
591 /** Return the number of local clones of this user
592 * @return The local clone count of this user
594 long LocalCloneCount();
596 /** Write text to this user, appending CR/LF.
597 * @param text A std::string to send to the user
599 void Write(std::string text);
601 /** Write text to this user, appending CR/LF.
602 * @param text The format string for text to send to the user
603 * @param ... POD-type format arguments
605 void Write(const char *text, ...);
607 /** Write text to this user, appending CR/LF and prepending :server.name
608 * @param text A std::string to send to the user
610 void WriteServ(const std::string& text);
612 /** Write text to this user, appending CR/LF and prepending :server.name
613 * @param text The format string for text to send to the user
614 * @param ... POD-type format arguments
616 void WriteServ(const char* text, ...);
618 /** Write text to this user, appending CR/LF and prepending :nick!user@host of the user provided in the first parameter.
619 * @param user The user to prepend the :nick!user@host of
620 * @param text A std::string to send to the user
622 void WriteFrom(userrec *user, const std::string &text);
624 /** Write text to this user, appending CR/LF and prepending :nick!user@host of the user provided in the first parameter.
625 * @param user The user to prepend the :nick!user@host of
626 * @param text The format string for text to send to the user
627 * @param ... POD-type format arguments
629 void WriteFrom(userrec *user, const char* text, ...);
631 /** Write text to the user provided in the first parameter, appending CR/LF, and prepending THIS user's :nick!user@host.
632 * @param dest The user to route the message to
633 * @param text A std::string to send to the user
635 void WriteTo(userrec *dest, const std::string &data);
637 /** Write text to the user provided in the first parameter, appending CR/LF, and prepending THIS user's :nick!user@host.
638 * @param dest The user to route the message to
639 * @param text The format string for text to send to the user
640 * @param ... POD-type format arguments
642 void WriteTo(userrec *dest, const char *data, ...);
644 /** Write to all users that can see this user (including this user in the list), appending CR/LF
645 * @param text A std::string to send to the users
647 void WriteCommon(const std::string &text);
649 /** Write to all users that can see this user (including this user in the list), appending CR/LF
650 * @param text The format string for text to send to the users
651 * @param ... POD-type format arguments
653 void WriteCommon(const char* text, ...);
655 /** Write to all users that can see this user (not including this user in the list), appending CR/LF
656 * @param text The format string for text to send to the users
657 * @param ... POD-type format arguments
659 void WriteCommonExcept(const char* text, ...);
661 /** Write to all users that can see this user (not including this user in the list), appending CR/LF
662 * @param text A std::string to send to the users
664 void WriteCommonExcept(const std::string &text);
666 /** Write a WALLOPS message from this user to all local opers.
667 * If this user is not opered, the function will return without doing anything.
668 * @param text The format string to send in the WALLOPS message
669 * @param ... Format arguments
671 void WriteWallOps(const char* text, ...);
673 /** Write a WALLOPS message from this user to all local opers.
674 * If this user is not opered, the function will return without doing anything.
675 * @param text The text to send in the WALLOPS message
677 void WriteWallOps(const std::string &text);
679 /** Return true if the user shares at least one channel with another user
680 * @param other The other user to compare the channel list against
681 * @return True if the given user shares at least one channel with this user
683 bool SharesChannelWith(userrec *other);
685 /** Change the displayed host of a user.
686 * ALWAYS use this function, rather than writing userrec::dhost directly,
687 * as this triggers module events allowing the change to be syncronized to
689 * @param host The new hostname to set
690 * @return True if the change succeeded, false if it didn't
692 bool ChangeDisplayedHost(const char* host);
694 /** Change a users realname field.
695 * ALWAYS use this function, rather than writing userrec::fullname directly,
696 * as this triggers module events allowing the change to be syncronized to
698 * @param gecos The user's new realname
699 * @return True if the change succeeded, false if otherwise
701 bool ChangeName(const char* gecos);
703 /** Return the total number of channels this user is on.
704 * @return The number of channels the user is on
708 /** Send a notice to all local users from this user
709 * @param text The text format string to send
710 * @param ... Format arguments
712 void NoticeAll(char* text, ...);
714 /** Compile a channel list for this user, and send it to the user 'source'
715 * Used internally by WHOIS
716 * @param The user to send the channel list to if it is not too long
717 * @return This user's channel list
719 std::string ChannelList(userrec* source);
721 /** Split the channel list in cl which came from dest, and spool it to this user
722 * Used internally by WHOIS
723 * @param dest The user the original channel list came from
724 * @param cl The channel list as a string obtained from userrec::ChannelList()
726 void SplitChanList(userrec* dest, const std::string &cl);
728 /** Remove this user from all channels they are on, and delete any that are now empty.
729 * This is used by QUIT, and will not send part messages!
731 void PurgeEmptyChannels();
733 /** Get the connect class which matches this user's host or IP address
734 * @return A reference to this user's connect class
736 ConnectClass& GetClass();
738 /** Show the message of the day to this user
742 /** Show the server RULES file to this user
746 /** Handle socket event.
747 * From EventHandler class.
749 void HandleEvent(EventType et);
751 /** Default destructor
759 /** Holds whowas related functions and classes
764 /** Used to hold WHOWAS information
766 class WhoWasGroup : public classbase
788 /** Initialize this WhoQasFroup with a user
790 WhoWasGroup(userrec* user);
796 /** A group of users related by nickname
798 typedef std::deque<WhoWasGroup*> whowas_set;
800 /** Sets of users in the whowas system
802 typedef std::map<irc::string,whowas_set*> whowas_users;
804 /** Called every hour by the core to remove expired entries
806 void MaintainWhoWas(time_t TIME);
810 /* Configuration callbacks */
812 bool InitTypes(ServerConfig* conf, const char* tag);
813 bool InitClasses(ServerConfig* conf, const char* tag);
814 bool DoType(ServerConfig* conf, const char* tag, char** entries, void** values, int* types);
815 bool DoClass(ServerConfig* conf, const char* tag, char** entries, void** values, int* types);
816 bool DoneClassesAndTypes(ServerConfig* conf, const char* tag);