Debian Codegraph @

testing/testmedia.cpp

raw
1 /*
2 * SRT - Secure, Reliable, Transport
3 * Copyright (c) 2018 Haivision Systems Inc.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 */
10
11 // Medium concretizations
12
13 // Just for formality. This file should be used
14 #include <iostream>
15 #include <fstream>
16 #include <sstream>
17 #include <string>
18 #include <stdexcept>
19 #include <iterator>
20 #include <map>
21 #include <chrono>
22 #include <thread>
23 #include <srt.h>
24 #if !defined(_WIN32)
25 #include <sys/ioctl.h>
26 #endif
27
28 // SRT protected includes
29 #include "netinet_any.h"
30 #include "common.h"
31 #include "api.h"
32 #include "udt.h"
33 #include "logging.h"
34 #include "utilities.h"
35
36 #include "apputil.hpp"
37 #include "socketoptions.hpp"
38 #include "uriparser.hpp"
39 #include "testmedia.hpp"
40 #include "srt_compat.h"
41 #include "verbose.hpp"
42
43 using namespace std;
44 using namespace srt;
45
46 using srt_logging::KmStateStr;
47 using srt_logging::SockStatusStr;
48 #if ENABLE_BONDING
49 using srt_logging::MemberStatusStr;
50 #endif
51
52 srt::sync::atomic<bool> transmit_throw_on_interrupt {false};
53 srt::sync::atomic<bool> transmit_int_state {false};
54 int transmit_bw_report = 0;
55 unsigned transmit_stats_report = 0;
56 size_t transmit_chunk_size = SRT_LIVE_DEF_PLSIZE;
57 bool transmit_printformat_json = false;
58 srt_listen_callback_fn* transmit_accept_hook_fn = nullptr;
59 void* transmit_accept_hook_op = nullptr;
60 bool transmit_use_sourcetime = false;
61 int transmit_retry_connect = 0;
62 bool transmit_retry_always = false;
63
64 // Do not unblock. Copy this to an app that uses applog and set appropriate name.
65 //srt_logging::Logger applog(SRT_LOGFA_APP, srt_logger_config, "srt-test");
66
67 std::shared_ptr<SrtStatsWriter> transmit_stats_writer;
68
69 string DirectionName(SRT_EPOLL_T direction)
70 {
71 string dir_name;
72 if (direction & ~SRT_EPOLL_ERR)
73 {
74 if (direction & SRT_EPOLL_IN)
75 {
76 dir_name = "source";
77 }
78
79 if (direction & SRT_EPOLL_OUT)
80 {
81 if (!dir_name.empty())
82 dir_name = "relay";
83 else
84 dir_name = "target";
85 }
86
87 if (direction & SRT_EPOLL_ERR)
88 {
89 dir_name += "+error";
90 }
91 }
92 else
93 {
94 // stupid name for a case of IPE
95 dir_name = "stone";
96 }
97
98 return dir_name;
99 }
100
101 template<class FileBase> inline
102 bytevector FileRead(FileBase& ifile, size_t chunk, const string& filename)
103 {
104 bytevector data(chunk);
105 ifile.read(data.data(), chunk);
106 size_t nread = ifile.gcount();
107 if (nread < data.size())
108 data.resize(nread);
109
110 if (data.empty())
111 throw Source::ReadEOF(filename);
112 return data;
113 }
114
115
116 class FileSource: public virtual Source
117 {
118 ifstream ifile;
119 string filename_copy;
120 public:
121
122 FileSource(const string& path): ifile(path, ios::in | ios::binary), filename_copy(path)
123 {
124 if (!ifile)
125 throw std::runtime_error(path + ": Can't open file for reading");
126 }
127
128 MediaPacket Read(size_t chunk) override { return FileRead(ifile, chunk, filename_copy); }
129
130 bool IsOpen() override { return bool(ifile); }
131 bool End() override { return ifile.eof(); }
132 //~FileSource() { ifile.close(); }
133 };
134
135 class FileTarget: public virtual Target
136 {
137 ofstream ofile;
138 public:
139
140 FileTarget(const string& path): ofile(path, ios::out | ios::trunc | ios::binary) {}
141
142 void Write(const MediaPacket& data) override
143 {
144 ofile.write(data.payload.data(), data.payload.size());
145 #ifdef PLEASE_LOG
146 applog.Debug() << "FileTarget::Write: " << data.payload.size() << " written to a file";
147 #endif
148 }
149
150 bool IsOpen() override { return !!ofile; }
151 bool Broken() override { return !ofile.good(); }
152 //~FileTarget() { ofile.close(); }
153 void Close() override
154 {
155 #ifdef PLEASE_LOG
156 applog.Debug() << "FileTarget::Close";
157 #endif
158 ofile.close();
159 }
160 };
161
162 // Can't base this class on FileSource and FileTarget classes because they use two
163 // separate fields, which makes it unable to reliably define IsOpen(). This would
164 // require to use 'fstream' type field in some kind of FileCommon first. Not worth
165 // a shot.
166 class FileRelay: public Relay
167 {
168 fstream iofile;
169 string filename_copy;
170 public:
171
172 FileRelay(const string& path):
173 iofile(path, ios::in | ios::out | ios::binary), filename_copy(path)
174 {
175 if (!iofile)
176 throw std::runtime_error(path + ": Can't open file for reading");
177 }
178 MediaPacket Read(size_t chunk) override { return FileRead(iofile, chunk, filename_copy); }
179
180 void Write(const MediaPacket& data) override
181 {
182 iofile.write(data.payload.data(), data.payload.size());
183 }
184
185 bool IsOpen() override { return !!iofile; }
186 bool End() override { return iofile.eof(); }
187 bool Broken() override { return !iofile.good(); }
188 void Close() override { iofile.close(); }
189 };
190
191 template <class Iface> struct File;
192 template <> struct File<Source> { typedef FileSource type; };
193 template <> struct File<Target> { typedef FileTarget type; };
194 template <> struct File<Relay> { typedef FileRelay type; };
195
196 template <class Iface>
197 Iface* CreateFile(const string& name) { return new typename File<Iface>::type (name); }
198
199 void SrtCommon::InitParameters(string host, string path, map<string,string> par)
200 {
201 // Application-specific options: mode, blocking, timeout, adapter
202 if ( Verbose::on && !par.empty())
203 {
204 Verb() << "SRT parameters specified:\n";
205 for (map<string,string>::iterator i = par.begin(); i != par.end(); ++i)
206 {
207 Verb() << "\t" << i->first << " = '" << i->second << "'\n";
208 }
209 }
210
211 if (path != "")
212 {
213 // Special case handling of an unusual specification.
214
215 if (path.substr(0, 2) != "//")
216 {
217 Error("Path specification not supported for SRT (use // in front for special cases)");
218 }
219
220 path = path.substr(2);
221
222 #if ENABLE_BONDING
223 if (path == "group")
224 {
225 // Group specified, check type.
226 m_group_type = par["type"];
227 if (m_group_type == "")
228 {
229 Error("With //group, the group 'type' must be specified.");
230 }
231
232 vector<string> parts;
233 Split(m_group_type, '/', back_inserter(parts));
234 if (parts.size() == 0 || parts.size() > 2)
235 {
236 Error("Invalid specification for 'type' parameter");
237 }
238
239 if (parts.size() == 2)
240 {
241 m_group_type = parts[0];
242 m_group_config = parts[1];
243 }
244
245 vector<string> nodes;
246 Split(par["nodes"], ',', back_inserter(nodes));
247
248 if (nodes.empty())
249 {
250 Error("With //group, 'nodes' must specify comma-separated host:port specs.");
251 }
252
253 int token = 1;
254
255 // Check if correctly specified
256 for (string& hostport: nodes)
257 {
258 if (hostport == "")
259 continue;
260
261 // The attribute string, as it was embedded in another URI,
262 // must have had replaced the & character with another ?, so
263 // now all ? character, except the first one, must be now
264 // restored so that UriParser interprets them correctly.
265
266 size_t atq = hostport.find('?');
267 if (atq != string::npos)
268 {
269 while (atq+1 < hostport.size())
270 {
271 size_t next = hostport.find('?', atq+1);
272 if (next == string::npos)
273 break;
274 hostport[next] = '&';
275 atq = next;
276 }
277 }
278
279 UriParser check(hostport, UriParser::EXPECT_HOST);
280 if (check.host() == "" || check.port() == "")
281 {
282 Error("With //group, 'nodes' must specify comma-separated host:port specs.");
283 }
284
285 if (check.portno() <= 1024)
286 {
287 Error("With //group, every node in 'nodes' must have port >1024");
288 }
289
290 Connection cc(check.host(), check.portno());
291 if (check.parameters().count("weight"))
292 {
293 cc.weight = stoi(check.queryValue("weight"));
294 }
295
296 if (check.parameters().count("source"))
297 {
298 UriParser sourcehp(check.queryValue("source"), UriParser::EXPECT_HOST);
299 cc.source = CreateAddr(sourcehp.host(), sourcehp.portno());
300 }
301
302 // Check if there's a key with 'srto.' prefix.
303
304 UriParser::query_it start = check.parameters().lower_bound("srto.");
305
306 SRT_SOCKOPT_CONFIG* config = nullptr;
307 bool all_clear = true;
308 vector<string> fails;
309 map<string, string> options;
310
311 if (start != check.parameters().end())
312 {
313 for (; start != check.parameters().end(); ++start)
314 {
315 auto& y = *start;
316 if (y.first.substr(0, 5) != "srto.")
317 break;
318
319 options[y.first.substr(5)] = y.second;
320 }
321 }
322
323 if (!options.empty())
324 {
325 config = srt_create_config();
326
327 for (auto o: srt_options)
328 {
329 if (!options.count(o.name))
330 continue;
331 string value = options.at(o.name);
332 bool ok = o.apply<SocketOption::SRT>(config, value);
333 if ( !ok )
334 {
335 fails.push_back(o.name);
336 all_clear = false;
337 }
338 }
339
340 if (!all_clear)
341 {
342 srt_delete_config(config);
343 Error("With //group, failed to set options: " + Printable(fails));
344 }
345
346 cc.options = config;
347 }
348
349 cc.token = token++;
350 m_group_nodes.push_back(std::move(cc));
351 }
352
353 par.erase("type");
354 par.erase("nodes");
355
356 // For a group-connect specification, it's
357 // always the caller mode.
358 // XXX change it here if maybe rendezvous is also
359 // possible in future.
360 par["mode"] = "caller";
361 }
362 #endif
363 }
364
365 if (par.count("bind"))
366 {
367 string bindspec = par.at("bind");
368 UriParser u (bindspec, UriParser::EXPECT_HOST);
369 if ( u.scheme() != ""
370 || u.path() != ""
371 || !u.parameters().empty()
372 || u.portno() == 0)
373 {
374 Error("Invalid syntax in 'bind' option");
375 }
376
377 if (u.host() != "")
378 par["adapter"] = u.host();
379 par["port"] = u.port();
380 par.erase("bind");
381 }
382
383 string adapter;
384 if (par.count("adapter"))
385 {
386 adapter = par.at("adapter");
387 }
388
389 m_mode = "default";
390 if (par.count("mode"))
391 {
392 m_mode = par.at("mode");
393 }
394 SocketOption::Mode mode = SrtInterpretMode(m_mode, host, adapter);
395 if (mode == SocketOption::FAILURE)
396 {
397 Error("Invalid mode");
398 }
399
400 if (!m_group_nodes.empty() && mode != SocketOption::CALLER)
401 {
402 Error("Group node specification is only available in caller mode");
403 }
404
405 // Fix the mode name after successful interpretation
406 m_mode = SocketOption::mode_names[mode];
407
408 par.erase("mode");
409
410 if (par.count("blocking"))
411 {
412 m_blocking_mode = !false_names.count(par.at("blocking"));
413 par.erase("blocking");
414 }
415
416 if (par.count("timeout"))
417 {
418 m_timeout = stoi(par.at("timeout"), 0, 0);
419 par.erase("timeout");
420 }
421
422 if (par.count("adapter"))
423 {
424 m_adapter = adapter;
425 par.erase("adapter");
426 }
427 else if (m_mode == "listener")
428 {
429 // For listener mode, adapter is taken from host,
430 // if 'adapter' parameter is not given
431 m_adapter = host;
432 }
433
434 if (par.count("tsbpd") && false_names.count(par.at("tsbpd")))
435 {
436 m_tsbpdmode = false;
437 }
438
439 if (par.count("port"))
440 {
441 m_outgoing_port = stoi(par.at("port"), 0, 0);
442 par.erase("port");
443 }
444
445 // That's kinda clumsy, but it must rely on the defaults.
446 // Default mode is live, so check if the file mode was enforced
447 if (par.count("transtype") == 0 || par["transtype"] != "file")
448 {
449 // If the Live chunk size was nondefault, enforce the size.
450 if (transmit_chunk_size != SRT_LIVE_DEF_PLSIZE)
451 {
452 if (transmit_chunk_size > SRT_LIVE_MAX_PLSIZE)
453 throw std::runtime_error("Chunk size in live mode exceeds 1456 bytes; this is not supported");
454
455 par["payloadsize"] = Sprint(transmit_chunk_size);
456 }
457 }
458
459 // Assigning group configuration from a special "groupconfig" attribute.
460 // This is the only way how you can set up this configuration at the listener side.
461 if (par.count("groupconfig"))
462 {
463 m_group_config = par.at("groupconfig");
464 par.erase("groupconfig");
465 }
466
467 // Fix Minversion, if specified as string
468 if (par.count("minversion"))
469 {
470 string v = par["minversion"];
471 if (v.find('.') != string::npos)
472 {
473 int version = srt::SrtParseVersion(v.c_str());
474 if (version == 0)
475 {
476 throw std::runtime_error(Sprint("Value for 'minversion' doesn't specify a valid version: ", v));
477 }
478 par["minversion"] = Sprint(version);
479 Verb() << "\tFIXED: minversion = 0x" << std::hex << std::setfill('0') << std::setw(8) << version << std::dec;
480 }
481 }
482
483 // Assign the others here.
484 m_options = par;
485 m_options["mode"] = m_mode;
486 }
487
488 void SrtCommon::PrepareListener(string host, int port, int backlog)
489 {
490 m_bindsock = srt_create_socket();
491 if (m_bindsock == SRT_ERROR)
492 Error("srt_create_socket");
493
494 int stat = ConfigurePre(m_bindsock);
495 if (stat == SRT_ERROR)
496 Error("ConfigurePre");
497
498 if (!m_blocking_mode)
499 {
500 srt_conn_epoll = AddPoller(m_bindsock, SRT_EPOLL_OUT);
501 }
502
503 auto sa = CreateAddr(host, port);
504 Verb() << "Binding a server on " << host << ":" << port << " ...";
505 stat = srt_bind(m_bindsock, sa.get(), sizeof sa);
506 if (stat == SRT_ERROR)
507 {
508 srt_close(m_bindsock);
509 Error("srt_bind");
510 }
511
512 Verb() << " listen... " << VerbNoEOL;
513 stat = srt_listen(m_bindsock, backlog);
514 if (stat == SRT_ERROR)
515 {
516 srt_close(m_bindsock);
517 Error("srt_listen");
518 }
519
520 }
521
522 void SrtCommon::StealFrom(SrtCommon& src)
523 {
524 // This is used when SrtCommon class designates a listener
525 // object that is doing Accept in appropriate direction class.
526 // The new object should get the accepted socket.
527 m_direction = src.m_direction;
528 m_blocking_mode = src.m_blocking_mode;
529 m_timeout = src.m_timeout;
530 m_tsbpdmode = src.m_tsbpdmode;
531 m_options = src.m_options;
532 m_bindsock = SRT_INVALID_SOCK; // no listener
533 m_sock = src.m_sock;
534 src.m_sock = SRT_INVALID_SOCK; // STEALING
535 }
536
537 void SrtCommon::AcceptNewClient()
538 {
539 sockaddr_any scl;
540
541 ::transmit_throw_on_interrupt = true;
542
543 if (!m_blocking_mode)
544 {
545 Verb() << "[ASYNC] (conn=" << srt_conn_epoll << ")";
546
547 int len = 2;
548 SRTSOCKET ready[2];
549 while (srt_epoll_wait(srt_conn_epoll, 0, 0, ready, &len, 1000, 0, 0, 0, 0) == -1)
550 {
551 if (::transmit_int_state)
552 Error("srt_epoll_wait for srt_accept: interrupt");
553
554 if (srt_getlasterror(NULL) == SRT_ETIMEOUT)
555 continue;
556 Error("srt_epoll_wait(srt_conn_epoll)");
557 }
558
559 Verb() << "[EPOLL: " << len << " sockets] " << VerbNoEOL;
560 }
561 Verb() << " accept..." << VerbNoEOL;
562
563 m_sock = srt_accept(m_bindsock, (scl.get()), (&scl.len));
564 if (m_sock == SRT_INVALID_SOCK)
565 {
566 srt_close(m_bindsock);
567 m_bindsock = SRT_INVALID_SOCK;
568 Error("srt_accept");
569 }
570
571 #if ENABLE_BONDING
572 if (m_sock & SRTGROUP_MASK)
573 {
574 m_listener_group = true;
575 if (m_group_config != "")
576 {
577 // Don't break the connection basing on this, just ignore.
578 Verb() << " (ignoring setting group config: '" << m_group_config << "') " << VerbNoEOL;
579 }
580 // There might be added a poller, remove it.
581 // We need it work different way.
582
583 #ifndef SRT_OLD_APP_READER
584
585 if (srt_epoll != -1)
586 {
587 Verb() << "(Group: erasing epoll " << srt_epoll << ") " << VerbNoEOL;
588 srt_epoll_release(srt_epoll);
589 }
590
591 // Don't add any sockets, they will have to be added
592 // anew every time again.
593 srt_epoll = srt_epoll_create();
594 #endif
595
596 // Group data must have a size of at least 1
597 // otherwise the srt_group_data() call will fail
598 if (m_group_data.empty())
599 m_group_data.resize(1);
600
601 Verb() << " connected(group epoll " << srt_epoll <<").";
602 }
603 else
604 #endif
605 {
606 sockaddr_any peeraddr(AF_INET6);
607 string peer = "<?PEER?>";
608 if (-1 != srt_getpeername(m_sock, (peeraddr.get()), (&peeraddr.len)))
609 {
610 peer = peeraddr.str();
611 }
612
613 sockaddr_any agentaddr(AF_INET6);
614 string agent = "<?AGENT?>";
615 if (-1 != srt_getsockname(m_sock, (agentaddr.get()), (&agentaddr.len)))
616 {
617 agent = agentaddr.str();
618 }
619
620 Verb() << " connected [" << agent << "] <-- " << peer;
621 }
622 ::transmit_throw_on_interrupt = false;
623
624 // ConfigurePre is done on bindsock, so any possible Pre flags
625 // are DERIVED by sock. ConfigurePost is done exclusively on sock.
626 int stat = ConfigurePost(m_sock);
627 if (stat == SRT_ERROR)
628 Error("ConfigurePost");
629 }
630
631 static string PrintEpollEvent(int events, int et_events)
632 {
633 static pair<int, const char*> const namemap [] = {
634 make_pair(SRT_EPOLL_IN, "R"),
635 make_pair(SRT_EPOLL_OUT, "W"),
636 make_pair(SRT_EPOLL_ERR, "E"),
637 make_pair(SRT_EPOLL_UPDATE, "U")
638 };
639
640 ostringstream os;
641 int N = (int)Size(namemap);
642
643 for (int i = 0; i < N; ++i)
644 {
645 if (events & namemap[i].first)
646 {
647 os << "[";
648 if (et_events & namemap[i].first)
649 os << "^";
650 os << namemap[i].second << "]";
651 }
652 }
653
654 return os.str();
655 }
656
657 void SrtCommon::Init(string host, int port, string path, map<string,string> par, SRT_EPOLL_OPT dir)
658 {
659 m_direction = dir;
660 InitParameters(host, path, par);
661
662 int backlog = 1;
663 if (m_mode == "listener" && par.count("groupconnect")
664 && true_names.count(par["groupconnect"]))
665 {
666 backlog = 10;
667 }
668
669 Verb() << "Opening SRT " << DirectionName(dir) << " " << m_mode
670 << "(" << (m_blocking_mode ? "" : "non-") << "blocking,"
671 << " backlog=" << backlog << ") on "
672 << host << ":" << port;
673
674 try
675 {
676 if (m_mode == "caller")
677 {
678 if (m_group_nodes.empty())
679 {
680 OpenClient(host, port);
681 }
682 #if ENABLE_BONDING
683 else
684 {
685 OpenGroupClient(); // Source data are in the fields already.
686 }
687 #endif
688 }
689 else if (m_mode == "listener")
690 OpenServer(m_adapter, port, backlog);
691 else if (m_mode == "rendezvous")
692 OpenRendezvous(m_adapter, host, port);
693 else
694 {
695 throw std::invalid_argument("Invalid 'mode'. Use 'client' or 'server'");
696 }
697 }
698 catch (...)
699 {
700 // This is an in-constructor-called function, so
701 // when the exception is thrown, the destructor won't
702 // close the sockets. This intercepts the exception
703 // to close them.
704 Verb() << "Open FAILED - closing SRT sockets";
705 if (m_bindsock != SRT_INVALID_SOCK)
706 srt_close(m_bindsock);
707 if (m_sock != SRT_INVALID_SOCK)
708 srt_close(m_sock);
709 m_sock = m_bindsock = SRT_INVALID_SOCK;
710 throw;
711 }
712
713 int pbkeylen = 0;
714 SRT_KM_STATE kmstate, snd_kmstate, rcv_kmstate;
715 int len = sizeof (int);
716 srt_getsockflag(m_sock, SRTO_PBKEYLEN, &pbkeylen, &len);
717 srt_getsockflag(m_sock, SRTO_KMSTATE, &kmstate, &len);
718 srt_getsockflag(m_sock, SRTO_SNDKMSTATE, &snd_kmstate, &len);
719 srt_getsockflag(m_sock, SRTO_RCVKMSTATE, &rcv_kmstate, &len);
720
721 Verb() << "ENCRYPTION status: " << KmStateStr(kmstate)
722 << " (SND:" << KmStateStr(snd_kmstate) << " RCV:" << KmStateStr(rcv_kmstate)
723 << ") PBKEYLEN=" << pbkeylen;
724
725 // Display some selected options on the socket.
726 if (Verbose::on)
727 {
728 int64_t bandwidth = 0;
729 int latency = 0;
730 bool blocking_snd = false, blocking_rcv = false;
731 int dropdelay = 0;
732 int size_int = sizeof (int), size_int64 = sizeof (int64_t), size_bool = sizeof (bool);
733 char packetfilter[100] = "";
734 int packetfilter_size = 100;
735
736 srt_getsockflag(m_sock, SRTO_MAXBW, &bandwidth, &size_int64);
737 srt_getsockflag(m_sock, SRTO_RCVLATENCY, &latency, &size_int);
738 srt_getsockflag(m_sock, SRTO_RCVSYN, &blocking_rcv, &size_bool);
739 srt_getsockflag(m_sock, SRTO_SNDSYN, &blocking_snd, &size_bool);
740 srt_getsockflag(m_sock, SRTO_SNDDROPDELAY, &dropdelay, &size_int);
741 srt_getsockflag(m_sock, SRTO_PACKETFILTER, (packetfilter), (&packetfilter_size));
742
743 Verb() << "OPTIONS: maxbw=" << bandwidth << " rcvlatency=" << latency << boolalpha
744 << " blocking{rcv=" << blocking_rcv << " snd=" << blocking_snd
745 << "} snddropdelay=" << dropdelay << " packetfilter=" << packetfilter;
746 }
747
748 if (!m_blocking_mode)
749 {
750 // Don't add new epoll if already created as a part
751 // of group management: if (srt_epoll == -1)...
752
753 if (m_mode == "caller")
754 dir = (dir | SRT_EPOLL_UPDATE);
755 Verb() << "NON-BLOCKING MODE - SUB FOR " << PrintEpollEvent(dir, 0);
756
757 srt_epoll = AddPoller(m_sock, dir);
758 }
759 }
760
761 int SrtCommon::AddPoller(SRTSOCKET socket, int modes)
762 {
763 int pollid = srt_epoll_create();
764 if (pollid == -1)
765 throw std::runtime_error("Can't create epoll in nonblocking mode");
766 Verb() << "EPOLL: creating eid=" << pollid << " and adding @" << socket
767 << " in " << DirectionName(SRT_EPOLL_OPT(modes)) << " mode";
768 srt_epoll_add_usock(pollid, socket, &modes);
769 return pollid;
770 }
771
772 int SrtCommon::ConfigurePost(SRTSOCKET sock)
773 {
774 bool yes = m_blocking_mode;
775 int result = 0;
776 if (m_direction & SRT_EPOLL_OUT)
777 {
778 Verb() << "Setting SND blocking mode: " << boolalpha << yes << " timeout=" << m_timeout;
779 result = srt_setsockopt(sock, 0, SRTO_SNDSYN, &yes, sizeof yes);
780 if (result == -1)
781 {
782 #ifdef PLEASE_LOG
783 extern srt_logging::Logger applog;
784 applog.Error() << "ERROR SETTING OPTION: SRTO_SNDSYN";
785 #endif
786 return result;
787 }
788
789 if (m_timeout)
790 result = srt_setsockopt(sock, 0, SRTO_SNDTIMEO, &m_timeout, sizeof m_timeout);
791 if (result == -1)
792 {
793 #ifdef PLEASE_LOG
794 extern srt_logging::Logger applog;
795 applog.Error() << "ERROR SETTING OPTION: SRTO_SNDTIMEO";
796 #endif
797 return result;
798 }
799 }
800
801 if (m_direction & SRT_EPOLL_IN)
802 {
803 Verb() << "Setting RCV blocking mode: " << boolalpha << yes << " timeout=" << m_timeout;
804 result = srt_setsockopt(sock, 0, SRTO_RCVSYN, &yes, sizeof yes);
805 if (result == -1)
806 return result;
807
808 if (m_timeout)
809 result = srt_setsockopt(sock, 0, SRTO_RCVTIMEO, &m_timeout, sizeof m_timeout);
810 else
811 {
812 int timeout = 1000;
813 result = srt_setsockopt(sock, 0, SRTO_RCVTIMEO, &timeout, sizeof timeout);
814 }
815 if (result == -1)
816 return result;
817 }
818
819 // host is only checked for emptiness and depending on that the connection mode is selected.
820 // Here we are not exactly interested with that information.
821 vector<string> failures;
822
823 SrtConfigurePost(sock, m_options, &failures);
824
825
826 if (!failures.empty())
827 {
828 if (Verbose::on)
829 {
830 Verb() << "WARNING: failed to set options: ";
831 copy(failures.begin(), failures.end(), ostream_iterator<string>(*Verbose::cverb, ", "));
832 Verb();
833 }
834 }
835
836 return 0;
837 }
838
839 int SrtCommon::ConfigurePre(SRTSOCKET sock)
840 {
841 int result = 0;
842
843 int no = 0;
844 if (!m_tsbpdmode)
845 {
846 result = srt_setsockopt(sock, 0, SRTO_TSBPDMODE, &no, sizeof no);
847 if (result == -1)
848 return result;
849 }
850
851 // Let's pretend async mode is set this way.
852 // This is for asynchronous connect.
853 int maybe = m_blocking_mode;
854 result = srt_setsockopt(sock, 0, SRTO_RCVSYN, &maybe, sizeof maybe);
855 if (result == -1)
856 return result;
857
858 // host is only checked for emptiness and depending on that the connection mode is selected.
859 // Here we are not exactly interested with that information.
860 vector<string> failures;
861
862 // NOTE: here host = "", so the 'connmode' will be returned as LISTENER always,
863 // but it doesn't matter here. We don't use 'connmode' for anything else than
864 // checking for failures.
865 SocketOption::Mode conmode = SrtConfigurePre(sock, "", m_options, &failures);
866
867 if (conmode == SocketOption::FAILURE)
868 {
869 if (Verbose::on )
870 {
871 Verb() << "WARNING: failed to set options: ";
872 copy(failures.begin(), failures.end(), ostream_iterator<string>(*Verbose::cverb, ", "));
873 Verb();
874 }
875
876 return SRT_ERROR;
877 }
878
879 return 0;
880 }
881
882 void SrtCommon::SetupAdapter(const string& host, int port)
883 {
884 Verb() << "Binding the caller socket to " << host << ":" << port << " ...";
885 auto lsa = CreateAddr(host, port);
886 int stat = srt_bind(m_sock, lsa.get(), sizeof lsa);
887 if (stat == SRT_ERROR)
888 Error("srt_bind");
889 }
890
891 void SrtCommon::OpenClient(string host, int port)
892 {
893 PrepareClient();
894
895 if (m_outgoing_port || m_adapter != "")
896 {
897 SetupAdapter(m_adapter, m_outgoing_port);
898 }
899
900 ConnectClient(host, port);
901 }
902
903 void SrtCommon::PrepareClient()
904 {
905 m_sock = srt_create_socket();
906 if (m_sock == SRT_ERROR)
907 Error("srt_create_socket");
908
909 int stat = ConfigurePre(m_sock);
910 if (stat == SRT_ERROR)
911 Error("ConfigurePre");
912
913 if (!m_blocking_mode)
914 {
915 srt_conn_epoll = AddPoller(m_sock, SRT_EPOLL_CONNECT | SRT_EPOLL_ERR);
916 }
917
918 }
919
920 #if ENABLE_BONDING
921 void TransmitGroupSocketConnect(void* srtcommon, SRTSOCKET sock, int error, const sockaddr* /*peer*/, int token)
922 {
923 SrtCommon* that = (SrtCommon*)srtcommon;
924
925 if (error == SRT_SUCCESS)
926 {
927 return; // nothing to do for a successful socket
928 }
929
930 #ifdef PLEASE_LOG
931 applog.Debug("connect callback: error on @", sock, " erc=", error, " token=", token);
932 #endif
933
934 /* Example: identify by target address
935 sockaddr_any peersa = peer;
936 sockaddr_any agentsa;
937 bool haveso = (srt_getsockname(sock, agentsa.get(), &agentsa.len) != -1);
938 */
939
940 for (auto& n: that->m_group_nodes)
941 {
942 if (n.token != -1 && n.token == token)
943 {
944 n.error = error;
945 n.reason = srt_getrejectreason(sock);
946 return;
947 }
948
949 /*
950
951 bool isso = haveso && !n.source.empty();
952 if (n.target == peersa && (!isso || n.source.equal_address(agentsa)))
953 {
954 Verb() << " (by target)" << VerbNoEOL;
955 n.error = error;
956 n.reason = srt_getrejectreason(sock);
957 return;
958 }
959 */
960 }
961
962 Verb() << " IPE: LINK NOT FOUND???]";
963 }
964
965 SRT_GROUP_TYPE ResolveGroupType(const string& name)
966 {
967 static struct
968 {
969 string name;
970 SRT_GROUP_TYPE type;
971 } table [] {
972 #define E(n) {#n, SRT_GTYPE_##n}
973 E(BROADCAST),
974 E(BACKUP)
975
976 #undef E
977 };
978
979 typedef int charxform(int c);
980
981 string uname;
982 transform(name.begin(), name.end(), back_inserter(uname), (charxform*)(&toupper));
983
984 for (auto& x: table)
985 if (x.name == uname)
986 return x.type;
987
988 return SRT_GTYPE_UNDEFINED;
989 }
990
991 void SrtCommon::OpenGroupClient()
992 {
993 SRT_GROUP_TYPE type = ResolveGroupType(m_group_type);
994 if (type == SRT_GTYPE_UNDEFINED)
995 {
996 Error("With //group, type='" + m_group_type + "' undefined");
997 }
998
999 m_sock = srt_create_group(type);
1000 if (m_sock == -1)
1001 Error("srt_create_group");
1002
1003 srt_connect_callback(m_sock, &TransmitGroupSocketConnect, this);
1004
1005 int stat = -1;
1006 if (m_group_config != "")
1007 {
1008 Verb() << "Ignoring setting group config: '" << m_group_config;
1009 }
1010
1011 stat = ConfigurePre(m_sock);
1012
1013 if ( stat == SRT_ERROR )
1014 Error("ConfigurePre");
1015
1016 if (!m_blocking_mode)
1017 {
1018 // Note: here the GROUP is added to the poller.
1019 srt_conn_epoll = AddPoller(m_sock, SRT_EPOLL_CONNECT | SRT_EPOLL_ERR);
1020 }
1021
1022 // Don't check this. Should this fail, the above would already.
1023
1024 // XXX Now do it regardless whether it's blocking or non-blocking
1025 // mode - reading from group is currently manually from every socket.
1026 srt_epoll = srt_epoll_create();
1027
1028 // ConnectClient can't be used here, the code must
1029 // be more-less repeated. In this case the situation
1030 // that not all connections can be established is tolerated,
1031 // the only case of error is when none of the connections
1032 // can be established.
1033
1034 bool any_node = false;
1035
1036 Verb() << "REDUNDANT connections with " << m_group_nodes.size() << " nodes:";
1037
1038 if (m_group_data.empty())
1039 m_group_data.resize(1);
1040
1041 vector<SRT_SOCKGROUPCONFIG> targets;
1042 int namelen = sizeof (sockaddr_any);
1043
1044 Verb() << "Connecting to nodes:";
1045 int i = 1;
1046 for (Connection& c: m_group_nodes)
1047 {
1048 auto sa = CreateAddr(c.host, c.port);
1049 c.target = sa;
1050 Verb() << "\t[" << c.token << "] " << c.host << ":" << c.port << VerbNoEOL;
1051 vector<string> extras;
1052 if (c.weight)
1053 extras.push_back(Sprint("weight=", c.weight));
1054
1055 if (!c.source.empty())
1056 extras.push_back("source=" + c.source.str());
1057
1058 if (!extras.empty())
1059 {
1060 Verb() << "?" << extras[0] << VerbNoEOL;
1061 for (size_t ii = 1; ii < extras.size(); ++ii)
1062 Verb() << "&" << extras[ii] << VerbNoEOL;
1063 }
1064
1065 Verb();
1066 ++i;
1067 const sockaddr* source = c.source.empty() ? nullptr : c.source.get();
1068 SRT_SOCKGROUPCONFIG gd = srt_prepare_endpoint(source, sa.get(), namelen);
1069 gd.weight = c.weight;
1070 gd.config = c.options;
1071
1072 targets.push_back(gd);
1073 }
1074
1075 ::transmit_throw_on_interrupt = true;
1076 for (;;) // REPEATABLE BLOCK
1077 {
1078 Connect_Again:
1079 Verb() << "Waiting for group connection... " << VerbNoEOL;
1080
1081 int fisock = srt_connect_group(m_sock, targets.data(), int(targets.size()));
1082
1083 if (fisock == SRT_ERROR)
1084 {
1085 // Complete the error information for every member
1086 ostringstream out;
1087 set<int> reasons;
1088 for (Connection& c: m_group_nodes)
1089 {
1090 if (c.error != SRT_SUCCESS)
1091 {
1092 out << "[" << c.token << "] " << c.host << ":" << c.port;
1093 if (!c.source.empty())
1094 out << "[[" << c.source.str() << "]]";
1095 out << ": " << srt_strerror(c.error, 0) << ": " << srt_rejectreason_str(c.reason) << endl;
1096 }
1097 reasons.insert(c.reason);
1098 }
1099
1100 if (transmit_retry_connect && (transmit_retry_always || (reasons.size() == 1 && *reasons.begin() == SRT_REJ_TIMEOUT)))
1101 {
1102 if (transmit_retry_connect != -1)
1103 --transmit_retry_connect;
1104
1105 Verb() << "...all links timeout, retrying (" << transmit_retry_connect << ")...";
1106 continue;
1107 }
1108
1109 Error("srt_connect_group, nodes:\n" + out.str());
1110 }
1111 else
1112 {
1113 Verb() << "[ASYNC] will wait..." << VerbNoEOL;
1114 }
1115
1116 break;
1117 }
1118
1119 if (m_blocking_mode)
1120 {
1121 Verb() << "SUCCESSFUL";
1122 }
1123 else
1124 {
1125 Verb() << "INITIATED [ASYNC]";
1126 }
1127
1128 // Configuration change applied on a group should
1129 // spread the setting on all sockets.
1130 ConfigurePost(m_sock);
1131
1132 for (size_t j = 0; j < targets.size(); ++j)
1133 {
1134 // As m_group_nodes is simply transformed into 'targets',
1135 // one index can be used to index them all. You don't
1136 // have to check if they have equal addresses because they
1137 // are equal by definition.
1138 if (targets[j].id != -1 && targets[j].errorcode == SRT_SUCCESS)
1139 {
1140 m_group_nodes[j].socket = targets[j].id;
1141 }
1142 }
1143
1144 // Now check which sockets were successful, only those
1145 // should be added to epoll.
1146 size_t size = m_group_data.size();
1147 stat = srt_group_data(m_sock, m_group_data.data(), &size);
1148 if (stat == -1 && size > m_group_data.size())
1149 {
1150 // Just too small buffer. Resize and continue.
1151 m_group_data.resize(size);
1152 stat = srt_group_data(m_sock, m_group_data.data(), &size);
1153 }
1154
1155 if (stat == -1)
1156 {
1157 Error("srt_group_data");
1158 }
1159 m_group_data.resize(size);
1160
1161 for (size_t j = 0; j < m_group_nodes.size(); ++j)
1162 {
1163 SRTSOCKET insock = m_group_nodes[j].socket;
1164 if (insock == -1)
1165 {
1166 Verb() << "TARGET '" << sockaddr_any(targets[i].peeraddr).str() << "' connection failed.";
1167 continue;
1168 }
1169
1170 // Have socket, store it into the group socket array.
1171 any_node = true;
1172 }
1173
1174 if (!any_node)
1175 Error("All connections failed");
1176
1177 // Wait for REAL connected state if nonblocking mode, for AT LEAST one node.
1178 if (!m_blocking_mode)
1179 {
1180 Verb() << "[ASYNC] " << VerbNoEOL;
1181
1182 // SPIN-WAITING version. Don't use it unless you know what you're doing.
1183 // SpinWaitAsync();
1184
1185 // Socket readiness for connection is checked by polling on WRITE allowed sockets.
1186 int len1 = 2, len2 = 2;
1187 SRTSOCKET ready_conn[2], ready_err[2];
1188 if (srt_epoll_wait(srt_conn_epoll,
1189 ready_err, &len2,
1190 ready_conn, &len1,
1191 -1, // Wait infinitely
1192 NULL, NULL,
1193 NULL, NULL) != -1)
1194 {
1195 Verb() << "[C]" << VerbNoEOL;
1196 for (int ii = 0; ii < len1; ++ii)
1197 Verb() << " " << ready_conn[ii] << VerbNoEOL;
1198 Verb() << "[E]" << VerbNoEOL;
1199 for (int ii = 0; ii < len2; ++ii)
1200 Verb() << " " << ready_err[ii] << VerbNoEOL;
1201
1202 Verb() << "";
1203
1204 // We are waiting for one entity to be ready so it's either
1205 // in one or the other
1206 if (find(ready_err, ready_err+len2, m_sock) != ready_err+len2)
1207 {
1208 Verb() << "[EPOLL: " << len2 << " entities FAILED]";
1209 // Complete the error information for every member
1210 ostringstream out;
1211 set<int> reasons;
1212 for (Connection& c: m_group_nodes)
1213 {
1214 if (c.error != SRT_SUCCESS)
1215 {
1216 out << "[" << c.token << "] " << c.host << ":" << c.port;
1217 if (!c.source.empty())
1218 out << "[[" << c.source.str() << "]]";
1219 out << ": " << srt_strerror(c.error, 0) << ": " << srt_rejectreason_str(c.reason) << endl;
1220 }
1221 reasons.insert(c.reason);
1222 }
1223
1224 if (transmit_retry_connect && (transmit_retry_always || (reasons.size() == 1 && *reasons.begin() == SRT_REJ_TIMEOUT)))
1225 {
1226 if (transmit_retry_connect != -1)
1227 --transmit_retry_connect;
1228
1229
1230 Verb() << "...all links timeout, retrying NOW (" << transmit_retry_connect << ")...";
1231 goto Connect_Again;
1232 }
1233
1234 Error("srt_connect_group, nodes:\n" + out.str());
1235 }
1236 else if (find(ready_conn, ready_conn+len1, m_sock) != ready_conn+len1)
1237 {
1238 Verb() << "[EPOLL: " << len1 << " entities] " << VerbNoEOL;
1239 }
1240 else
1241 {
1242 Error("Group: SPURIOUS epoll readiness");
1243 }
1244 }
1245 else
1246 {
1247 Error("srt_epoll_wait");
1248 }
1249 }
1250
1251 stat = ConfigurePost(m_sock);
1252 if (stat == -1)
1253 {
1254 // This kind of error must reject the whole operation.
1255 // Usually you'll get this error on the first socket,
1256 // and doing this on the others would result in the same.
1257 Error("ConfigurePost");
1258 }
1259
1260 ::transmit_throw_on_interrupt = false;
1261
1262 Verb() << "Group connection report:";
1263 for (auto& d: m_group_data)
1264 {
1265 // id, status, result, peeraddr
1266 Verb() << "@" << d.id << " <" << SockStatusStr(d.sockstate) << "> (=" << d.result << ") PEER:"
1267 << sockaddr_any((sockaddr*)&d.peeraddr, sizeof d.peeraddr).str();
1268 }
1269
1270 // Prepare group data for monitoring the group status.
1271 m_group_data.resize(m_group_nodes.size());
1272 }
1273 #endif
1274
1275 /*
1276 This may be used sometimes for testing, but it's nonportable.
1277 void SrtCommon::SpinWaitAsync()
1278 {
1279 static string udt_status_names [] = {
1280 "INIT" , "OPENED", "LISTENING", "CONNECTING", "CONNECTED", "BROKEN", "CLOSING", "CLOSED", "NONEXIST"
1281 };
1282
1283 for (;;)
1284 {
1285 SRT_SOCKSTATUS state = srt_getsockstate(m_sock);
1286 if (int(state) < SRTS_CONNECTED)
1287 {
1288 if (Verbose::on)
1289 Verb() << state;
1290 usleep(250000);
1291 continue;
1292 }
1293 else if (int(state) > SRTS_CONNECTED)
1294 {
1295 Error("UDT::connect status=" + udt_status_names[state]);
1296 }
1297
1298 return;
1299 }
1300 }
1301 */
1302
1303 struct TransmitErrorReason
1304 {
1305 int error;
1306 int reason;
1307 };
1308
1309 static std::map<SRTSOCKET, TransmitErrorReason> transmit_error_storage;
1310
1311 static void TransmitConnectCallback(void*, SRTSOCKET socket, int errorcode, const sockaddr* /*peer*/, int /*token*/)
1312 {
1313 int reason = srt_getrejectreason(socket);
1314 transmit_error_storage[socket] = TransmitErrorReason { errorcode, reason };
1315 Verb() << "[Connection error reported on @" << socket << "]";
1316 }
1317
1318 void SrtCommon::ConnectClient(string host, int port)
1319 {
1320 auto sa = CreateAddr(host, port);
1321 Verb() << "Connecting to " << host << ":" << port << " ... " << VerbNoEOL;
1322
1323 if (!m_blocking_mode)
1324 {
1325 srt_connect_callback(m_sock, &TransmitConnectCallback, 0);
1326 }
1327
1328 int stat = -1;
1329 for (;;)
1330 {
1331 ::transmit_throw_on_interrupt = true;
1332 stat = srt_connect(m_sock, sa.get(), sizeof sa);
1333 ::transmit_throw_on_interrupt = false;
1334 if (stat == SRT_ERROR)
1335 {
1336 int reason = srt_getrejectreason(m_sock);
1337 #if PLEASE_LOG
1338 LOGP(applog.Error, "ERROR reported by srt_connect - closing socket @", m_sock,
1339 " reject reason: ", reason, ": ", srt_rejectreason_str(reason));
1340 #endif
1341 if (transmit_retry_connect && (transmit_retry_always || reason == SRT_REJ_TIMEOUT))
1342 {
1343 if (transmit_retry_connect != -1)
1344 --transmit_retry_connect;
1345
1346 Verb() << "...timeout, retrying (" << transmit_retry_connect << ")...";
1347 continue;
1348 }
1349
1350 srt_close(m_sock);
1351 Error("srt_connect", reason);
1352 }
1353 break;
1354 }
1355
1356 // Wait for REAL connected state if nonblocking mode
1357 if (!m_blocking_mode)
1358 {
1359 Verb() << "[ASYNC] " << VerbNoEOL;
1360
1361 // SPIN-WAITING version. Don't use it unless you know what you're doing.
1362 // SpinWaitAsync();
1363
1364 // Socket readiness for connection is checked by polling on WRITE allowed sockets.
1365 int lenc = 2, lene = 2;
1366 SRTSOCKET ready_connect[2], ready_error[2];
1367 if (srt_epoll_wait(srt_conn_epoll, ready_error, &lene, ready_connect, &lenc, -1, 0, 0, 0, 0) != -1)
1368 {
1369 // We should have just one socket, so check whatever socket
1370 // is in the transmit_error_storage.
1371 if (!transmit_error_storage.empty())
1372 {
1373 Verb() << "[CALLBACK(error): " << VerbNoEOL;
1374 int error, reason;
1375 bool failed = false;
1376 for (pair<const SRTSOCKET, TransmitErrorReason>& e: transmit_error_storage)
1377 {
1378 Verb() << "{@" << e.first << " error=" << e.second.error
1379 << " reason=" << e.second.reason << "} " << VerbNoEOL;
1380 error = e.second.error;
1381 reason = e.second.reason;
1382 if (error != SRT_SUCCESS)
1383 failed = true;
1384 }
1385 Verb() << "]";
1386 transmit_error_storage.clear();
1387 if (failed)
1388 Error("srt_connect(async/cb)", reason, error);
1389 }
1390
1391 if (lene > 0)
1392 {
1393 Verb() << "[EPOLL(error): " << lene << " sockets]";
1394 int reason = srt_getrejectreason(ready_error[0]);
1395 Error("srt_connect(async)", reason, SRT_ECONNREJ);
1396 }
1397 Verb() << "[EPOLL: " << lenc << " sockets] " << VerbNoEOL;
1398 }
1399 else
1400 {
1401 transmit_error_storage.clear();
1402 Error("srt_epoll_wait(srt_conn_epoll)");
1403 }
1404
1405 transmit_error_storage.clear();
1406 }
1407
1408 Verb() << " connected.";
1409 stat = ConfigurePost(m_sock);
1410 if (stat == SRT_ERROR)
1411 Error("ConfigurePost");
1412 }
1413
1414 void SrtCommon::Error(string src, int reason, int force_result)
1415 {
1416 int errnov = 0;
1417 const int result = force_result == 0 ? srt_getlasterror(&errnov) : force_result;
1418 if (result == SRT_SUCCESS)
1419 {
1420 cerr << "\nERROR (app): " << src << endl;
1421 throw std::runtime_error(src);
1422 }
1423 string message = srt_strerror(result, errnov);
1424 if (result == SRT_ECONNREJ)
1425 {
1426 if ( Verbose::on )
1427 Verb() << "FAILURE\n" << src << ": [" << result << "] "
1428 << "Connection rejected: [" << int(reason) << "]: "
1429 << srt_rejectreason_str(reason);
1430 else
1431 cerr << "\nERROR #" << result
1432 << ": Connection rejected: [" << int(reason) << "]: "
1433 << srt_rejectreason_str(reason);
1434 }
1435 else
1436 {
1437 if ( Verbose::on )
1438 Verb() << "FAILURE\n" << src << ": [" << result << "." << errnov << "] " << message;
1439 else
1440 cerr << "\nERROR #" << result << "." << errnov << ": " << message << endl;
1441 }
1442
1443 throw TransmissionError("error: " + src + ": " + message);
1444 }
1445
1446 void SrtCommon::SetupRendezvous(string adapter, string host, int port)
1447 {
1448 sockaddr_any target = CreateAddr(host, port);
1449 if (target.family() == AF_UNSPEC)
1450 {
1451 Error("Unable to resolve target host: " + host);
1452 }
1453
1454 bool yes = true;
1455 srt_setsockopt(m_sock, 0, SRTO_RENDEZVOUS, &yes, sizeof yes);
1456
1457 const int outport = m_outgoing_port ? m_outgoing_port : port;
1458
1459 // Prefer the same IPv as target host
1460 auto localsa = CreateAddr(adapter, outport, target.family());
1461 string showhost = adapter;
1462 if (showhost == "")
1463 showhost = "ANY";
1464 if (target.family() == AF_INET6)
1465 showhost = "[" + showhost + "]";
1466 Verb() << "Binding rendezvous: " << showhost << ":" << outport << " ...";
1467 int stat = srt_bind(m_sock, localsa.get(), localsa.size());
1468 if (stat == SRT_ERROR)
1469 {
1470 srt_close(m_sock);
1471 Error("srt_bind");
1472 }
1473 }
1474
1475 void SrtCommon::Close()
1476 {
1477 #if PLEASE_LOG
1478 extern srt_logging::Logger applog;
1479 LOGP(applog.Error, "CLOSE requested - closing socket @", m_sock);
1480 #endif
1481 bool any = false;
1482 bool yes = true;
1483 if (m_sock != SRT_INVALID_SOCK)
1484 {
1485 Verb() << "SrtCommon: DESTROYING CONNECTION, closing socket (rt%" << m_sock << ")...";
1486 srt_setsockflag(m_sock, SRTO_SNDSYN, &yes, sizeof yes);
1487 srt_close(m_sock);
1488 any = true;
1489 }
1490
1491 if (m_bindsock != SRT_INVALID_SOCK)
1492 {
1493 Verb() << "SrtCommon: DESTROYING SERVER, closing socket (ls%" << m_bindsock << ")...";
1494 // Set sndsynchro to the socket to synch-close it.
1495 srt_setsockflag(m_bindsock, SRTO_SNDSYN, &yes, sizeof yes);
1496 srt_close(m_bindsock);
1497 any = true;
1498 }
1499
1500 if (any)
1501 Verb() << "SrtCommon: ... done.";
1502 }
1503
1504 SrtCommon::~SrtCommon()
1505 {
1506 Close();
1507 }
1508
1509 #if ENABLE_BONDING
1510 void SrtCommon::UpdateGroupStatus(const SRT_SOCKGROUPDATA* grpdata, size_t grpdata_size)
1511 {
1512 if (!grpdata)
1513 {
1514 // This happens when you passed too small array. Treat this as error and stop.
1515 cerr << "ERROR: broadcast group update reports " << grpdata_size
1516 << " existing sockets, but app registered only " << m_group_nodes.size() << endl;
1517 Error("Too many unpredicted sockets in the group");
1518 }
1519
1520 // Clear the active flag in all nodes so that they are reactivated
1521 // if they are in the group list, REGARDLESS OF THE STATUS. We need to
1522 // see all connections that are in the nodes, but not in the group,
1523 // and this one would have to be activated.
1524 const SRT_SOCKGROUPDATA* gend = grpdata + grpdata_size;
1525 for (auto& n: m_group_nodes)
1526 {
1527 bool active = (find_if(grpdata, gend,
1528 [&n] (const SRT_SOCKGROUPDATA& sg) { return sg.id == n.socket; }) != gend);
1529 if (!active)
1530 n.socket = SRT_INVALID_SOCK;
1531 }
1532
1533 // Note: sockets are not necessarily in the same order. Find
1534 // the socket by id.
1535 for (size_t i = 0; i < grpdata_size; ++i)
1536 {
1537 const SRT_SOCKGROUPDATA& d = grpdata[i];
1538 SRTSOCKET id = d.id;
1539
1540 SRT_SOCKSTATUS status = d.sockstate;
1541 int result = d.result;
1542 SRT_MEMBERSTATUS mstatus = d.memberstate;
1543
1544 if (result != -1 && status == SRTS_CONNECTED)
1545 {
1546 // Short report with the state.
1547 Verb() << "G@" << id << "<" << MemberStatusStr(mstatus) << "> " << VerbNoEOL;
1548 continue;
1549 }
1550 // id, status, result, peeraddr
1551 Verb() << "\n\tG@" << id << " <" << SockStatusStr(status) << "/" << MemberStatusStr(mstatus) << "> (=" << result << ") PEER:"
1552 << sockaddr_any((sockaddr*)&d.peeraddr, sizeof d.peeraddr).str() << VerbNoEOL;
1553
1554 if (status >= SRTS_BROKEN)
1555 {
1556 Verb() << "NOTE: socket @" << id << " is pending for destruction, waiting for it.";
1557 }
1558 }
1559
1560 // This was only informative. Now we check all nodes if they
1561 // are not active
1562
1563 int i = 1;
1564 for (auto& n: m_group_nodes)
1565 {
1566 if (n.error != SRT_SUCCESS)
1567 {
1568 Verb() << "[" << i << "] CONNECTION FAILURE to '" << n.host << ":" << n.port << "': "
1569 << srt_strerror(n.error, 0) << ":" << srt_rejectreason_str(n.reason);
1570 }
1571
1572 // Check which nodes are no longer active and activate them.
1573 if (n.socket != SRT_INVALID_SOCK)
1574 continue;
1575
1576 auto sa = CreateAddr(n.host, n.port);
1577 Verb() << "[" << i << "] RECONNECTING to node " << n.host << ":" << n.port << " ... " << VerbNoEOL;
1578 ++i;
1579
1580 n.error = SRT_SUCCESS;
1581 n.reason = SRT_REJ_UNKNOWN;
1582
1583 const sockaddr* source = n.source.empty() ? nullptr : n.source.get();
1584 SRT_SOCKGROUPCONFIG gd = srt_prepare_endpoint(source, sa.get(), sa.size());
1585 gd.weight = n.weight;
1586 gd.config = n.options;
1587 gd.token = n.token;
1588
1589 int fisock = srt_connect_group(m_sock, &gd, 1);
1590 if (fisock == SRT_ERROR)
1591 {
1592 // Whatever. Skip the node.
1593 Verb() << "FAILED: ";
1594 }
1595 else
1596 {
1597 // Have socket, store it into the group socket array.
1598 n.socket = gd.id;
1599 }
1600 }
1601 }
1602 #endif
1603
1604 SrtSource::SrtSource(string host, int port, std::string path, const map<string,string>& par)
1605 {
1606 Init(host, port, path, par, SRT_EPOLL_IN);
1607 ostringstream os;
1608 os << host << ":" << port;
1609 hostport_copy = os.str();
1610 }
1611
1612 static void PrintSrtStats(SRTSOCKET sock, bool clr, bool bw, bool stats)
1613 {
1614 CBytePerfMon perf;
1615 // clear only if stats report is to be read
1616 srt_bstats(sock, &perf, clr);
1617
1618 if (bw)
1619 cout << transmit_stats_writer->WriteBandwidth(perf.mbpsBandwidth);
1620 if (stats)
1621 cout << transmit_stats_writer->WriteStats(sock, perf);
1622 }
1623
1624
1625 #ifdef SRT_OLD_APP_READER
1626
1627 // NOTE: 'output' is expected to be EMPTY here.
1628 bool SrtSource::GroupCheckPacketAhead(bytevector& output)
1629 {
1630 bool status = false;
1631 vector<SRTSOCKET> past_ahead;
1632
1633 // This map no longer maps only ahead links.
1634 // Here are all links, and whether ahead, it's defined by the sequence.
1635 for (auto i = m_group_positions.begin(); i != m_group_positions.end(); ++i)
1636 {
1637 // i->first: socket ID
1638 // i->second: ReadPos { sequence, packet }
1639 // We are not interested with the socket ID because we
1640 // aren't going to read from it - we have the packet already.
1641 ReadPos& a = i->second;
1642
1643 int seqdiff = CSeqNo::seqcmp(a.sequence, m_group_seqno);
1644 if ( seqdiff == 1)
1645 {
1646 // The very next packet. Return it.
1647 m_group_seqno = a.sequence;
1648 Verb() << " (SRT group: ahead delivery %" << a.sequence << " from @" << i->first << ")";
1649 swap(output, a.packet);
1650 status = true;
1651 }
1652 else if (seqdiff < 1 && !a.packet.empty())
1653 {
1654 Verb() << " (@" << i->first << " dropping collected ahead %" << a.sequence << ")";
1655 a.packet.clear();
1656 }
1657 // In case when it's >1, keep it in ahead
1658 }
1659
1660 return status;
1661 }
1662
1663 static string DisplayEpollResults(const std::set<SRTSOCKET>& sockset, std::string prefix)
1664 {
1665 typedef set<SRTSOCKET> fset_t;
1666 ostringstream os;
1667 os << prefix << " ";
1668 for (fset_t::const_iterator i = sockset.begin(); i != sockset.end(); ++i)
1669 {
1670 os << "@" << *i << " ";
1671 }
1672
1673 return os.str();
1674 }
1675
1676 bytevector SrtSource::GroupRead(size_t chunk)
1677 {
1678 // Read the current group status. m_sock is here the group id.
1679 bytevector output;
1680
1681 // Later iteration over it might be less efficient than
1682 // by vector, but we'll also often try to check a single id
1683 // if it was ever seen broken, so that it's skipped.
1684 set<SRTSOCKET> broken;
1685
1686 RETRY_READING:
1687
1688 size_t size = m_group_data.size();
1689 int stat = srt_group_data(m_sock, m_group_data.data(), &size);
1690 if (stat == -1 && size > m_group_data.size())
1691 {
1692 // Just too small buffer. Resize and continue.
1693 m_group_data.resize(size);
1694 stat = srt_group_data(m_sock, m_group_data.data(), &size);
1695 }
1696 else
1697 {
1698 // Downsize if needed.
1699 m_group_data.resize(size);
1700 }
1701
1702 if (stat == -1) // Also after the above fix
1703 {
1704 Error(UDT::getlasterror(), "FAILURE when reading group data");
1705 }
1706
1707 if (size == 0)
1708 {
1709 Error("No sockets in the group - disconnected");
1710 }
1711
1712 bool connected = false;
1713 for (auto& d: m_group_data)
1714 {
1715 if (d.status == SRTS_CONNECTED)
1716 {
1717 connected = true;
1718 break;
1719 }
1720 }
1721 if (!connected)
1722 {
1723 Error("All sockets in the group disconnected");
1724 }
1725
1726 if (Verbose::on)
1727 {
1728 for (auto& d: m_group_data)
1729 {
1730 if (d.status != SRTS_CONNECTED)
1731 // id, status, result, peeraddr
1732 Verb() << "@" << d.id << " <" << SockStatusStr(d.status) << "> (=" << d.result << ") PEER:"
1733 << sockaddr_any((sockaddr*)&d.peeraddr, sizeof d.peeraddr).str();
1734 }
1735 }
1736
1737 // Check first the ahead packets if you have any to deliver.
1738 if (m_group_seqno != -1 && !m_group_positions.empty())
1739 {
1740 bytevector ahead_packet;
1741
1742 // This function also updates the group sequence pointer.
1743 if (GroupCheckPacketAhead(ahead_packet))
1744 return move(ahead_packet);
1745 }
1746
1747 // LINK QUALIFICATION NAMES:
1748 //
1749 // HORSE: Correct link, which delivers the very next sequence.
1750 // Not necessarily this link is currently active.
1751 //
1752 // KANGAROO: Got some packets dropped and the sequence number
1753 // of the packet jumps over the very next sequence and delivers
1754 // an ahead packet.
1755 //
1756 // ELEPHANT: Is not ready to read, while others are, or reading
1757 // up to the current latest delivery sequence number does not
1758 // reach this sequence and the link becomes non-readable earlier.
1759
1760 // The above condition has ruled out one kangaroo and turned it
1761 // into a horse.
1762
1763 // Below there's a loop that will try to extract packets. Kangaroos
1764 // will be among the polled ones because skipping them risks that
1765 // the elephants will take over the reading. Links already known as
1766 // elephants will be also polled in an attempt to revitalize the
1767 // connection that experienced just a short living choking.
1768 //
1769 // After polling we attempt to read from every link that reported
1770 // read-readiness and read at most up to the sequence equal to the
1771 // current delivery sequence.
1772
1773 // Links that deliver a packet below that sequence will be retried
1774 // until they deliver no more packets or deliver the packet of
1775 // expected sequence. Links that don't have a record in m_group_positions
1776 // and report readiness will be always read, at least to know what
1777 // sequence they currently stand on.
1778 //
1779 // Links that are already known as kangaroos will be polled, but
1780 // no reading attempt will be done. If after the reading series
1781 // it will turn out that we have no more horses, the slowest kangaroo
1782 // will be "advanced to a horse" (the ahead link with a sequence
1783 // closest to the current delivery sequence will get its sequence
1784 // set as current delivered and its recorded ahead packet returned
1785 // as the read packet).
1786
1787 // If we find at least one horse, the packet read from that link
1788 // will be delivered. All other link will be just ensured update
1789 // up to this sequence number, or at worst all available packets
1790 // will be read. In this case all kangaroos remain kangaroos,
1791 // until the current delivery sequence m_group_seqno will be lifted
1792 // to the sequence recorded for these links in m_group_positions,
1793 // during the next time ahead check, after which they will become
1794 // horses.
1795
1796 Verb() << "E(" << srt_epoll << ") " << VerbNoEOL;
1797
1798 for (size_t i = 0; i < size; ++i)
1799 {
1800 SRT_SOCKGROUPDATA& d = m_group_data[i];
1801 if (d.status == SRTS_CONNECTING)
1802 {
1803 Verb() << "@" << d.id << "<pending> " << VerbNoEOL;
1804 int modes = SRT_EPOLL_OUT | SRT_EPOLL_ERR;
1805 srt_epoll_add_usock(srt_epoll, d.id, &modes);
1806 continue; // don't read over a failed or pending socket
1807 }
1808
1809 if (d.status >= SRTS_BROKEN)
1810 {
1811 broken.insert(d.id);
1812 }
1813
1814 if (broken.count(d.id))
1815 {
1816 Verb() << "@" << d.id << "<broken> " << VerbNoEOL;
1817 continue;
1818 }
1819
1820 if (d.status != SRTS_CONNECTED)
1821 {
1822 Verb() << "@" << d.id << "<idle:" << SockStatusStr(d.status) << "> " << VerbNoEOL;
1823 // Sockets in this state are ignored. We are waiting until it
1824 // achieves CONNECTING state, then it's added to write.
1825 continue;
1826 }
1827
1828 // Don't skip packets that are ahead because if we have a situation
1829 // that all links are either "elephants" (do not report read readiness)
1830 // and "kangaroos" (have already delivered an ahead packet) then
1831 // omitting kangaroos will result in only elephants to be polled for
1832 // reading. Elephants, due to the strict timing requirements and
1833 // ensurance that TSBPD on every link will result in exactly the same
1834 // delivery time for a packet of given sequence, having an elephant
1835 // and kangaroo in one cage means that the elephant is simply a broken
1836 // or half-broken link (the data are not delivered, but it will get
1837 // repaired soon, enough for SRT to maintain the connection, but it
1838 // will still drop packets that didn't arrive in time), in both cases
1839 // it may potentially block the reading for an indefinite time, while
1840 // simultaneously a kangaroo might be a link that got some packets
1841 // dropped, but then it's still capable to deliver packets on time.
1842
1843 // Note also that about the fact that some links turn out to be
1844 // elephants we'll learn only after we try to poll and read them.
1845
1846 // Note that d.id might be a socket that was previously being polled
1847 // on write, when it's attempting to connect, but now it's connected.
1848 // This will update the socket with the new event set.
1849
1850 int modes = SRT_EPOLL_IN | SRT_EPOLL_ERR;
1851 srt_epoll_add_usock(srt_epoll, d.id, &modes);
1852 Verb() << "@" << d.id << "[READ] " << VerbNoEOL;
1853 }
1854
1855 Verb() << "";
1856
1857 // Here we need to make an additional check.
1858 // There might be a possibility that all sockets that
1859 // were added to the reader group, are ahead. At least
1860 // surely we don't have a situation that any link contains
1861 // an ahead-read subsequent packet, because GroupCheckPacketAhead
1862 // already handled that case.
1863 //
1864 // What we can have is that every link has:
1865 // - no known seq position yet (is not registered in the position map yet)
1866 // - the position equal to the latest delivered sequence
1867 // - the ahead position
1868
1869 // Now the situation is that we don't have any packets
1870 // waiting for delivery so we need to wait for any to report one.
1871 // XXX We support blocking mode only at the moment.
1872 // The non-blocking mode would need to simply check the readiness
1873 // with only immediate report, and read-readiness would have to
1874 // be done in background.
1875
1876 SrtPollState sready;
1877
1878 // Poll on this descriptor until reading is available, indefinitely.
1879 if (UDT::epoll_swait(srt_epoll, sready, -1) == SRT_ERROR)
1880 {
1881 Error(UDT::getlasterror(), "UDT::epoll_swait(srt_epoll, group)");
1882 }
1883 if (Verbose::on)
1884 {
1885 Verb() << "RDY: {"
1886 << DisplayEpollResults(sready.rd(), "[R]")
1887 << DisplayEpollResults(sready.wr(), "[W]")
1888 << DisplayEpollResults(sready.ex(), "[E]")
1889 << "} " << VerbNoEOL;
1890
1891 }
1892
1893 LOGC(applog.Debug, log << "epoll_swait: "
1894 << DisplayEpollResults(sready.rd(), "[R]")
1895 << DisplayEpollResults(sready.wr(), "[W]")
1896 << DisplayEpollResults(sready.ex(), "[E]"));
1897
1898 typedef set<SRTSOCKET> fset_t;
1899
1900 // Handle sockets of pending connection and with errors.
1901 broken = sready.ex();
1902
1903 // We don't do anything about sockets that have been configured to
1904 // poll on writing (that is, pending for connection). What we need
1905 // is that the epoll_swait call exit on that fact. Probably if this
1906 // was the only socket reported, no broken and no read-ready, this
1907 // will later check on output if still empty, if so, repeat the whole
1908 // function. This write-ready socket will be there already in the
1909 // connected state and will be added to read-polling.
1910
1911 // Ok, now we need to have some extra qualifications:
1912 // 1. If a socket has no registry yet, we read anyway, just
1913 // to notify the current position. We read ONLY ONE PACKET this time,
1914 // we'll worry later about adjusting it to the current group sequence
1915 // position.
1916 // 2. If a socket is already position ahead, DO NOT read from it, even
1917 // if it is ready.
1918
1919 // The state of things whether we were able to extract the very next
1920 // sequence will be simply defined by the fact that `output` is nonempty.
1921
1922 int32_t next_seq = m_group_seqno;
1923
1924 // If this set is empty, it won't roll even once, therefore output
1925 // will be surely empty. This will be checked then same way as when
1926 // reading from every socket resulted in error.
1927 for (fset_t::const_iterator i = sready.rd().begin(); i != sready.rd().end(); ++i)
1928 {
1929 // Check if this socket is in aheads
1930 // If so, don't read from it, wait until the ahead is flushed.
1931
1932 SRTSOCKET id = *i;
1933 ReadPos* p = nullptr;
1934 auto pe = m_group_positions.find(id);
1935 if (pe != m_group_positions.end())
1936 {
1937 p = &pe->second;
1938 // Possible results of comparison:
1939 // x < 0: the sequence is in the past, the socket should be adjusted FIRST
1940 // x = 0: the socket should be ready to get the exactly next packet
1941 // x = 1: the case is already handled by GroupCheckPacketAhead.
1942 // x > 1: AHEAD. DO NOT READ.
1943 int seqdiff = CSeqNo::seqcmp(p->sequence, m_group_seqno);
1944 if (seqdiff > 1)
1945 {
1946 Verb() << "EPOLL: @" << id << " %" << p->sequence << " AHEAD, not reading.";
1947 continue;
1948 }
1949 }
1950
1951
1952 // Read from this socket stubbornly, until:
1953 // - reading is no longer possible (AGAIN)
1954 // - the sequence difference is >= 1
1955
1956 int fi = 1; // marker for Verb to display flushing
1957 for (;;)
1958 {
1959 bytevector data(chunk);
1960 SRT_MSGCTRL mctrl = srt_msgctrl_default;
1961 stat = srt_recvmsg2(id, data.data(), chunk, &mctrl);
1962 if (stat == SRT_ERROR)
1963 {
1964 if (fi == 0)
1965 {
1966 if (Verbose::on)
1967 {
1968 if (p)
1969 {
1970 int32_t pktseq = p->sequence;
1971 int seqdiff = CSeqNo::seqcmp(p->sequence, m_group_seqno);
1972 Verb() << ". %" << pktseq << " " << seqdiff << ")";
1973 }
1974 else
1975 {
1976 Verb() << ".)";
1977 }
1978 }
1979 fi = 1;
1980 }
1981 int err = srt_getlasterror(0);
1982 if (err == SRT_EASYNCRCV)
1983 {
1984 // Do not treat this as spurious, just stop reading.
1985 break;
1986 }
1987 Verb() << "Error @" << id << ": " << srt_getlasterror_str();
1988 broken.insert(id);
1989 break;
1990 }
1991
1992 // NOTE: checks against m_group_seqno and decisions based on it
1993 // must NOT be done if m_group_seqno is -1, which means that we
1994 // are about to deliver the very first packet and we take its
1995 // sequence number as a good deal.
1996
1997 // The order must be:
1998 // - check discrepancy
1999 // - record the sequence
2000 // - check ordering.
2001 // The second one must be done always, but failed discrepancy
2002 // check should exclude the socket from any further checks.
2003 // That's why the common check for m_group_seqno != -1 can't
2004 // embrace everything below.
2005
2006 // We need to first qualify the sequence, just for a case
2007 if (m_group_seqno != -1 && abs(m_group_seqno - mctrl.pktseq) > CSeqNo::m_iSeqNoTH)
2008 {
2009 // This error should be returned if the link turns out
2010 // to be the only one, or set to the group data.
2011 // err = SRT_ESECFAIL;
2012 if (fi == 0)
2013 {
2014 Verb() << ".)";
2015 fi = 1;
2016 }
2017 Verb() << "Error @" << id << ": SEQUENCE DISCREPANCY: base=%" << m_group_seqno << " vs pkt=%" << mctrl.pktseq << ", setting ESECFAIL";
2018 broken.insert(id);
2019 break;
2020 }
2021
2022 // Rewrite it to the state for a case when next reading
2023 // would not succeed. Do not insert the buffer here because
2024 // this is only required when the sequence is ahead; for that
2025 // it will be fixed later.
2026 if (!p)
2027 {
2028 p = &(m_group_positions[id] = ReadPos { mctrl.pktseq, {} });
2029 }
2030 else
2031 {
2032 p->sequence = mctrl.pktseq;
2033 }
2034
2035 if (m_group_seqno != -1)
2036 {
2037 // Now we can safely check it.
2038 int seqdiff = CSeqNo::seqcmp(mctrl.pktseq, m_group_seqno);
2039
2040 if (seqdiff <= 0)
2041 {
2042 if (fi == 1)
2043 {
2044 Verb() << "(@" << id << " FLUSH:" << VerbNoEOL;
2045 fi = 0;
2046 }
2047
2048 Verb() << "." << VerbNoEOL;
2049
2050 // The sequence is recorded, the packet has to be discarded.
2051 // That's all.
2052 continue;
2053 }
2054
2055 // Finish flush reporting if fallen into here
2056 if (fi == 0)
2057 {
2058 Verb() << ". %" << mctrl.pktseq << " " << (-seqdiff) << ")";
2059 fi = 1;
2060 }
2061
2062 // Now we have only two possibilities:
2063 // seqdiff == 1: The very next sequence, we want to read and return the packet.
2064 // seqdiff > 1: The packet is ahead - record the ahead packet, but continue with the others.
2065
2066 if (seqdiff > 1)
2067 {
2068 Verb() << "@" << id << " %" << mctrl.pktseq << " AHEAD";
2069 p->packet = move(data);
2070 break; // Don't read from that socket anymore.
2071 }
2072 }
2073
2074 // We have seqdiff = 1, or we simply have the very first packet
2075 // which's sequence is taken as a good deal. Update the sequence
2076 // and record output.
2077
2078 if (!output.empty())
2079 {
2080 Verb() << "@" << id << " %" << mctrl.pktseq << " REDUNDANT";
2081 break;
2082 }
2083
2084
2085 Verb() << "@" << id << " %" << mctrl.pktseq << " DELIVERING";
2086 output = move(data);
2087
2088 // Record, but do not update yet, until all sockets are handled.
2089 next_seq = mctrl.pktseq;
2090 break;
2091 }
2092 }
2093
2094 // ready_len is only the length of currently reported
2095 // ready sockets, NOT NECESSARILY containing all sockets from the group.
2096 if (broken.size() == size)
2097 {
2098 // All broken
2099 Error("All sockets broken");
2100 }
2101
2102 if (Verbose::on && !broken.empty())
2103 {
2104 Verb() << "BROKEN: " << Printable(broken) << " - removing";
2105 }
2106
2107 // Now remove all broken sockets from aheads, if any.
2108 // Even if they have already delivered a packet.
2109 for (SRTSOCKET d: broken)
2110 {
2111 m_group_positions.erase(d);
2112 srt_close(d);
2113 }
2114
2115 // May be required to be re-read.
2116 broken.clear();
2117
2118 if (!output.empty())
2119 {
2120 // We have extracted something, meaning that we have the sequence shift.
2121 // Update it now and don't do anything else with the sockets.
2122
2123 // Sanity check
2124 if (next_seq == -1)
2125 {
2126 Error("IPE: next_seq not set after output extracted!");
2127 }
2128 m_group_seqno = next_seq;
2129 return output;
2130 }
2131
2132 // Check if we have any sockets left :D
2133
2134 // Here we surely don't have any more HORSES,
2135 // only ELEPHANTS and KANGAROOS. Qualify them and
2136 // attempt to at least take advantage of KANGAROOS.
2137
2138 // In this position all links are either:
2139 // - updated to the current position
2140 // - updated to the newest possible position available
2141 // - not yet ready for extraction (not present in the group)
2142
2143 // If we haven't extracted the very next sequence position,
2144 // it means that we might only have the ahead packets read,
2145 // that is, the next sequence has been dropped by all links.
2146
2147 if (!m_group_positions.empty())
2148 {
2149 // This might notify both lingering links, which didn't
2150 // deliver the required sequence yet, and links that have
2151 // the sequence ahead. Review them, and if you find at
2152 // least one packet behind, just wait for it to be ready.
2153 // Use again the waiting function because we don't want
2154 // the general waiting procedure to skip others.
2155 set<SRTSOCKET> elephants;
2156
2157 // const because it's `typename decltype(m_group_positions)::value_type`
2158 pair<const SRTSOCKET, ReadPos>* slowest_kangaroo = nullptr;
2159
2160 for (auto& sock_rp: m_group_positions)
2161 {
2162 // NOTE that m_group_seqno in this place wasn't updated
2163 // because we haven't successfully extracted anything.
2164 int seqdiff = CSeqNo::seqcmp(sock_rp.second.sequence, m_group_seqno);
2165 if (seqdiff < 0)
2166 {
2167 elephants.insert(sock_rp.first);
2168 }
2169 // If seqdiff == 0, we have a socket ON TRACK.
2170 else if (seqdiff > 0)
2171 {
2172 if (!slowest_kangaroo)
2173 {
2174 slowest_kangaroo = &sock_rp;
2175 }
2176 else
2177 {
2178 // Update to find the slowest kangaroo.
2179 int seqdiff = CSeqNo::seqcmp(slowest_kangaroo->second.sequence, sock_rp.second.sequence);
2180 if (seqdiff > 0)
2181 {
2182 slowest_kangaroo = &sock_rp;
2183 }
2184 }
2185 }
2186 }
2187
2188 // Note that if no "slowest_kangaroo" was found, it means
2189 // that we don't have kangaroos.
2190 if (slowest_kangaroo)
2191 {
2192 // We have a slowest kangaroo. Elephants must be ignored.
2193 // Best case, they will get revived, worst case they will be
2194 // soon broken.
2195 //
2196 // As we already have the packet delivered by the slowest
2197 // kangaroo, we can simply return it.
2198
2199 m_group_seqno = slowest_kangaroo->second.sequence;
2200 Verb() << "@" << slowest_kangaroo->first << " %" << m_group_seqno << " KANGAROO->HORSE";
2201 swap(output, slowest_kangaroo->second.packet);
2202 return output;
2203 }
2204
2205 // Here ALL LINKS ARE ELEPHANTS, stating that we still have any.
2206 if (Verbose::on)
2207 {
2208 if (!elephants.empty())
2209 {
2210 // If we don't have kangaroos, then simply reattempt to
2211 // poll all elephants again anyway (at worst they are all
2212 // broken and we'll learn about it soon).
2213 Verb() << "ALL LINKS ELEPHANTS. Re-polling.";
2214 }
2215 else
2216 {
2217 Verb() << "ONLY BROKEN WERE REPORTED. Re-polling.";
2218 }
2219 }
2220 goto RETRY_READING;
2221 }
2222
2223 // We have checked so far only links that were ready to poll.
2224 // Links that are not ready should be re-checked.
2225 // Links that were not ready at the entrance should be checked
2226 // separately, and probably here is the best moment to do it.
2227 // After we make sure that at least one link is ready, we can
2228 // reattempt to read a packet from it.
2229
2230 // Ok, so first collect all sockets that are in
2231 // connecting state, make a poll for connection.
2232 srt_epoll_clear_usocks(srt_epoll);
2233 bool have_connectors = false, have_ready = false;
2234 for (auto& d: m_group_data)
2235 {
2236 if (d.status < SRTS_CONNECTED)
2237 {
2238 // Not sure anymore if IN or OUT signals the connect-readiness,
2239 // but no matter. The signal will be cleared once it is used,
2240 // while it will be always on when there's anything ready to read.
2241 int modes = SRT_EPOLL_IN | SRT_EPOLL_OUT;
2242 srt_epoll_add_usock(srt_epoll, d.id, &modes);
2243 have_connectors = true;
2244 }
2245 else if (d.status == SRTS_CONNECTED)
2246 {
2247 have_ready = true;
2248 }
2249 }
2250
2251 if (have_ready || have_connectors)
2252 {
2253 Verb() << "(still have: " << (have_ready ? "+" : "-") << "ready, "
2254 << (have_connectors ? "+" : "-") << "connectors).";
2255 goto RETRY_READING;
2256 }
2257
2258 if (have_ready)
2259 {
2260 Verb() << "(connected in the meantime)";
2261 // Some have connected in the meantime, don't
2262 // waste time on the pending ones.
2263 goto RETRY_READING;
2264 }
2265
2266 if (have_connectors)
2267 {
2268 Verb() << "(waiting for pending connectors to connect)";
2269 // Wait here for them to be connected.
2270 vector<SRTSOCKET> sready;
2271 sready.resize(m_group_data.size());
2272 int ready_len = m_group_data.size();
2273 if (srt_epoll_wait(srt_epoll, sready.data(), &ready_len, 0, 0, -1, 0, 0, 0, 0) == SRT_ERROR)
2274 {
2275 Error("All sockets in the group disconnected");
2276 }
2277
2278 goto RETRY_READING;
2279 }
2280
2281 Error("No data extracted");
2282 return output; // Just a marker - this above function throws an exception
2283 }
2284
2285 #endif
2286
2287 MediaPacket SrtSource::Read(size_t chunk)
2288 {
2289 static size_t counter = 1;
2290
2291 bool have_group SRT_ATR_UNUSED = !m_group_nodes.empty();
2292
2293 bytevector data(chunk);
2294 // EXPERIMENTAL
2295 #ifdef SRT_OLD_APP_READER
2296 if (have_group || m_listener_group)
2297 {
2298 data = GroupRead(chunk);
2299 }
2300
2301 if (have_group)
2302 {
2303 // This is to be done for caller mode only
2304 UpdateGroupStatus(m_group_data.data(), m_group_data.size());
2305 }
2306 #else
2307
2308 SRT_MSGCTRL mctrl = srt_msgctrl_default;
2309 bool ready = true;
2310 int stat;
2311
2312 do
2313 {
2314 #if ENABLE_BONDING
2315 if (have_group || m_listener_group)
2316 {
2317 mctrl.grpdata = m_group_data.data();
2318 mctrl.grpdata_size = m_group_data.size();
2319 }
2320 #endif
2321
2322 if (::transmit_int_state)
2323 Error("srt_recvmsg2: interrupted");
2324
2325 ::transmit_throw_on_interrupt = true;
2326 stat = srt_recvmsg2(m_sock, data.data(), int(chunk), &mctrl);
2327 ::transmit_throw_on_interrupt = false;
2328 if (stat != SRT_ERROR)
2329 {
2330 ready = true;
2331 }
2332 else
2333 {
2334 int syserr = 0;
2335 int err = srt_getlasterror(&syserr);
2336
2337 if (!m_blocking_mode)
2338 {
2339 // EAGAIN for SRT READING
2340 if (err == SRT_EASYNCRCV)
2341 {
2342 Epoll_again:
2343 Verb() << "AGAIN: - waiting for data by epoll(" << srt_epoll << ")...";
2344 // Poll on this descriptor until reading is available, indefinitely.
2345 int len = 2;
2346 SRT_EPOLL_EVENT sready[2];
2347 len = srt_epoll_uwait(srt_epoll, sready, len, -1);
2348 if (len != -1)
2349 {
2350 Verb() << "... epoll reported ready " << len << " sockets";
2351 // If the event was SRT_EPOLL_UPDATE, report it, and still wait.
2352
2353 bool any_read_ready = false;
2354 vector<int> errored;
2355 for (int i = 0; i < len; ++i)
2356 {
2357 if (sready[i].events & SRT_EPOLL_UPDATE)
2358 {
2359 Verb() << "... [BROKEN CONNECTION reported on @" << sready[i].fd << "]";
2360 }
2361
2362 if (sready[i].events & SRT_EPOLL_IN)
2363 any_read_ready = true;
2364
2365 if (sready[i].events & SRT_EPOLL_ERR)
2366 {
2367 errored.push_back(sready[i].fd);
2368 }
2369 }
2370
2371 if (!any_read_ready)
2372 {
2373 Verb() << " ... [NOT READ READY - AGAIN (" << errored.size() << " errored: " << Printable(errored) << ")]";
2374 goto Epoll_again;
2375 }
2376
2377 continue;
2378 }
2379 // If was -1, then passthru.
2380 }
2381 }
2382 else
2383 {
2384 // In blocking mode it uses a minimum of 1s timeout,
2385 // and continues only if interrupt not requested.
2386 if (!::transmit_int_state && (err == SRT_EASYNCRCV || err == SRT_ETIMEOUT))
2387 {
2388 ready = false;
2389 continue;
2390 }
2391 }
2392 Error("srt_recvmsg2");
2393 }
2394
2395 if (stat == 0)
2396 {
2397 throw ReadEOF(hostport_copy);
2398 }
2399 #if PLEASE_LOG
2400 extern srt_logging::Logger applog;
2401 LOGC(applog.Debug, log << "recv: #" << mctrl.msgno << " %" << mctrl.pktseq << " "
2402 << BufferStamp(data.data(), stat) << " BELATED: " << ((srt_time_now()-mctrl.srctime)/1000.0) << "ms");
2403 #endif
2404
2405 Verb() << "(#" << mctrl.msgno << " %" << mctrl.pktseq << " " << BufferStamp(data.data(), stat) << ") " << VerbNoEOL;
2406 }
2407 while (!ready);
2408
2409 chunk = size_t(stat);
2410 if (chunk < data.size())
2411 data.resize(chunk);
2412
2413 const bool need_bw_report = transmit_bw_report && int(counter % transmit_bw_report) == transmit_bw_report - 1;
2414 const bool need_stats_report = transmit_stats_report && counter % transmit_stats_report == transmit_stats_report - 1;
2415
2416 #if ENABLE_BONDING
2417 if (have_group) // Means, group with caller mode
2418 {
2419 UpdateGroupStatus(mctrl.grpdata, mctrl.grpdata_size);
2420 if (transmit_stats_writer && (need_stats_report || need_bw_report))
2421 {
2422 PrintSrtStats(m_sock, need_stats_report, need_bw_report, need_stats_report);
2423 for (size_t i = 0; i < mctrl.grpdata_size; ++i)
2424 PrintSrtStats(mctrl.grpdata[i].id, need_stats_report, need_bw_report, need_stats_report);
2425 }
2426 }
2427 else
2428 #endif
2429 {
2430 if (transmit_stats_writer && (need_stats_report || need_bw_report))
2431 {
2432 PrintSrtStats(m_sock, need_stats_report, need_bw_report, need_stats_report);
2433 }
2434 }
2435 #endif
2436
2437 ++counter;
2438
2439 return MediaPacket(data, mctrl.srctime);
2440 }
2441
2442 SrtTarget::SrtTarget(std::string host, int port, std::string path, const std::map<std::string,std::string>& par)
2443 {
2444 Init(host, port, path, par, SRT_EPOLL_OUT);
2445 }
2446
2447
2448 int SrtTarget::ConfigurePre(SRTSOCKET sock)
2449 {
2450 int result = SrtCommon::ConfigurePre(sock);
2451 if (result == -1)
2452 return result;
2453
2454 int yes = 1;
2455 // This is for the HSv4 compatibility; if both parties are HSv5
2456 // (min. version 1.2.1), then this setting simply does nothing.
2457 // In HSv4 this setting is obligatory; otherwise the SRT handshake
2458 // extension will not be done at all.
2459 result = srt_setsockopt(sock, 0, SRTO_SENDER, &yes, sizeof yes);
2460 if (result == -1)
2461 return result;
2462
2463 return 0;
2464 }
2465
2466 void SrtTarget::Write(const MediaPacket& data)
2467 {
2468 static int counter = 1;
2469 ::transmit_throw_on_interrupt = true;
2470
2471 // Check first if it's ready to write.
2472 // If not, wait indefinitely.
2473 if (!m_blocking_mode)
2474 {
2475 Epoll_again:
2476 int len = 2;
2477 SRT_EPOLL_EVENT sready[2];
2478 len = srt_epoll_uwait(srt_epoll, sready, len, -1);
2479 if (len != -1)
2480 {
2481 bool any_write_ready = false;
2482 for (int i = 0; i < len; ++i)
2483 {
2484 if (sready[i].events & SRT_EPOLL_UPDATE)
2485 {
2486 Verb() << "... [BROKEN CONNECTION reported on @" << sready[i].fd << "]";
2487 }
2488
2489 if (sready[i].events & SRT_EPOLL_OUT)
2490 any_write_ready = true;
2491 }
2492
2493 if (!any_write_ready)
2494 {
2495 Verb() << " ... [NOT WRITE READY - AGAIN]";
2496 goto Epoll_again;
2497 }
2498
2499 // Pass on, write ready.
2500 }
2501 else
2502 {
2503 Error("srt_epoll_uwait");
2504 }
2505 }
2506
2507 SRT_MSGCTRL mctrl = srt_msgctrl_default;
2508 #if ENABLE_BONDING
2509 bool have_group = !m_group_nodes.empty();
2510 if (have_group || m_listener_group)
2511 {
2512 mctrl.grpdata = m_group_data.data();
2513 mctrl.grpdata_size = m_group_data.size();
2514 }
2515 #endif
2516
2517 if (transmit_use_sourcetime)
2518 {
2519 mctrl.srctime = data.time;
2520 }
2521
2522 int stat = srt_sendmsg2(m_sock, data.payload.data(), int(data.payload.size()), &mctrl);
2523
2524 // For a socket group, the error is reported only
2525 // if ALL links from the group have failed to perform
2526 // the operation. If only one did, the result will be
2527 // visible in the status array.
2528 if (stat == SRT_ERROR)
2529 Error("srt_sendmsg");
2530 ::transmit_throw_on_interrupt = false;
2531
2532 const bool need_bw_report = transmit_bw_report && int(counter % transmit_bw_report) == transmit_bw_report - 1;
2533 const bool need_stats_report = transmit_stats_report && counter % transmit_stats_report == transmit_stats_report - 1;
2534
2535 #if ENABLE_BONDING
2536 if (have_group)
2537 {
2538 // For listener group this is not necessary. The group information
2539 // is updated in mctrl.
2540 UpdateGroupStatus(mctrl.grpdata, mctrl.grpdata_size);
2541 if (transmit_stats_writer && (need_stats_report || need_bw_report))
2542 {
2543 PrintSrtStats(m_sock, need_stats_report, need_bw_report, need_stats_report);
2544 for (size_t i = 0; i < mctrl.grpdata_size; ++i)
2545 PrintSrtStats(mctrl.grpdata[i].id, need_stats_report, need_bw_report, need_stats_report);
2546 }
2547 }
2548 else
2549 #endif
2550 {
2551 if (transmit_stats_writer && (need_stats_report || need_bw_report))
2552 {
2553 PrintSrtStats(m_sock, need_stats_report, need_bw_report, need_stats_report);
2554 }
2555 }
2556
2557 Verb() << "(#" << mctrl.msgno << " %" << mctrl.pktseq << " " << BufferStamp(data.payload.data(), data.payload.size()) << ") " << VerbNoEOL;
2558
2559 ++counter;
2560 }
2561
2562 SrtRelay::SrtRelay(std::string host, int port, std::string path, const std::map<std::string,std::string>& par)
2563 {
2564 Init(host, port, path, par, SRT_EPOLL_IN | SRT_EPOLL_OUT);
2565 }
2566
2567 SrtModel::SrtModel(string host, int port, map<string,string> par)
2568 {
2569 InitParameters(host, "", par);
2570 if (m_mode == "caller")
2571 is_caller = true;
2572 else if (m_mode == "rendezvous")
2573 is_rend = true;
2574 else if (m_mode != "listener")
2575 throw std::invalid_argument("Wrong 'mode' attribute; expected: caller, listener, rendezvous");
2576
2577 m_host = host;
2578 m_port = port;
2579 }
2580
2581 void SrtModel::Establish(std::string& w_name)
2582 {
2583 // This does connect or accept.
2584 // When this returned true, the caller should create
2585 // a new SrtSource or SrtTaget then call StealFrom(*this) on it.
2586
2587 // If this is a connector and the peer doesn't have a corresponding
2588 // medium, it should send back a single byte with value 0. This means
2589 // that agent should stop connecting.
2590
2591 if (is_rend)
2592 {
2593 OpenRendezvous(m_adapter, m_host, m_port);
2594 }
2595 else if (is_caller)
2596 {
2597 // Establish a connection
2598
2599 PrepareClient();
2600
2601 if (w_name != "")
2602 {
2603 Verb() << "Connect with requesting stream [" << w_name << "]";
2604 srt::setstreamid(m_sock, w_name);
2605 }
2606 else
2607 {
2608 Verb() << "NO STREAM ID for SRT connection";
2609 }
2610
2611 if (m_outgoing_port || m_adapter != "")
2612 {
2613 Verb() << "Setting outgoing port: " << m_outgoing_port << " adapter:" << m_adapter;
2614 SetupAdapter(m_adapter, m_outgoing_port);
2615 }
2616
2617 ConnectClient(m_host, m_port);
2618
2619 if (m_outgoing_port == 0)
2620 {
2621 // Must rely on a randomly selected one. Extract the port
2622 // so that it will be reused next time.
2623 sockaddr_any s(AF_INET);
2624 int namelen = s.size();
2625 if (srt_getsockname(Socket(), (s.get()), (&namelen)) == SRT_ERROR)
2626 {
2627 Error("srt_getsockname");
2628 }
2629
2630 m_outgoing_port = s.hport();
2631 Verb() << "Extracted outgoing port: " << m_outgoing_port;
2632 }
2633 }
2634 else
2635 {
2636 // Listener - get a socket by accepting.
2637 // Check if the listener is already created first
2638 if (Listener() == SRT_INVALID_SOCK)
2639 {
2640 Verb() << "Setting up listener: port=" << m_port << " backlog=5";
2641 PrepareListener(m_adapter, m_port, 5);
2642 }
2643
2644 Verb() << "Accepting a client...";
2645 AcceptNewClient();
2646 // This rewrites m_sock with a new SRT socket ("accepted" socket)
2647 w_name = UDT::getstreamid(m_sock);
2648 Verb() << "... GOT CLIENT for stream [" << w_name << "]";
2649 }
2650 }
2651
2652
2653 template <class Iface> struct Srt;
2654 template <> struct Srt<Source> { typedef SrtSource type; };
2655 template <> struct Srt<Target> { typedef SrtTarget type; };
2656 template <> struct Srt<Relay> { typedef SrtRelay type; };
2657
2658 template <class Iface>
2659 Iface* CreateSrt(const string& host, int port, std::string path, const map<string,string>& par)
2660 { return new typename Srt<Iface>::type (host, port, path, par); }
2661
2662 MediaPacket ConsoleRead(size_t chunk)
2663 {
2664 bytevector data(chunk);
2665 bool st = cin.read(data.data(), chunk).good();
2666 chunk = cin.gcount();
2667 if (chunk == 0 && !st)
2668 return bytevector();
2669
2670 int64_t stime = 0;
2671 if (transmit_use_sourcetime)
2672 stime = srt_time_now();
2673
2674 if (chunk < data.size())
2675 data.resize(chunk);
2676 if (data.empty())
2677 throw Source::ReadEOF("CONSOLE device");
2678
2679 return MediaPacket(data, stime);
2680 }
2681
2682 class ConsoleSource: public virtual Source
2683 {
2684 public:
2685
2686 ConsoleSource()
2687 {
2688 }
2689
2690 MediaPacket Read(size_t chunk) override
2691 {
2692 return ConsoleRead(chunk);
2693 }
2694
2695 bool IsOpen() override { return cin.good(); }
2696 bool End() override { return cin.eof(); }
2697 };
2698
2699 class ConsoleTarget: public virtual Target
2700 {
2701 public:
2702
2703 ConsoleTarget()
2704 {
2705 }
2706
2707 void Write(const MediaPacket& data) override
2708 {
2709 cout.write(data.payload.data(), data.payload.size());
2710 }
2711
2712 bool IsOpen() override { return cout.good(); }
2713 bool Broken() override { return cout.eof(); }
2714 };
2715
2716 class ConsoleRelay: public Relay, public ConsoleSource, public ConsoleTarget
2717 {
2718 public:
2719 ConsoleRelay() = default;
2720
2721 bool IsOpen() override { return cin.good() && cout.good(); }
2722 };
2723
2724 template <class Iface> struct Console;
2725 template <> struct Console<Source> { typedef ConsoleSource type; };
2726 template <> struct Console<Target> { typedef ConsoleTarget type; };
2727 template <> struct Console<Relay> { typedef ConsoleRelay type; };
2728
2729 template <class Iface>
2730 Iface* CreateConsole() { return new typename Console<Iface>::type (); }
2731
2732
2733 // More options can be added in future.
2734 SocketOption udp_options [] {
2735 { "iptos", IPPROTO_IP, IP_TOS, SocketOption::PRE, SocketOption::INT, nullptr },
2736 // IP_TTL and IP_MULTICAST_TTL are handled separately by a common option, "ttl".
2737 { "mcloop", IPPROTO_IP, IP_MULTICAST_LOOP, SocketOption::PRE, SocketOption::INT, nullptr }
2738 };
2739
2740 static inline bool IsMulticast(in_addr adr)
2741 {
2742 unsigned char* abytes = (unsigned char*)&adr.s_addr;
2743 unsigned char c = abytes[0];
2744 return c >= 224 && c <= 239;
2745 }
2746
2747 void UdpCommon::Setup(string host, int port, map<string,string> attr)
2748 {
2749 m_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
2750 if (m_sock == -1)
2751 Error(SysError(), "UdpCommon::Setup: socket");
2752
2753 int yes = 1;
2754 ::setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&yes, sizeof yes);
2755
2756 interface_addr = CreateAddr("", port, AF_INET);
2757 target_addr = CreateAddr(host, port);
2758
2759 is_multicast = false;
2760
2761 if (target_addr.family() == AF_INET)
2762 {
2763 if (attr.count("multicast"))
2764 {
2765 if (!IsMulticast(target_addr.sin.sin_addr))
2766 {
2767 throw std::runtime_error("UdpCommon: requested multicast for a non-multicast-type IP address");
2768 }
2769 is_multicast = true;
2770 }
2771 else if (IsMulticast(target_addr.sin.sin_addr))
2772 {
2773 is_multicast = true;
2774 }
2775
2776 if (is_multicast)
2777 {
2778 ip_mreq mreq;
2779 int opt_name;
2780 const char* mreq_arg_ptr;
2781 socklen_t mreq_arg_size;
2782
2783 adapter = attr.count("adapter") ? attr.at("adapter") : string();
2784 if (adapter == "")
2785 {
2786 Verb() << "Multicast: home address: INADDR_ANY:" << port;
2787 }
2788 else
2789 {
2790 Verb() << "Multicast: home address: " << adapter << ":" << port;
2791 interface_addr = CreateAddr(adapter, port);
2792 }
2793
2794 if (attr.count("source"))
2795 {
2796 #ifdef IP_ADD_SOURCE_MEMBERSHIP
2797 ip_mreq_source mreq_ssm;
2798 /* this is an ssm. we need to use the right struct and opt */
2799 opt_name = IP_ADD_SOURCE_MEMBERSHIP;
2800 mreq_ssm.imr_multiaddr.s_addr = target_addr.sin.sin_addr.s_addr;
2801 mreq_ssm.imr_interface.s_addr = interface_addr.sin.sin_addr.s_addr;
2802 inet_pton(AF_INET, attr.at("source").c_str(), &mreq_ssm.imr_sourceaddr);
2803 mreq_arg_size = sizeof(mreq_ssm);
2804 mreq_arg_ptr = (const char*)&mreq_ssm;
2805 #else
2806 throw std::runtime_error("UdpCommon: source-filter multicast not supported by OS");
2807 #endif
2808 }
2809 else
2810 {
2811 opt_name = IP_ADD_MEMBERSHIP;
2812 mreq.imr_multiaddr.s_addr = target_addr.sin.sin_addr.s_addr;
2813 mreq.imr_interface.s_addr = interface_addr.sin.sin_addr.s_addr;
2814 mreq_arg_size = sizeof(mreq);
2815 mreq_arg_ptr = (const char*)&mreq;
2816 }
2817
2818 #ifdef _WIN32
2819 const auto status_error = SOCKET_ERROR;
2820 #else
2821 const auto status_error = -1;
2822 #endif
2823 auto res = setsockopt(m_sock, IPPROTO_IP, opt_name, mreq_arg_ptr, mreq_arg_size);
2824
2825 if (res == status_error)
2826 {
2827 Error(errno, "adding to multicast membership failed");
2828 }
2829
2830 attr.erase("multicast");
2831 attr.erase("adapter");
2832 }
2833 }
2834
2835 // The "ttl" options is handled separately, it maps to both IP_TTL
2836 // and IP_MULTICAST_TTL so that TTL setting works for both uni- and multicast.
2837 if (attr.count("ttl"))
2838 {
2839 int ttl = stoi(attr.at("ttl"));
2840 int res = setsockopt(m_sock, IPPROTO_IP, IP_TTL, (const char*)&ttl, sizeof ttl);
2841 if (res == -1)
2842 Verb() << "WARNING: failed to set 'ttl' (IP_TTL) to " << ttl;
2843 res = setsockopt(m_sock, IPPROTO_IP, IP_MULTICAST_TTL, (const char*)&ttl, sizeof ttl);
2844 if (res == -1)
2845 Verb() << "WARNING: failed to set 'ttl' (IP_MULTICAST_TTL) to " << ttl;
2846
2847 attr.erase("ttl");
2848 }
2849
2850 m_options = attr;
2851
2852 for (auto o: udp_options)
2853 {
2854 // Ignore "binding" - for UDP there are no post options.
2855 if (m_options.count(o.name))
2856 {
2857 string value = m_options.at(o.name);
2858 bool ok = o.apply<SocketOption::SYSTEM>(m_sock, value);
2859 if (!ok)
2860 Verb() << "WARNING: failed to set '" << o.name << "' to " << value;
2861 }
2862 }
2863 }
2864
2865 void UdpCommon::Error(int err, string src)
2866 {
2867 char buf[512];
2868 string message = SysStrError(err, buf, 512u);
2869
2870 if (Verbose::on)
2871 Verb() << "FAILURE\n" << src << ": [" << err << "] " << message;
2872 else
2873 cerr << "\nERROR #" << err << ": " << message << endl;
2874
2875 throw TransmissionError("error: " + src + ": " + message);
2876 }
2877
2878 UdpCommon::~UdpCommon()
2879 {
2880 #ifdef _WIN32
2881 if (m_sock != -1)
2882 {
2883 shutdown(m_sock, SD_BOTH);
2884 closesocket(m_sock);
2885 m_sock = -1;
2886 }
2887 #else
2888 close(m_sock);
2889 #endif
2890 }
2891
2892 UdpSource::UdpSource(string host, int port, const map<string,string>& attr)
2893 {
2894 Setup(host, port, attr);
2895
2896 // On Windows it somehow doesn't work when bind()
2897 // is called with multicast address. Write the address
2898 // that designates the network device here, always.
2899
2900 // Hance we have two fields holding the address:
2901 // * target_addr: address from which reading will be done
2902 // * unicast: local address of the interface
2903 // * multicast: the IGMP address
2904 // * interface_addr: address of the local interface
2905 // (same as target_addr for unicast)
2906
2907 // In case of multicast, binding should be done:
2908 // On most POSIX systems, to the multicast address (target_addr in this case)
2909 // On Windows, to a local address (hence use interface_addr, as in this
2910 // case it differs to target_addr).
2911
2912 #if defined(_WIN32) || defined(__CYGWIN__)
2913 sockaddr_any baddr = is_multicast ? interface_addr : target_addr;
2914 static const char* const sysname = "Windows";
2915 #else
2916 static const char* const sysname = "POSIX";
2917 sockaddr_any baddr = target_addr;
2918 #endif
2919 Verb("UDP:", is_multicast ? "Multicast" : "Unicast", "(", sysname,
2920 "): will bind to: ", baddr.str());
2921 int stat = ::bind(m_sock, baddr.get(), baddr.size());
2922
2923 if (stat == -1)
2924 Error(SysError(), "Binding address for UDP");
2925 eof = false;
2926 struct timeval tv;
2927 tv.tv_sec = 1;
2928 tv.tv_usec = 0;
2929 if (::setsockopt(m_sock, SOL_SOCKET, SO_RCVTIMEO, (const char*) &tv, sizeof(tv)) < 0)
2930 Error(SysError(), "Setting timeout for UDP");
2931 }
2932
2933 MediaPacket UdpSource::Read(size_t chunk)
2934 {
2935 bytevector data(chunk);
2936 sockaddr_any sa(target_addr.family());
2937 int64_t srctime = 0;
2938 AGAIN:
2939 int stat = recvfrom(m_sock, data.data(), (int) chunk, 0, sa.get(), &sa.syslen());
2940 int err = SysError();
2941 if (transmit_use_sourcetime)
2942 {
2943 srctime = srt_time_now();
2944 }
2945 if (stat == -1)
2946 {
2947 if (!::transmit_int_state && err == SysAGAIN)
2948 goto AGAIN;
2949
2950 Error(SysError(), "UDP Read/recvfrom");
2951 }
2952
2953 if (stat < 1)
2954 {
2955 eof = true;
2956 return bytevector();
2957 }
2958
2959 chunk = size_t(stat);
2960 if (chunk < data.size())
2961 data.resize(chunk);
2962
2963 return MediaPacket(data, srctime);
2964 }
2965
2966 UdpTarget::UdpTarget(string host, int port, const map<string,string>& attr)
2967 {
2968 Setup(host, port, attr);
2969 if (adapter != "")
2970 {
2971 auto maddr = CreateAddr(adapter, 0);
2972 in_addr addr = maddr.sin.sin_addr;
2973
2974 int res = setsockopt(m_sock, IPPROTO_IP, IP_MULTICAST_IF, reinterpret_cast<const char*>(&addr), sizeof(addr));
2975 if (res == -1)
2976 {
2977 Error(SysError(), "setsockopt/IP_MULTICAST_IF: " + adapter);
2978 }
2979 }
2980 }
2981
2982 void UdpTarget::Write(const MediaPacket& data)
2983 {
2984 int stat = sendto(m_sock, data.payload.data(), int(data.payload.size()), 0, target_addr.get(), (int)target_addr.size());
2985 if (stat == -1)
2986 Error(SysError(), "UDP Write/sendto");
2987 }
2988
2989
2990 template <class Iface> struct Udp;
2991 template <> struct Udp<Source> { typedef UdpSource type; };
2992 template <> struct Udp<Target> { typedef UdpTarget type; };
2993 template <> struct Udp<Relay> { typedef UdpRelay type; };
2994
2995 template <class Iface>
2996 Iface* CreateUdp(const string& host, int port, const map<string,string>& par) { return new typename Udp<Iface>::type (host, port, par); }
2997
2998 template<class Base>
2999 inline bool IsOutput() { return false; }
3000
3001 template<>
3002 inline bool IsOutput<Target>() { return true; }
3003
3004 template <class Base>
3005 extern unique_ptr<Base> CreateMedium(const string& uri)
3006 {
3007 unique_ptr<Base> ptr;
3008
3009 UriParser u(uri);
3010
3011 int iport = 0;
3012 switch ( u.type() )
3013 {
3014 default:
3015 break; // do nothing, return nullptr
3016 case UriParser::FILE:
3017 if (u.host() == "con" || u.host() == "console")
3018 {
3019 if ( IsOutput<Base>() && (
3020 (Verbose::on && Verbose::cverb == &cout)
3021 || transmit_bw_report || transmit_stats_report) )
3022 {
3023 cerr << "ERROR: file://con with -v or -r or -s would result in mixing the data and text info.\n";
3024 cerr << "ERROR: HINT: you can stream through a FIFO (named pipe)\n";
3025 throw invalid_argument("incorrect parameter combination");
3026 }
3027 ptr.reset( CreateConsole<Base>() );
3028 }
3029 else
3030 ptr.reset( CreateFile<Base>(u.path()));
3031 break;
3032
3033 case UriParser::SRT:
3034 ptr.reset( CreateSrt<Base>(u.host(), u.portno(), u.path(), u.parameters()) );
3035 break;
3036
3037
3038 case UriParser::UDP:
3039 iport = atoi(u.port().c_str());
3040 if (iport < 1024)
3041 {
3042 cerr << "Port value invalid: " << iport << " - must be >=1024\n";
3043 throw invalid_argument("Invalid port number");
3044 }
3045 ptr.reset( CreateUdp<Base>(u.host(), iport, u.parameters()) );
3046 break;
3047 }
3048
3049 if (ptr)
3050 ptr->uri = std::move(u);
3051 return ptr;
3052 }
3053
3054
3055 std::unique_ptr<Source> Source::Create(const std::string& url)
3056 {
3057 return CreateMedium<Source>(url);
3058 }
3059
3060 std::unique_ptr<Target> Target::Create(const std::string& url)
3061 {
3062 return CreateMedium<Target>(url);
3063 }