-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathechoserver.cpp
More file actions
368 lines (314 loc) · 10 KB
/
Copy pathechoserver.cpp
File metadata and controls
368 lines (314 loc) · 10 KB
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include "rtmfp/RunLoops.hpp"
#include "rtmfp/FlashCryptoAdapter_OpenSSL.hpp"
#include "rtmfp/PerformerPosixPlatformAdapter.hpp"
#include "rtmfp/Hex.hpp"
#include "rtmfp/RedirectorClient.hpp"
#include "redirectorspec.hpp"
using namespace com::zenomt;
using namespace com::zenomt::rtmfp;
namespace {
int verbose = 0;
const char *name = "echo";
int port = 0;
bool requireHMAC = true;
bool requireSSEQ = true;
bool requireHostname = false;
bool interrupted = false;
void signal_handler(int param)
{
interrupted = true;
}
class Client : public Object {
public:
~Client()
{
if(verbose > 1)
printf("~Client\n");
}
static std::shared_ptr<Client> newClient(std::shared_ptr<RecvFlow> recvFlow)
{
auto client = share_ref(new Client(), false);
client->m_recv = recvFlow;
Bytes metadata = client->m_recv->getMetadata();
uint8_t tag[] = { ' ', 'r', 'e', 't', 'u', 'r', 'n' };
metadata.insert(metadata.end(), tag, tag + sizeof(tag));
client->m_send = recvFlow->openReturnFlow(metadata);
client->m_send->onException = [client] (uintmax_t reason) { client->onException(reason); };
client->m_send->onWritable = [client] { return client->onWritable(); };
client->m_recv->onMessage = [client] (const uint8_t *bytes, size_t len, uintmax_t sequenceNumber, size_t fragmentCount) { client->onMessage(bytes, len, sequenceNumber, fragmentCount); };
client->m_recv->onComplete = [client] (bool error) { client->onComplete(error); };
client->printInfo("new RecvFlow");
client->m_recv->setBufferCapacity(16*1024*1024);
client->m_send->setBufferCapacity(2*1024*1024);
client->m_recv->accept();
client->m_recv->onFarAddressDidChange = [client] { client->onAddressChanged(); };
return client;
}
void printInfo(const char *msg)
{
printf("Client %p: %s\n", (void *)this, msg);
if(not m_recv)
return;
printf(" addr: %s\n", m_recv->getFarAddress().toPresentation().c_str());
auto epd = m_recv->getFarCanonicalEPD();
if((epd.size() == 34) and (0x21 == epd[0]) and (0x0f == epd[1]))
printf(" fingerprint: %s\n", Hex::encode(epd.data() + 2, 32).c_str());
else
printf(" EPD: %s\n", Hex::encode(epd.data(), epd.size()).c_str());
printf(" metadata: %s\n", Hex::encode(m_recv->getMetadata()).c_str());
printf(" near nonce: %s\n", Hex::encode(m_recv->getNearNonce()).c_str());
printf(" far nonce: %s\n", Hex::encode(m_recv->getFarNonce()).c_str());
if(verbose > 1)
Hex::print(" certificate", m_recv->getFarCertificate());
printf("\n");
}
protected:
bool onWritable()
{
if(verbose)
printf("onWritable, re-enabling receive\n");
m_recv->setReceiveOrder(RO_SEQUENCE);
return false;
}
void onException(uintmax_t reason)
{
printf("exception\n");
m_recv->setReceiveOrder(RO_SEQUENCE);
m_send.reset();
}
void onMessage(const uint8_t *bytes, size_t len, uintmax_t sequenceNumber, size_t fragmentCount)
{
if(m_send)
{
m_send->write(bytes, len, 60, 60);
if(not m_send->isWritable())
{
m_recv->setReceiveOrder(RO_HOLD);
m_send->notifyWhenWritable();
if(verbose)
printf("send flow full, suspending receive\n");
}
}
if(verbose)
printf("onMessage %lu-%lu %lu\n", sequenceNumber, sequenceNumber + fragmentCount - 1, len);
}
void onComplete(bool error)
{
if(verbose)
printInfo(error ? "onComplete (error)" : "onComplete");
else
printf("Client %p: onComplete%s\n", (void *)this, error ? " (error)" : "");
if(m_send)
m_send->close();
m_send.reset();
m_recv.reset();
}
void onAddressChanged()
{
printInfo("far address changed");
}
std::shared_ptr<RecvFlow> m_recv;
std::shared_ptr<SendFlow> m_send;
};
void worker(RunLoop *rl)
{
printf("starting worker run loop\n");
rl->run();
printf("worker run loop and thread end\n");
}
bool addInterface(PerformerPosixPlatformAdapter *platform, int port, int family)
{
const char *familyName = (AF_INET6 == family) ? "IPv6" : "IPv4";
auto addr = platform->addUdpInterface(port, family);
if(addr)
printf("bound to %s port %d\n", familyName, addr->getPort());
else
printf("error: couldn't bind to %s port %d\n", familyName, port);
return !!addr;
}
int usage(const char *prog, const char *msg, int rv)
{
if(msg)
printf("%s\n", msg);
printf("usage: %s (-4 | -6 | -B addr:port) [options]\n", prog);
printf(" -p port -- port for -4/-6 (default %d)\n", port);
printf(" -4 -- bind to IPv4 0.0.0.0:%d\n", port);
printf(" -6 -- bind to IPv6 [::]:%d\n", port);
printf(" -B addr:port -- bind to addr:port explicitly\n");
printf(" -n name -- hostname (default %s)\n", name);
printf(" -N -- require hostname to connect\n");
printf(" -H -- don't require HMAC\n");
printf(" -S -- don't require session sequence numbers\n");
printf(" -l user:passw -- add redirector (load balancer) username:password\n");
printf(" -L redir-spec -- add redirector spec <hostname>@<ip:port>[,ip:port...]\n");
printf(" -A addr:port -- advertise addr:port at redirector\n");
printf(" -R -- suppress redirector advertising reflexive (derived) address\n");
printf(" -v -- increase verbose output\n");
printf(" -h -- show this help\n");
return rv;
}
}
int main(int argc, char **argv)
{
bool ipv4 = false;
bool ipv6 = false;
bool advertiseReflexive = true;
std::vector<Address> bindAddrs;
int ch;
std::map<std::string, std::string> redirectAuth;
std::map<std::string, std::vector<Address>> redirectorSpecs;
std::vector<std::shared_ptr<RedirectorClient>> redirectors;
std::vector<Address> advertiseAddresses;
srand(time(NULL));
while((ch = getopt(argc, argv, "vh46B:NHSn:p:l:L:A:R")) != -1)
{
switch(ch)
{
case 'v':
verbose++;
break;
case '4':
ipv4 = true;
break;
case '6':
ipv6 = true;
break;
case 'B':
{
Address addr;
if(not addr.setFromPresentation(optarg))
{
printf("can't parse address %s\n", optarg);
return 1;
}
bindAddrs.push_back(addr);
}
break;
case 'N':
requireHostname = true;
break;
case 'H':
requireHMAC = false;
break;
case 'S':
requireSSEQ = false;
break;
case 'n':
name = optarg;
break;
case 'p':
port = atoi(optarg);
break;
// redirector stuff
case 'l':
{
std::string str = optarg;
memset(optarg, '#', strlen(optarg));
auto pos = str.find(':');
if(std::string::npos == pos)
{
printf("can't parse redirector username:password\n");
return 1;
}
redirectAuth[str.substr(0, pos)] = str.substr(pos + 1);
}
break;
case 'L':
{
if(not parse_redirector_spec(optarg, redirectorSpecs))
{
printf("bad redirector spec '%s'\nredirector spec is <hostname>@<addr:port>[,addr:port...]\n", optarg);
return 1;
}
}
break;
case 'A':
{
Address addr;
if(not addr.setFromPresentation(optarg))
{
printf("can't parse address %s\n", optarg);
return 1;
}
advertiseAddresses.push_back(addr);
}
break;
case 'R':
advertiseReflexive = false;
break;
case 'h':
default:
return usage(argv[0], NULL, 'h' == ch);
}
}
if(not (bindAddrs.size() or ipv4 or ipv6))
return usage(argv[0], "specify at least -4, -6, or -B", 1);
FlashCryptoAdapter_OpenSSL crypto;
if(not crypto.init(not requireHostname, name))
{
printf("crypto.init error\n");
return 1;
}
crypto.setHMACSendAlways(requireHMAC);
crypto.setHMACRecvRequired(requireHMAC);
crypto.setSSeqSendAlways(requireSSEQ);
crypto.setSSeqRecvRequired(requireSSEQ);
printf("my fingerprint: %s static: %s\n", Hex::encode(crypto.getFingerprint()).c_str(), crypto.isStatic() ? "yes" : "no");
printf("my name: %s\n", name);
PreferredRunLoop rl;
Performer performer(&rl);
PreferredRunLoop workerRL;
Performer workerPerformer(&workerRL);
PerformerPosixPlatformAdapter platform(&rl, &performer, &workerPerformer);
RTMFP rtmfp(&platform, &crypto);
platform.setRtmfp(&rtmfp);
rtmfp.setDefaultSessionKeepalivePeriod(10);
rtmfp.setDefaultSessionRetransmitLimit(20);
rtmfp.setDefaultSessionIdleLimit(300);
rtmfp.onRecvFlow = Client::newClient;
for(auto it = bindAddrs.begin(); it != bindAddrs.end(); it++)
{
auto boundAddr = platform.addUdpInterface(it->getSockaddr());
if(not boundAddr)
{
printf("can't bind to requested address: %s\n", it->toPresentation().c_str());
return 1;
}
printf("bound to %s\n", boundAddr->toPresentation().c_str());
}
// do IPv4 first in case IPv6 binds to both families
if(ipv4 and not addInterface(&platform, port, AF_INET))
return 1;
if(ipv6 and not addInterface(&platform, port, AF_INET6))
return 1;
for(auto it = redirectorSpecs.begin(); it != redirectorSpecs.end(); it++)
{
auto hostname = it->first;
Bytes epd = crypto.makeEPD(nullptr, nullptr, hostname.c_str());
auto redirectorClient = share_ref(new FlashCryptoRunLoopRedirectorClient(&rtmfp, epd, &rl, &crypto), false);
config_redirector_client(redirectorClient.get(), redirectAuth, it->second, advertiseAddresses, advertiseReflexive);
redirectorClient->onReflexiveAddress = [hostname] (const Address &addr) { if(verbose) printf("redirector %s reports reflexive address %s\n", hostname.c_str(), addr.toPresentation().c_str()); };
redirectorClient->onStatus = [hostname, redirectorClient] (RedirectorClient::Status status) {
if(verbose) printf("redirector %s status %d\n", hostname.c_str(), status);
if(verbose and (RedirectorClient::STATUS_CONNECTED == redirectorClient->getStatus()))
printf("Connected to redirector %s\n", redirectorClient->getRedirectorAddress().toPresentation().c_str());
};
redirectorClient->connect();
redirectors.push_back(redirectorClient);
}
::signal(SIGINT, signal_handler);
::signal(SIGTERM, signal_handler);
rl.onEveryCycle = [&rtmfp] { if(interrupted) { interrupted = false; rtmfp.shutdown(true); printf("interrupted. shutting down.\n"); } };
platform.onShutdownCompleteCallback = [&rl] { rl.stop(); };
auto workerThread = std::thread(worker, &workerRL);
rl.run();
workerPerformer.perform([&workerRL] { workerRL.stop(); });
workerThread.join();
printf("end.\n");
return 0;
}