datachannel.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /**
  2. * Copyright (c) 2019 Paul-Louis Ageneau
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include "datachannel.hpp"
  19. #include "include.hpp"
  20. #include "peerconnection.hpp"
  21. #include "sctptransport.hpp"
  22. #ifdef _WIN32
  23. #include <winsock2.h>
  24. #else
  25. #include <arpa/inet.h>
  26. #endif
  27. namespace rtc {
  28. using std::shared_ptr;
  29. using std::weak_ptr;
  30. using std::chrono::milliseconds;
  31. // Messages for the DataChannel establishment protocol
  32. // See https://tools.ietf.org/html/draft-ietf-rtcweb-data-protocol-09
  33. enum MessageType : uint8_t {
  34. MESSAGE_OPEN_REQUEST = 0x00,
  35. MESSAGE_OPEN_RESPONSE = 0x01,
  36. MESSAGE_ACK = 0x02,
  37. MESSAGE_OPEN = 0x03,
  38. MESSAGE_CLOSE = 0x04
  39. };
  40. enum ChannelType : uint8_t {
  41. CHANNEL_RELIABLE = 0x00,
  42. CHANNEL_PARTIAL_RELIABLE_REXMIT = 0x01,
  43. CHANNEL_PARTIAL_RELIABLE_TIMED = 0x02
  44. };
  45. #pragma pack(push, 1)
  46. struct OpenMessage {
  47. uint8_t type = MESSAGE_OPEN;
  48. uint8_t channelType;
  49. uint16_t priority;
  50. uint32_t reliabilityParameter;
  51. uint16_t labelLength;
  52. uint16_t protocolLength;
  53. // The following fields are:
  54. // uint8_t[labelLength] label
  55. // uint8_t[protocolLength] protocol
  56. };
  57. struct AckMessage {
  58. uint8_t type = MESSAGE_ACK;
  59. };
  60. struct CloseMessage {
  61. uint8_t type = MESSAGE_CLOSE;
  62. };
  63. #pragma pack(pop)
  64. DataChannel::DataChannel(weak_ptr<PeerConnection> pc, unsigned int stream, string label,
  65. string protocol, Reliability reliability)
  66. : mPeerConnection(pc), mStream(stream), mLabel(std::move(label)),
  67. mProtocol(std::move(protocol)),
  68. mReliability(std::make_shared<Reliability>(std::move(reliability))),
  69. mRecvQueue(RECV_QUEUE_LIMIT, message_size_func) {}
  70. DataChannel::DataChannel(weak_ptr<PeerConnection> pc, weak_ptr<SctpTransport> transport,
  71. unsigned int stream)
  72. : mPeerConnection(pc), mSctpTransport(transport), mStream(stream),
  73. mReliability(std::make_shared<Reliability>()),
  74. mRecvQueue(RECV_QUEUE_LIMIT, message_size_func) {}
  75. DataChannel::~DataChannel() {
  76. close();
  77. }
  78. unsigned int DataChannel::stream() const { return mStream; }
  79. string DataChannel::label() const { return mLabel; }
  80. string DataChannel::protocol() const { return mProtocol; }
  81. Reliability DataChannel::reliability() const { return *mReliability; }
  82. void DataChannel::close() {
  83. mIsClosed = true;
  84. if (mIsOpen.exchange(false))
  85. if (auto transport = mSctpTransport.lock())
  86. transport->closeStream(mStream);
  87. mSctpTransport.reset();
  88. resetCallbacks();
  89. }
  90. void DataChannel::remoteClose() {
  91. if (!mIsClosed.exchange(true))
  92. triggerClosed();
  93. mIsOpen = false;
  94. mSctpTransport.reset();
  95. }
  96. bool DataChannel::send(message_variant data) { return outgoing(make_message(std::move(data))); }
  97. bool DataChannel::send(const byte *data, size_t size) {
  98. return outgoing(std::make_shared<Message>(data, data + size, Message::Binary));
  99. }
  100. std::optional<message_variant> DataChannel::receive() {
  101. while (auto next = mRecvQueue.tryPop()) {
  102. message_ptr message = *next;
  103. if (message->type != Message::Control)
  104. return to_variant(std::move(*message));
  105. auto raw = reinterpret_cast<const uint8_t *>(message->data());
  106. if (!message->empty() && raw[0] == MESSAGE_CLOSE)
  107. remoteClose();
  108. }
  109. return nullopt;
  110. }
  111. std::optional<message_variant> DataChannel::peek() {
  112. while (auto next = mRecvQueue.peek()) {
  113. message_ptr message = *next;
  114. if (message->type != Message::Control)
  115. return to_variant(std::move(*message));
  116. auto raw = reinterpret_cast<const uint8_t *>(message->data());
  117. if (!message->empty() && raw[0] == MESSAGE_CLOSE)
  118. remoteClose();
  119. mRecvQueue.tryPop();
  120. }
  121. return nullopt;
  122. }
  123. bool DataChannel::isOpen(void) const { return mIsOpen; }
  124. bool DataChannel::isClosed(void) const { return mIsClosed; }
  125. size_t DataChannel::maxMessageSize() const {
  126. size_t remoteMax = DEFAULT_MAX_MESSAGE_SIZE;
  127. if (auto pc = mPeerConnection.lock())
  128. if (auto description = pc->remoteDescription())
  129. if (auto *application = description->application())
  130. if (auto maxMessageSize = application->maxMessageSize())
  131. remoteMax = *maxMessageSize > 0 ? *maxMessageSize : LOCAL_MAX_MESSAGE_SIZE;
  132. return std::min(remoteMax, LOCAL_MAX_MESSAGE_SIZE);
  133. }
  134. size_t DataChannel::availableAmount() const { return mRecvQueue.amount(); }
  135. void DataChannel::open(shared_ptr<SctpTransport> transport) {
  136. mSctpTransport = transport;
  137. uint8_t channelType;
  138. uint32_t reliabilityParameter;
  139. switch (mReliability->type) {
  140. case Reliability::Type::Rexmit:
  141. channelType = CHANNEL_PARTIAL_RELIABLE_REXMIT;
  142. reliabilityParameter = uint32_t(std::get<int>(mReliability->rexmit));
  143. break;
  144. case Reliability::Type::Timed:
  145. channelType = CHANNEL_PARTIAL_RELIABLE_TIMED;
  146. reliabilityParameter = uint32_t(std::get<milliseconds>(mReliability->rexmit).count());
  147. break;
  148. default:
  149. channelType = CHANNEL_RELIABLE;
  150. reliabilityParameter = 0;
  151. break;
  152. }
  153. if (mReliability->unordered)
  154. channelType |= 0x80;
  155. const size_t len = sizeof(OpenMessage) + mLabel.size() + mProtocol.size();
  156. binary buffer(len, byte(0));
  157. auto &open = *reinterpret_cast<OpenMessage *>(buffer.data());
  158. open.type = MESSAGE_OPEN;
  159. open.channelType = channelType;
  160. open.priority = htons(0);
  161. open.reliabilityParameter = htonl(reliabilityParameter);
  162. open.labelLength = htons(uint16_t(mLabel.size()));
  163. open.protocolLength = htons(uint16_t(mProtocol.size()));
  164. auto end = reinterpret_cast<char *>(buffer.data() + sizeof(OpenMessage));
  165. std::copy(mLabel.begin(), mLabel.end(), end);
  166. std::copy(mProtocol.begin(), mProtocol.end(), end + mLabel.size());
  167. transport->send(make_message(buffer.begin(), buffer.end(), Message::Control, mStream));
  168. }
  169. bool DataChannel::outgoing(message_ptr message) {
  170. if (mIsClosed)
  171. throw std::runtime_error("DataChannel is closed");
  172. if (message->size() > maxMessageSize())
  173. throw std::runtime_error("Message size exceeds limit");
  174. auto transport = mSctpTransport.lock();
  175. if (!transport)
  176. throw std::runtime_error("DataChannel transport is not open");
  177. // Before the ACK has been received on a DataChannel, all messages must be sent ordered
  178. message->reliability = mIsOpen ? mReliability : nullptr;
  179. message->stream = mStream;
  180. return transport->send(message);
  181. }
  182. void DataChannel::incoming(message_ptr message) {
  183. if (!message)
  184. return;
  185. switch (message->type) {
  186. case Message::Control: {
  187. if (message->size() == 0)
  188. break; // Ignore
  189. auto raw = reinterpret_cast<const uint8_t *>(message->data());
  190. switch (raw[0]) {
  191. case MESSAGE_OPEN:
  192. processOpenMessage(message);
  193. break;
  194. case MESSAGE_ACK:
  195. if (!mIsOpen.exchange(true)) {
  196. triggerOpen();
  197. }
  198. break;
  199. case MESSAGE_CLOSE:
  200. // The close message will be processed in-order in receive()
  201. mRecvQueue.push(message);
  202. triggerAvailable(mRecvQueue.size());
  203. break;
  204. default:
  205. // Ignore
  206. break;
  207. }
  208. break;
  209. }
  210. case Message::String:
  211. case Message::Binary:
  212. mRecvQueue.push(message);
  213. triggerAvailable(mRecvQueue.size());
  214. break;
  215. default:
  216. // Ignore
  217. break;
  218. }
  219. }
  220. void DataChannel::processOpenMessage(message_ptr message) {
  221. auto transport = mSctpTransport.lock();
  222. if (!transport)
  223. throw std::runtime_error("DataChannel has no transport");
  224. if (message->size() < sizeof(OpenMessage))
  225. throw std::invalid_argument("DataChannel open message too small");
  226. OpenMessage open = *reinterpret_cast<const OpenMessage *>(message->data());
  227. open.priority = ntohs(open.priority);
  228. open.reliabilityParameter = ntohl(open.reliabilityParameter);
  229. open.labelLength = ntohs(open.labelLength);
  230. open.protocolLength = ntohs(open.protocolLength);
  231. if (message->size() < sizeof(OpenMessage) + size_t(open.labelLength + open.protocolLength))
  232. throw std::invalid_argument("DataChannel open message truncated");
  233. auto end = reinterpret_cast<const char *>(message->data() + sizeof(OpenMessage));
  234. mLabel.assign(end, open.labelLength);
  235. mProtocol.assign(end + open.labelLength, open.protocolLength);
  236. mReliability->unordered = (open.reliabilityParameter & 0x80) != 0;
  237. switch (open.channelType & 0x7F) {
  238. case CHANNEL_PARTIAL_RELIABLE_REXMIT:
  239. mReliability->type = Reliability::Type::Rexmit;
  240. mReliability->rexmit = int(open.reliabilityParameter);
  241. break;
  242. case CHANNEL_PARTIAL_RELIABLE_TIMED:
  243. mReliability->type = Reliability::Type::Timed;
  244. mReliability->rexmit = milliseconds(open.reliabilityParameter);
  245. break;
  246. default:
  247. mReliability->type = Reliability::Type::Reliable;
  248. mReliability->rexmit = int(0);
  249. }
  250. binary buffer(sizeof(AckMessage), byte(0));
  251. auto &ack = *reinterpret_cast<AckMessage *>(buffer.data());
  252. ack.type = MESSAGE_ACK;
  253. transport->send(make_message(buffer.begin(), buffer.end(), Message::Control, mStream));
  254. mIsOpen = true;
  255. triggerOpen();
  256. }
  257. } // namespace rtc