-
Notifications
You must be signed in to change notification settings - Fork 53
/
Network.cpp
345 lines (251 loc) · 11 KB
/
Network.cpp
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
#include "Network.h"
#include <cryptoTools/Common/Defines.h>
#include <cryptoTools/Network/Channel.h>
#include <cryptoTools/Network/IOService.h>
using namespace osuCrypto;
void networkTutorial()
{
std::cout << "\n"
<< "/*#####################################################\n"
<< "## Network tutorial ##\n"
<< "/*#####################################################" << std::endl;
/*#####################################################
## Setup ##
#####################################################*/
// create network I/O service with 4 background threads.
// This object must stay in scope until everything is cleaned up.
IOService ios(4);
std::string serversIpAddress = "127.0.0.1:1212";
// Network fully supports the multi party setting. A single
// server can connect to many clients with a single port.
// This is mannaged with connection names.
std::string connectionName = "party0_party1";
// connectionName denotes an identifier that both people on either side
// of this connection will use. If a server connects to several clients,
// they should all use different connection names.
Endpoint server(ios, serversIpAddress, EpMode::Server, connectionName);
Endpoint client(ios, serversIpAddress, EpMode::Client, connectionName);
// Two endpoints with the same connectionName can have many channels, each independent.
// To support that, each channel pair will have a unique name.
std::string channelName = "channelName";
// Actually get the channel that can be used to communicate on.
Channel chl0 = client.addChannel(channelName);
Channel chl1 = server.addChannel(channelName);
// we now have a pair of channels, but it is possible that they have yet
// to actually connect to each other in the background. To test that the
// channel has a completed the connection, we can do
std::cout << "Channel connected = " << chl0.isConnected() << std::endl;
// To block until we know for sure the channel is open, we can call
chl0.waitForConnection();
// This call will now always return true.
std::cout << "Channel connected = " << chl0.isConnected() << std::endl;
/*#####################################################
## The Basics ##
#####################################################*/
// There are several ways and modes to send and receive data.
// The simplest mode is block, i.e. when data is sent, the caller
// blocks until all data is sent.
// For example:
{
std::vector<int> data{ 0,1,2,3,4,5,6,7 };
chl0.send(data);
std::vector<int> dest;
chl1.recv(dest);
}
// It is now the case that data == dest. When data is received,
// the Channel will call dest.resize(8)
// In the example above,
// the Channel can tell that data is an STL like container.
// That is, it has member functions and types:
//
// Container<T>::data() -> Container<T>::pointer
// Container<T>::size() -> Container<T>::size_type
// Container<T>::value_type
//
// Anything with these traits can be used, e.g. std::array<T,N>.
{
std::array<int, 4> data{ 0,1,2,3 };
chl0.send(data);
std::array<int, 4> dest;
chl1.recv(dest);
}
// You can also use a pointer and length to send and receive data.
// In the case that the data being recieved is the wrong size,
// Channel::recv(...) will throw.
{
std::array<int, 4> data{ 0,1,2,3 };
chl0.send(data.data(), data.size());
std::array<int, 4> dest;
chl1.recv(dest.data(), dest.size()); // may throw
}
// One issue with this approach is that the call
//
// chl0.send(...);
//
// blocks until all of the data has been sent over the network. If data
// is large, or if we send amny things, then this may take awhile.
/*#####################################################
## Asynchronous ##
#####################################################*/
// We can overcome this with Asynchronous IO. These calls do not block.
// In this example, note that std::move semantics are used.
{
std::vector<int> data{ 0,1,2,3,4,5,6,7 };
chl0.asyncSend(std::move(data)); // will not block.
std::vector<int> dest;
chl1.recv(dest); // will block.
}
// the call
//
// Channel::asyncSend(...);
//
// does not block. Instead, it "steals" the data contained inside
// the vector. As a result, data is empty after this call.
// When move semantics are not supported by Container or if you want to
// share ownership of the data, we can use a unique/shared pointer.
{
std::unique_ptr<std::array<int, 8>> unique{ new std::array<int,8>{0,1,2,3,4,5,6,7 } };
chl0.asyncSend(std::move(unique)); // will not block.
// unique = empty
std::shared_ptr<std::array<int, 8>> shared{ new std::array<int,8>{0,1,2,3,4,5,6,7 } };
chl0.asyncSend(std::move(shared)); // will not block.
// shared's refernce counter = 2.
std::vector<int> dest;
chl1.recv(dest); // block for unique's data.
chl1.recv(dest); // block for shared's data.
// shared's refernce counter = 1.
}
// We can also perform asynchronous receive. In this case, we will tell the channel
// where to store data in the future...
{
std::vector<int> dest;
auto future = chl1.asyncRecv(dest); // will not block.
// dest == {}
// in the future, send the data.
std::vector<int> data{ 0,1,2,3,4,5,6,7 };
chl0.asyncSend(std::move(data)); // will not block.
// dest == ???
future.get(); // will block
// dest == {0,1,...,7}
}
// The above asyncRecv(...) is not often used, but it has at least one
// advantage. The implementation of Channel is optimize to store the
// data directly into dest. As opposed to buffering it interally, and
// the later copying it to dest when Channel::recv(...) is called.
// Channel::asyncSend(...) also support the pointer length interface.
// In this case, it is up to the user to ensure that the lifetime
// of data is larger than the time required to send. In this case, we are
// ok since chl1.recv(...) will block until this condition is true.
{
std::array<int, 4> data{ 0,1,2,3 };
chl0.asyncSend(data.data(), data.size());
std::vector<int> dest;
chl1.recv(dest);
}
// As an additional option for this interface, a call back
// function can be provided. This call back will be called
// once the data has been sent.
{
int size = 4;
int* data = new int[size]();
chl0.asyncSend(data, size, [data]()
{
// we are done with data now, delete it.
delete[] data;
});
std::vector<int> dest;
chl1.recv(dest);
}
// Finally, there is also a method to make a deep copy and send asynchronously.
{
std::vector<int> data{ 0,1,2,3,4,5,6,7 };
chl0.asyncSendCopy(data);
std::vector<int> dest;
chl1.recv(dest);
}
/*#####################################################
## Error Handling ##
#####################################################*/
// While not required, it is possible to recover from errors that
// are thrown when the receive buffer does not match the incoming
// data and can not be resized. Consider the following example
{
std::array<int, 4> data{ 0,1,2,3 };
chl0.send(data);
std::array<int, 2> dest;
try
{
// will throw, dest.size() != dat.size(); and no resize() member.
chl1.recv(dest);
}
catch (BadReceiveBufferSize b)
{
// catch the error, creat a new dest in bytes.
std::vector<u8> backup(b.mSize);
// tell the
b.mRescheduler(backup.data());
}
}
/*#####################################################
## Using your own socket ##
#####################################################*/
// It is also possible to use your own socket implementation
// with Channel. There are two methods for doing this. First,
// the osuCrypto::SocketAdapter<T> class can be used with your
// socket and then provided to a Channel with an osuCrypto::IOService
//
// SocketAdapter<T> requires that T implements
//
// void send(const char* data, u64 size);
// void recv( char* data, u64 size);
//
// Or a signature that is convertable from those parameter.
{
// Lets say you have a socket type that implements send(...),
// recv(...) and that is called YourSocketType
typedef Channel YourSocketType;
// Assuming your socket meets these rquirements, then a Channel
// can be constructed as follows. These Channels will function
// equivolently to the original ones.
//
// WARNING: The lifetime of the SocketAdapter<T> is managed by
// the Channel.
Channel aChl0(ios, new SocketAdapter<YourSocketType>(chl0));
Channel aChl1(ios, new SocketAdapter<YourSocketType>(chl1));
// We can now use the new channels
std::array<int, 4> data{ 0,1,2,3 };
aChl0.send(data);
aChl1.recv(data);
}
// If your Socket type does not have these methods a custom adapter
// will be required. The tamplate SocketAdapter<T> implements the
// interface SocketInterface in the <cryptoTools/Network/SocketAdapter.h>
// file. You will also have to define a class that inherits the
// SocketInterface class and implements:
//
// void send(ArrayView<boost::asio::mutable_buffer> buffers, bool& error, u64& bytesTransfered) override;
// void recv(ArrayView<boost::asio::mutable_buffer> buffers, bool& error, u64& bytesTransfered) override;
//
// For an example on how to implement these functions, see the
// defintion of SocketAdapter<T> in <cryptoTools/Network/SocketAdapter.h>
/*#####################################################
## Statistics ##
#####################################################*/
// Print interesting information.
std::cout
<< "Connection: " << chl0.getEndpoint().getName() << std::endl
<< " Channel: " << chl0.getName() << std::endl
<< " Send: " << chl0.getTotalDataSent() << std::endl
<< " received: " << chl0.getTotalDataRecv() << std::endl;
// Reset the data sent coutners.
chl0.resetStats();
/*#####################################################
## Clean up ##
#####################################################*/
// close everything down in this order. Must be done.
chl0.close();
chl1.close();
server.stop();
client.stop();
ios.stop();
}