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