Debian Codegraph @

srtcore/common.h

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 - 2009, 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 08/01/2009
49 modified by
50 Haivision Systems Inc.
51 *****************************************************************************/
52
53 #ifndef INC_SRT_COMMON_H
54 #define INC_SRT_COMMON_H
55
56 #include <memory>
57 #include <cstdlib>
58 #include <cstdio>
59 #ifndef _WIN32
60 #include <sys/time.h>
61 #include <sys/uio.h>
62 #else
63 // #include <winsock2.h>
64 //#include <windows.h>
65 #endif
66
67 #include "srt.h"
68 #include "utilities.h"
69 #include "sync.h"
70 #include "netinet_any.h"
71 #include "packetfilter_api.h"
72
73 // System-independent errno
74 #ifndef _WIN32
75 #define NET_ERROR errno
76 #else
77 #define NET_ERROR WSAGetLastError()
78 #endif
79
80 #ifdef _DEBUG
81 #if defined(SRT_ENABLE_THREADCHECK)
82 #include "threadcheck.h"
83 #define SRT_ASSERT(cond) ASSERT(cond)
84 #else
85 #include <assert.h>
86 #define SRT_ASSERT(cond) assert(cond)
87 #endif
88 #else
89 #define SRT_ASSERT(cond)
90 #endif
91
92 #if HAVE_FULL_CXX11
93 #define SRT_STATIC_ASSERT(cond, msg) static_assert(cond, msg)
94 #else
95 #define SRT_STATIC_ASSERT(cond, msg)
96 #endif
97
98 #include <exception>
99
100 namespace srt_logging
101 {
102 std::string SockStatusStr(SRT_SOCKSTATUS s);
103 #if ENABLE_BONDING
104 std::string MemberStatusStr(SRT_MEMBERSTATUS s);
105 #endif
106 }
107
108 namespace srt
109 {
110
111 // Class CUDTException exposed for C++ API.
112 // This is actually useless, unless you'd use a DIRECT C++ API,
113 // however there's no such API so far. The current C++ API for UDT/SRT
114 // is predicted to NEVER LET ANY EXCEPTION out of implementation,
115 // so it's useless to catch this exception anyway.
116
117 class CUDTException: public std::exception
118 {
119 public:
120
121 CUDTException(CodeMajor major = MJ_SUCCESS, CodeMinor minor = MN_NONE, int err = -1);
122 virtual ~CUDTException() ATR_NOTHROW {}
123
124 /// Get the description of the exception.
125 /// @return Text message for the exception description.
126 const char* getErrorMessage() const ATR_NOTHROW;
127
128 virtual const char* what() const ATR_NOTHROW ATR_OVERRIDE
129 {
130 return getErrorMessage();
131 }
132
133 std::string getErrorString() const;
134
135 /// Get the system errno for the exception.
136 /// @return errno.
137 int getErrorCode() const;
138
139 /// Get the system network errno for the exception.
140 /// @return errno.
141 int getErrno() const;
142
143 /// Clear the error code.
144 void clear();
145
146 private:
147 CodeMajor m_iMajor; // major exception categories
148 CodeMinor m_iMinor; // for specific error reasons
149 int m_iErrno; // errno returned by the system if there is any
150 mutable std::string m_strMsg; // text error message (cache)
151
152 std::string m_strAPI; // the name of UDT function that returns the error
153 std::string m_strDebug; // debug information, set to the original place that causes the error
154
155 public: // Legacy Error Code
156
157 static const int EUNKNOWN = SRT_EUNKNOWN;
158 static const int SUCCESS = SRT_SUCCESS;
159 static const int ECONNSETUP = SRT_ECONNSETUP;
160 static const int ENOSERVER = SRT_ENOSERVER;
161 static const int ECONNREJ = SRT_ECONNREJ;
162 static const int ESOCKFAIL = SRT_ESOCKFAIL;
163 static const int ESECFAIL = SRT_ESECFAIL;
164 static const int ECONNFAIL = SRT_ECONNFAIL;
165 static const int ECONNLOST = SRT_ECONNLOST;
166 static const int ENOCONN = SRT_ENOCONN;
167 static const int ERESOURCE = SRT_ERESOURCE;
168 static const int ETHREAD = SRT_ETHREAD;
169 static const int ENOBUF = SRT_ENOBUF;
170 static const int EFILE = SRT_EFILE;
171 static const int EINVRDOFF = SRT_EINVRDOFF;
172 static const int ERDPERM = SRT_ERDPERM;
173 static const int EINVWROFF = SRT_EINVWROFF;
174 static const int EWRPERM = SRT_EWRPERM;
175 static const int EINVOP = SRT_EINVOP;
176 static const int EBOUNDSOCK = SRT_EBOUNDSOCK;
177 static const int ECONNSOCK = SRT_ECONNSOCK;
178 static const int EINVPARAM = SRT_EINVPARAM;
179 static const int EINVSOCK = SRT_EINVSOCK;
180 static const int EUNBOUNDSOCK = SRT_EUNBOUNDSOCK;
181 static const int ESTREAMILL = SRT_EINVALMSGAPI;
182 static const int EDGRAMILL = SRT_EINVALBUFFERAPI;
183 static const int ENOLISTEN = SRT_ENOLISTEN;
184 static const int ERDVNOSERV = SRT_ERDVNOSERV;
185 static const int ERDVUNBOUND = SRT_ERDVUNBOUND;
186 static const int EINVALMSGAPI = SRT_EINVALMSGAPI;
187 static const int EINVALBUFFERAPI = SRT_EINVALBUFFERAPI;
188 static const int EDUPLISTEN = SRT_EDUPLISTEN;
189 static const int ELARGEMSG = SRT_ELARGEMSG;
190 static const int EINVPOLLID = SRT_EINVPOLLID;
191 static const int EASYNCFAIL = SRT_EASYNCFAIL;
192 static const int EASYNCSND = SRT_EASYNCSND;
193 static const int EASYNCRCV = SRT_EASYNCRCV;
194 static const int ETIMEOUT = SRT_ETIMEOUT;
195 static const int ECONGEST = SRT_ECONGEST;
196 static const int EPEERERR = SRT_EPEERERR;
197 };
198
199
200
201 enum UDTSockType
202 {
203 UDT_UNDEFINED = 0, // initial trap representation
204 UDT_STREAM = 1,
205 UDT_DGRAM
206 };
207
208
209 /// The message types used by UDT protocol. This is a part of UDT
210 /// protocol and should never be changed.
211 enum UDTMessageType
212 {
213 UMSG_HANDSHAKE = 0, //< Connection Handshake. Control: see @a CHandShake.
214 UMSG_KEEPALIVE = 1, //< Keep-alive.
215 UMSG_ACK = 2, //< Acknowledgement. Control: past-the-end sequence number up to which packets have been received.
216 UMSG_LOSSREPORT = 3, //< Negative Acknowledgement (NAK). Control: Loss list.
217 UMSG_CGWARNING = 4, //< Congestion warning.
218 UMSG_SHUTDOWN = 5, //< Shutdown.
219 UMSG_ACKACK = 6, //< Acknowledgement of Acknowledgement. Add info: The ACK sequence number
220 UMSG_DROPREQ = 7, //< Message Drop Request. Add info: Message ID. Control Info: (first, last) number of the message.
221 UMSG_PEERERROR = 8, //< Signal from the Peer side. Add info: Error code.
222 // ... add extra code types here
223 UMSG_END_OF_TYPES,
224 UMSG_EXT = 0x7FFF //< For the use of user-defined control packets.
225 };
226
227 // This side's role is: INITIATOR prepares the environment first, and sends
228 // appropriate information to the peer. The peer must be RESPONDER and be ready
229 // to receive it. It's important for the encryption: the INITIATOR side generates
230 // the KM, and sends it to RESPONDER. RESPONDER awaits KM received from the
231 // INITIATOR. Note that in bidirectional mode - that is always with HSv5 - the
232 // INITIATOR creates both sending and receiving contexts, then sends the key to
233 // RESPONDER, which creates both sending and receiving contexts, using the same
234 // key received from INITIATOR.
235 //
236 // The method of selection:
237 //
238 // In HSv4, it's always data sender (the party that sets SRTO_SENDER flag on the
239 // socket) INITIATOR, and receiver - RESPONDER. The HSREQ and KMREQ are done
240 // AFTER the UDT connection is done using UMSG_EXT extension messages. As this
241 // is unidirectional, the INITIATOR prepares the sending context only, the
242 // RESPONDER - receiving context only.
243 //
244 // In HSv5, for caller-listener configuration, it's simple: caller is INITIATOR,
245 // listener is RESPONDER. In case of rendezvous the parties are equivalent,
246 // so the role is resolved by "cookie contest". Rendezvous sockets both know
247 // each other's cookie generated during the URQ_WAVEAHAND handshake phase.
248 // The cookies are simply compared as integer numbers; the party which's cookie
249 // is a greater number becomes an INITIATOR, and the other party becomes a
250 // RESPONDER.
251 //
252 // The case of a draw - that both occasionally have baked identical cookies -
253 // is treated as an extremely rare and virtually impossible case, so this
254 // results in connection rejected.
255 enum HandshakeSide
256 {
257 HSD_DRAW,
258 HSD_INITIATOR, //< Side that initiates HSREQ/KMREQ. HSv4: data sender, HSv5: connecting socket or winner rendezvous socket
259 HSD_RESPONDER //< Side that expects HSREQ/KMREQ from the peer. HSv4: data receiver, HSv5: accepted socket or loser rendezvous socket
260 };
261
262 // For debug
263 std::string MessageTypeStr(UDTMessageType mt, uint32_t extt = 0);
264
265 ////////////////////////////////////////////////////////////////////////////////
266
267 // Commonly used by various reading facilities
268 enum EReadStatus
269 {
270 RST_OK = 0, //< A new portion of data has been received
271 RST_AGAIN, //< Nothing has been received, try again
272 RST_ERROR = -1 //< Irrecoverable error, please close descriptor and stop reading.
273 };
274
275 enum EConnectStatus
276 {
277 CONN_ACCEPT = 0, //< Received final handshake that confirms connection established
278 CONN_REJECT = -1, //< Error during processing handshake.
279 CONN_CONTINUE = 1, //< induction->conclusion phase
280 CONN_RENDEZVOUS = 2, //< pass to a separate rendezvous processing (HSv5 only)
281 CONN_CONFUSED = 3, //< listener thinks it's connected, but caller missed conclusion
282 CONN_RUNNING = 10, //< no connection in progress, already connected
283 CONN_AGAIN = -2 //< No data was read, don't change any state.
284 };
285
286 enum EConnectMethod
287 {
288 COM_ASYNCHRO,
289 COM_SYNCHRO
290 };
291
292 std::string ConnectStatusStr(EConnectStatus est);
293
294
295 const int64_t BW_INFINITE = 1000000000/8; //Infinite=> 1 Gbps
296
297
298 enum ETransmissionEvent
299 {
300 TEV_INIT, // --> After creation, and after any parameters were updated.
301 TEV_ACK, // --> When handling UMSG_ACK - older CCC:onAck()
302 TEV_ACKACK, // --> UDT does only RTT sync, can be read from CUDT::SRTT().
303 TEV_LOSSREPORT, // --> When handling UMSG_LOSSREPORT - older CCC::onLoss()
304 TEV_CHECKTIMER, // --> See TEV_CHT_REXMIT
305 TEV_SEND, // --> When the packet is scheduled for sending - older CCC::onPktSent
306 TEV_RECEIVE, // --> When a data packet was received - older CCC::onPktReceived
307 TEV_CUSTOM, // --> probably dead call - older CCC::processCustomMsg
308 TEV_SYNC, // --> Backup group. When rate estimation is derived from an active member, and update is needed.
309
310 TEV_E_SIZE
311 };
312
313 std::string TransmissionEventStr(ETransmissionEvent ev);
314
315 // Special parameter for TEV_CHECKTIMER
316 enum ECheckTimerStage
317 {
318 TEV_CHT_INIT, // --> UDT: just update parameters, don't call any CCC::*
319 TEV_CHT_FASTREXMIT, // --> not available on UDT
320 TEV_CHT_REXMIT // --> CCC::onTimeout() in UDT
321 };
322
323 enum EInitEvent
324 {
325 TEV_INIT_RESET = 0,
326 TEV_INIT_INPUTBW,
327 TEV_INIT_OHEADBW
328 };
329
330 class CPacket;
331
332 // XXX Use some more standard less hand-crafted solution, if possible
333 // XXX Consider creating a mapping between TEV_* values and associated types,
334 // so that the type is compiler-enforced when calling updateCC() and when
335 // connecting signals to slots.
336 struct EventVariant
337 {
338 enum Type {UNDEFINED, PACKET, ARRAY, ACK, STAGE, INIT} type;
339 union U
340 {
341 const srt::CPacket* packet;
342 int32_t ack;
343 struct
344 {
345 const int32_t* ptr;
346 size_t len;
347 } array;
348 ECheckTimerStage stage;
349 EInitEvent init;
350 } u;
351
352
353 template<Type t>
354 struct VariantFor;
355
356
357 // Note: UNDEFINED and ARRAY don't have assignment operator.
358 // For ARRAY you'll use 'set' function. For UNDEFINED there's nothing.
359
360 explicit EventVariant(const srt::CPacket* arg)
361 {
362 type = PACKET;
363 u.packet = arg;
364 }
365
366 explicit EventVariant(int32_t arg)
367 {
368 type = ACK;
369 u.ack = arg;
370 }
371
372 explicit EventVariant(ECheckTimerStage arg)
373 {
374 type = STAGE;
375 u.stage = arg;
376 }
377
378 explicit EventVariant(EInitEvent arg)
379 {
380 type = INIT;
381 u.init = arg;
382 }
383
384 const int32_t* get_ptr() const
385 {
386 return u.array.ptr;
387 }
388
389 size_t get_len() const
390 {
391 return u.array.len;
392 }
393
394 void set(const int32_t* ptr, size_t len)
395 {
396 type = ARRAY;
397 u.array.ptr = ptr;
398 u.array.len = len;
399 }
400
401 EventVariant(const int32_t* ptr, size_t len)
402 {
403 set(ptr, len);
404 }
405
406 template<Type T>
407 typename VariantFor<T>::type get() const
408 {
409 return u.*(VariantFor<T>::field());
410 }
411 };
412
413 /*
414 Maybe later.
415 This had to be a solution for automatic extraction of the
416 type hidden in particular EventArg for particular event so
417 that it's not runtime-mistaken.
418
419 In order that this make sense there would be required an array
420 indexed by event id (just like a slot array m_Slots in CUDT),
421 where the "type distiller" function would be extracted and then
422 combined with the user-connected slot function this would call
423 it already with correct type. Note that also the ConnectSignal
424 function would have to get the signal id by template parameter,
425 not function parameter. For example:
426
427 m_parent->ConnectSignal<TEV_ACK>(SSLOT(updateOnSent));
428
429 in which updateOnSent would have to receive an appropriate type.
430 This has a disadvantage that you can't connect multiple signals
431 with different argument types to the same slot, you'd have to
432 make slot wrappers to translate arguments.
433
434 It seems that a better idea would be to create binders that would
435 translate the argument from EventArg to the correct type according
436 to the rules imposed by particular event id. But I'd not make it
437 until there's a green light on C++11 for SRT, so maybe in a far future.
438
439 template <ETransmissionEvent type>
440 class EventArgType;
441 #define MAP_EVENT_TYPE(tev, tp) template<> class EventArgType<tev> { typedef tp type; }
442 */
443
444
445 // The 'type' field wouldn't be even necessary if we
446 // use a full-templated version. TBD.
447 template<> struct EventVariant::VariantFor<EventVariant::PACKET>
448 {
449 typedef const srt::CPacket* type;
450 static type U::*field() {return &U::packet;}
451 };
452
453 template<> struct EventVariant::VariantFor<EventVariant::ACK>
454 {
455 typedef int32_t type;
456 static type U::*field() { return &U::ack; }
457 };
458
459 template<> struct EventVariant::VariantFor<EventVariant::STAGE>
460 {
461 typedef ECheckTimerStage type;
462 static type U::*field() { return &U::stage; }
463 };
464
465 template<> struct EventVariant::VariantFor<EventVariant::INIT>
466 {
467 typedef EInitEvent type;
468 static type U::*field() { return &U::init; }
469 };
470
471 // Using a hand-crafted solution because there's a non-backward-compatible
472 // change between C++03 and others on the way up to C++17 (and we want this
473 // code to be compliant with all C++ standards):
474 //
475 // - there's std::mem_fun in C++03 - deprecated in C++11, removed in C++17
476 // - std::function in C++11 would be perfect, but not in C++03
477
478 // This can be changed in future to use C++11 way, but only after C++03
479 // compatibility is finally abaondoned. Until then, this stays with a custom
480 // class.
481
482 class EventSlotBase
483 {
484 public:
485 virtual void emit(ETransmissionEvent tev, EventVariant var) = 0;
486 typedef void dispatcher_t(void* opaque, ETransmissionEvent tev, EventVariant var);
487
488 virtual ~EventSlotBase() {}
489 };
490
491 class SimpleEventSlot: public EventSlotBase
492 {
493 public:
494 void* opaque;
495 dispatcher_t* dispatcher;
496
497 SimpleEventSlot(void* op, dispatcher_t* disp): opaque(op), dispatcher(disp) {}
498
499 void emit(ETransmissionEvent tev, EventVariant var) ATR_OVERRIDE
500 {
501 (*dispatcher)(opaque, tev, var);
502 }
503 };
504
505 template <class Class>
506 class ObjectEventSlot: public EventSlotBase
507 {
508 public:
509 typedef void (Class::*method_ptr_t)(ETransmissionEvent tev, EventVariant var);
510
511 method_ptr_t pm;
512 Class* po;
513
514 ObjectEventSlot(Class* o, method_ptr_t m): pm(m), po(o) {}
515
516 void emit(ETransmissionEvent tev, EventVariant var) ATR_OVERRIDE
517 {
518 (po->*pm)(tev, var);
519 }
520 };
521
522
523 struct EventSlot
524 {
525 mutable EventSlotBase* slot;
526 // Create empty slot. Calls are ignored.
527 EventSlot(): slot(0) {}
528
529 // "Stealing" copy constructor, following the auto_ptr method.
530 // This isn't very nice, but no other way to do it in C++03
531 // without rvalue-reference and move.
532 void moveFrom(const EventSlot& victim)
533 {
534 slot = victim.slot; // Should MOVE.
535 victim.slot = 0;
536 }
537
538 EventSlot(const EventSlot& victim) { moveFrom(victim); }
539 EventSlot& operator=(const EventSlot& victim) { moveFrom(victim); return *this; }
540
541 EventSlot(void* op, EventSlotBase::dispatcher_t* disp)
542 {
543 slot = new SimpleEventSlot(op, disp);
544 }
545
546 template <class ObjectClass>
547 EventSlot(ObjectClass* obj, typename ObjectEventSlot<ObjectClass>::method_ptr_t method)
548 {
549 slot = new ObjectEventSlot<ObjectClass>(obj, method);
550 }
551
552 void emit(ETransmissionEvent tev, EventVariant var)
553 {
554 if (!slot)
555 return;
556 slot->emit(tev, var);
557 }
558
559 ~EventSlot()
560 {
561 delete slot;
562 }
563 };
564
565
566 // UDT Sequence Number 0 - (2^31 - 1)
567
568 // seqcmp: compare two seq#, considering the wrapping
569 // seqlen: length from the 1st to the 2nd seq#, including both
570 // seqoff: offset from the 2nd to the 1st seq#
571 // incseq: increase the seq# by 1
572 // decseq: decrease the seq# by 1
573 // incseq: increase the seq# by a given offset
574
575 class CSeqNo
576 {
577 int32_t value;
578
579 public:
580
581 explicit CSeqNo(int32_t v): value(v) {}
582
583 // Comparison
584 bool operator == (const CSeqNo& other) const { return other.value == value; }
585 bool operator < (const CSeqNo& other) const
586 {
587 return seqcmp(value, other.value) < 0;
588 }
589
590 // The std::rel_ops namespace cannot be "imported"
591 // as a whole into the class - it can only be used
592 // in the application code.
593 bool operator != (const CSeqNo& other) const { return other.value != value; }
594 bool operator > (const CSeqNo& other) const { return other < *this; }
595 bool operator >= (const CSeqNo& other) const
596 {
597 return seqcmp(value, other.value) >= 0;
598 }
599 bool operator <=(const CSeqNo& other) const
600 {
601 return seqcmp(value, other.value) <= 0;
602 }
603
604 // circular arithmetic
605 friend int operator-(const CSeqNo& c1, const CSeqNo& c2)
606 {
607 return seqoff(c2.value, c1.value);
608 }
609
610 friend CSeqNo operator-(const CSeqNo& c1, int off)
611 {
612 return CSeqNo(decseq(c1.value, off));
613 }
614
615 friend CSeqNo operator+(const CSeqNo& c1, int off)
616 {
617 return CSeqNo(incseq(c1.value, off));
618 }
619
620 friend CSeqNo operator+(int off, const CSeqNo& c1)
621 {
622 return CSeqNo(incseq(c1.value, off));
623 }
624
625 CSeqNo& operator++()
626 {
627 value = incseq(value);
628 return *this;
629 }
630
631 /// This behaves like seq1 - seq2, in comparison to numbers,
632 /// and with the statement that only the sign of the result matters.
633 /// Returns a negative value if seq1 < seq2,
634 /// positive if seq1 > seq2, and zero if they are equal.
635 /// The only correct application of this function is when you
636 /// compare two values and it works faster than seqoff. However
637 /// the result's meaning is only in its sign. DO NOT USE THE
638 /// VALUE for any other purpose. It is not meant to be the
639 /// distance between two sequence numbers.
640 ///
641 /// Example: to check if (seq1 %> seq2): seqcmp(seq1, seq2) > 0.
642 /// Note: %> stands for "later than".
643 inline static int seqcmp(int32_t seq1, int32_t seq2)
644 {return (abs(seq1 - seq2) < m_iSeqNoTH) ? (seq1 - seq2) : (seq2 - seq1);}
645
646 /// This function measures a length of the range from seq1 to seq2,
647 /// including endpoints (seqlen(a, a) = 1; seqlen(a, a + 1) = 2),
648 /// WITH A PRECONDITION that certainly @a seq1 is earlier than @a seq2.
649 /// This can also include an enormously large distance between them,
650 /// that is, exceeding the m_iSeqNoTH value (can be also used to test
651 /// if this distance is larger).
652 /// Prior to calling this function the caller must be certain that
653 /// @a seq2 is a sequence coming from a later time than @a seq1,
654 /// and that the distance does not exceed m_iMaxSeqNo.
655 inline static int seqlen(int32_t seq1, int32_t seq2)
656 {
657 SRT_ASSERT(seq1 >= 0 && seq1 <= m_iMaxSeqNo);
658 SRT_ASSERT(seq2 >= 0 && seq2 <= m_iMaxSeqNo);
659 return (seq1 <= seq2) ? (seq2 - seq1 + 1) : (seq2 - seq1 + m_iMaxSeqNo + 2);
660 }
661
662 /// This behaves like seq2 - seq1, with the precondition that the true
663 /// distance between two sequence numbers never exceeds m_iSeqNoTH.
664 /// That is, if the difference in numeric values of these two arguments
665 /// exceeds m_iSeqNoTH, it is treated as if the later of these two
666 /// sequence numbers has overflown and actually a segment of the
667 /// MAX+1 value should be added to it to get the proper result.
668 ///
669 /// Note: this function does more calculations than seqcmp, so it should
670 /// be used if you need the exact distance between two sequences. If
671 /// you are only interested with their relationship, use seqcmp.
672 inline static int seqoff(int32_t seq1, int32_t seq2)
673 {
674 if (abs(seq1 - seq2) < m_iSeqNoTH)
675 return seq2 - seq1;
676
677 if (seq1 < seq2)
678 return seq2 - seq1 - m_iMaxSeqNo - 1;
679
680 return seq2 - seq1 + m_iMaxSeqNo + 1;
681 }
682
683 inline static int32_t incseq(int32_t seq)
684 {return (seq == m_iMaxSeqNo) ? 0 : seq + 1;}
685
686 inline static int32_t decseq(int32_t seq)
687 {return (seq == 0) ? m_iMaxSeqNo : seq - 1;}
688
689 inline static int32_t incseq(int32_t seq, int32_t inc)
690 {return (m_iMaxSeqNo - seq >= inc) ? seq + inc : seq - m_iMaxSeqNo + inc - 1;}
691 // m_iMaxSeqNo >= inc + sec --- inc + sec <= m_iMaxSeqNo
692 // if inc + sec > m_iMaxSeqNo then return seq + inc - (m_iMaxSeqNo+1)
693
694 inline static int32_t decseq(int32_t seq, int32_t dec)
695 {
696 // Check if seq - dec < 0, but before it would have happened
697 if ( seq < dec )
698 {
699 int32_t left = dec - seq; // This is so many that is left after dragging dec to 0
700 // So now decrement the (m_iMaxSeqNo+1) by "left"
701 return m_iMaxSeqNo - left + 1;
702 }
703 return seq - dec;
704 }
705
706 static int32_t maxseq(int32_t seq1, int32_t seq2)
707 {
708 if (seqcmp(seq1, seq2) < 0)
709 return seq2;
710 return seq1;
711 }
712
713 public:
714 static const int32_t m_iSeqNoTH = 0x3FFFFFFF; // threshold for comparing seq. no.
715 static const int32_t m_iMaxSeqNo = 0x7FFFFFFF; // maximum sequence number used in UDT
716 };
717
718 ////////////////////////////////////////////////////////////////////////////////
719
720 // UDT ACK Sub-sequence Number: 0 - (2^31 - 1)
721
722 class CAckNo
723 {
724 public:
725 inline static int32_t incack(int32_t ackno)
726 {return (ackno == m_iMaxAckSeqNo) ? 0 : ackno + 1;}
727
728 public:
729 static const int32_t m_iMaxAckSeqNo = 0x7FFFFFFF; // maximum ACK sub-sequence number used in UDT
730 };
731
732 template <size_t BITS, uint32_t MIN = 0>
733 class RollNumber
734 {
735 typedef RollNumber<BITS, MIN> this_t;
736 typedef Bits<BITS, 0> number_t;
737 uint32_t number;
738
739 public:
740
741 static const size_t OVER = number_t::mask+1;
742 static const size_t HALF = (OVER-MIN)/2;
743
744 private:
745 static int Diff(uint32_t left, uint32_t right)
746 {
747 // UNExpected order, diff is negative
748 if ( left < right )
749 {
750 int32_t diff = right - left;
751 if ( diff >= int32_t(HALF) ) // over barrier
752 {
753 // It means that left is less than right because it was overflown
754 // For example: left = 0x0005, right = 0xFFF0; diff = 0xFFEB > HALF
755 left += OVER - MIN; // left was really 0x00010005, just narrowed.
756 // Now the difference is 0x0015, not 0xFFFF0015
757 }
758 }
759 else
760 {
761 int32_t diff = left - right;
762 if ( diff >= int32_t(HALF) )
763 {
764 right += OVER - MIN;
765 }
766 }
767
768 return left - right;
769 }
770
771 public:
772 explicit RollNumber(uint32_t val): number(val)
773 {
774 }
775
776 bool operator<(const this_t& right) const
777 {
778 int32_t ndiff = number - right.number;
779 if (ndiff < -int32_t(HALF))
780 {
781 // it' like ndiff > 0
782 return false;
783 }
784
785 if (ndiff > int32_t(HALF))
786 {
787 // it's like ndiff < 0
788 return true;
789 }
790
791 return ndiff < 0;
792 }
793
794 bool operator>(const this_t& right) const
795 {
796 return right < *this;
797 }
798
799 bool operator==(const this_t& right) const
800 {
801 return number == right.number;
802 }
803
804 bool operator<=(const this_t& right) const
805 {
806 return !(*this > right);
807 }
808
809 bool operator>=(const this_t& right) const
810 {
811 return !(*this < right);
812 }
813
814 void operator++(int)
815 {
816 ++number;
817 if (number > number_t::mask)
818 number = MIN;
819 }
820
821 this_t& operator++() { (*this)++; return *this; }
822
823 void operator--(int)
824 {
825 if (number == MIN)
826 number = number_t::mask;
827 else
828 --number;
829 }
830 this_t& operator--() { (*this)--; return *this; }
831
832 int32_t operator-(this_t right)
833 {
834 return Diff(this->number, right.number);
835 }
836
837 void operator+=(int32_t delta)
838 {
839 // NOTE: this condition in practice tests if delta is negative.
840 // That's because `number` is always positive, so negated delta
841 // can't be ever greater than this, unless it's negative.
842 if (-delta > int64_t(number))
843 {
844 number = OVER - MIN + number + delta; // NOTE: delta is negative
845 }
846 else
847 {
848 number += delta;
849 if (number >= OVER)
850 number -= OVER - MIN;
851 }
852 }
853
854 operator uint32_t() const { return number; }
855 };
856
857 ////////////////////////////////////////////////////////////////////////////////
858
859 struct CIPAddress
860 {
861 static bool ipcmp(const struct sockaddr* addr1, const struct sockaddr* addr2, int ver = AF_INET);
862 static void ntop(const struct sockaddr_any& addr, uint32_t ip[4]);
863 static void pton(sockaddr_any& addr, const uint32_t ip[4], const sockaddr_any& peer);
864 static std::string show(const struct sockaddr* adr);
865 };
866
867 ////////////////////////////////////////////////////////////////////////////////
868
869 struct CMD5
870 {
871 static void compute(const char* input, unsigned char result[16]);
872 };
873
874 // Debug stats
875 template <size_t SIZE>
876 class StatsLossRecords
877 {
878 int32_t initseq;
879 std::bitset<SIZE> array;
880
881 public:
882 StatsLossRecords(): initseq(SRT_SEQNO_NONE) {}
883
884 // To check if this structure still keeps record of that sequence.
885 // This is to check if the information about this not being found
886 // is still reliable.
887 bool exists(int32_t seq)
888 {
889 return initseq != SRT_SEQNO_NONE && CSeqNo::seqcmp(seq, initseq) >= 0;
890 }
891
892 int32_t base() { return initseq; }
893
894 void clear()
895 {
896 initseq = SRT_SEQNO_NONE;
897 array.reset();
898 }
899
900 void add(int32_t lo, int32_t hi)
901 {
902 int32_t end = CSeqNo::incseq(hi);
903 for (int32_t i = lo; i != end; i = CSeqNo::incseq(i))
904 add(i);
905 }
906
907 void add(int32_t seq)
908 {
909 if ( array.none() )
910 {
911 // May happen it wasn't initialized. Set it as initial loss sequence.
912 initseq = seq;
913 array[0] = true;
914 return;
915 }
916
917 // Calculate the distance between this seq and the oldest one.
918 int seqdiff = CSeqNo::seqoff(initseq, seq);
919 if ( seqdiff > int(SIZE) )
920 {
921 // Size exceeded. Drop the oldest sequences.
922 // First calculate how many must be removed.
923 size_t toremove = seqdiff - SIZE;
924 // Now, since that position, find the nearest 1
925 while ( !array[toremove] && toremove <= SIZE )
926 ++toremove;
927
928 // All have to be dropped, so simply reset the array
929 if ( toremove == SIZE )
930 {
931 initseq = seq;
932 array[0] = true;
933 return;
934 }
935
936 // Now do the shift of the first found 1 to position 0
937 // and its index add to initseq
938 initseq += toremove;
939 seqdiff -= toremove;
940 array >>= toremove;
941 }
942
943 // Now set appropriate bit that represents this seq
944 array[seqdiff] = true;
945 }
946
947 StatsLossRecords& operator << (int32_t seq)
948 {
949 add(seq);
950 return *this;
951 }
952
953 void remove(int32_t seq)
954 {
955 // Check if is in range. If not, ignore.
956 int seqdiff = CSeqNo::seqoff(initseq, seq);
957 if ( seqdiff < 0 )
958 return; // already out of array
959 if ( seqdiff > SIZE )
960 return; // never was added!
961
962 array[seqdiff] = true;
963 }
964
965 bool find(int32_t seq) const
966 {
967 int seqdiff = CSeqNo::seqoff(initseq, seq);
968 if ( seqdiff < 0 )
969 return false; // already out of array
970 if ( size_t(seqdiff) > SIZE )
971 return false; // never was added!
972
973 return array[seqdiff];
974 }
975
976 #if HAVE_CXX11
977
978 std::string to_string() const
979 {
980 std::string out;
981 for (size_t i = 0; i < SIZE; ++i)
982 {
983 if ( array[i] )
984 out += std::to_string(initseq+i) + " ";
985 }
986
987 return out;
988 }
989 #endif
990 };
991
992
993 // There are some better or worse things you can find outside,
994 // there's also boost::circular_buffer, but it's too overspoken
995 // to be included here. We also can't rely on boost. Maybe in future
996 // when it's added to the standard and SRT can heighten C++ standard
997 // requirements; until then it needs this replacement.
998 template <class Value>
999 class CircularBuffer
1000 {
1001 #ifdef SRT_TEST_CIRCULAR_BUFFER
1002 public:
1003 #endif
1004 int m_iSize;
1005 Value* m_aStorage;
1006 int m_xBegin;
1007 int m_xEnd;
1008
1009 static void destr(Value& v)
1010 {
1011 v.~Value();
1012 }
1013
1014 static void constr(Value& v)
1015 {
1016 new ((void*)&v) Value();
1017 }
1018
1019 template <class V>
1020 static void constr(Value& v, const V& source)
1021 {
1022 new ((void*)&v) Value(source);
1023 }
1024
1025 // Wipe the copy constructor
1026 CircularBuffer(const CircularBuffer&);
1027
1028 public:
1029 typedef Value value_type;
1030
1031 CircularBuffer(int size)
1032 :m_iSize(size+1),
1033 m_xBegin(0),
1034 m_xEnd(0)
1035 {
1036 // We reserve one spare element just for a case.
1037 if (size == 0)
1038 m_aStorage = 0;
1039 else
1040 m_aStorage = (Value*)::operator new (sizeof(Value) * m_iSize);
1041 }
1042
1043 void set_capacity(int size)
1044 {
1045 reset();
1046
1047 // This isn't called resize (the size is 0 after the operation)
1048 // nor reserve (the existing elements are removed).
1049 if (size != m_iSize)
1050 {
1051 if (m_aStorage)
1052 ::operator delete (m_aStorage);
1053 m_iSize = size+1;
1054 m_aStorage = (Value*)::operator new (sizeof(Value) * m_iSize);
1055 }
1056 }
1057
1058 void reset()
1059 {
1060 if (m_xEnd < m_xBegin)
1061 {
1062 for (int i = m_xBegin; i < m_iSize; ++i)
1063 destr(m_aStorage[i]);
1064 for (int i = 0; i < m_xEnd; ++i)
1065 destr(m_aStorage[i]);
1066 }
1067 else
1068 {
1069 for (int i = m_xBegin; i < m_xEnd; ++i)
1070 destr(m_aStorage[i]);
1071 }
1072
1073 m_xBegin = 0;
1074 m_xEnd = 0;
1075 }
1076
1077 ~CircularBuffer()
1078 {
1079 reset();
1080 ::operator delete (m_aStorage);
1081 }
1082
1083 // In the beginning, m_xBegin == m_xEnd, which
1084 // means that the container is empty. Adding can
1085 // be done exactly at the place pointed to by m_xEnd,
1086 // and m_xEnd must be then shifted to the next unused one.
1087 // When (m_xEnd + 1) % m_zSize == m_xBegin, the container
1088 // is considered full and the element adding is rejected.
1089 //
1090 // This container is not designed to be STL-compatible
1091 // because it doesn't make much sense. It's not a typical
1092 // container, even treated as random-access container.
1093
1094 int shift(int basepos, int shift) const
1095 {
1096 return (basepos + shift) % m_iSize;
1097 }
1098
1099 // Simplified versions with ++ and --; avoid using division instruction
1100 int shift_forward(int basepos) const
1101 {
1102 if (++basepos == m_iSize)
1103 return 0;
1104 return basepos;
1105 }
1106
1107 int shift_backward(int basepos) const
1108 {
1109 if (basepos == 0)
1110 return m_iSize-1;
1111 return --basepos;
1112 }
1113
1114 int size() const
1115 {
1116 // Count the distance between begin and end
1117 if (m_xEnd < m_xBegin)
1118 {
1119 // Use "merge two slices" method.
1120 // (BEGIN - END) is the distance of the unused
1121 // space in the middle. Used space is left to END
1122 // and right to BEGIN, the sum of the left and right
1123 // slice and the free space is the size.
1124
1125 // This includes also a case when begin and end
1126 // are equal, which means that it's empty, so
1127 // spaceleft() should simply return m_iSize.
1128 return m_iSize - (m_xBegin - m_xEnd);
1129 }
1130
1131 return m_xEnd - m_xBegin;
1132 }
1133
1134 bool empty() const { return m_xEnd == m_xBegin; }
1135
1136 size_t capacity() const { return m_iSize-1; }
1137
1138 int spaceleft() const
1139 {
1140 // It's kinda tautology, but this will be more efficient.
1141 if (m_xEnd < m_xBegin)
1142 {
1143 return m_xBegin - m_xEnd;
1144 }
1145
1146 return m_iSize - (m_xEnd - m_xBegin);
1147 }
1148
1149 // This is rather written for testing and rather won't
1150 // be used in the real code.
1151 template <class V>
1152 int push(const V& v)
1153 {
1154 // Check if you can add
1155 int nend = shift_forward(m_xEnd);
1156 if ( nend == m_xBegin)
1157 return -1;
1158
1159 constr(m_aStorage[m_xEnd], v);
1160 m_xEnd = nend;
1161 return size() - 1;
1162 }
1163
1164 Value* push()
1165 {
1166 int nend = shift_forward(m_xEnd);
1167 if ( nend == m_xBegin)
1168 return NULL;
1169
1170 Value* pos = &m_aStorage[m_xEnd];
1171 constr(*pos);
1172 m_xEnd = nend;
1173 return pos;
1174 }
1175
1176 bool access(int position, Value*& w_v)
1177 {
1178 // This version doesn't require the boolean value to report
1179 // whether the element is newly added because it never adds
1180 // a new element.
1181 int ipos, vend;
1182
1183 if (!INT_checkAccess(position, ipos, vend))
1184 return false;
1185 if (ipos >= vend) // exceeds
1186 return false;
1187
1188 INT_access(ipos, false, (w_v)); // never exceeds
1189 return true;
1190 }
1191
1192 // Ok, now it's the real deal.
1193 bool access(int position, Value*& w_v, bool& w_isnew)
1194 {
1195 int ipos, vend;
1196
1197 if (!INT_checkAccess(position, ipos, vend))
1198 return false;
1199 bool exceeds = (ipos >= vend);
1200 w_isnew = exceeds;
1201
1202 INT_access(ipos, exceeds, (w_v));
1203 return true;
1204 }
1205
1206 private:
1207 bool INT_checkAccess(int position, int& ipos, int& vend)
1208 {
1209 // Reject if no space left.
1210 // Also INVAL if negative position.
1211 if (position >= (m_iSize-1) || position < 0)
1212 return false; // That's way to far, we can't even calculate
1213
1214 ipos = m_xBegin + position;
1215
1216 vend = m_xEnd;
1217 if (m_xEnd < m_xBegin)
1218 vend += m_iSize;
1219
1220 return true;
1221 }
1222
1223 void INT_access(int ipos, bool exceeds, Value*& w_v)
1224 {
1225 if (ipos >= m_iSize)
1226 ipos -= m_iSize; // wrap around
1227
1228 // Update the end position.
1229 if (exceeds)
1230 {
1231 int nend = ipos+1;
1232 if (m_xEnd > nend)
1233 {
1234 // Here we know that the current index exceeds the size.
1235 // So, if this happens, it's m_xEnd wrapped around.
1236 // Clear out elements in two slices:
1237 // - from m_xEnd to m_iSize-1
1238 // - from 0 to nend
1239 for (int i = m_xEnd; i < m_iSize; ++i)
1240 constr(m_aStorage[i]);
1241 for (int i = 0; i < nend; ++i)
1242 constr(m_aStorage[i]);
1243 }
1244 else
1245 {
1246 for (int i = m_xEnd; i < nend; ++i)
1247 constr(m_aStorage[i]);
1248 }
1249
1250 if (nend == m_iSize)
1251 nend = 0;
1252
1253 m_xEnd = nend;
1254 }
1255
1256 w_v = &m_aStorage[ipos];
1257 }
1258
1259 public:
1260 bool set(int position, const Value& newval, bool overwrite = true)
1261 {
1262 Value* pval = 0;
1263 bool isnew = false;
1264 if (!access(position, (pval), (isnew)))
1265 return false;
1266
1267 if (isnew || overwrite)
1268 *pval = newval;
1269 return true;
1270 }
1271
1272 template<class Updater>
1273 bool update(int position, Updater updater)
1274 {
1275 Value* pval = 0;
1276 bool isnew = false;
1277 if (!access(position, (pval), (isnew)))
1278 return false;
1279
1280 updater(*pval, isnew);
1281 return true;
1282 }
1283
1284 int getIndexFor(int position) const
1285 {
1286 int ipos = m_xBegin + position;
1287
1288 int vend = m_xEnd;
1289 if (vend < m_xBegin)
1290 vend += m_iSize;
1291
1292 if (ipos >= vend)
1293 return -1;
1294
1295 if (ipos >= m_iSize)
1296 ipos -= m_iSize;
1297
1298 return ipos;
1299 }
1300
1301 bool get(int position, Value& w_out) const
1302 {
1303 // Check if that position is occupied
1304 if (position > m_iSize || position < 0)
1305 return false;
1306
1307 int ipos = getIndexFor(position);
1308 if (ipos == -1)
1309 return false;
1310
1311 w_out = m_aStorage[ipos];
1312 return true;
1313 }
1314
1315 bool drop(int position)
1316 {
1317 // This function "deletes" items by shifting the
1318 // given position to position 0. That is,
1319 // elements from the beginning are being deleted
1320 // up to (including) the given position.
1321 if (position > m_iSize || position < 1)
1322 return false;
1323
1324 int ipos = m_xBegin + position;
1325 int vend = m_xEnd;
1326 if (vend < m_xBegin)
1327 vend += m_iSize;
1328
1329 // Destroy the elements in the removed range
1330
1331 if (ipos >= vend)
1332 {
1333 // There was a request to drop; the position
1334 // is higher than the number of items. Allow this
1335 // and simply make the container empty.
1336 reset();
1337 return true;
1338 }
1339
1340 // Otherwise we have a new beginning.
1341 int nbegin = ipos;
1342
1343 // Destroy the old elements
1344 if (nbegin >= m_iSize)
1345 {
1346 nbegin -= m_iSize;
1347
1348 for (int i = m_xBegin; i < m_iSize; ++i)
1349 destr(m_aStorage[i]);
1350 for (int i = 0; i < nbegin; ++i)
1351 destr(m_aStorage[i]);
1352 }
1353 else
1354 {
1355 for (int i = m_xBegin; i < nbegin; ++i)
1356 destr(m_aStorage[i]);
1357 }
1358
1359 m_xBegin = nbegin;
1360
1361 return true;
1362 }
1363
1364 // This function searches for an element that satisfies
1365 // the given predicate. If none found, returns -1.
1366 template <class Predicate>
1367 int find_if(Predicate pred)
1368 {
1369 if (m_xEnd < m_xBegin)
1370 {
1371 // Loop in two slices
1372 for (int i = m_xBegin; i < m_iSize; ++i)
1373 if (pred(m_aStorage[i]))
1374 return i - m_xBegin;
1375
1376 for (int i = 0; i < m_xEnd; ++i)
1377 if (pred(m_aStorage[i]))
1378 return i + m_iSize - m_xBegin;
1379 }
1380 else
1381 {
1382 for (int i = m_xBegin; i < m_xEnd; ++i)
1383 if (pred(m_aStorage[i]))
1384 return i - m_xBegin;
1385 }
1386
1387 return -1;
1388 }
1389 };
1390
1391 // Version parsing
1392 inline ATR_CONSTEXPR uint32_t SrtVersion(int major, int minor, int patch)
1393 {
1394 return patch + minor*0x100 + major*0x10000;
1395 }
1396
1397 inline int32_t SrtParseVersion(const char* v)
1398 {
1399 int major, minor, patch;
1400 #if defined(_MSC_VER)
1401 int result = sscanf_s(v, "%d.%d.%d", &major, &minor, &patch);
1402 #else
1403 int result = sscanf(v, "%d.%d.%d", &major, &minor, &patch);
1404 #endif
1405 if (result != 3)
1406 {
1407 return 0;
1408 }
1409
1410 return SrtVersion(major, minor, patch);
1411 }
1412
1413 inline std::string SrtVersionString(int version)
1414 {
1415 int patch = version % 0x100;
1416 int minor = (version/0x100)%0x100;
1417 int major = version/0x10000;
1418
1419 char buf[22];
1420 #if defined(_MSC_VER) && _MSC_VER < 1900
1421 _snprintf(buf, sizeof(buf) - 1, "%d.%d.%d", major, minor, patch);
1422 #else
1423 snprintf(buf, sizeof(buf), "%d.%d.%d", major, minor, patch);
1424 #endif
1425 return buf;
1426 }
1427
1428 bool SrtParseConfig(const std::string& s, SrtConfig& w_config);
1429
1430 bool checkMappedIPv4(const uint16_t* sa);
1431
1432 inline bool checkMappedIPv4(const sockaddr_in6& sa)
1433 {
1434 const uint16_t* addr = reinterpret_cast<const uint16_t*>(&sa.sin6_addr.s6_addr);
1435 return checkMappedIPv4(addr);
1436 }
1437
1438 std::string FormatLossArray(const std::vector< std::pair<int32_t, int32_t> >& lra);
1439 std::ostream& PrintEpollEvent(std::ostream& os, int events, int et_events = 0);
1440 std::string FormatValue(int value, int factor, const char* unit);
1441
1442 } // namespace srt
1443
1444 #endif