Debian Codegraph @

apps/srt-tunnel.cpp

raw
1 // MSVS likes to complain about lots of standard C functions being unsafe.
2 #ifdef _MSC_VER
3 #define _CRT_SECURE_NO_WARNINGS 1
4 #include <io.h>
5 #endif
6
7 #include "platform_sys.h"
8
9 #define REQUIRE_CXX11 1
10
11 #include <cctype>
12 #include <iostream>
13 #include <fstream>
14 #include <string>
15 #include <map>
16 #include <set>
17 #include <vector>
18 #include <deque>
19 #include <memory>
20 #include <algorithm>
21 #include <iterator>
22 #include <stdexcept>
23 #include <cstring>
24 #include <csignal>
25 #include <chrono>
26 #include <thread>
27 #include <mutex>
28 #include <condition_variable>
29
30 #include "srt_compat.h"
31 #include "apputil.hpp" // CreateAddr
32 #include "uriparser.hpp" // UriParser
33 #include "socketoptions.hpp"
34 #include "logsupport.hpp"
35 #include "transmitbase.hpp" // bytevector typedef to avoid collisions
36 #include "verbose.hpp"
37
38 // NOTE: This is without "haisrt/" because it uses an internal path
39 // to the library. Application using the "installed" library should
40 // use <srt/srt.h>
41 #include <srt.h>
42 #include <udt.h> // This TEMPORARILY contains extra C++-only SRT API.
43 #include <logging.h>
44 #include <api.h>
45 #include <utilities.h>
46
47 /*
48 # MAF contents for this file. Note that not every file from the support
49 # library is used, but to simplify the build definition it links against
50 # the whole srtsupport library.
51
52 SOURCES
53 srt-test-tunnel.cpp
54 testmedia.cpp
55 ../apps/verbose.cpp
56 ../apps/socketoptions.cpp
57 ../apps/uriparser.cpp
58 ../apps/logsupport.cpp
59
60 */
61
62 using namespace std;
63 using namespace srt;
64
65 const srt_logging::LogFA SRT_LOGFA_APP = 10;
66 namespace srt_logging
67 {
68 Logger applog(SRT_LOGFA_APP, srt_logger_config, "TUNNELAPP");
69 }
70
71 using srt_logging::applog;
72
73 class Medium
74 {
75 static int s_counter;
76 int m_counter;
77 public:
78 enum ReadStatus
79 {
80 RD_DATA, RD_AGAIN, RD_EOF, RD_ERROR
81 };
82
83 enum Mode
84 {
85 LISTENER, CALLER
86 };
87
88 protected:
89 UriParser m_uri;
90 size_t m_chunk = 0;
91 map<string, string> m_options;
92 Mode m_mode;
93
94 bool m_listener = false;
95 bool m_open = false;
96 bool m_eof = false;
97 bool m_broken = false;
98
99 std::mutex access; // For closing
100
101 template <class DerivedMedium, class SocketType>
102 static Medium* CreateAcceptor(DerivedMedium* self, const sockaddr_any& sa, SocketType sock, size_t chunk)
103 {
104 string addr = sockaddr_any(sa.get(), sizeof sa).str();
105 DerivedMedium* m = new DerivedMedium(UriParser(self->type() + string("://") + addr), chunk);
106 m->m_socket = sock;
107 return m;
108 }
109
110 public:
111
112 string uri() { return m_uri.uri(); }
113 string id()
114 {
115 std::ostringstream os;
116 os << type() << m_counter;
117 return os.str();
118 }
119
120 Medium(const UriParser& u, size_t ch): m_counter(s_counter++), m_uri(u), m_chunk(ch) {}
121 Medium(): m_counter(s_counter++) {}
122
123 virtual const char* type() = 0;
124 virtual bool IsOpen() = 0;
125 virtual void CloseInternal() = 0;
126
127 void CloseState()
128 {
129 m_open = false;
130 m_broken = true;
131 }
132
133 // External API for this class that allows to close
134 // the entity on request. The CloseInternal should
135 // redirect to a type-specific function, the same that
136 // should be also called in destructor.
137 void Close()
138 {
139 CloseState();
140 CloseInternal();
141 }
142 virtual bool End() = 0;
143
144 virtual int ReadInternal(char* output, int size) = 0;
145 virtual bool IsErrorAgain() = 0;
146
147 ReadStatus Read(bytevector& output);
148 virtual void Write(bytevector& portion) = 0;
149
150 virtual void CreateListener() = 0;
151 virtual void CreateCaller() = 0;
152 virtual unique_ptr<Medium> Accept() = 0;
153 virtual void Connect() = 0;
154
155 static std::unique_ptr<Medium> Create(const std::string& url, size_t chunk, Mode);
156
157 virtual bool Broken() = 0;
158 virtual size_t Still() { return 0; }
159
160 class ReadEOF: public std::runtime_error
161 {
162 public:
163 ReadEOF(const std::string& fn): std::runtime_error( "EOF while reading file: " + fn )
164 {
165 }
166 };
167
168 class TransmissionError: public std::runtime_error
169 {
170 public:
171 TransmissionError(const std::string& fn): std::runtime_error( fn )
172 {
173 }
174 };
175
176 static void Error(const string& text)
177 {
178 throw TransmissionError("ERROR (internal): " + text);
179 }
180
181 virtual ~Medium()
182 {
183 CloseState();
184 }
185
186 protected:
187 void InitMode(Mode m)
188 {
189 m_mode = m;
190 Init();
191
192 if (m_mode == LISTENER)
193 {
194 CreateListener();
195 m_listener = true;
196 }
197 else
198 {
199 CreateCaller();
200 }
201
202 m_open = true;
203 }
204
205 virtual void Init() {}
206
207 };
208
209 class Engine
210 {
211 Medium* media[2];
212 std::thread thr;
213 class Tunnel* parent_tunnel;
214 std::string nameid;
215
216 int status = 0;
217 Medium::ReadStatus rdst = Medium::RD_ERROR;
218 UDT::ERRORINFO srtx;
219
220 public:
221 enum Dir { DIR_IN, DIR_OUT };
222
223 int stat() { return status; }
224
225 Engine(Tunnel* p, Medium* m1, Medium* m2, const std::string& nid)
226 :
227 #ifdef HAVE_FULL_CXX11
228 media {m1, m2},
229 #endif
230 parent_tunnel(p), nameid(nid)
231 {
232 #ifndef HAVE_FULL_CXX11
233 // MSVC is not exactly C++11 compliant and complains around
234 // initialization of an array.
235 // Leaving this method of initialization for clarity and
236 // possibly more preferred performance.
237 media[0] = m1;
238 media[1] = m2;
239 #endif
240 }
241
242 void Start()
243 {
244 Verb() << "START: " << media[DIR_IN]->uri() << " --> " << media[DIR_OUT]->uri();
245 const std::string thrn = media[DIR_IN]->id() + ">" + media[DIR_OUT]->id();
246 srt::ThreadName tn(thrn);
247
248 thr = thread([this]() { Worker(); });
249 }
250
251 void Stop()
252 {
253 // If this thread is already stopped, don't stop.
254 if (thr.joinable())
255 {
256 LOGP(applog.Debug, "Engine::Stop: Closing media:");
257 // Close both media as a hanged up reading thread
258 // will block joining.
259 media[0]->Close();
260 media[1]->Close();
261
262 LOGP(applog.Debug, "Engine::Stop: media closed, joining engine thread:");
263 if (thr.get_id() == std::this_thread::get_id())
264 {
265 // If this is this thread which called this, no need
266 // to stop because this thread will exit by itself afterwards.
267 // You must, however, detach yourself, or otherwise the thr's
268 // destructor would kill the program.
269 thr.detach();
270 LOGP(applog.Debug, "DETACHED.");
271 }
272 else
273 {
274 thr.join();
275 LOGP(applog.Debug, "Joined.");
276 }
277 }
278 }
279
280 void Worker();
281 };
282
283
284 struct Tunnelbox;
285
286 class Tunnel
287 {
288 Tunnelbox* parent_box;
289 std::unique_ptr<Medium> med_acp, med_clr;
290 Engine acp_to_clr, clr_to_acp;
291 srt::sync::atomic<bool> running{true};
292 std::mutex access;
293
294 public:
295
296 string show()
297 {
298 return med_acp->uri() + " <-> " + med_clr->uri();
299 }
300
301 Tunnel(Tunnelbox* m, std::unique_ptr<Medium>&& acp, std::unique_ptr<Medium>&& clr):
302 parent_box(m),
303 med_acp(std::move(acp)), med_clr(std::move(clr)),
304 acp_to_clr(this, med_acp.get(), med_clr.get(), med_acp->id() + ">" + med_clr->id()),
305 clr_to_acp(this, med_clr.get(), med_acp.get(), med_clr->id() + ">" + med_acp->id())
306 {
307 }
308
309 void Start()
310 {
311 acp_to_clr.Start();
312 clr_to_acp.Start();
313 }
314
315 // This is to be called by an Engine from Engine::Worker
316 // thread.
317 // [[affinity = acp_to_clr.thr || clr_to_acp.thr]];
318 void decommission_engine(Medium* which_medium)
319 {
320 // which_medium is the medium that failed.
321 // Upon breaking of one medium from the pair,
322 // the other needs to be closed as well.
323 Verb() << "Medium broken: " << which_medium->uri();
324
325 bool stop = true;
326
327 /*
328 {
329 lock_guard<std::mutex> lk(access);
330 if (acp_to_clr.stat() == -1 && clr_to_acp.stat() == -1)
331 {
332 Verb() << "Tunnel: Both engine decommissioned, will stop the tunnel.";
333 // Both engines are down, decommission the tunnel.
334 // Note that the status -1 means that particular engine
335 // is not currently running and you can safely
336 // join its thread.
337 stop = true;
338 }
339 else
340 {
341 Verb() << "Tunnel: Decommissioned one engine, waiting for the other one to report";
342 }
343 }
344 */
345
346 if (stop)
347 {
348 // First, stop all media.
349 med_acp->Close();
350 med_clr->Close();
351
352 // Then stop the tunnel (this is only a signal
353 // to a cleanup thread to delete it).
354 Stop();
355 }
356 }
357
358 void Stop();
359
360 bool decommission_if_dead(bool forced); // [[affinity = g_tunnels.thr]]
361 };
362
363 void Engine::Worker()
364 {
365 bytevector outbuf;
366
367 Medium* which_medium = media[DIR_IN];
368
369 for (;;)
370 {
371 try
372 {
373 which_medium = media[DIR_IN];
374 rdst = media[DIR_IN]->Read((outbuf));
375 switch (rdst)
376 {
377 case Medium::RD_DATA:
378 {
379 which_medium = media[DIR_OUT];
380 // We get the data, write them to the output
381 media[DIR_OUT]->Write((outbuf));
382 }
383 break;
384
385 case Medium::RD_EOF:
386 status = -1;
387 throw Medium::ReadEOF("");
388
389 case Medium::RD_AGAIN:
390 // Theoretically RD_AGAIN should not be reported
391 // because it should be taken care of internally by
392 // repeated sending - unless we get m_broken set.
393 // If it is, however, it should be handled just like error.
394 case Medium::RD_ERROR:
395 status = -1;
396 Medium::Error("Error while reading");
397 }
398 }
399 catch (Medium::ReadEOF&)
400 {
401 Verb() << "EOF. Exiting engine.";
402 break;
403 }
404 catch (Medium::TransmissionError& er)
405 {
406 Verb() << er.what() << " - interrupting engine: " << nameid;
407 break;
408 }
409 }
410
411 // This is an engine thread and it should simply
412 // tell the parent_box Tunnel that it is no longer
413 // operative. It's not necessary to inform it which
414 // of two engines is decommissioned - it should only
415 // know that one of them got down. It will then check
416 // if both are down here and decommission the whole
417 // tunnel if so.
418 parent_tunnel->decommission_engine(which_medium);
419 }
420
421 class SrtMedium: public Medium
422 {
423 SRTSOCKET m_socket = SRT_ERROR;
424 friend class Medium;
425 public:
426
427 #ifdef HAVE_FULL_CXX11
428 using Medium::Medium;
429
430 #else // MSVC and gcc 4.7 not exactly support C++11
431
432 SrtMedium(UriParser u, size_t ch): Medium(u, ch) {}
433
434 #endif
435
436 bool IsOpen() override { return m_open; }
437 bool End() override { return m_eof; }
438 bool Broken() override { return m_broken; }
439
440 void CloseSrt()
441 {
442 Verb() << "Closing SRT socket for " << uri();
443 lock_guard<std::mutex> lk(access);
444 if (m_socket == SRT_ERROR)
445 return;
446 srt_close(m_socket);
447 m_socket = SRT_ERROR;
448 }
449
450 // Forwarded in order to separate the implementation from
451 // the virtual function so that virtual function is not
452 // being called in destructor.
453 void CloseInternal() override { return CloseSrt(); }
454
455 const char* type() override { return "srt"; }
456 int ReadInternal(char* output, int size) override;
457 bool IsErrorAgain() override;
458
459 void Write(bytevector& portion) override;
460 void CreateListener() override;
461 void CreateCaller() override;
462 unique_ptr<Medium> Accept() override;
463 void Connect() override;
464
465 protected:
466 void Init() override;
467
468 void ConfigurePre();
469 void ConfigurePost(SRTSOCKET socket);
470
471 using Medium::Error;
472
473 static void Error(UDT::ERRORINFO& ri, const string& text)
474 {
475 throw TransmissionError("ERROR: " + text + ": " + ri.getErrorMessage());
476 }
477
478 ~SrtMedium() override
479 {
480 CloseState();
481 CloseSrt();
482 }
483 };
484
485 class TcpMedium: public Medium
486 {
487 int m_socket = -1;
488 friend class Medium;
489 public:
490
491 #ifdef HAVE_FULL_CXX11
492 using Medium::Medium;
493
494 #else // MSVC not exactly supports C++11
495
496 TcpMedium(UriParser u, size_t ch): Medium(u, ch) {}
497
498 #endif
499
500 #ifdef _WIN32
501 static int tcp_close(int socket)
502 {
503 return ::closesocket(socket);
504 }
505
506 enum { DEF_SEND_FLAG = 0 };
507
508 #elif defined(LINUX) || defined(GNU) || defined(CYGWIN)
509 static int tcp_close(int socket)
510 {
511 return ::close(socket);
512 }
513
514 enum { DEF_SEND_FLAG = MSG_NOSIGNAL };
515
516 #else
517 static int tcp_close(int socket)
518 {
519 return ::close(socket);
520 }
521
522 enum { DEF_SEND_FLAG = 0 };
523
524 #endif
525
526 bool IsOpen() override { return m_open; }
527 bool End() override { return m_eof; }
528 bool Broken() override { return m_broken; }
529
530 void CloseTcp()
531 {
532 Verb() << "Closing TCP socket for " << uri();
533 lock_guard<std::mutex> lk(access);
534 if (m_socket == -1)
535 return;
536 tcp_close(m_socket);
537 m_socket = -1;
538 }
539 void CloseInternal() override { return CloseTcp(); }
540
541 const char* type() override { return "tcp"; }
542 int ReadInternal(char* output, int size) override;
543 bool IsErrorAgain() override;
544 void Write(bytevector& portion) override;
545 void CreateListener() override;
546 void CreateCaller() override;
547 unique_ptr<Medium> Accept() override;
548 void Connect() override;
549
550 protected:
551
552 void ConfigurePre()
553 {
554 #if defined(__APPLE__)
555 int optval = 1;
556 setsockopt(m_socket, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval));
557 #endif
558 }
559
560 void ConfigurePost(int)
561 {
562 }
563
564 using Medium::Error;
565
566 static void Error(int verrno, const string& text)
567 {
568 char rbuf[1024];
569 throw TransmissionError("ERROR: " + text + ": " + SysStrError(verrno, rbuf, 1024));
570 }
571
572 virtual ~TcpMedium()
573 {
574 CloseState();
575 CloseTcp();
576 }
577 };
578
579 void SrtMedium::Init()
580 {
581 // This function is required due to extra option
582 // check need
583
584 if (m_options.count("mode"))
585 Error("No option 'mode' is required, it defaults to position of the argument");
586
587 if (m_options.count("blocking"))
588 Error("Blocking is not configurable here.");
589
590 // XXX
591 // Look also for other options that should not be here.
592
593 // Enforce the transtype = file
594 m_options["transtype"] = "file";
595 }
596
597 void SrtMedium::ConfigurePre()
598 {
599 vector<string> fails;
600 m_options["mode"] = "caller";
601 SrtConfigurePre(m_socket, "", m_options, &fails);
602 if (!fails.empty())
603 {
604 cerr << "Failed options: " << Printable(fails) << endl;
605 }
606 }
607
608 void SrtMedium::ConfigurePost(SRTSOCKET so)
609 {
610 vector<string> fails;
611 SrtConfigurePost(so, m_options, &fails);
612 if (!fails.empty())
613 {
614 cerr << "Failed options: " << Printable(fails) << endl;
615 }
616 }
617
618 void SrtMedium::CreateListener()
619 {
620 int backlog = 5; // hardcoded!
621
622 m_socket = srt_create_socket();
623
624 ConfigurePre();
625
626 sockaddr_any sa = CreateAddr(m_uri.host(), m_uri.portno());
627
628 int stat = srt_bind(m_socket, sa.get(), sizeof sa);
629
630 if ( stat == SRT_ERROR )
631 {
632 srt_close(m_socket);
633 Error(UDT::getlasterror(), "srt_bind");
634 }
635
636 stat = srt_listen(m_socket, backlog);
637 if ( stat == SRT_ERROR )
638 {
639 srt_close(m_socket);
640 Error(UDT::getlasterror(), "srt_listen");
641 }
642
643 m_listener = true;
644 };
645
646 void TcpMedium::CreateListener()
647 {
648 int backlog = 5; // hardcoded!
649
650
651 sockaddr_any sa = CreateAddr(m_uri.host(), m_uri.portno());
652
653 m_socket = (int)socket(sa.get()->sa_family, SOCK_STREAM, IPPROTO_TCP);
654 ConfigurePre();
655
656 int stat = ::bind(m_socket, sa.get(), sa.size());
657
658 if (stat == -1)
659 {
660 tcp_close(m_socket);
661 Error(errno, "bind");
662 }
663
664 stat = listen(m_socket, backlog);
665 if ( stat == -1 )
666 {
667 tcp_close(m_socket);
668 Error(errno, "listen");
669 }
670
671 m_listener = true;
672 }
673
674 unique_ptr<Medium> SrtMedium::Accept()
675 {
676 sockaddr_any sa;
677 SRTSOCKET s = srt_accept(m_socket, (sa.get()), (&sa.len));
678 if (s == SRT_ERROR)
679 {
680 Error(UDT::getlasterror(), "srt_accept");
681 }
682
683 ConfigurePost(s);
684
685 // Configure 1s timeout
686 int timeout_1s = 1000;
687 srt_setsockflag(m_socket, SRTO_RCVTIMEO, &timeout_1s, sizeof timeout_1s);
688
689 unique_ptr<Medium> med(CreateAcceptor(this, sa, s, m_chunk));
690 Verb() << "accepted a connection from " << med->uri();
691
692 return med;
693 }
694
695 unique_ptr<Medium> TcpMedium::Accept()
696 {
697 sockaddr_any sa;
698 int s = (int)::accept(m_socket, (sa.get()), (&sa.syslen()));
699 if (s == -1)
700 {
701 Error(errno, "accept");
702 }
703
704 // Configure 1s timeout
705 timeval timeout_1s { 1, 0 };
706 int st SRT_ATR_UNUSED = setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout_1s, sizeof timeout_1s);
707 timeval re;
708 socklen_t size = sizeof re;
709 int st2 SRT_ATR_UNUSED = getsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&re, &size);
710
711 LOGP(applog.Debug, "Setting SO_RCVTIMEO to @", m_socket, ": ", st == -1 ? "FAILED" : "SUCCEEDED",
712 ", read-back value: ", st2 == -1 ? int64_t(-1) : (int64_t(re.tv_sec)*1000000 + re.tv_usec)/1000, "ms");
713
714 unique_ptr<Medium> med(CreateAcceptor(this, sa, s, m_chunk));
715 Verb() << "accepted a connection from " << med->uri();
716
717 return med;
718 }
719
720 void SrtMedium::CreateCaller()
721 {
722 m_socket = srt_create_socket();
723 ConfigurePre();
724
725 // XXX setting up outgoing port not supported
726 }
727
728 void TcpMedium::CreateCaller()
729 {
730 m_socket = (int)::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
731 ConfigurePre();
732 }
733
734 void SrtMedium::Connect()
735 {
736 sockaddr_any sa = CreateAddr(m_uri.host(), m_uri.portno());
737
738 int st = srt_connect(m_socket, sa.get(), sizeof sa);
739 if (st == SRT_ERROR)
740 Error(UDT::getlasterror(), "srt_connect");
741
742 ConfigurePost(m_socket);
743
744 // Configure 1s timeout
745 int timeout_1s = 1000;
746 srt_setsockflag(m_socket, SRTO_RCVTIMEO, &timeout_1s, sizeof timeout_1s);
747 }
748
749 void TcpMedium::Connect()
750 {
751 sockaddr_any sa = CreateAddr(m_uri.host(), m_uri.portno());
752
753 int st = ::connect(m_socket, sa.get(), sa.size());
754 if (st == -1)
755 Error(errno, "connect");
756
757 ConfigurePost(m_socket);
758
759 // Configure 1s timeout
760 timeval timeout_1s { 1, 0 };
761 setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout_1s, sizeof timeout_1s);
762 }
763
764 int SrtMedium::ReadInternal(char* w_buffer, int size)
765 {
766 int st = -1;
767 do
768 {
769 st = srt_recv(m_socket, (w_buffer), size);
770 if (st == SRT_ERROR)
771 {
772 int syserr;
773 if (srt_getlasterror(&syserr) == SRT_EASYNCRCV && !m_broken)
774 continue;
775 }
776 break;
777
778 } while (true);
779
780 return st;
781 }
782
783 int TcpMedium::ReadInternal(char* w_buffer, int size)
784 {
785 int st = -1;
786 LOGP(applog.Debug, "TcpMedium:recv @", m_socket, " - begin");
787 do
788 {
789 st = ::recv(m_socket, (w_buffer), size, 0);
790 if (st == -1)
791 {
792 if ((errno == EAGAIN || errno == EWOULDBLOCK))
793 {
794 if (!m_broken)
795 {
796 LOGP(applog.Debug, "TcpMedium: read:AGAIN, repeating");
797 continue;
798 }
799 LOGP(applog.Debug, "TcpMedium: read:AGAIN, not repeating - already broken");
800 }
801 else
802 {
803 LOGP(applog.Debug, "TcpMedium: read:ERROR: ", errno);
804 }
805 }
806 break;
807 } while (true);
808 LOGP(applog.Debug, "TcpMedium:recv @", m_socket, " - result: ", st);
809 return st;
810 }
811
812 bool SrtMedium::IsErrorAgain()
813 {
814 return srt_getlasterror(NULL) == SRT_EASYNCRCV;
815 }
816
817 bool TcpMedium::IsErrorAgain()
818 {
819 return errno == EAGAIN;
820 }
821
822 // The idea of Read function is to get the buffer that
823 // possibly contains some data not written to the output yet,
824 // but the time has come to read. We can't let the buffer expand
825 // more than the size of the chunk, so if the buffer size already
826 // exceeds it, don't return any data, but behave as if they were read.
827 // This will cause the worker loop to redirect to Write immediately
828 // thereafter and possibly will flush out the remains of the buffer.
829 // It's still possible that the buffer won't be completely purged
830 Medium::ReadStatus Medium::Read(bytevector& w_output)
831 {
832 // Don't read, but fake that you read
833 if (w_output.size() > m_chunk)
834 {
835 Verb() << "BUFFER EXCEEDED";
836 return RD_DATA;
837 }
838
839 // Resize to maximum first
840 size_t shift = w_output.size();
841 if (shift && m_eof)
842 {
843 // You have nonempty buffer, but eof was already
844 // encountered. Report as if something was read.
845 //
846 // Don't read anything because this will surely
847 // result in error since now.
848 return RD_DATA;
849 }
850
851 size_t pred_size = shift + m_chunk;
852
853 w_output.resize(pred_size);
854 int st = ReadInternal((w_output.data() + shift), (int)m_chunk);
855 if (st == -1)
856 {
857 if (IsErrorAgain())
858 return RD_AGAIN;
859
860 return RD_ERROR;
861 }
862
863 if (st == 0)
864 {
865 m_eof = true;
866 if (shift)
867 {
868 // If there's 0 (eof), but you still have data
869 // in the buffer, fake that they were read. Only
870 // when the buffer was empty at entrance should this
871 // result with EOF.
872 //
873 // Set back the size this buffer had before we attempted
874 // to read into it.
875 w_output.resize(shift);
876 return RD_DATA;
877 }
878 w_output.clear();
879 return RD_EOF;
880 }
881
882 w_output.resize(shift+st);
883 return RD_DATA;
884 }
885
886 void SrtMedium::Write(bytevector& w_buffer)
887 {
888 int st = srt_send(m_socket, w_buffer.data(), (int)w_buffer.size());
889 if (st == SRT_ERROR)
890 {
891 Error(UDT::getlasterror(), "srt_send");
892 }
893
894 // This should be ==, whereas > is not possible, but
895 // this should simply embrace this case as a sanity check.
896 if (st >= int(w_buffer.size()))
897 w_buffer.clear();
898 else if (st == 0)
899 {
900 Error("Unexpected EOF on Write");
901 }
902 else
903 {
904 // Remove only those bytes that were sent
905 w_buffer.erase(w_buffer.begin(), w_buffer.begin()+st);
906 }
907 }
908
909 void TcpMedium::Write(bytevector& w_buffer)
910 {
911 int st = ::send(m_socket, w_buffer.data(), (int)w_buffer.size(), DEF_SEND_FLAG);
912 if (st == -1)
913 {
914 Error(errno, "send");
915 }
916
917 // This should be ==, whereas > is not possible, but
918 // this should simply embrace this case as a sanity check.
919 if (st >= int(w_buffer.size()))
920 w_buffer.clear();
921 else if (st == 0)
922 {
923 Error("Unexpected EOF on Write");
924 }
925 else
926 {
927 // Remove only those bytes that were sent
928 w_buffer.erase(w_buffer.begin(), w_buffer.begin()+st);
929 }
930 }
931
932 std::unique_ptr<Medium> Medium::Create(const std::string& url, size_t chunk, Medium::Mode mode)
933 {
934 UriParser uri(url);
935 std::unique_ptr<Medium> out;
936
937 // Might be something smarter, but there are only 2 types.
938 if (uri.scheme() == "srt")
939 {
940 out.reset(new SrtMedium(uri, chunk));
941 }
942 else if (uri.scheme() == "tcp")
943 {
944 out.reset(new TcpMedium(uri, chunk));
945 }
946 else
947 {
948 Error("Medium not supported");
949 }
950
951 out->InitMode(mode);
952
953 return out;
954 }
955
956 struct Tunnelbox
957 {
958 list<unique_ptr<Tunnel>> tunnels;
959 std::mutex access;
960 condition_variable decom_ready;
961 bool main_running = true;
962 thread thr;
963
964 void signal_decommission()
965 {
966 lock_guard<std::mutex> lk(access);
967 decom_ready.notify_one();
968 }
969
970 void install(std::unique_ptr<Medium>&& acp, std::unique_ptr<Medium>&& clr)
971 {
972 lock_guard<std::mutex> lk(access);
973 Verb() << "Tunnelbox: Starting tunnel: " << acp->uri() << " <-> " << clr->uri();
974
975 tunnels.emplace_back(new Tunnel(this, std::move(acp), std::move(clr)));
976 // Note: after this instruction, acp and clr are no longer valid!
977 auto& it = tunnels.back();
978
979 it->Start();
980 }
981
982 void start_cleaner()
983 {
984 thr = thread( [this]() { CleanupWorker(); } );
985 }
986
987 void stop_cleaner()
988 {
989 if (thr.joinable())
990 thr.join();
991 }
992
993 private:
994
995 void CleanupWorker()
996 {
997 unique_lock<std::mutex> lk(access);
998
999 while (main_running)
1000 {
1001 decom_ready.wait(lk);
1002
1003 // Got a signal, find a tunnel ready to cleanup.
1004 // We just get the signal, but we don't know which
1005 // tunnel has generated it.
1006 for (auto i = tunnels.begin(), i_next = i; i != tunnels.end(); i = i_next)
1007 {
1008 ++i_next;
1009 // Bound in one call the check if the tunnel is dead
1010 // and decommissioning because this must be done in
1011 // the one critical section - make sure no other thread
1012 // is accessing it at the same time and also make join all
1013 // threads that might have been accessing it. After
1014 // exiting as true (meaning that it was decommissioned
1015 // as expected) it can be safely deleted.
1016 if ((*i)->decommission_if_dead(main_running))
1017 {
1018 tunnels.erase(i);
1019 }
1020 }
1021 }
1022 }
1023 };
1024
1025 void Tunnel::Stop()
1026 {
1027 // Check for running must be done without locking
1028 // because if the tunnel isn't running
1029 if (!running)
1030 return; // already stopped
1031
1032 lock_guard<std::mutex> lk(access);
1033
1034 // Ok, you are the first to make the tunnel
1035 // not running and inform the tunnelbox.
1036 running = false;
1037 parent_box->signal_decommission();
1038 }
1039
1040 bool Tunnel::decommission_if_dead(bool forced)
1041 {
1042 lock_guard<std::mutex> lk(access);
1043 if (running && !forced)
1044 return false; // working, not to be decommissioned
1045
1046 // Join the engine threads, make sure nothing
1047 // is running that could use the data.
1048 acp_to_clr.Stop();
1049 clr_to_acp.Stop();
1050
1051
1052 // Done. The tunnelbox after calling this can
1053 // safely delete the decommissioned tunnel.
1054 return true;
1055 }
1056
1057 int Medium::s_counter = 1;
1058
1059 Tunnelbox g_tunnels;
1060 std::unique_ptr<Medium> main_listener;
1061
1062 size_t default_chunk = 4096;
1063
1064 int OnINT_StopService(int)
1065 {
1066 g_tunnels.main_running = false;
1067 g_tunnels.signal_decommission();
1068
1069 // Will cause the Accept() block to exit.
1070 main_listener->Close();
1071
1072 return 0;
1073 }
1074
1075 int main( int argc, char** argv )
1076 {
1077 if (!SysInitializeNetwork())
1078 {
1079 cerr << "Fail to initialize network module.";
1080 return 1;
1081 }
1082
1083 size_t chunk = default_chunk;
1084
1085 OptionName
1086 o_loglevel = { "ll", "loglevel" },
1087 o_logfa = { "lf", "logfa" },
1088 o_chunk = {"c", "chunk" },
1089 o_verbose = {"v", "verbose" },
1090 o_noflush = {"s", "skipflush" };
1091
1092 // Options that expect no arguments (ARG_NONE) need not be mentioned.
1093 vector<OptionScheme> optargs = {
1094 { o_loglevel, OptionScheme::ARG_ONE },
1095 { o_logfa, OptionScheme::ARG_ONE },
1096 { o_chunk, OptionScheme::ARG_ONE }
1097 };
1098 options_t params = ProcessOptions(argv, argc, optargs);
1099
1100 /*
1101 cerr << "OPTIONS (DEBUG)\n";
1102 for (auto o: params)
1103 {
1104 cerr << "[" << o.first << "] ";
1105 copy(o.second.begin(), o.second.end(), ostream_iterator<string>(cerr, " "));
1106 cerr << endl;
1107 }
1108 */
1109
1110 vector<string> args = params[""];
1111 if ( args.size() < 2 )
1112 {
1113 cerr << "Usage: " << argv[0] << " <listen-uri> <call-uri>\n";
1114 return 1;
1115 }
1116
1117 string loglevel = Option<OutString>(params, "error", o_loglevel);
1118 string logfa = Option<OutString>(params, "", o_logfa);
1119 srt_logging::LogLevel::type lev = SrtParseLogLevel(loglevel);
1120 srt::setloglevel(lev);
1121 if (logfa == "")
1122 {
1123 srt::addlogfa(SRT_LOGFA_APP);
1124 }
1125 else
1126 {
1127 // Add only selected FAs
1128 set<string> unknown_fas;
1129 set<srt_logging::LogFA> fas = SrtParseLogFA(logfa, &unknown_fas);
1130 srt::resetlogfa(fas);
1131
1132 // The general parser doesn't recognize the "app" FA, we check it here.
1133 if (unknown_fas.count("app"))
1134 srt::addlogfa(SRT_LOGFA_APP);
1135 }
1136
1137 string verbo = Option<OutString>(params, "no", o_verbose);
1138 if ( verbo == "" || !false_names.count(verbo) )
1139 {
1140 Verbose::on = true;
1141 Verbose::cverb = &std::cout;
1142 }
1143
1144 string chunks = Option<OutString>(params, "", o_chunk);
1145 if ( chunks!= "" )
1146 {
1147 chunk = stoi(chunks);
1148 }
1149
1150 string listen_node = args[0];
1151 string call_node = args[1];
1152
1153 UriParser ul(listen_node), uc(call_node);
1154
1155 // It is allowed to use both media of the same type,
1156 // but only srt and tcp are allowed.
1157
1158 set<string> allowed = {"srt", "tcp"};
1159 if (!allowed.count(ul.scheme())|| !allowed.count(uc.scheme()))
1160 {
1161 cerr << "ERROR: only tcp and srt schemes supported";
1162 return -1;
1163 }
1164
1165 Verb() << "LISTEN type=" << ul.scheme() << ", CALL type=" << uc.scheme();
1166
1167 g_tunnels.start_cleaner();
1168
1169 main_listener = Medium::Create(listen_node, chunk, Medium::LISTENER);
1170
1171 // The main program loop is only to catch
1172 // new connections and manage them. Also takes care
1173 // of the broken connections.
1174
1175 for (;;)
1176 {
1177 try
1178 {
1179 Verb() << "Waiting for connection...";
1180 std::unique_ptr<Medium> accepted = main_listener->Accept();
1181 if (!g_tunnels.main_running)
1182 {
1183 Verb() << "Service stopped. Exiting.";
1184 break;
1185 }
1186 Verb() << "Connection accepted. Connecting to the relay...";
1187
1188 // Now call the target address.
1189 std::unique_ptr<Medium> caller = Medium::Create(call_node, chunk, Medium::CALLER);
1190 caller->Connect();
1191
1192 Verb() << "Connected. Establishing pipe.";
1193
1194 // No exception, we are free to pass :)
1195 g_tunnels.install(std::move(accepted), std::move(caller));
1196 }
1197 catch (...)
1198 {
1199 Verb() << "Connection reported, but failed";
1200 }
1201 }
1202
1203 g_tunnels.stop_cleaner();
1204
1205 return 0;
1206 }
1207
1208