forked from Haivision/srt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
srt-tunnel.cpp
1207 lines (989 loc) · 29.8 KB
/
srt-tunnel.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
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// MSVS likes to complain about lots of standard C functions being unsafe.
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS 1
#include <io.h>
#endif
#include "platform_sys.h"
#define REQUIRE_CXX11 1
#include <cctype>
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <set>
#include <vector>
#include <deque>
#include <memory>
#include <algorithm>
#include <iterator>
#include <stdexcept>
#include <cstring>
#include <csignal>
#include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>
#include "apputil.hpp" // CreateAddr
#include "uriparser.hpp" // UriParser
#include "socketoptions.hpp"
#include "logsupport.hpp"
#include "transmitbase.hpp" // bytevector typedef to avoid collisions
#include "verbose.hpp"
// NOTE: This is without "haisrt/" because it uses an internal path
// to the library. Application using the "installed" library should
// use <srt/srt.h>
#include <srt.h>
#include <udt.h> // This TEMPORARILY contains extra C++-only SRT API.
#include <logging.h>
#include <api.h>
#include <utilities.h>
/*
# MAF contents for this file. Note that not every file from the support
# library is used, but to simplify the build definition it links against
# the whole srtsupport library.
SOURCES
srt-test-tunnel.cpp
testmedia.cpp
../apps/verbose.cpp
../apps/socketoptions.cpp
../apps/uriparser.cpp
../apps/logsupport.cpp
*/
using namespace std;
using namespace srt;
const srt_logging::LogFA SRT_LOGFA_APP = 10;
namespace srt_logging
{
Logger applog(SRT_LOGFA_APP, srt_logger_config, "TUNNELAPP");
}
using srt_logging::applog;
class Medium
{
static int s_counter;
int m_counter;
public:
enum ReadStatus
{
RD_DATA, RD_AGAIN, RD_EOF, RD_ERROR
};
enum Mode
{
LISTENER, CALLER
};
protected:
UriParser m_uri;
size_t m_chunk = 0;
map<string, string> m_options;
Mode m_mode;
bool m_listener = false;
bool m_open = false;
bool m_eof = false;
bool m_broken = false;
std::mutex access; // For closing
template <class DerivedMedium, class SocketType>
static Medium* CreateAcceptor(DerivedMedium* self, const sockaddr_any& sa, SocketType sock, size_t chunk)
{
string addr = sockaddr_any(sa.get(), sizeof sa).str();
DerivedMedium* m = new DerivedMedium(UriParser(self->type() + string("://") + addr), chunk);
m->m_socket = sock;
return m;
}
public:
string uri() { return m_uri.uri(); }
string id()
{
std::ostringstream os;
os << type() << m_counter;
return os.str();
}
Medium(const UriParser& u, size_t ch): m_counter(s_counter++), m_uri(u), m_chunk(ch) {}
Medium(): m_counter(s_counter++) {}
virtual const char* type() = 0;
virtual bool IsOpen() = 0;
virtual void CloseInternal() = 0;
void CloseState()
{
m_open = false;
m_broken = true;
}
// External API for this class that allows to close
// the entity on request. The CloseInternal should
// redirect to a type-specific function, the same that
// should be also called in destructor.
void Close()
{
CloseState();
CloseInternal();
}
virtual bool End() = 0;
virtual int ReadInternal(char* output, int size) = 0;
virtual bool IsErrorAgain() = 0;
ReadStatus Read(bytevector& output);
virtual void Write(bytevector& portion) = 0;
virtual void CreateListener() = 0;
virtual void CreateCaller() = 0;
virtual unique_ptr<Medium> Accept() = 0;
virtual void Connect() = 0;
static std::unique_ptr<Medium> Create(const std::string& url, size_t chunk, Mode);
virtual bool Broken() = 0;
virtual size_t Still() { return 0; }
class ReadEOF: public std::runtime_error
{
public:
ReadEOF(const std::string& fn): std::runtime_error( "EOF while reading file: " + fn )
{
}
};
class TransmissionError: public std::runtime_error
{
public:
TransmissionError(const std::string& fn): std::runtime_error( fn )
{
}
};
static void Error(const string& text)
{
throw TransmissionError("ERROR (internal): " + text);
}
virtual ~Medium()
{
CloseState();
}
protected:
void InitMode(Mode m)
{
m_mode = m;
Init();
if (m_mode == LISTENER)
{
CreateListener();
m_listener = true;
}
else
{
CreateCaller();
}
m_open = true;
}
virtual void Init() {}
};
class Engine
{
Medium* media[2];
std::thread thr;
class Tunnel* parent_tunnel;
std::string nameid;
int status = 0;
Medium::ReadStatus rdst = Medium::RD_ERROR;
UDT::ERRORINFO srtx;
public:
enum Dir { DIR_IN, DIR_OUT };
int stat() { return status; }
Engine(Tunnel* p, Medium* m1, Medium* m2, const std::string& nid)
:
#ifdef HAVE_FULL_CXX11
media {m1, m2},
#endif
parent_tunnel(p), nameid(nid)
{
#ifndef HAVE_FULL_CXX11
// MSVC is not exactly C++11 compliant and complains around
// initialization of an array.
// Leaving this method of initialization for clarity and
// possibly more preferred performance.
media[0] = m1;
media[1] = m2;
#endif
}
void Start()
{
Verb() << "START: " << media[DIR_IN]->uri() << " --> " << media[DIR_OUT]->uri();
const std::string thrn = media[DIR_IN]->id() + ">" + media[DIR_OUT]->id();
srt::ThreadName tn(thrn);
thr = thread([this]() { Worker(); });
}
void Stop()
{
// If this thread is already stopped, don't stop.
if (thr.joinable())
{
LOGP(applog.Debug, "Engine::Stop: Closing media:");
// Close both media as a hanged up reading thread
// will block joining.
media[0]->Close();
media[1]->Close();
LOGP(applog.Debug, "Engine::Stop: media closed, joining engine thread:");
if (thr.get_id() == std::this_thread::get_id())
{
// If this is this thread which called this, no need
// to stop because this thread will exit by itself afterwards.
// You must, however, detach yourself, or otherwise the thr's
// destructor would kill the program.
thr.detach();
LOGP(applog.Debug, "DETACHED.");
}
else
{
thr.join();
LOGP(applog.Debug, "Joined.");
}
}
}
void Worker();
};
struct Tunnelbox;
class Tunnel
{
Tunnelbox* parent_box;
std::unique_ptr<Medium> med_acp, med_clr;
Engine acp_to_clr, clr_to_acp;
srt::sync::atomic<bool> running{true};
std::mutex access;
public:
string show()
{
return med_acp->uri() + " <-> " + med_clr->uri();
}
Tunnel(Tunnelbox* m, std::unique_ptr<Medium>&& acp, std::unique_ptr<Medium>&& clr):
parent_box(m),
med_acp(std::move(acp)), med_clr(std::move(clr)),
acp_to_clr(this, med_acp.get(), med_clr.get(), med_acp->id() + ">" + med_clr->id()),
clr_to_acp(this, med_clr.get(), med_acp.get(), med_clr->id() + ">" + med_acp->id())
{
}
void Start()
{
acp_to_clr.Start();
clr_to_acp.Start();
}
// This is to be called by an Engine from Engine::Worker
// thread.
// [[affinity = acp_to_clr.thr || clr_to_acp.thr]];
void decommission_engine(Medium* which_medium)
{
// which_medium is the medium that failed.
// Upon breaking of one medium from the pair,
// the other needs to be closed as well.
Verb() << "Medium broken: " << which_medium->uri();
bool stop = true;
/*
{
lock_guard<std::mutex> lk(access);
if (acp_to_clr.stat() == -1 && clr_to_acp.stat() == -1)
{
Verb() << "Tunnel: Both engine decommissioned, will stop the tunnel.";
// Both engines are down, decommission the tunnel.
// Note that the status -1 means that particular engine
// is not currently running and you can safely
// join its thread.
stop = true;
}
else
{
Verb() << "Tunnel: Decommissioned one engine, waiting for the other one to report";
}
}
*/
if (stop)
{
// First, stop all media.
med_acp->Close();
med_clr->Close();
// Then stop the tunnel (this is only a signal
// to a cleanup thread to delete it).
Stop();
}
}
void Stop();
bool decommission_if_dead(bool forced); // [[affinity = g_tunnels.thr]]
};
void Engine::Worker()
{
bytevector outbuf;
Medium* which_medium = media[DIR_IN];
for (;;)
{
try
{
which_medium = media[DIR_IN];
rdst = media[DIR_IN]->Read((outbuf));
switch (rdst)
{
case Medium::RD_DATA:
{
which_medium = media[DIR_OUT];
// We get the data, write them to the output
media[DIR_OUT]->Write((outbuf));
}
break;
case Medium::RD_EOF:
status = -1;
throw Medium::ReadEOF("");
case Medium::RD_AGAIN:
// Theoreticall RD_AGAIN should not be reported
// because it should be taken care of internally by
// repeated sending - unless we get m_broken set.
// If it is, however, it should be handled just like error.
case Medium::RD_ERROR:
status = -1;
Medium::Error("Error while reading");
}
}
catch (Medium::ReadEOF&)
{
Verb() << "EOF. Exiting engine.";
break;
}
catch (Medium::TransmissionError& er)
{
Verb() << er.what() << " - interrupting engine: " << nameid;
break;
}
}
// This is an engine thread and it should simply
// tell the parent_box Tunnel that it is no longer
// operative. It's not necessary to inform it which
// of two engines is decommissioned - it should only
// know that one of them got down. It will then check
// if both are down here and decommission the whole
// tunnel if so.
parent_tunnel->decommission_engine(which_medium);
}
class SrtMedium: public Medium
{
SRTSOCKET m_socket = SRT_ERROR;
friend class Medium;
public:
#ifdef HAVE_FULL_CXX11
using Medium::Medium;
#else // MSVC and gcc 4.7 not exactly support C++11
SrtMedium(UriParser u, size_t ch): Medium(u, ch) {}
#endif
bool IsOpen() override { return m_open; }
bool End() override { return m_eof; }
bool Broken() override { return m_broken; }
void CloseSrt()
{
Verb() << "Closing SRT socket for " << uri();
lock_guard<std::mutex> lk(access);
if (m_socket == SRT_ERROR)
return;
srt_close(m_socket);
m_socket = SRT_ERROR;
}
// Forwarded in order to separate the implementation from
// the virtual function so that virtual function is not
// being called in destructor.
void CloseInternal() override { return CloseSrt(); }
const char* type() override { return "srt"; }
int ReadInternal(char* output, int size) override;
bool IsErrorAgain() override;
void Write(bytevector& portion) override;
void CreateListener() override;
void CreateCaller() override;
unique_ptr<Medium> Accept() override;
void Connect() override;
protected:
void Init() override;
void ConfigurePre();
void ConfigurePost(SRTSOCKET socket);
using Medium::Error;
static void Error(UDT::ERRORINFO& ri, const string& text)
{
throw TransmissionError("ERROR: " + text + ": " + ri.getErrorMessage());
}
~SrtMedium() override
{
CloseState();
CloseSrt();
}
};
class TcpMedium: public Medium
{
int m_socket = -1;
friend class Medium;
public:
#ifdef HAVE_FULL_CXX11
using Medium::Medium;
#else // MSVC not exactly supports C++11
TcpMedium(UriParser u, size_t ch): Medium(u, ch) {}
#endif
#ifdef _WIN32
static int tcp_close(int socket)
{
return ::closesocket(socket);
}
enum { DEF_SEND_FLAG = 0 };
#elif defined(LINUX) || defined(GNU) || defined(CYGWIN)
static int tcp_close(int socket)
{
return ::close(socket);
}
enum { DEF_SEND_FLAG = MSG_NOSIGNAL };
#else
static int tcp_close(int socket)
{
return ::close(socket);
}
enum { DEF_SEND_FLAG = 0 };
#endif
bool IsOpen() override { return m_open; }
bool End() override { return m_eof; }
bool Broken() override { return m_broken; }
void CloseTcp()
{
Verb() << "Closing TCP socket for " << uri();
lock_guard<std::mutex> lk(access);
if (m_socket == -1)
return;
tcp_close(m_socket);
m_socket = -1;
}
void CloseInternal() override { return CloseTcp(); }
const char* type() override { return "tcp"; }
int ReadInternal(char* output, int size) override;
bool IsErrorAgain() override;
void Write(bytevector& portion) override;
void CreateListener() override;
void CreateCaller() override;
unique_ptr<Medium> Accept() override;
void Connect() override;
protected:
void ConfigurePre()
{
#if defined(__APPLE__)
int optval = 1;
setsockopt(m_socket, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval));
#endif
}
void ConfigurePost(int)
{
}
using Medium::Error;
static void Error(int verrno, const string& text)
{
char rbuf[1024];
throw TransmissionError("ERROR: " + text + ": " + SysStrError(verrno, rbuf, 1024));
}
virtual ~TcpMedium()
{
CloseState();
CloseTcp();
}
};
void SrtMedium::Init()
{
// This function is required due to extra option
// check need
if (m_options.count("mode"))
Error("No option 'mode' is required, it defaults to position of the argument");
if (m_options.count("blocking"))
Error("Blocking is not configurable here.");
// XXX
// Look also for other options that should not be here.
// Enforce the transtype = file
m_options["transtype"] = "file";
}
void SrtMedium::ConfigurePre()
{
vector<string> fails;
m_options["mode"] = "caller";
SrtConfigurePre(m_socket, "", m_options, &fails);
if (!fails.empty())
{
cerr << "Failed options: " << Printable(fails) << endl;
}
}
void SrtMedium::ConfigurePost(SRTSOCKET so)
{
vector<string> fails;
SrtConfigurePost(so, m_options, &fails);
if (!fails.empty())
{
cerr << "Failed options: " << Printable(fails) << endl;
}
}
void SrtMedium::CreateListener()
{
int backlog = 5; // hardcoded!
m_socket = srt_create_socket();
ConfigurePre();
sockaddr_any sa = CreateAddr(m_uri.host(), m_uri.portno());
int stat = srt_bind(m_socket, sa.get(), sizeof sa);
if ( stat == SRT_ERROR )
{
srt_close(m_socket);
Error(UDT::getlasterror(), "srt_bind");
}
stat = srt_listen(m_socket, backlog);
if ( stat == SRT_ERROR )
{
srt_close(m_socket);
Error(UDT::getlasterror(), "srt_listen");
}
m_listener = true;
};
void TcpMedium::CreateListener()
{
int backlog = 5; // hardcoded!
sockaddr_any sa = CreateAddr(m_uri.host(), m_uri.portno());
m_socket = (int)socket(sa.get()->sa_family, SOCK_STREAM, IPPROTO_TCP);
ConfigurePre();
int stat = ::bind(m_socket, sa.get(), sa.size());
if (stat == -1)
{
tcp_close(m_socket);
Error(errno, "bind");
}
stat = listen(m_socket, backlog);
if ( stat == -1 )
{
tcp_close(m_socket);
Error(errno, "listen");
}
m_listener = true;
}
unique_ptr<Medium> SrtMedium::Accept()
{
sockaddr_any sa;
SRTSOCKET s = srt_accept(m_socket, (sa.get()), (&sa.len));
if (s == SRT_ERROR)
{
Error(UDT::getlasterror(), "srt_accept");
}
ConfigurePost(s);
// Configure 1s timeout
int timeout_1s = 1000;
srt_setsockflag(m_socket, SRTO_RCVTIMEO, &timeout_1s, sizeof timeout_1s);
unique_ptr<Medium> med(CreateAcceptor(this, sa, s, m_chunk));
Verb() << "accepted a connection from " << med->uri();
return med;
}
unique_ptr<Medium> TcpMedium::Accept()
{
sockaddr_any sa;
int s = (int)::accept(m_socket, (sa.get()), (&sa.syslen()));
if (s == -1)
{
Error(errno, "accept");
}
// Configure 1s timeout
timeval timeout_1s { 1, 0 };
int st SRT_ATR_UNUSED = setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout_1s, sizeof timeout_1s);
timeval re;
socklen_t size = sizeof re;
int st2 SRT_ATR_UNUSED = getsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&re, &size);
LOGP(applog.Debug, "Setting SO_RCVTIMEO to @", m_socket, ": ", st == -1 ? "FAILED" : "SUCCEEDED",
", read-back value: ", st2 == -1 ? int64_t(-1) : (int64_t(re.tv_sec)*1000000 + re.tv_usec)/1000, "ms");
unique_ptr<Medium> med(CreateAcceptor(this, sa, s, m_chunk));
Verb() << "accepted a connection from " << med->uri();
return med;
}
void SrtMedium::CreateCaller()
{
m_socket = srt_create_socket();
ConfigurePre();
// XXX setting up outgoing port not supported
}
void TcpMedium::CreateCaller()
{
m_socket = (int)::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
ConfigurePre();
}
void SrtMedium::Connect()
{
sockaddr_any sa = CreateAddr(m_uri.host(), m_uri.portno());
int st = srt_connect(m_socket, sa.get(), sizeof sa);
if (st == SRT_ERROR)
Error(UDT::getlasterror(), "srt_connect");
ConfigurePost(m_socket);
// Configure 1s timeout
int timeout_1s = 1000;
srt_setsockflag(m_socket, SRTO_RCVTIMEO, &timeout_1s, sizeof timeout_1s);
}
void TcpMedium::Connect()
{
sockaddr_any sa = CreateAddr(m_uri.host(), m_uri.portno());
int st = ::connect(m_socket, sa.get(), sa.size());
if (st == -1)
Error(errno, "connect");
ConfigurePost(m_socket);
// Configure 1s timeout
timeval timeout_1s { 1, 0 };
setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout_1s, sizeof timeout_1s);
}
int SrtMedium::ReadInternal(char* w_buffer, int size)
{
int st = -1;
do
{
st = srt_recv(m_socket, (w_buffer), size);
if (st == SRT_ERROR)
{
int syserr;
if (srt_getlasterror(&syserr) == SRT_EASYNCRCV && !m_broken)
continue;
}
break;
} while (true);
return st;
}
int TcpMedium::ReadInternal(char* w_buffer, int size)
{
int st = -1;
LOGP(applog.Debug, "TcpMedium:recv @", m_socket, " - begin");
do
{
st = ::recv(m_socket, (w_buffer), size, 0);
if (st == -1)
{
if ((errno == EAGAIN || errno == EWOULDBLOCK))
{
if (!m_broken)
{
LOGP(applog.Debug, "TcpMedium: read:AGAIN, repeating");
continue;
}
LOGP(applog.Debug, "TcpMedium: read:AGAIN, not repeating - already broken");
}
else
{
LOGP(applog.Debug, "TcpMedium: read:ERROR: ", errno);
}
}
break;
} while (true);
LOGP(applog.Debug, "TcpMedium:recv @", m_socket, " - result: ", st);
return st;
}
bool SrtMedium::IsErrorAgain()
{
return srt_getlasterror(NULL) == SRT_EASYNCRCV;
}
bool TcpMedium::IsErrorAgain()
{
return errno == EAGAIN;
}
// The idea of Read function is to get the buffer that
// possibly contains some data not written to the output yet,
// but the time has come to read. We can't let the buffer expand
// more than the size of the chunk, so if the buffer size already
// exceeds it, don't return any data, but behave as if they were read.
// This will cause the worker loop to redirect to Write immediately
// thereafter and possibly will flush out the remains of the buffer.
// It's still possible that the buffer won't be completely purged
Medium::ReadStatus Medium::Read(bytevector& w_output)
{
// Don't read, but fake that you read
if (w_output.size() > m_chunk)
{
Verb() << "BUFFER EXCEEDED";
return RD_DATA;
}
// Resize to maximum first
size_t shift = w_output.size();
if (shift && m_eof)
{
// You have nonempty buffer, but eof was already
// encountered. Report as if something was read.
//
// Don't read anything because this will surely
// result in error since now.
return RD_DATA;
}
size_t pred_size = shift + m_chunk;
w_output.resize(pred_size);
int st = ReadInternal((w_output.data() + shift), (int)m_chunk);
if (st == -1)
{
if (IsErrorAgain())
return RD_AGAIN;
return RD_ERROR;
}
if (st == 0)
{
m_eof = true;
if (shift)
{
// If there's 0 (eof), but you still have data
// in the buffer, fake that they were read. Only
// when the buffer was empty at entrance should this
// result with EOF.
//
// Set back the size this buffer had before we attempted
// to read into it.
w_output.resize(shift);
return RD_DATA;
}
w_output.clear();
return RD_EOF;
}
w_output.resize(shift+st);
return RD_DATA;
}
void SrtMedium::Write(bytevector& w_buffer)
{
int st = srt_send(m_socket, w_buffer.data(), (int)w_buffer.size());
if (st == SRT_ERROR)
{
Error(UDT::getlasterror(), "srt_send");
}
// This should be ==, whereas > is not possible, but
// this should simply embrace this case as a sanity check.
if (st >= int(w_buffer.size()))
w_buffer.clear();
else if (st == 0)
{
Error("Unexpected EOF on Write");
}
else
{
// Remove only those bytes that were sent
w_buffer.erase(w_buffer.begin(), w_buffer.begin()+st);
}
}
void TcpMedium::Write(bytevector& w_buffer)
{
int st = ::send(m_socket, w_buffer.data(), (int)w_buffer.size(), DEF_SEND_FLAG);
if (st == -1)
{
Error(errno, "send");
}
// This should be ==, whereas > is not possible, but
// this should simply embrace this case as a sanity check.
if (st >= int(w_buffer.size()))
w_buffer.clear();
else if (st == 0)
{
Error("Unexpected EOF on Write");
}
else
{
// Remove only those bytes that were sent
w_buffer.erase(w_buffer.begin(), w_buffer.begin()+st);
}
}
std::unique_ptr<Medium> Medium::Create(const std::string& url, size_t chunk, Medium::Mode mode)
{
UriParser uri(url);
std::unique_ptr<Medium> out;
// Might be something smarter, but there are only 2 types.
if (uri.scheme() == "srt")
{
out.reset(new SrtMedium(uri, chunk));
}
else if (uri.scheme() == "tcp")
{
out.reset(new TcpMedium(uri, chunk));
}
else
{
Error("Medium not supported");
}
out->InitMode(mode);
return out;
}
struct Tunnelbox
{
list<unique_ptr<Tunnel>> tunnels;
std::mutex access;
condition_variable decom_ready;
bool main_running = true;
thread thr;
void signal_decommission()
{
lock_guard<std::mutex> lk(access);
decom_ready.notify_one();
}
void install(std::unique_ptr<Medium>&& acp, std::unique_ptr<Medium>&& clr)
{
lock_guard<std::mutex> lk(access);
Verb() << "Tunnelbox: Starting tunnel: " << acp->uri() << " <-> " << clr->uri();
tunnels.emplace_back(new Tunnel(this, std::move(acp), std::move(clr)));
// Note: after this instruction, acp and clr are no longer valid!
auto& it = tunnels.back();
it->Start();
}
void start_cleaner()
{
thr = thread( [this]() { CleanupWorker(); } );
}
void stop_cleaner()
{
if (thr.joinable())
thr.join();
}
private:
void CleanupWorker()
{
unique_lock<std::mutex> lk(access);
while (main_running)
{
decom_ready.wait(lk);