Debian Codegraph @

srtcore/common.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 /*****************************************************************************
12 Copyright (c) 2001 - 2016, The Board of Trustees of the University of Illinois.
13 All rights reserved.
14
15 Redistribution and use in source and binary forms, with or without
16 modification, are permitted provided that the following conditions are
17 met:
18
19 * Redistributions of source code must retain the above
20 copyright notice, this list of conditions and the
21 following disclaimer.
22
23 * Redistributions in binary form must reproduce the
24 above copyright notice, this list of conditions
25 and the following disclaimer in the documentation
26 and/or other materials provided with the distribution.
27
28 * Neither the name of the University of Illinois
29 nor the names of its contributors may be used to
30 endorse or promote products derived from this
31 software without specific prior written permission.
32
33 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
34 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
35 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
36 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
37 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
38 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
39 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
40 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
41 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
42 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
43 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 *****************************************************************************/
45
46 /*****************************************************************************
47 written by
48 Yunhong Gu, last updated 07/25/2010
49 modified by
50 Haivision Systems Inc.
51 *****************************************************************************/
52
53 #define SRT_IMPORT_TIME 1
54 #include "platform_sys.h"
55
56 #include <string>
57 #include <sstream>
58 #include <cmath>
59 #include <iostream>
60 #include <iomanip>
61 #include <iterator>
62 #include <vector>
63 #include "udt.h"
64 #include "md5.h"
65 #include "common.h"
66 #include "netinet_any.h"
67 #include "logging.h"
68 #include "packet.h"
69 #include "threadname.h"
70 #include "logger_defs.h"
71
72 using namespace std;
73 using namespace srt::sync;
74 using namespace srt_logging;
75
76 namespace srt_logging
77 {
78 extern Logger inlog;
79 }
80
81 namespace srt
82 {
83
84 const char* strerror_get_message(size_t major, size_t minor);
85 } // namespace srt
86
87
88 srt::CUDTException::CUDTException(CodeMajor major, CodeMinor minor, int err):
89 m_iMajor(major),
90 m_iMinor(minor)
91 {
92 if (err == -1)
93 m_iErrno = NET_ERROR;
94 else
95 m_iErrno = err;
96 HLOGC(aclog.Debug, log << "CREATED SRT EXCEPTION: " << (1000*major+minor) << " errno=" << m_iErrno);
97 }
98
99 const char* srt::CUDTException::getErrorMessage() const ATR_NOTHROW
100 {
101 return strerror_get_message(m_iMajor, m_iMinor);
102 }
103
104 std::string srt::CUDTException::getErrorString() const
105 {
106 return getErrorMessage();
107 }
108
109 #define UDT_XCODE(mj, mn) (int(mj)*1000)+int(mn)
110
111 int srt::CUDTException::getErrorCode() const
112 {
113 return UDT_XCODE(m_iMajor, m_iMinor);
114 }
115
116 int srt::CUDTException::getErrno() const
117 {
118 return m_iErrno;
119 }
120
121
122 void srt::CUDTException::clear()
123 {
124 m_iMajor = MJ_SUCCESS;
125 m_iMinor = MN_NONE;
126 m_iErrno = 0;
127 }
128
129 #undef UDT_XCODE
130
131 //
132 bool srt::CIPAddress::ipcmp(const sockaddr* addr1, const sockaddr* addr2, int ver)
133 {
134 if (AF_INET == ver)
135 {
136 sockaddr_in* a1 = (sockaddr_in*)addr1;
137 sockaddr_in* a2 = (sockaddr_in*)addr2;
138
139 if ((a1->sin_port == a2->sin_port) && (a1->sin_addr.s_addr == a2->sin_addr.s_addr))
140 return true;
141 }
142 else
143 {
144 sockaddr_in6* a1 = (sockaddr_in6*)addr1;
145 sockaddr_in6* a2 = (sockaddr_in6*)addr2;
146
147 if (a1->sin6_port == a2->sin6_port)
148 {
149 for (int i = 0; i < 16; ++ i)
150 if (*((char*)&(a1->sin6_addr) + i) != *((char*)&(a2->sin6_addr) + i))
151 return false;
152
153 return true;
154 }
155 }
156
157 return false;
158 }
159
160 void srt::CIPAddress::ntop(const sockaddr_any& addr, uint32_t ip[4])
161 {
162 if (addr.family() == AF_INET)
163 {
164 // SRT internal format of IPv4 address.
165 // The IPv4 address is in the first field. The rest is 0.
166 ip[0] = addr.sin.sin_addr.s_addr;
167 ip[1] = ip[2] = ip[3] = 0;
168 }
169 else
170 {
171 std::memcpy(ip, addr.sin6.sin6_addr.s6_addr, 16);
172 }
173 }
174
175 namespace srt {
176 bool checkMappedIPv4(const uint16_t* addr)
177 {
178 static const uint16_t ipv4on6_model [8] =
179 {
180 0, 0, 0, 0, 0, 0xFFFF, 0, 0
181 };
182
183 // Compare only first 6 words. Remaining 2 words
184 // comprise the IPv4 address, if these first 6 match.
185 const uint16_t* mbegin = ipv4on6_model;
186 const uint16_t* mend = ipv4on6_model + 6;
187
188 return std::equal(mbegin, mend, addr);
189 }
190 }
191
192 // XXX This has void return and the first argument is passed by reference.
193 // Consider simply returning sockaddr_any by value.
194 void srt::CIPAddress::pton(sockaddr_any& w_addr, const uint32_t ip[4], const sockaddr_any& peer)
195 {
196 //using ::srt_logging::inlog;
197 uint32_t* target_ipv4_addr = NULL;
198
199 if (peer.family() == AF_INET)
200 {
201 sockaddr_in* a = (&w_addr.sin);
202 target_ipv4_addr = (uint32_t*) &a->sin_addr.s_addr;
203 }
204 else // AF_INET6
205 {
206 // Check if the peer address is a model of IPv4-mapped-on-IPv6.
207 // If so, it means that the `ip` array should be interpreted as IPv4.
208 const bool is_mapped_ipv4 = checkMappedIPv4(peer.sin6);
209
210 sockaddr_in6* a = (&w_addr.sin6);
211
212 // This whole above procedure was only in order to EXCLUDE the
213 // possibility of IPv4-mapped-on-IPv6. This below may only happen
214 // if BOTH peers are IPv6. Otherwise we have a situation of cross-IP
215 // version connection in which case the address in question is always
216 // IPv4 in various mapping formats.
217 if (!is_mapped_ipv4)
218 {
219 // Here both agent and peer use IPv6, in which case
220 // `ip` contains the full IPv6 address, so just copy
221 // it as is.
222 std::memcpy(a->sin6_addr.s6_addr, ip, 16);
223 return; // The address is written, nothing left to do.
224 }
225
226 //
227 // IPv4 mapped on IPv6
228
229 // Here agent uses IPv6 with IPPROTO_IPV6/IPV6_V6ONLY == 0
230 // In this case, the address in `ip` is always an IPv4,
231 // although we are not certain as to whether it's using the
232 // IPv6 encoding (0::FFFF:IPv4) or SRT encoding (IPv4::0);
233 // this must be extra determined.
234 //
235 // Unfortunately, sockaddr_in6 doesn't give any straightforward
236 // method for it, although the official size of a single element
237 // of the IPv6 address is 16-bit.
238
239 memset((a->sin6_addr.s6_addr), 0, sizeof a->sin6_addr.s6_addr);
240
241 // The sin6_addr.s6_addr32 is non that portable to use here.
242 uint32_t* paddr32 = (uint32_t*)a->sin6_addr.s6_addr;
243 uint16_t* paddr16 = (uint16_t*)a->sin6_addr.s6_addr;
244
245 // layout: of IPv4 address 192.168.128.2
246 // 16-bit:
247 // [0000: 0000: 0000: 0000: 0000: FFFF: 192.168:128.2]
248 // 8-bit
249 // [00/00/00/00/00/00/00/00/00/00/FF/FF/192/168/128/2]
250 // 32-bit
251 // [00000000 && 00000000 && 0000FFFF && 192.168.128.2]
252
253 // Spreading every 16-bit word separately to avoid endian dilemmas
254 paddr16[2 * 2 + 1] = 0xFFFF;
255
256 target_ipv4_addr = &paddr32[3];
257 }
258
259 // Now we have two possible formats of encoding the IPv4 address:
260 // 1. If peer is IPv4, it's IPv4::0
261 // 2. If peer is IPv6, it's 0::FFFF:IPv4.
262 //
263 // Has any other possibility happen here, copy an empty address,
264 // which will be the only sign of an error.
265
266 const uint16_t* peeraddr16 = (uint16_t*)ip;
267 const bool is_mapped_ipv4 = checkMappedIPv4(peeraddr16);
268
269 if (is_mapped_ipv4)
270 {
271 *target_ipv4_addr = ip[3];
272 HLOGC(inlog.Debug, log << "pton: Handshake address: " << w_addr.str() << " provided in IPv6 mapping format");
273 }
274 // Check SRT IPv4 format.
275 else if ((ip[1] | ip[2] | ip[3]) == 0)
276 {
277 *target_ipv4_addr = ip[0];
278 HLOGC(inlog.Debug, log << "pton: Handshake address: " << w_addr.str() << " provided in SRT IPv4 format");
279 }
280 else
281 {
282 LOGC(inlog.Error, log << "pton: IPE or net error: can't determine IPv4 carryover format: " << std::hex
283 << peeraddr16[0] << ":"
284 << peeraddr16[1] << ":"
285 << peeraddr16[2] << ":"
286 << peeraddr16[3] << ":"
287 << peeraddr16[4] << ":"
288 << peeraddr16[5] << ":"
289 << peeraddr16[6] << ":"
290 << peeraddr16[7] << std::dec);
291 *target_ipv4_addr = 0;
292 if (peer.family() != AF_INET)
293 {
294 // Additionally overwrite the 0xFFFF that has been
295 // just written 50 lines above.
296 w_addr.sin6.sin6_addr.s6_addr[10] = 0;
297 w_addr.sin6.sin6_addr.s6_addr[11] = 0;
298 }
299 }
300 }
301
302
303 namespace srt {
304 static string ShowIP4(const sockaddr_in* sin)
305 {
306 ostringstream os;
307 union
308 {
309 in_addr sinaddr;
310 unsigned char ip[4];
311 };
312 sinaddr = sin->sin_addr;
313
314 os << int(ip[0]);
315 os << ".";
316 os << int(ip[1]);
317 os << ".";
318 os << int(ip[2]);
319 os << ".";
320 os << int(ip[3]);
321 return os.str();
322 }
323
324 static string ShowIP6(const sockaddr_in6* sin)
325 {
326 ostringstream os;
327 os.setf(ios::uppercase);
328
329 bool sep = false;
330 for (size_t i = 0; i < 16; ++i)
331 {
332 int v = sin->sin6_addr.s6_addr[i];
333 if ( v )
334 {
335 if ( sep )
336 os << ":";
337
338 os << hex << v;
339 sep = true;
340 }
341 }
342
343 return os.str();
344 }
345
346 string CIPAddress::show(const sockaddr* adr)
347 {
348 if ( adr->sa_family == AF_INET )
349 return ShowIP4((const sockaddr_in*)adr);
350 else if ( adr->sa_family == AF_INET6 )
351 return ShowIP6((const sockaddr_in6*)adr);
352 else
353 return "(unsupported sockaddr type)";
354 }
355 } // namespace srt
356
357 //
358 void srt::CMD5::compute(const char* input, unsigned char result[16])
359 {
360 md5_state_t state;
361
362 md5_init(&state);
363 md5_append(&state, (const md5_byte_t *)input, (int) strlen(input));
364 md5_finish(&state, result);
365 }
366
367 namespace srt {
368 std::string MessageTypeStr(UDTMessageType mt, uint32_t extt)
369 {
370 using std::string;
371
372 static const char* const udt_types [] = {
373 "handshake",
374 "keepalive",
375 "ack",
376 "lossreport",
377 "cgwarning", //4
378 "shutdown",
379 "ackack",
380 "dropreq",
381 "peererror", //8
382 };
383
384 static const char* const srt_types [] = {
385 "EXT:none",
386 "EXT:hsreq",
387 "EXT:hsrsp",
388 "EXT:kmreq",
389 "EXT:kmrsp",
390 "EXT:sid",
391 "EXT:congctl",
392 "EXT:filter",
393 "EXT:group"
394 };
395
396
397 if ( mt == UMSG_EXT )
398 {
399 if ( extt >= Size(srt_types) )
400 return "EXT:unknown";
401
402 return srt_types[extt];
403 }
404
405 if ( size_t(mt) > Size(udt_types) )
406 return "unknown";
407
408 return udt_types[mt];
409 }
410
411 std::string ConnectStatusStr(EConnectStatus cst)
412 {
413 return
414 cst == CONN_CONTINUE ? "INDUCED/CONCLUDING"
415 : cst == CONN_RUNNING ? "RUNNING"
416 : cst == CONN_ACCEPT ? "ACCEPTED"
417 : cst == CONN_RENDEZVOUS ? "RENDEZVOUS (HSv5)"
418 : cst == CONN_AGAIN ? "AGAIN"
419 : cst == CONN_CONFUSED ? "MISSING HANDSHAKE"
420 : "REJECTED";
421 }
422
423 std::string TransmissionEventStr(ETransmissionEvent ev)
424 {
425 static const char* const vals [] =
426 {
427 "init",
428 "ack",
429 "ackack",
430 "lossreport",
431 "checktimer",
432 "send",
433 "receive",
434 "custom",
435 "sync"
436 };
437
438 size_t vals_size = Size(vals);
439
440 if (size_t(ev) >= vals_size)
441 return "UNKNOWN";
442 return vals[ev];
443 }
444
445 bool SrtParseConfig(const string& s, SrtConfig& w_config)
446 {
447 using namespace std;
448
449 vector<string> parts;
450 Split(s, ',', back_inserter(parts));
451 if (parts.empty())
452 return false;
453
454 w_config.type = parts[0];
455
456 for (vector<string>::iterator i = parts.begin()+1; i != parts.end(); ++i)
457 {
458 vector<string> keyval;
459 Split(*i, ':', back_inserter(keyval));
460 if (keyval.size() != 2)
461 return false;
462 if (keyval[1] != "")
463 w_config.parameters[keyval[0]] = keyval[1];
464 }
465
466 return true;
467 }
468
469 string FormatLossArray(const vector< pair<int32_t, int32_t> >& lra)
470 {
471 ostringstream os;
472
473 os << "[ ";
474 for (vector< pair<int32_t, int32_t> >::const_iterator i = lra.begin(); i != lra.end(); ++i)
475 {
476 int len = CSeqNo::seqoff(i->first, i->second);
477 os << "%" << i->first;
478 if (len > 1)
479 os << "+" << len;
480 os << " ";
481 }
482
483 os << "]";
484 return os.str();
485 }
486
487 string FormatValue(int value, int factor, const char* unit)
488 {
489 ostringstream out;
490 double showval = value;
491 showval /= factor;
492 out << std::fixed << showval << unit;
493 return out.str();
494 }
495
496
497 ostream& PrintEpollEvent(ostream& os, int events, int et_events)
498 {
499 static pair<int, const char*> const namemap [] = {
500 make_pair(SRT_EPOLL_IN, "R"),
501 make_pair(SRT_EPOLL_OUT, "W"),
502 make_pair(SRT_EPOLL_ERR, "E"),
503 make_pair(SRT_EPOLL_UPDATE, "U")
504 };
505 bool any = false;
506
507 const int N = (int)Size(namemap);
508
509 for (int i = 0; i < N; ++i)
510 {
511 if (events & namemap[i].first)
512 {
513 os << "[";
514 if (et_events & namemap[i].first)
515 os << "^";
516 os << namemap[i].second << "]";
517 any = true;
518 }
519 }
520
521 if (!any)
522 os << "[]";
523
524 return os;
525 }
526 } // namespace srt
527
528 namespace srt_logging
529 {
530
531 // Value display utilities
532 // (also useful for applications)
533
534 std::string SockStatusStr(SRT_SOCKSTATUS s)
535 {
536 if (int(s) < int(SRTS_INIT) || int(s) > int(SRTS_NONEXIST))
537 return "???";
538
539 static struct AutoMap
540 {
541 // Values start from 1, so do -1 to avoid empty cell
542 std::string names[int(SRTS_NONEXIST)-1+1];
543
544 AutoMap()
545 {
546 #define SINI(statename) names[SRTS_##statename-1] = #statename
547 SINI(INIT);
548 SINI(OPENED);
549 SINI(LISTENING);
550 SINI(CONNECTING);
551 SINI(CONNECTED);
552 SINI(BROKEN);
553 SINI(CLOSING);
554 SINI(CLOSED);
555 SINI(NONEXIST);
556 #undef SINI
557 }
558 } names;
559
560 return names.names[int(s)-1];
561 }
562
563 #if ENABLE_BONDING
564 std::string MemberStatusStr(SRT_MEMBERSTATUS s)
565 {
566 if (int(s) < int(SRT_GST_PENDING) || int(s) > int(SRT_GST_BROKEN))
567 return "???";
568
569 static struct AutoMap
570 {
571 std::string names[int(SRT_GST_BROKEN)+1];
572
573 AutoMap()
574 {
575 #define SINI(statename) names[SRT_GST_##statename] = #statename
576 SINI(PENDING);
577 SINI(IDLE);
578 SINI(RUNNING);
579 SINI(BROKEN);
580 #undef SINI
581 }
582 } names;
583
584 return names.names[int(s)];
585 }
586 #endif
587
588
589 } // (end namespace srt_logging)
590