]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - include/users.h
Sync helpop chmodes s and p with docs
[user/henk/code/inspircd.git] / include / users.h
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2019-2020 Matt Schatz <genius3000@g3k.solutions>
5  *   Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
6  *   Copyright (C) 2013 Daniel Vassdal <shutter@canternet.org>
7  *   Copyright (C) 2012-2016, 2018 Attila Molnar <attilamolnar@hush.com>
8  *   Copyright (C) 2012-2013, 2016-2021 Sadie Powell <sadie@witchery.services>
9  *   Copyright (C) 2012, 2019 Robby <robby@chatbelgie.be>
10  *   Copyright (C) 2012 DjSlash <djslash@djslash.org>
11  *   Copyright (C) 2012 ChrisTX <xpipe@hotmail.de>
12  *   Copyright (C) 2011 jackmcbarn <jackmcbarn@inspircd.org>
13  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
14  *   Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
15  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
16  *   Copyright (C) 2008 John Brooks <special@inspircd.org>
17  *   Copyright (C) 2007, 2009 Dennis Friis <peavey@inspircd.org>
18  *   Copyright (C) 2006-2009 Robin Burchell <robin+git@viroteck.net>
19  *   Copyright (C) 2003-2008 Craig Edwards <brain@inspircd.org>
20  *
21  * This file is part of InspIRCd.  InspIRCd is free software: you can
22  * redistribute it and/or modify it under the terms of the GNU General Public
23  * License as published by the Free Software Foundation, version 2.
24  *
25  * This program is distributed in the hope that it will be useful, but WITHOUT
26  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
27  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
28  * details.
29  *
30  * You should have received a copy of the GNU General Public License
31  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
32  */
33
34
35 #pragma once
36
37 #include "socket.h"
38 #include "inspsocket.h"
39 #include "mode.h"
40 #include "membership.h"
41
42 /** connect class types
43  */
44 enum ClassTypes {
45         /** connect:allow */
46         CC_ALLOW = 0,
47         /** connect:deny */
48         CC_DENY  = 1,
49         /** named connect block (for opers, etc) */
50         CC_NAMED = 2
51 };
52
53 /** Registration state of a user, e.g.
54  * have they sent USER, NICK, PASS yet?
55  */
56 enum RegistrationState {
57
58 #ifndef _WIN32   // Burlex: This is already defined in win32, luckily it is still 0.
59         REG_NONE = 0,           /* Has sent nothing */
60 #endif
61
62         REG_USER = 1,           /* Has sent USER */
63         REG_NICK = 2,           /* Has sent NICK */
64         REG_NICKUSER = 3,       /* Bitwise combination of REG_NICK and REG_USER */
65         REG_ALL = 7                     /* REG_NICKUSER plus next bit along */
66 };
67
68 enum UserType {
69         USERTYPE_LOCAL = 1,
70         USERTYPE_REMOTE = 2,
71         USERTYPE_SERVER = 3
72 };
73
74 /** Holds information relevant to &lt;connect allow&gt; and &lt;connect deny&gt; tags in the config file.
75  */
76 struct CoreExport ConnectClass : public refcountbase
77 {
78         reference<ConfigTag> config;
79         /** Type of line, either CC_ALLOW or CC_DENY
80          */
81         char type;
82
83         /** True if this class uses fake lag to manage flood, false if it kills */
84         bool fakelag;
85
86         /** Connect class name
87          */
88         std::string name;
89
90         /** Max time to register the connection in seconds
91          */
92         unsigned int registration_timeout;
93
94         /** Hosts that this user can connect from as a string. */
95         std::string host;
96
97         /** Hosts that this user can connect from as a vector. */
98         std::vector<std::string> hosts;
99
100         /** Number of seconds between pings for this line
101          */
102         unsigned int pingtime;
103
104         /** Maximum size of sendq for users in this class (bytes)
105          * Users cannot send commands if they go over this limit
106          */
107         unsigned long softsendqmax;
108
109         /** Maximum size of sendq for users in this class (bytes)
110          * Users are killed if they go over this limit
111          */
112         unsigned long hardsendqmax;
113
114         /** Maximum size of recvq for users in this class (bytes)
115          */
116         unsigned long recvqmax;
117
118         /** Seconds worth of penalty before penalty system activates
119          */
120         unsigned int penaltythreshold;
121
122         /** Maximum rate of commands (units: millicommands per second) */
123         unsigned int commandrate;
124
125         /** Local max when connecting by this connection class
126          */
127         unsigned long maxlocal;
128
129         /** Global max when connecting by this connection class
130          */
131         unsigned long maxglobal;
132
133         /** True if max connections for this class is hit and a warning is wanted
134          */
135         bool maxconnwarn;
136
137         /** Max channels for this class
138          */
139         unsigned int maxchans;
140
141         /** How many users may be in this connect class before they are refused?
142          * (0 = no limit = default)
143          */
144         unsigned long limit;
145
146         /** If set to true, no user DNS lookups are to be performed
147          */
148         bool resolvehostnames;
149
150         /**
151          * If non-empty the server ports which this user has to be using
152          */
153         insp::flat_set<int> ports;
154
155         /** If non-empty then the password a user must specify in PASS to be assigned to this class. */
156         std::string password;
157
158         /** If non-empty then the hash algorithm that the password field is hashed with. */
159         std::string passwordhash;
160
161         /** Create a new connect class with no settings.
162          */
163         ConnectClass(ConfigTag* tag, char type, const std::string& mask);
164         /** Create a new connect class with inherited settings.
165          */
166         ConnectClass(ConfigTag* tag, char type, const std::string& mask, const ConnectClass& parent);
167
168         /** Update the settings in this block to match the given block */
169         void Update(const ConnectClass* newSettings);
170
171         const std::string& GetName() const { return name; }
172         const std::string& GetHost() const { return host; }
173         const std::vector<std::string>& GetHosts() const { return hosts; }
174
175         /** Returns the registration timeout
176          */
177         time_t GetRegTimeout()
178         {
179                 return (registration_timeout ? registration_timeout : 90);
180         }
181
182         /** Returns the ping frequency
183          */
184         unsigned int GetPingTime()
185         {
186                 return (pingtime ? pingtime : 120);
187         }
188
189         /** Returns the maximum sendq value (soft limit)
190          * Note that this is in addition to internal OS buffers
191          */
192         unsigned long GetSendqSoftMax()
193         {
194                 return (softsendqmax ? softsendqmax : 4096);
195         }
196
197         /** Returns the maximum sendq value (hard limit)
198          */
199         unsigned long GetSendqHardMax()
200         {
201                 return (hardsendqmax ? hardsendqmax : 0x100000);
202         }
203
204         /** Returns the maximum recvq value
205          */
206         unsigned long GetRecvqMax()
207         {
208                 return (recvqmax ? recvqmax : 4096);
209         }
210
211         /** Returns the penalty threshold value
212          */
213         unsigned int GetPenaltyThreshold()
214         {
215                 return penaltythreshold ? penaltythreshold : (fakelag ? 10 : 20);
216         }
217
218         unsigned int GetCommandRate()
219         {
220                 return commandrate ? commandrate : 1000;
221         }
222
223         /** Return the maximum number of local sessions
224          */
225         unsigned long GetMaxLocal()
226         {
227                 return maxlocal;
228         }
229
230         /** Returns the maximum number of global sessions
231          */
232         unsigned long GetMaxGlobal()
233         {
234                 return maxglobal;
235         }
236 };
237
238 /** Holds all information about a user
239  * This class stores all information about a user connected to the irc server. Everything about a
240  * connection is stored here primarily, from the user's socket ID (file descriptor) through to the
241  * user's nickname and hostname.
242  */
243 class CoreExport User : public Extensible
244 {
245  private:
246         /** Cached nick!ident\@dhost value using the displayed hostname
247          */
248         std::string cached_fullhost;
249
250         /** Cached ident\@ip value using the real IP address
251          */
252         std::string cached_hostip;
253
254         /** Cached ident\@realhost value using the real hostname
255          */
256         std::string cached_makehost;
257
258         /** Cached nick!ident\@realhost value using the real hostname
259          */
260         std::string cached_fullrealhost;
261
262         /** Set by GetIPString() to avoid constantly re-grabbing IP via sockets voodoo.
263          */
264         std::string cachedip;
265
266         /** If set then the hostname which is displayed to users. */
267         std::string displayhost;
268
269         /** The real hostname of this user. */
270         std::string realhost;
271
272         /** The real name of this user. */
273         std::string realname;
274
275         /** The user's mode list.
276          * Much love to the STL for giving us an easy to use bitset, saving us RAM.
277          * if (modes[modeid]) is set, then the mode is set.
278          * For example, to work out if mode +i is set, we check the field
279          * User::modes[invisiblemode->modeid] == true.
280          */
281         std::bitset<ModeParser::MODEID_MAX> modes;
282
283  public:
284         /** To execute a function for each local neighbor of a user, inherit from this class and
285          * pass an instance of it to User::ForEachNeighbor().
286          */
287         class ForEachNeighborHandler
288         {
289          public:
290                 /** Method to execute for each local neighbor of a user.
291                  * Derived classes must implement this.
292                  * @param user Current neighbor
293                  */
294                 virtual void Execute(LocalUser* user) = 0;
295         };
296
297         /** List of Memberships for this user
298          */
299         typedef insp::intrusive_list<Membership> ChanList;
300
301         /** Time that the object was instantiated (used for TS calculation etc)
302         */
303         time_t age;
304
305         /** Time the connection was created, set in the constructor. This
306          * may be different from the time the user's classbase object was
307          * created.
308          */
309         time_t signon;
310
311         /** Client address that the user is connected from.
312          * Do not modify this value directly, use SetClientIP() to change it.
313          * Port is not valid for remote users.
314          */
315         irc::sockets::sockaddrs client_sa;
316
317         /** The users nickname.
318          * An invalid nickname indicates an unregistered connection prior to the NICK command.
319          * Use InspIRCd::IsNick() to validate nicknames.
320          */
321         std::string nick;
322
323         /** The user's unique identifier.
324          * This is the unique identifier which the user has across the network.
325          */
326         const std::string uuid;
327
328         /** The users ident reply.
329          * Two characters are added to the user-defined limit to compensate for the tilde etc.
330          */
331         std::string ident;
332
333         /** What snomasks are set on this user.
334          * This functions the same as the above modes.
335          */
336         std::bitset<64> snomasks;
337
338         /** Channels this user is on
339          */
340         ChanList chans;
341
342         /** The server the user is connected to.
343          */
344         Server* server;
345
346         /** The user's away message.
347          * If this string is empty, the user is not marked as away.
348          */
349         std::string awaymsg;
350
351         /** Time the user last went away.
352          * This is ONLY RELIABLE if user IsAway()!
353          */
354         time_t awaytime;
355
356         /** The oper type they logged in as, if they are an oper.
357          */
358         reference<OperInfo> oper;
359
360         /** Used by User to indicate the registration status of the connection
361          * It is a bitfield of the REG_NICK, REG_USER and REG_ALL bits to indicate
362          * the connection state.
363          */
364         unsigned int registered:3;
365
366         /** If this is set to true, then all socket operations for the user
367          * are dropped into the bit-bucket.
368          * This value is set by QuitUser, and is not needed separately from that call.
369          * Please note that setting this value alone will NOT cause the user to quit.
370          */
371         unsigned int quitting:1;
372
373         /** What type of user is this? */
374         const unsigned int usertype:2;
375
376         /** Get client IP string from sockaddr, using static internal buffer
377          * @return The IP string
378          */
379         const std::string& GetIPString();
380
381         /** Retrieves this user's hostname.
382          * @param uncloak If true then return the real host; otherwise, the display host.
383          */
384         const std::string& GetHost(bool uncloak) const;
385
386         /** Retrieves this user's displayed hostname. */
387         const std::string& GetDisplayedHost() const;
388
389         /** Retrieves this user's real hostname. */
390         const std::string& GetRealHost() const;
391
392         /** Retrieves this user's real name. */
393         const std::string& GetRealName() const;
394
395         /** Get CIDR mask, using default range, for this user
396          */
397         irc::sockets::cidr_mask GetCIDRMask();
398
399         /** Sets the client IP for this user
400          * @return true if the conversion was successful
401          */
402         virtual bool SetClientIP(const std::string& address);
403
404         virtual void SetClientIP(const irc::sockets::sockaddrs& sa);
405
406         /** Constructor
407          * @throw CoreException if the UID allocated to the user already exists
408          */
409         User(const std::string& uid, Server* srv, UserType objtype);
410
411         /** Returns the full displayed host of the user
412          * This member function returns the hostname of the user as seen by other users
413          * on the server, in nick!ident\@host form.
414          * @return The full masked host of the user
415          */
416         virtual const std::string& GetFullHost();
417
418         /** Returns the full real host of the user
419          * This member function returns the hostname of the user as seen by other users
420          * on the server, in nick!ident\@host form. If any form of hostname cloaking is in operation,
421          * e.g. through a module, then this method will ignore it and return the true hostname.
422          * @return The full real host of the user
423          */
424         virtual const std::string& GetFullRealHost();
425
426         /** This clears any cached results that are used for GetFullRealHost() etc.
427          * The results of these calls are cached as generating them can be generally expensive.
428          */
429         void InvalidateCache();
430
431         /** Returns whether this user is currently away or not. If true,
432          * further information can be found in User::awaymsg and User::awaytime
433          * @return True if the user is away, false otherwise
434          */
435         bool IsAway() const { return (!awaymsg.empty()); }
436
437         /** Returns whether this user is an oper or not. If true,
438          * oper information can be obtained from User::oper
439          * @return True if the user is an oper, false otherwise
440          */
441         bool IsOper() const { return oper; }
442
443         /** Returns true if a notice mask is set
444          * @param sm A notice mask character to check
445          * @return True if the notice mask is set
446          */
447         bool IsNoticeMaskSet(unsigned char sm);
448
449         /** Get the mode letters of modes set on the user as a string.
450          * @param includeparams True to get the parameters of the modes as well. Defaults to false.
451          * @return Mode letters of modes set on the user and optionally the parameters of those modes, if any.
452          * The returned string always begins with a '+' character. If the user has no modes set, "+" is returned.
453          */
454         std::string GetModeLetters(bool includeparams = false) const;
455
456         /** Returns true if a specific mode is set
457          * @param m The user mode
458          * @return True if the mode is set
459          */
460         bool IsModeSet(unsigned char m) const;
461         bool IsModeSet(const ModeHandler* mh) const;
462         bool IsModeSet(const ModeHandler& mh) const { return IsModeSet(&mh); }
463         bool IsModeSet(UserModeReference& moderef) const;
464
465         /** Set a specific usermode to on or off
466          * @param mh The user mode
467          * @param value On or off setting of the mode
468          */
469         void SetMode(ModeHandler* mh, bool value);
470         void SetMode(ModeHandler& mh, bool value) { SetMode(&mh, value); }
471
472         /** Returns true or false for if a user can execute a privilaged oper command.
473          * This is done by looking up their oper type from User::oper, then referencing
474          * this to their oper classes and checking the commands they can execute.
475          * @param command A command (should be all CAPS)
476          * @return True if this user can execute the command
477          */
478         virtual bool HasCommandPermission(const std::string& command);
479
480         /** Returns true if a user has a given permission.
481          * This is used to check whether or not users may perform certain actions which admins may not wish to give to
482          * all operators, yet are not commands. An example might be oper override, mass messaging (/notice $*), etc.
483          *
484          * @param privstr The priv to chec, e.g. "users/override/topic". These are loaded free-form from the config file.
485          * @return True if this user has the permission in question.
486          */
487         virtual bool HasPrivPermission(const std::string& privstr);
488
489         /** Returns true or false if a user can set a privileged user or channel mode.
490          * This is done by looking up their oper type from User::oper, then referencing
491          * this to their oper classes, and checking the modes they can set.
492          * @param mh Mode to check
493          * @return True if the user can set or unset this mode.
494          */
495         virtual bool HasModePermission(const ModeHandler* mh) const;
496
497         /** Determines whether this user can set the specified snomask.
498          * @param chr The server notice mask character to look up.
499          * @return True if the user can set the specified snomask; otherwise, false.
500          */
501         virtual bool HasSnomaskPermission(char chr) const;
502
503         /** Creates a usermask with real host.
504          * Takes a buffer to use and fills the given buffer with the hostmask in the format user\@host
505          * @return the usermask in the format user\@host
506          */
507         const std::string& MakeHost();
508
509         /** Creates a usermask with real ip.
510          * Takes a buffer to use and fills the given buffer with the ipmask in the format user\@ip
511          * @return the usermask in the format user\@ip
512          */
513         const std::string& MakeHostIP();
514
515         /** Oper up the user using the given opertype.
516          * This will also give the +o usermode.
517          */
518         void Oper(OperInfo* info);
519
520         /** Oper down.
521          * This will clear the +o usermode and unset the user's oper type
522          */
523         void UnOper();
524
525         /** Sends a server notice to this user.
526          * @param text The contents of the message to send.
527          */
528         void WriteNotice(const std::string& text);
529
530         /** Send a NOTICE message from the local server to the user.
531          * @param text Text to send
532          */
533         virtual void WriteRemoteNotice(const std::string& text);
534
535         virtual void WriteRemoteNumeric(const Numeric::Numeric& numeric);
536
537         template <typename T1>
538         void WriteRemoteNumeric(unsigned int numeric, T1 p1)
539         {
540                 Numeric::Numeric n(numeric);
541                 n.push(p1);
542                 WriteRemoteNumeric(n);
543         }
544
545         template <typename T1, typename T2>
546         void WriteRemoteNumeric(unsigned int numeric, T1 p1, T2 p2)
547         {
548                 Numeric::Numeric n(numeric);
549                 n.push(p1);
550                 n.push(p2);
551                 WriteRemoteNumeric(n);
552         }
553
554         template <typename T1, typename T2, typename T3>
555         void WriteRemoteNumeric(unsigned int numeric, T1 p1, T2 p2, T3 p3)
556         {
557                 Numeric::Numeric n(numeric);
558                 n.push(p1);
559                 n.push(p2);
560                 n.push(p3);
561                 WriteRemoteNumeric(n);
562         }
563
564         template <typename T1, typename T2, typename T3, typename T4>
565         void WriteRemoteNumeric(unsigned int numeric, T1 p1, T2 p2, T3 p3, T4 p4)
566         {
567                 Numeric::Numeric n(numeric);
568                 n.push(p1);
569                 n.push(p2);
570                 n.push(p3);
571                 n.push(p4);
572                 WriteRemoteNumeric(n);
573         }
574
575         template <typename T1, typename T2, typename T3, typename T4, typename T5>
576         void WriteRemoteNumeric(unsigned int numeric, T1 p1, T2 p2, T3 p3, T4 p4, T5 p5)
577         {
578                 Numeric::Numeric n(numeric);
579                 n.push(p1);
580                 n.push(p2);
581                 n.push(p3);
582                 n.push(p4);
583                 n.push(p5);
584                 WriteRemoteNumeric(n);
585         }
586
587         void WriteNumeric(const Numeric::Numeric& numeric);
588
589         template <typename T1>
590         void WriteNumeric(unsigned int numeric, T1 p1)
591         {
592                 Numeric::Numeric n(numeric);
593                 n.push(p1);
594                 WriteNumeric(n);
595         }
596
597         template <typename T1, typename T2>
598         void WriteNumeric(unsigned int numeric, T1 p1, T2 p2)
599         {
600                 Numeric::Numeric n(numeric);
601                 n.push(p1);
602                 n.push(p2);
603                 WriteNumeric(n);
604         }
605
606         template <typename T1, typename T2, typename T3>
607         void WriteNumeric(unsigned int numeric, T1 p1, T2 p2, T3 p3)
608         {
609                 Numeric::Numeric n(numeric);
610                 n.push(p1);
611                 n.push(p2);
612                 n.push(p3);
613                 WriteNumeric(n);
614         }
615
616         template <typename T1, typename T2, typename T3, typename T4>
617         void WriteNumeric(unsigned int numeric, T1 p1, T2 p2, T3 p3, T4 p4)
618         {
619                 Numeric::Numeric n(numeric);
620                 n.push(p1);
621                 n.push(p2);
622                 n.push(p3);
623                 n.push(p4);
624                 WriteNumeric(n);
625         }
626
627         template <typename T1, typename T2, typename T3, typename T4, typename T5>
628         void WriteNumeric(unsigned int numeric, T1 p1, T2 p2, T3 p3, T4 p4, T5 p5)
629         {
630                 Numeric::Numeric n(numeric);
631                 n.push(p1);
632                 n.push(p2);
633                 n.push(p3);
634                 n.push(p4);
635                 n.push(p5);
636                 WriteNumeric(n);
637         }
638
639         /** Write to all users that can see this user (including this user in the list if include_self is true), appending CR/LF
640          * @param protoev Protocol event to send, may contain any number of messages.
641          * @param include_self Should the message be sent back to the author?
642          */
643         void WriteCommonRaw(ClientProtocol::Event& protoev, bool include_self = true);
644
645         /** Execute a function once for each local neighbor of this user. By default, the neighbors of a user are the users
646          * who have at least one common channel with the user. Modules are allowed to alter the set of neighbors freely.
647          * This function is used for example to send something conditionally to neighbors, or to send different messages
648          * to different users depending on their oper status.
649          * @param handler Function object to call, inherited from ForEachNeighborHandler.
650          * @param include_self True to include this user in the set of neighbors, false otherwise.
651          * Modules may override this. Has no effect if this user is not local.
652          */
653         void ForEachNeighbor(ForEachNeighborHandler& handler, bool include_self = true);
654
655         /** Return true if the user shares at least one channel with another user
656          * @param other The other user to compare the channel list against
657          * @return True if the given user shares at least one channel with this user
658          */
659         bool SharesChannelWith(User *other);
660
661         /** Change the displayed hostname of this user.
662          * @param host The new displayed hostname of this user.
663          * @return True if the hostname was changed successfully; otherwise, false.
664          */
665         bool ChangeDisplayedHost(const std::string& host);
666
667         /** Change the real hostname of this user.
668          * @param host The new real hostname of this user.
669          * @param resetdisplay Whether to reset the display host to this value.
670          */
671         void ChangeRealHost(const std::string& host, bool resetdisplay);
672
673         /** Change the ident (username) of a user.
674          * ALWAYS use this function, rather than writing User::ident directly,
675          * as this triggers module events allowing the change to be syncronized to
676          * remote servers.
677          * @param newident The new ident to set
678          * @return True if the change succeeded, false if it didn't
679          */
680         bool ChangeIdent(const std::string& newident);
681
682         /** Change a users realname field.
683          * @param real The user's new real name
684          * @return True if the change succeeded, false if otherwise
685          */
686         bool ChangeRealName(const std::string& real);
687
688         /** Change a user's nick
689          * @param newnick The new nick. If equal to the users uuid, the nick change always succeeds.
690          * @param newts The time at which this nick change happened.
691          * @return True if the change succeeded
692          */
693         bool ChangeNick(const std::string& newnick, time_t newts = 0);
694
695         /** Remove this user from all channels they are on, and delete any that are now empty.
696          * This is used by QUIT, and will not send part messages!
697          */
698         void PurgeEmptyChannels();
699
700         /** Default destructor
701          */
702         virtual ~User();
703         CullResult cull() CXX11_OVERRIDE;
704
705         /** @copydoc Serializable::Deserialize */
706         bool Deserialize(Data& data) CXX11_OVERRIDE;
707
708         /** @copydoc Serializable::Deserialize */
709         bool Serialize(Serializable::Data& data) CXX11_OVERRIDE;
710 };
711
712 class CoreExport UserIOHandler : public StreamSocket
713 {
714  private:
715         size_t checked_until;
716  public:
717         LocalUser* const user;
718         UserIOHandler(LocalUser* me)
719                 : StreamSocket(StreamSocket::SS_USER)
720                 , checked_until(0)
721                 , user(me)
722         {
723         }
724         void OnDataReady() CXX11_OVERRIDE;
725         bool OnSetEndPoint(const irc::sockets::sockaddrs& local, const irc::sockets::sockaddrs& remote) CXX11_OVERRIDE;
726         void OnError(BufferedSocketError error) CXX11_OVERRIDE;
727
728         /** Adds to the user's write buffer.
729          * You may add any amount of text up to this users sendq value, if you exceed the
730          * sendq value, the user will be removed, and further buffer adds will be dropped.
731          * @param data The data to add to the write buffer
732          */
733         void AddWriteBuf(const std::string &data);
734
735         /** Swaps the internals of this UserIOHandler with another one.
736          * @param other A UserIOHandler to swap internals with.
737          */
738         void SwapInternals(UserIOHandler& other);
739 };
740
741 typedef unsigned int already_sent_t;
742
743 class CoreExport LocalUser : public User, public insp::intrusive_list_node<LocalUser>
744 {
745         /** Add a serialized message to the send queue of the user.
746          * @param serialized Bytes to add.
747          */
748         void Write(const ClientProtocol::SerializedMessage& serialized);
749
750         /** Send a protocol event to the user, consisting of one or more messages.
751          * @param protoev Event to send, may contain any number of messages.
752          * @param msglist Message list used temporarily internally to pass to hooks and store messages
753          * before Write().
754          */
755         void Send(ClientProtocol::Event& protoev, ClientProtocol::MessageList& msglist);
756
757         /** Message list, can be passed to the two parameter Send().
758          */
759         static ClientProtocol::MessageList sendmsglist;
760
761  public:
762         LocalUser(int fd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server);
763         LocalUser(int fd, const std::string& uuid, Serializable::Data& data);
764
765         CullResult cull() CXX11_OVERRIDE;
766
767         UserIOHandler eh;
768
769         /** Serializer to use when communicating with the user
770          */
771         ClientProtocol::Serializer* serializer;
772
773         /** Stats counter for bytes inbound
774          */
775         unsigned int bytes_in;
776
777         /** Stats counter for bytes outbound
778          */
779         unsigned int bytes_out;
780
781         /** Stats counter for commands inbound
782          */
783         unsigned int cmds_in;
784
785         /** Stats counter for commands outbound
786          */
787         unsigned int cmds_out;
788
789         /** Password specified by the user when they registered (if any).
790          * This is stored even if the \<connect> block doesnt need a password, so that
791          * modules may check it.
792          */
793         std::string password;
794
795         /** Contains a pointer to the connect class a user is on from
796          */
797         reference<ConnectClass> MyClass;
798
799         /** Get the connect class which this user belongs to.
800          * @return A pointer to this user's connect class.
801          */
802         ConnectClass* GetClass() const { return MyClass; }
803
804         /** Call this method to find the matching \<connect> for a user, and to check them against it.
805          */
806         void CheckClass(bool clone_count = true);
807
808         /** Server address and port that this user is connected to.
809          */
810         irc::sockets::sockaddrs server_sa;
811
812         /** Recursion fix: user is out of SendQ and will be quit as soon as possible.
813          * This can't be handled normally because QuitUser itself calls Write on other
814          * users, which could trigger their SendQ to overrun.
815          */
816         unsigned int quitting_sendq:1;
817
818         /** has the user responded to their previous ping?
819          */
820         unsigned int lastping:1;
821
822         /** This is true if the user matched an exception (E-line). It is used to save time on ban checks.
823          */
824         unsigned int exempt:1;
825
826         /** The time at which this user should be pinged next. */
827         time_t nextping;
828
829         /** Time that the connection last sent a message, used to calculate idle time
830          */
831         time_t idle_lastmsg;
832
833         /** This value contains how far into the penalty threshold the user is.
834          * This is used either to enable fake lag or for excess flood quits
835          */
836         unsigned int CommandFloodPenalty;
837
838         already_sent_t already_sent;
839
840         /** Check if the user matches a G- or K-line, and disconnect them if they do.
841          * @param doZline True if Z-lines should be checked (if IP has changed since initial connect)
842          * Returns true if the user matched a ban, false else.
843          */
844         bool CheckLines(bool doZline = false);
845
846         /** Use this method to fully connect a user.
847          * This will send the message of the day, check G/K/E-lines, etc.
848          */
849         void FullConnect();
850
851         /** Set the connect class to which this user belongs to.
852          * @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.
853          */
854         void SetClass(const std::string &explicit_name = "");
855
856         bool SetClientIP(const std::string& address) CXX11_OVERRIDE;
857
858         void SetClientIP(const irc::sockets::sockaddrs& sa) CXX11_OVERRIDE;
859
860         /** Send a NOTICE message from the local server to the user.
861          * The message will be sent even if the user is connected to a remote server.
862          * @param text Text to send
863          */
864         void WriteRemoteNotice(const std::string& text) CXX11_OVERRIDE;
865
866         /** Returns true or false for if a user can execute a privilaged oper command.
867          * This is done by looking up their oper type from User::oper, then referencing
868          * this to their oper classes and checking the commands they can execute.
869          * @param command A command (should be all CAPS)
870          * @return True if this user can execute the command
871          */
872         bool HasCommandPermission(const std::string& command) CXX11_OVERRIDE;
873
874         /** Returns true if a user has a given permission.
875          * This is used to check whether or not users may perform certain actions which admins may not wish to give to
876          * all operators, yet are not commands. An example might be oper override, mass messaging (/notice $*), etc.
877          *
878          * @param privstr The priv to chec, e.g. "users/override/topic". These are loaded free-form from the config file.
879          * @return True if this user has the permission in question.
880          */
881         bool HasPrivPermission(const std::string& privstr) CXX11_OVERRIDE;
882
883         /** Returns true or false if a user can set a privileged user or channel mode.
884          * This is done by looking up their oper type from User::oper, then referencing
885          * this to their oper classes, and checking the modes they can set.
886          * @param mh Mode to check
887          * @return True if the user can set or unset this mode.
888          */
889         bool HasModePermission(const ModeHandler* mh) const CXX11_OVERRIDE;
890
891         /** @copydoc User::HasSnomaskPermission */
892         bool HasSnomaskPermission(char chr) const CXX11_OVERRIDE;
893
894         /** Change nick to uuid, unset REG_NICK and send a nickname overruled numeric.
895          * This is called when another user (either local or remote) needs the nick of this user and this user
896          * isn't registered.
897          */
898         void OverruleNick();
899
900         /** Send a protocol event to the user, consisting of one or more messages.
901          * @param protoev Event to send, may contain any number of messages.
902          */
903         void Send(ClientProtocol::Event& protoev);
904
905         /** Send a single message to the user.
906          * @param protoevprov Protocol event provider.
907          * @param msg Message to send.
908          */
909         void Send(ClientProtocol::EventProvider& protoevprov, ClientProtocol::Message& msg);
910
911         /** @copydoc Serializable::Deserialize */
912         bool Deserialize(Data& data) CXX11_OVERRIDE;
913
914         /** @copydoc Serializable::Deserialize */
915         bool Serialize(Serializable::Data& data) CXX11_OVERRIDE;
916 };
917
918 class RemoteUser : public User
919 {
920  public:
921         RemoteUser(const std::string& uid, Server* srv) : User(uid, srv, USERTYPE_REMOTE)
922         {
923         }
924 };
925
926 class CoreExport FakeUser : public User
927 {
928  public:
929         FakeUser(const std::string& uid, Server* srv)
930                 : User(uid, srv, USERTYPE_SERVER)
931         {
932                 nick = srv->GetName();
933         }
934
935         FakeUser(const std::string& uid, const std::string& sname, const std::string& sdesc)
936                 : User(uid, new Server(uid, sname, sdesc), USERTYPE_SERVER)
937         {
938                 nick = sname;
939         }
940
941         CullResult cull() CXX11_OVERRIDE;
942         const std::string& GetFullHost() CXX11_OVERRIDE;
943         const std::string& GetFullRealHost() CXX11_OVERRIDE;
944 };
945
946 /* Faster than dynamic_cast */
947 /** Is a local user */
948 inline LocalUser* IS_LOCAL(User* u)
949 {
950         return (u != NULL && u->usertype == USERTYPE_LOCAL) ? static_cast<LocalUser*>(u) : NULL;
951 }
952 /** Is a remote user */
953 inline RemoteUser* IS_REMOTE(User* u)
954 {
955         return (u != NULL && u->usertype == USERTYPE_REMOTE) ? static_cast<RemoteUser*>(u) : NULL;
956 }
957 /** Is a server fakeuser */
958 inline FakeUser* IS_SERVER(User* u)
959 {
960         return (u != NULL && u->usertype == USERTYPE_SERVER) ? static_cast<FakeUser*>(u) : NULL;
961 }
962
963 inline bool User::IsModeSet(const ModeHandler* mh) const
964 {
965         return ((mh->GetId() != ModeParser::MODEID_MAX) && (modes[mh->GetId()]));
966 }
967
968 inline bool User::IsModeSet(UserModeReference& moderef) const
969 {
970         if (!moderef)
971                 return false;
972         return IsModeSet(*moderef);
973 }
974
975 inline void User::SetMode(ModeHandler* mh, bool value)
976 {
977         if (mh && mh->GetId() != ModeParser::MODEID_MAX)
978                 modes[mh->GetId()] = value;
979 }