summaryrefslogtreecommitdiff
path: root/src/network/protocol.h
blob: f925af41f92f62f1d71eee25d80177ddf61bd635 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#pragma once

#include "channel.h"

#include <erebos/storage.h>

#include <netinet/in.h>

#include <cstdint>
#include <memory>
#include <mutex>
#include <variant>
#include <vector>
#include <optional>

namespace erebos {

using std::mutex;
using std::optional;
using std::unique_ptr;
using std::variant;
using std::vector;

class NetworkProtocol
{
public:
	NetworkProtocol();
	explicit NetworkProtocol(int sock, Identity self);
	NetworkProtocol(const NetworkProtocol &) = delete;
	NetworkProtocol(NetworkProtocol &&);
	NetworkProtocol & operator=(const NetworkProtocol &) = delete;
	NetworkProtocol & operator=(NetworkProtocol &&);
	~NetworkProtocol();

	static constexpr char defaultVersion[] = "0.1";

	class Connection;
	class Stream;
	class InStream;
	class OutStream;

	struct Header;
	struct StreamData;

	struct ReceivedAnnounce;
	struct NewConnection;
	struct ConnectionReadReady;
	struct ProtocolClosed {};

	using PollResult = variant<
		ReceivedAnnounce,
		NewConnection,
		ConnectionReadReady,
		ProtocolClosed>;

	PollResult poll();

	struct Cookie { vector<uint8_t> value; };

	using ChannelState = variant<monostate,
		Stored<ChannelRequest>,
		shared_ptr<struct WaitingRef>,
		Stored<ChannelAccept>,
		unique_ptr<Channel>>;

	Connection connect(sockaddr_in6 addr);

	void updateIdentity(Identity self);
	void announceTo(variant<sockaddr_in, sockaddr_in6> addr);

	void shutdown();

private:
	bool recvfrom(vector<uint8_t> & buffer, sockaddr_in6 & addr);
	void sendto(const vector<uint8_t> & buffer, variant<sockaddr_in, sockaddr_in6> addr);

	void sendCookie(variant<sockaddr_in, sockaddr_in6> addr);
	optional<Connection> verifyNewConnection(const Header & header, sockaddr_in6 addr);

	Cookie generateCookie(variant<sockaddr_in, sockaddr_in6> addr) const;
	bool verifyCookie(variant<sockaddr_in, sockaddr_in6> addr, const Cookie & cookie) const;

	int sock;

	mutex protocolMutex;
	vector<uint8_t> buffer;

	optional<Identity> self;

	struct ConnectionPriv;
	vector<ConnectionPriv *> connections;
};

class NetworkProtocol::Connection
{
	friend class NetworkProtocol;
	Connection(unique_ptr<ConnectionPriv> p);
public:
	Connection(const Connection &) = delete;
	Connection(Connection &&);
	Connection & operator=(const Connection &) = delete;
	Connection & operator=(Connection &&);
	~Connection();

	using Id = uintptr_t;
	Id id() const;

	const sockaddr_in6 & peerAddress() const;

	optional<Header> receive(const PartialStorage &);
	bool send(const PartialStorage &, NetworkProtocol::Header,
			const vector<Object> &, bool secure);
	bool send( const StreamData & chunk );

	void close();

	shared_ptr< InStream > openInStream( uint8_t sid );
	shared_ptr< OutStream > openOutStream( uint8_t sid );

	// temporary:
	ChannelState & channel();
	void trySendOutQueue();

private:
	static variant< monostate, Header, StreamData >
		parsePacket(vector<uint8_t> & buf,
				Channel * channel, const PartialStorage & st,
				optional<uint64_t> & secure);

	unique_ptr<ConnectionPriv> p;
};

class NetworkProtocol::Stream
{
	friend class NetworkProtocol;
	friend class NetworkProtocol::Connection;

protected:
	Stream(uint8_t id_): id( id_ ) {}

	bool hasDataLocked() const;

	size_t writeLocked( const uint8_t * buf, size_t size );
	size_t readLocked( uint8_t * buf, size_t size );

