]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_spanningtree/treesocket.h
046f0eb0a3651c77afc89801773e0624ee5f0a59
[user/henk/code/inspircd.git] / src / modules / m_spanningtree / treesocket.h
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2019 Matt Schatz <genius3000@g3k.solutions>
5  *   Copyright (C) 2013, 2017-2019 Sadie Powell <sadie@witchery.services>
6  *   Copyright (C) 2012-2015 Attila Molnar <attilamolnar@hush.com>
7  *   Copyright (C) 2012, 2019 Robby <robby@chatbelgie.be>
8  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
9  *   Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
10  *   Copyright (C) 2007-2008 Robin Burchell <robin+git@viroteck.net>
11  *   Copyright (C) 2007, 2010 Craig Edwards <brain@inspircd.org>
12  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
13  *
14  * This file is part of InspIRCd.  InspIRCd is free software: you can
15  * redistribute it and/or modify it under the terms of the GNU General Public
16  * License as published by the Free Software Foundation, version 2.
17  *
18  * This program is distributed in the hope that it will be useful, but WITHOUT
19  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
20  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
21  * details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
25  */
26
27
28 #pragma once
29
30 #include "inspircd.h"
31
32 #include "utils.h"
33
34 /*
35  * The server list in InspIRCd is maintained as two structures
36  * which hold the data in different ways. Most of the time, we
37  * want to very quicky obtain three pieces of information:
38  *
39  * (1) The information on a server
40  * (2) The information on the server we must send data through
41  *     to actually REACH the server we're after
42  * (3) Potentially, the child/parent objects of this server
43  *
44  * The InspIRCd spanning protocol provides easy access to these
45  * by storing the data firstly in a recursive structure, where
46  * each item references its parent item, and a dynamic list
47  * of child items, and another structure which stores the items
48  * hashed, linearly. This means that if we want to find a server
49  * by name quickly, we can look it up in the hash, avoiding
50  * any O(n) lookups. If however, during a split or sync, we want
51  * to apply an operation to a server, and any of its child objects
52  * we can resort to recursion to walk the tree structure.
53  * Any socket can have one of five states at any one time.
54  *
55  * CONNECTING:  indicates an outbound socket which is
56  *                                                      waiting to be writeable.
57  * WAIT_AUTH_1: indicates the socket is outbound and
58  *                                                      has successfully connected, but has not
59  *                                                      yet sent and received SERVER strings.
60  * WAIT_AUTH_2: indicates that the socket is inbound
61  *                                                      but has not yet sent and received
62  *                                                      SERVER strings.
63  * CONNECTED:   represents a fully authorized, fully
64  *                                                      connected server.
65  * DYING:       represents a server that has had an error.
66  */
67 enum ServerState { CONNECTING, WAIT_AUTH_1, WAIT_AUTH_2, CONNECTED, DYING };
68
69 struct CapabData
70 {
71         reference<Link> link;                   /* Link block used for this connection */
72         reference<Autoconnect> ac;              /* Autoconnect used to cause this connection, if any */
73         std::string ModuleList;                 /* Required module list of other server from CAPAB */
74         std::string OptModuleList;              /* Optional module list of other server from CAPAB */
75         std::string ChanModes;
76         std::string UserModes;
77         std::map<std::string,std::string> CapKeys;      /* CAPAB keys from other server */
78         std::string ourchallenge;               /* Challenge sent for challenge/response */
79         std::string theirchallenge;             /* Challenge recv for challenge/response */
80         int capab_phase;                        /* Have sent CAPAB already */
81         bool auth_fingerprint;                  /* Did we auth using SSL certificate fingerprint */
82         bool auth_challenge;                    /* Did we auth using challenge/response */
83
84         // Data saved from incoming SERVER command, for later use when our credentials have been accepted by the other party
85         std::string description;
86         std::string sid;
87         std::string name;
88         bool hidden;
89 };
90
91 /** Every SERVER connection inbound or outbound is represented by an object of
92  * type TreeSocket. During setup, the object can be found in Utils->timeoutlist;
93  * after setup, MyRoot will have been created as a child of Utils->TreeRoot
94  */
95 class TreeSocket : public BufferedSocket
96 {
97         struct BurstState;
98
99         std::string linkID;                     /* Description for this link */
100         ServerState LinkState;                  /* Link state */
101         CapabData* capab;                       /* Link setup data (held until burst is sent) */
102         TreeServer* MyRoot;                     /* The server we are talking to */
103         unsigned int proto_version;                     /* Remote protocol version */
104
105         /** True if we've sent our burst.
106          * This only changes the behavior of message translation for 1202 protocol servers and it can be
107          * removed once 1202 support is dropped.
108          */
109         bool burstsent;
110
111         /** Checks if the given servername and sid are both free
112          */
113         bool CheckDuplicate(const std::string& servername, const std::string& sid);
114
115         /** Send all ListModeBase modes set on the channel
116          */
117         void SendListModes(Channel* chan);
118
119         /** Send all known information about a channel */
120         void SyncChannel(Channel* chan, BurstState& bs);
121
122         /** Send all users and their oper state, away state and metadata */
123         void SendUsers(BurstState& bs);
124
125         /** Send all additional info about the given server to this server */
126         void SendServerInfo(TreeServer* from);
127
128         /** Find the User source of a command given a prefix and a command string.
129          * This connection must be fully up when calling this function.
130          * @param prefix Prefix string to find the source User object for. Can be a sid, a uuid or a server name.
131          * @param command The command whose source to find. This is required because certain commands (like mode
132          * changes and kills) must be processed even if their claimed source doesn't exist. If the given command is
133          * such a command and the source does not exist, the function returns a valid FakeUser that can be used to
134          * to process the command with.
135          * @return The command source to use when processing the command or NULL if the source wasn't found.
136          * Note that the direction of the returned source is not verified.
137          */
138         User* FindSource(const std::string& prefix, const std::string& command);
139
140         /** Finish the authentication phase of this connection.
141          * Change the state of the connection to CONNECTED, create a TreeServer object for the server on the
142          * other end of the connection using the details provided in the parameters, and finally send a burst.
143          * @param remotename Name of the remote server
144          * @param remotesid SID of the remote server
145          * @param remotedesc Description of the remote server
146          * @param hidden True if the remote server is hidden according to the configuration
147          */
148         void FinishAuth(const std::string& remotename, const std::string& remotesid, const std::string& remotedesc, bool hidden);
149
150         /** Authenticate the remote server.
151          * Validate the parameters and find the link block that matches the remote server. In case of an error,
152          * an appropriate snotice is generated, an ERROR message is sent and the connection is closed.
153          * Failing to find a matching link block counts as an error.
154          * @param params Parameters they sent in the SERVER command
155          * @return Link block for the remote server, or NULL if an error occurred
156          */
157         Link* AuthRemote(const CommandBase::Params& params);
158
159         /** Write a line on this socket with a new line character appended, skipping all translation for old protocols
160          * @param line Line to write without a new line character at the end
161          */
162         void WriteLineNoCompat(const std::string& line);
163
164  public:
165         const time_t age;
166
167         /** Because most of the I/O gubbins are encapsulated within
168          * BufferedSocket, we just call the superclass constructor for
169          * most of the action, and append a few of our own values
170          * to it.
171          */
172         TreeSocket(Link* link, Autoconnect* myac, const irc::sockets::sockaddrs& sa);
173
174         /** When a listening socket gives us a new file descriptor,
175          * we must associate it with a socket without creating a new
176          * connection. This constructor is used for this purpose.
177          */
178         TreeSocket(int newfd, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server);
179
180         /** Get link state
181          */
182         ServerState GetLinkState() const { return LinkState; }
183
184         /** Get challenge set in our CAPAB for challenge/response
185          */
186         const std::string& GetOurChallenge();
187
188         /** Get challenge set in our CAPAB for challenge/response
189          */
190         void SetOurChallenge(const std::string &c);
191
192         /** Get challenge set in their CAPAB for challenge/response
193          */
194         const std::string& GetTheirChallenge();
195
196         /** Get challenge set in their CAPAB for challenge/response
197          */
198         void SetTheirChallenge(const std::string &c);
199
200         /** Compare two passwords based on authentication scheme
201          */
202         bool ComparePass(const Link& link, const std::string &theirs);
203
204         /** Clean up information used only during server negotiation
205          */
206         void CleanNegotiationInfo();
207
208         CullResult cull() CXX11_OVERRIDE;
209         /** Destructor
210          */
211         ~TreeSocket();
212
213         /** Construct a password, optionally hashed with the other side's
214          * challenge string
215          */
216         std::string MakePass(const std::string &password, const std::string &challenge);
217
218         /** When an outbound connection finishes connecting, we receive
219          * this event, and must send our SERVER string to the other
220          * side. If the other side is happy, as outlined in the server
221          * to server docs on the inspircd.org site, the other side
222          * will then send back its own server string.
223          */
224         void OnConnected() CXX11_OVERRIDE;
225
226         /** Handle socket error event
227          */
228         void OnError(BufferedSocketError e) CXX11_OVERRIDE;
229
230         /** Sends an error to the remote server, and displays it locally to show
231          * that it was sent.
232          */
233         void SendError(const std::string &errormessage);
234
235         /** Recursively send the server tree with distances as hops.
236          * This is used during network burst to inform the other server
237          * (and any of ITS servers too) of what servers we know about.
238          */
239         void SendServers(TreeServer* Current, TreeServer* s);
240
241         /** Returns module list as a string, filtered by filter
242          * @param filter a module version bitmask, such as VF_COMMON or VF_OPTCOMMON
243          */
244         std::string MyModules(int filter);
245
246         /** Returns mode list as a string, filtered by type.
247          * @param type The type of modes to return.
248          */
249         std::string BuildModeList(ModeType type);
250
251         /** Send my capabilities to the remote side
252          */
253         void SendCapabilities(int phase);
254
255         /* Isolate and return the elements that are different between two lists */
256         void ListDifference(const std::string &one, const std::string &two, char sep,
257                 std::string& mleft, std::string& mright);
258
259         bool Capab(const CommandBase::Params& params);
260
261         /** Send one or more FJOINs for a channel of users.
262          * If the length of a single line is more than 480-NICKMAX
263          * in length, it is split over multiple lines.
264          */
265         void SendFJoins(Channel* c);
266
267         /** Send G-, Q-, Z- and E-lines */
268         void SendXLines();
269
270         /** Send all known information about a channel */
271         void SyncChannel(Channel* chan);
272
273         /** This function is called when we want to send a netburst to a local
274          * server. There is a set order we must do this, because for example
275          * users require their servers to exist, and channels require their
276          * users to exist. You get the idea.
277          */
278         void DoBurst(TreeServer* s);
279
280         /** This function is called when we receive data from a remote
281          * server.
282          */
283         void OnDataReady() CXX11_OVERRIDE;
284
285         /** Send one or more complete lines down the socket
286          */
287         void WriteLine(const std::string& line);
288
289         /** Handle ERROR command */
290         void Error(CommandBase::Params& params);
291
292         /** (local) -> SERVER
293          */
294         bool Outbound_Reply_Server(CommandBase::Params& params);
295
296         /** (local) <- SERVER
297          */
298         bool Inbound_Server(CommandBase::Params& params);
299
300         /** Handle IRC line split
301          */
302         void Split(const std::string& line, std::string& tags, std::string& prefix, std::string& command, CommandBase::Params& params);
303
304         /** Process complete line from buffer
305          */
306         void ProcessLine(std::string &line);
307
308         /** Process message tags received from a remote server. */
309         void ProcessTag(User* source, const std::string& tag, ClientProtocol::TagMap& tags);
310
311         /** Process a message for a fully connected server. */
312         void ProcessConnectedLine(std::string& tags, std::string& prefix, std::string& command, CommandBase::Params& params);
313
314         /** Handle socket timeout from connect()
315          */
316         void OnTimeout() CXX11_OVERRIDE;
317         /** Handle server quit on close
318          */
319         void Close() CXX11_OVERRIDE;
320
321         /** Fixes messages coming from old servers so the new command handlers understand them
322          */
323         bool PreProcessOldProtocolMessage(User*& who, std::string& cmd, CommandBase::Params& params);
324 };