Debian Codegraph @

srtcore/api.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 - 2010, 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 09/28/2010
49 modified by
50 Haivision Systems Inc.
51 *****************************************************************************/
52
53 #ifndef INC_SRT_API_H
54 #define INC_SRT_API_H
55
56 #include <map>
57 #include <vector>
58 #include <string>
59 #include "netinet_any.h"
60 #include "udt.h"
61 #include "packet.h"
62 #include "queue.h"
63 #include "cache.h"
64 #include "epoll.h"
65 #include "handshake.h"
66 #include "core.h"
67 #if ENABLE_BONDING
68 #include "group.h"
69 #endif
70
71 // Please refer to structure and locking information provided in the
72 // docs/dev/low-level-info.md document.
73
74 namespace srt
75 {
76
77 class CUDT;
78
79 /// @brief Class CUDTSocket is a control layer on top of the CUDT core functionality layer.
80 /// CUDTSocket owns CUDT.
81 class CUDTSocket
82 {
83 public:
84 CUDTSocket()
85 : m_Status(SRTS_INIT)
86 , m_SocketID(0)
87 , m_ListenSocket(0)
88 , m_PeerID(0)
89 #if ENABLE_BONDING
90 , m_GroupMemberData()
91 , m_GroupOf()
92 #endif
93 , m_iISN(0)
94 , m_UDT(this)
95 , m_AcceptCond()
96 , m_AcceptLock()
97 , m_uiBackLog(0)
98 , m_iMuxID(-1)
99 {
100 construct();
101 }
102
103 CUDTSocket(const CUDTSocket& ancestor)
104 : m_Status(SRTS_INIT)
105 , m_SocketID(0)
106 , m_ListenSocket(0)
107 , m_PeerID(0)
108 #if ENABLE_BONDING
109 , m_GroupMemberData()
110 , m_GroupOf()
111 #endif
112 , m_iISN(0)
113 , m_UDT(this, ancestor.m_UDT)
114 , m_AcceptCond()
115 , m_AcceptLock()
116 , m_uiBackLog(0)
117 , m_iMuxID(-1)
118 {
119 construct();
120 }
121
122 ~CUDTSocket();
123 void resetAtFork();
124
125 void construct();
126
127 private:
128 srt::sync::atomic<int> m_iBusy;
129 public:
130 void apiAcquire() { ++m_iBusy; }
131 void apiRelease() { --m_iBusy; }
132
133 int isStillBusy() const
134 {
135 return m_iBusy;
136 }
137
138
139 SRT_ATTR_GUARDED_BY(m_ControlLock)
140 sync::atomic<SRT_SOCKSTATUS> m_Status; //< current socket state
141
142 /// Time when the socket is closed.
143 /// When the socket is closed, it is not removed immediately from the list
144 /// of sockets in order to prevent other methods from accessing invalid address.
145 /// A timer is started and the socket will be removed after approximately
146 /// 1 second (see CUDTUnited::checkBrokenSockets()).
147 //sync::steady_clock::time_point m_tsClosureTimeStamp;
148 sync::AtomicClock<sync::steady_clock> m_tsClosureTimeStamp;
149
150 sockaddr_any m_SelfAddr; //< local address of the socket
151 sockaddr_any m_PeerAddr; //< peer address of the socket
152
153 SRTSOCKET m_SocketID; //< socket ID
154 SRTSOCKET m_ListenSocket; //< ID of the listener socket; 0 means this is an independent socket
155
156 SRTSOCKET m_PeerID; //< peer socket ID
157 #if ENABLE_BONDING
158 groups::SocketData* m_GroupMemberData; //< Pointer to group member data, or NULL if not a group member
159 CUDTGroup* m_GroupOf; //< Group this socket is a member of, or NULL if it isn't
160 #endif
161
162 int32_t m_iISN; //< initial sequence number, used to tell different connection from same IP:port
163
164 private:
165 CUDT m_UDT; //< internal SRT socket logic
166
167 public:
168 std::map<SRTSOCKET, sockaddr_any> m_QueuedSockets; //< set of connections waiting for accept()
169
170 sync::Condition m_AcceptCond; //< used to block "accept" call
171 sync::Mutex m_AcceptLock; //< mutex associated to m_AcceptCond
172
173 unsigned int m_uiBackLog; //< maximum number of connections in queue
174
175 // XXX A refactoring might be needed here.
176
177 // There are no reasons found why the socket can't contain a list iterator to a
178 // multiplexer INSTEAD of m_iMuxID. There's no danger in this solution because
179 // the multiplexer is never deleted until there's at least one socket using it.
180 //
181 // The multiplexer may even physically be contained in the CUDTUnited object,
182 // just track the multiple users of it (the listener and the accepted sockets).
183 // When deleting, you simply "unsubscribe" yourself from the multiplexer, which
184 // will unref it and remove the list element by the iterator kept by the
185 // socket.
186 int m_iMuxID; //< multiplexer ID
187
188 sync::Mutex m_ControlLock; //< lock this socket exclusively for control APIs: bind/listen/connect
189
190 CUDT& core() { return m_UDT; }
191 const CUDT& core() const { return m_UDT; }
192
193 static int64_t getPeerSpec(SRTSOCKET id, int32_t isn) { return (int64_t(id) << 30) + isn; }
194 int64_t getPeerSpec() { return getPeerSpec(m_PeerID, m_iISN); }
195
196 SRT_SOCKSTATUS getStatus();
197
198 /// This function shall be called always wherever
199 /// you'd like to call cudtsocket->m_pUDT->close(),
200 /// from within the GC thread only (that is, only when
201 /// the socket should be no longer visible in the
202 /// connection, including for sending remaining data).
203 void breakSocket_LOCKED();
204
205 /// This makes the socket no longer capable of performing any transmission
206 /// operation, but continues to be responsive in the connection in order
207 /// to finish sending the data that were scheduled for sending so far.
208 void setClosed();
209
210 // This is necessary to be called from the group before the group clears
211 // the connection with the socket. As for managed groups (and there are
212 // currently no other group types), a socket disconnected from the group
213 // is no longer usable.
214 void setClosing()
215 {
216 core().m_bClosing = true;
217 }
218
219 void setBreaking()
220 {
221 core().m_bBreaking = true;
222 }
223
224 /// This does the same as setClosed, plus sets the m_bBroken to true.
225 /// Such a socket can still be read from so that remaining data from
226 /// the receiver buffer can be read, but no longer sends anything.
227 void setBrokenClosed();
228 void removeFromGroup(bool broken);
229
230 // Instrumentally used by select() and also required for non-blocking
231 // mode check in groups
232 bool readReady();
233 bool writeReady() const;
234 bool broken() const;
235
236 private:
237 CUDTSocket& operator=(const CUDTSocket&);
238 };
239
240 ////////////////////////////////////////////////////////////////////////////////
241
242 class CUDTUnited
243 {
244 friend class CUDT;
245 friend class CUDTGroup;
246 friend class CRendezvousQueue;
247 friend class CCryptoControl;
248
249 public:
250 CUDTUnited();
251 ~CUDTUnited();
252
253 // Public constants
254 static const int32_t MAX_SOCKET_VAL = SRTGROUP_MASK - 1; // maximum value for a regular socket
255
256 public:
257 enum ErrorHandling
258 {
259 ERH_RETURN,
260 ERH_THROW,
261 ERH_ABORT
262 };
263 static std::string CONID(SRTSOCKET sock);
264
265 /// initialize the UDT library.
266 /// @return 0 if success, otherwise -1 is returned.
267 int startup();
268
269 /// release the UDT library.
270 /// @return 0 if success, otherwise -1 is returned.
271 int cleanup();
272 int cleanupAtFork();
273
274 /// Create a new UDT socket.
275 /// @param [out] pps Variable (optional) to which the new socket will be written, if succeeded
276 /// @return The new UDT socket ID, or INVALID_SOCK.
277 SRTSOCKET newSocket(CUDTSocket** pps = NULL);
278
279 /// Create (listener-side) a new socket associated with the incoming connection request.
280 /// @param [in] listen the listening socket ID.
281 /// @param [in] peer peer address.
282 /// @param [in,out] hs handshake information from peer side (in), negotiated value (out);
283 /// @param [out] w_error error code in case of failure.
284 /// @param [out] w_acpu reference to the existing associated socket if already exists.
285 /// @return 1: if the new connection was successfully created (accepted), @a w_acpu is NULL;
286 /// 0: the connection already exists (reference to the corresponding socket is returned in @a w_acpu).
287 /// -1: The connection processing failed due to memory alloation error, exceeding listener's backlog,
288 /// any error propagated from CUDT::open and CUDT::acceptAndRespond.
289 int newConnection(const SRTSOCKET listen,
290 const sockaddr_any& peer,
291 const CPacket& hspkt,
292 CHandShake& w_hs,
293 int& w_error,
294 CUDT*& w_acpu);
295
296 int installAcceptHook(const SRTSOCKET lsn, srt_listen_callback_fn* hook, void* opaq);
297 int installConnectHook(const SRTSOCKET lsn, srt_connect_callback_fn* hook, void* opaq);
298
299 /// Check the status of the UDT socket.
300 /// @param [in] u the UDT socket ID.
301 /// @return UDT socket status, or NONEXIST if not found.
302 SRT_SOCKSTATUS getStatus(const SRTSOCKET u);
303
304 // socket APIs
305
306 int bind(CUDTSocket* u, const sockaddr_any& name);
307 int bind(CUDTSocket* u, UDPSOCKET udpsock);
308 int listen(const SRTSOCKET u, int backlog);
309 SRTSOCKET accept(const SRTSOCKET listen, sockaddr* addr, int* addrlen);
310 SRTSOCKET accept_bond(const SRTSOCKET listeners[], int lsize, int64_t msTimeOut);
311 int connect(SRTSOCKET u, const sockaddr* srcname, const sockaddr* tarname, int tarlen);
312 int connect(const SRTSOCKET u, const sockaddr* name, int namelen, int32_t forced_isn);
313 int connectIn(CUDTSocket* s, const sockaddr_any& target, int32_t forced_isn);
314 #if ENABLE_BONDING
315 int groupConnect(CUDTGroup* g, SRT_SOCKGROUPCONFIG targets[], int arraysize);
316 int singleMemberConnect(CUDTGroup* g, SRT_SOCKGROUPCONFIG* target);
317 #endif
318 int close(const SRTSOCKET u);
319 int close(CUDTSocket* s);
320 void getpeername(const SRTSOCKET u, sockaddr* name, int* namelen);
321 void getsockname(const SRTSOCKET u, sockaddr* name, int* namelen);
322 int select(UDT::UDSET* readfds, UDT::UDSET* writefds, UDT::UDSET* exceptfds, const timeval* timeout);
323 int selectEx(const std::vector<SRTSOCKET>& fds,
324 std::vector<SRTSOCKET>* readfds,
325 std::vector<SRTSOCKET>* writefds,
326 std::vector<SRTSOCKET>* exceptfds,
327 int64_t msTimeOut);
328 int epoll_create();
329 int epoll_clear_usocks(int eid);
330 int epoll_add_usock(const int eid, const SRTSOCKET u, const int* events = NULL);
331 int epoll_add_usock_INTERNAL(const int eid, CUDTSocket* s, const int* events);
332 int epoll_add_ssock(const int eid, const SYSSOCKET s, const int* events = NULL);
333 int epoll_remove_usock(const int eid, const SRTSOCKET u);
334 template <class EntityType>
335 int epoll_remove_entity(const int eid, EntityType* ent);
336 int epoll_remove_socket_INTERNAL(const int eid, CUDTSocket* ent);
337 #if ENABLE_BONDING
338 int epoll_remove_group_INTERNAL(const int eid, CUDTGroup* ent);
339 #endif
340 int epoll_remove_ssock(const int eid, const SYSSOCKET s);
341 int epoll_update_ssock(const int eid, const SYSSOCKET s, const int* events = NULL);
342 int epoll_uwait(const int eid, SRT_EPOLL_EVENT* fdsSet, int fdsSize, int64_t msTimeOut);
343 int32_t epoll_set(const int eid, int32_t flags);
344 int epoll_release(const int eid);
345
346 #if ENABLE_BONDING
347 SRT_ATR_NODISCARD SRT_ATTR_REQUIRES(m_GlobControlLock)
348 CUDTGroup& addGroup(SRTSOCKET id, SRT_GROUP_TYPE type)
349 {
350 // This only ensures that the element exists.
351 // If the element was newly added, it will be NULL.
352 CUDTGroup*& g = m_Groups[id];
353 if (!g)
354 {
355 // This is a reference to the cell, so it will
356 // rewrite it into the map.
357 g = new CUDTGroup(type);
358 }
359
360 // Now we are sure that g is not NULL,
361 // and persistence of this object is in the map.
362 // The reference to the object can be safely returned here.
363 return *g;
364 }
365
366 void deleteGroup(CUDTGroup* g);
367 void deleteGroup_LOCKED(CUDTGroup* g);
368
369 SRT_ATR_NODISCARD SRT_ATTR_REQUIRES(m_GlobControlLock)
370 CUDTGroup* findPeerGroup_LOCKED(SRTSOCKET peergroup)
371 {
372 for (groups_t::iterator i = m_Groups.begin(); i != m_Groups.end(); ++i)
373 {
374 if (i->second->peerid() == peergroup)
375 return i->second;
376 }
377 return NULL;
378 }
379 #endif
380
381 CEPoll& epoll_ref() { return m_EPoll; }
382
383 private:
384 /// Generates a new socket ID. This function starts from a randomly
385 /// generated value (at initialization time) and goes backward with
386 /// with next calls. The possible values come from the range without
387 /// the SRTGROUP_MASK bit, and the group bit is set when the ID is
388 /// generated for groups. It is also internally checked if the
389 /// newly generated ID isn't already used by an existing socket or group.
390 ///
391 /// Socket ID value range.
392 /// - [0]: reserved for handshake procedure. If the destination Socket ID is 0
393 /// (destination Socket ID unknown) the packet will be sent to the listening socket
394 /// or to a socket that is in the rendezvous connection phase.
395 /// - [1; 2 ^ 30): single socket ID range.
396 /// - (2 ^ 30; 2 ^ 31): group socket ID range. Effectively any positive number
397 /// from [1; 2 ^ 30) with bit 30 set to 1. Bit 31 is zero.
398 /// The most significant bit 31 (sign bit) is left unused so that checking for a value <= 0 identifies an invalid
399 /// socket ID.
400 ///
401 /// @param group The socket id should be for socket group.
402 /// @return The new socket ID.
403 /// @throw CUDTException if after rolling over all possible ID values nothing can be returned
404 SRTSOCKET generateSocketID(bool group = false);
405
406 private:
407 typedef std::map<SRTSOCKET, CUDTSocket*> sockets_t; // stores all the socket structures
408 SRT_ATTR_GUARDED_BY(m_GlobControlLock)
409 sockets_t m_Sockets;
410
411 #if ENABLE_BONDING
412 typedef std::map<SRTSOCKET, CUDTGroup*> groups_t;
413 SRT_ATTR_GUARDED_BY(m_GlobControlLock)
414 groups_t m_Groups;
415 #endif
416
417 sync::SharedMutex m_GlobControlLock; // used to synchronize UDT API
418
419 sync::Mutex m_IDLock; // used to synchronize ID generation
420
421 SRTSOCKET m_SocketIDGenerator; // seed to generate a new unique socket ID
422 SRTSOCKET m_SocketIDGenerator_init; // Keeps track of the very first one
423
424 SRT_ATTR_GUARDED_BY(m_GlobControlLock)
425 std::map<int64_t, std::set<SRTSOCKET> >
426 m_PeerRec; // record sockets from peers to avoid repeated connection request, int64_t = (socker_id << 30) + isn
427
428 private:
429 friend struct FLookupSocketWithEvent_LOCKED;
430
431 CUDTSocket* locateSocket(SRTSOCKET u, ErrorHandling erh = ERH_RETURN);
432 // This function does the same as locateSocket, except that:
433 // - lock on m_GlobControlLock is expected (so that you don't unlock between finding and using)
434 // - only return NULL if not found
435 CUDTSocket* locateSocket_LOCKED(SRTSOCKET u);
436 CUDTSocket* locatePeer(const sockaddr_any& peer, const SRTSOCKET id, int32_t isn);
437
438 #if ENABLE_BONDING
439 CUDTGroup* locateAcquireGroup(SRTSOCKET u, ErrorHandling erh = ERH_RETURN);
440 CUDTGroup* acquireSocketsGroup(CUDTSocket* s);
441
442 struct GroupKeeper
443 {
444 CUDTGroup* group;
445
446 // This is intended for API functions to lock the group's existence
447 // for the lifetime of their call.
448 GroupKeeper(CUDTUnited& glob, SRTSOCKET id, ErrorHandling erh) { group = glob.locateAcquireGroup(id, erh); }
449
450 // This is intended for TSBPD thread that should lock the group's
451 // existence until it exits.
452 GroupKeeper(CUDTUnited& glob, CUDTSocket* s) { group = glob.acquireSocketsGroup(s); }
453
454 ~GroupKeeper()
455 {
456 if (group)
457 {
458 // We have a guarantee that if `group` was set
459 // as non-NULL here, it is also acquired and will not
460 // be deleted until this busy flag is set back to false.
461 sync::ScopedLock cgroup(*group->exp_groupLock());
462 group->apiRelease();
463 // Only now that the group lock is lifted, can the
464 // group be now deleted and this pointer potentially dangling
465 }
466 }
467 };
468 #endif
469
470 CUDTSocket* locateAcquireSocket(SRTSOCKET u, ErrorHandling erh = ERH_RETURN);
471 bool acquireSocket(CUDTSocket* s);
472 bool startGarbageCollector();
473 void stopGarbageCollector();
474 void cleanupAllSockets();
475 void closeAllSockets();
476
477 public:
478 struct SocketKeeper
479 {
480 CUDTSocket* socket;
481
482 SocketKeeper(): socket(NULL) {}
483
484 // This is intended for API functions to lock the socket's existence
485 // for the lifetime of their call.
486 SocketKeeper(CUDTUnited& glob, SRTSOCKET id, ErrorHandling erh = ERH_RETURN) { socket = glob.locateAcquireSocket(id, erh); }
487
488 // This is intended for TSBPD thread that should lock the socket's
489 // existence until it exits.
490 SocketKeeper(CUDTUnited& glob, CUDTSocket* s)
491 {
492 acquire(glob, s);
493 }
494
495 // Note: acquire doesn't check if the keeper already keeps anything.
496 // This is only for a use together with an empty constructor.
497 bool acquire(CUDTUnited& glob, CUDTSocket* s)
498 {
499 if (s == NULL)
500 {
501 socket = NULL;
502 return false;
503 }
504
505 const bool caught = glob.acquireSocket(s);
506 socket = caught ? s : NULL;
507 return caught;
508 }
509
510 ~SocketKeeper()
511 {
512 if (socket)
513 {
514 SRT_ASSERT(socket->isStillBusy() > 0);
515 socket->apiRelease();
516 }
517 }
518 };
519
520 private:
521
522 void updateMux(CUDTSocket* s, const sockaddr_any& addr, const UDPSOCKET* = NULL);
523 bool updateListenerMux(CUDTSocket* s, const CUDTSocket* ls);
524
525 // Utility functions for updateMux
526 void configureMuxer(CMultiplexer& w_m, const CUDTSocket* s, int af);
527 uint16_t installMuxer(CUDTSocket* w_s, CMultiplexer& sm);
528
529 /// @brief Checks if channel configuration matches the socket configuration.
530 /// @param cfgMuxer multiplexer configuration.
531 /// @param cfgSocket socket configuration.
532 /// @return true if configurations match, false otherwise.
533 static bool channelSettingsMatch(const CSrtMuxerConfig& cfgMuxer, const CSrtConfig& cfgSocket);
534 static bool inet6SettingsCompat(const sockaddr_any& muxaddr, const CSrtMuxerConfig& cfgMuxer,
535 const sockaddr_any& reqaddr, const CSrtMuxerConfig& cfgSocket);
536
537 private:
538 SRT_ATTR_GUARDED_BY(m_GlobControlLock)
539 std::map<int, CMultiplexer> m_mMultiplexer; // UDP multiplexer
540
541 /// UDT network information cache.
542 /// Existence is guarded by m_GlobControlLock, but the cache itself is thread-safe.
543 SRT_ATTR_GUARDED_BY(m_GlobControlLock)
544 CCache<CInfoBlock>* const m_pCache;
545
546 private:
547 srt::sync::atomic<bool> m_bClosing;
548 sync::Mutex m_GCStartLock;
549 sync::Mutex m_GCStopLock;
550 sync::Condition m_GCStopCond;
551
552 sync::Mutex m_InitLock;
553 SRT_ATTR_GUARDED_BY(m_InitLock)
554 int m_iInstanceCount; // number of startup() called by application
555 SRT_ATTR_GUARDED_BY(m_InitLock)
556 bool m_bGCStatus; // if the GC thread is working (true)
557
558 SRT_ATTR_GUARDED_BY(m_InitLock)
559 sync::CThread m_GCThread;
560 static void* garbageCollect(void*);
561
562 SRT_ATTR_GUARDED_BY(m_GlobControlLock)
563 sockets_t m_ClosedSockets; // temporarily store closed sockets
564 #if ENABLE_BONDING
565 SRT_ATTR_GUARDED_BY(m_GlobControlLock)
566 groups_t m_ClosedGroups;
567 #endif
568
569 void checkBrokenSockets();
570 void removeSocket(const SRTSOCKET u);
571
572 CEPoll m_EPoll; // handling epoll data structures and events
573
574 private:
575 CUDTUnited(const CUDTUnited&);
576 CUDTUnited& operator=(const CUDTUnited&);
577 };
578
579 } // namespace srt
580
581 #endif