	uint8_t id;
	bool closed { false };
	vector< uint8_t > writeBuffer;
	vector< uint8_t > readBuffer;
	vector< uint8_t >::const_iterator readPtr;
	mutable mutex streamMutex;
};

class NetworkProtocol::InStream : public NetworkProtocol::Stream
{
	friend class NetworkProtocol;
	friend class NetworkProtocol::Connection;

protected:
	InStream(uint8_t id): Stream( id ) {}

public:
	bool isComplete() const;
	vector< uint8_t > readAll();
	size_t read( uint8_t * buf, size_t size );

protected:
	void writeChunk( StreamData chunk );
	bool tryUseChunkLocked( const StreamData & chunk );

private:
	uint64_t nextSequence { 0 };
	vector< StreamData > outOfOrderChunks;
};

class NetworkProtocol::OutStream : public NetworkProtocol::Stream
{
	friend class NetworkProtocol;
	friend class NetworkProtocol::Connection;

protected:
	OutStream(uint8_t id): Stream( id ) {}

private:
	StreamData getNextChunkLocked( size_t size );

	uint64_t nextSequence { 0 };
};

struct NetworkProtocol::ReceivedAnnounce { sockaddr_in6 addr; Digest digest; };
struct NetworkProtocol::NewConnection { Connection conn; };
struct NetworkProtocol::ConnectionReadReady { Connection::Id id; };

struct NetworkProtocol::Header
{
	struct Acknowledged { Digest value; };
	struct AcknowledgedSingle { uint64_t value; };
	struct Version { string value; };
	struct Initiation { Digest value; };
	struct CookieSet { Cookie value; };
	struct CookieEcho { Cookie value; };
	struct DataRequest { Digest value; };
	struct DataResponse { Digest value; };
	struct AnnounceSelf { Digest value; };
	struct AnnounceUpdate { Digest value; };
	struct ChannelRequest { Digest value; };
	struct ChannelAccept { Digest value; };
	struct ServiceType { UUID value; };
	struct ServiceRef { Digest value; };
	struct StreamOpen { uint8_t value; };

	using Item = variant<
		Acknowledged,
		AcknowledgedSingle,
		Version,
		Initiation,
		CookieSet,
		CookieEcho,
		DataRequest,
		DataResponse,
		AnnounceSelf,
		AnnounceUpdate,
		ChannelRequest,
		ChannelAccept,
		ServiceType,
		ServiceRef,
		StreamOpen>;

	Header(const vector<Item> & items): items(items) {}
	static optional<Header> load(const PartialRef &);
	static optional<Header> load(const PartialObject &);
	PartialObject toObject(const PartialStorage &) const;

	template<class T> const T * lookupFirst() const;
	bool isAcknowledged() const;

	vector<Item> items;
};

struct NetworkProtocol::StreamData
{
	uint8_t id;
	uint8_t sequence;
	vector< uint8_t > data;
};

template<class T>
const T * NetworkProtocol::Header::lookupFirst() const
{
	for (const auto & h : items)
		if (auto ptr = std::get_if<T>(&h))
			return ptr;
	return nullptr;
}

bool operator==(const NetworkProtocol::Header::Item &, const NetworkProtocol::Header::Item &);
inline bool operator!=(const NetworkProtocol::Header::Item & left,
		const NetworkProtocol::Header::Item & right)
{ return not (left == right); }

inline bool operator==(const NetworkProtocol::Cookie & left, const NetworkProtocol::Cookie & right)
{ return left.value == right.value; }

class ReplyBuilder
{
public:
	void header(NetworkProtocol::Header::Item &&);
	void body(const Ref &);

	const vector<NetworkProtocol::Header::Item> & header() const { return mheader; }
	vector<Object> body() const;

private:
	vector<NetworkProtocol::Header::Item> mheader;
	vector<Ref> mbody;
};

struct WaitingRef
{
	const Storage storage;
	const PartialRef ref;
	vector<Digest> missing;

	optional<Ref> check();
	optional<Ref> check( ReplyBuilder &, const vector< Digest > &);
};

}