Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

RTCPeerConnection.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import { NativeModules } from 'react-native';
  2. import { RTCPeerConnection, RTCSessionDescription } from 'react-native-webrtc';
  3. /* eslint-disable no-unused-vars */
  4. // Address families.
  5. const AF_INET6 = 30; /* IPv6 */
  6. // Protocols (RFC 1700)
  7. const IPPROTO_TCP = 6; /* tcp */
  8. const IPPROTO_UDP = 17; /* user datagram protocol */
  9. // Protocol families, same as address families for now.
  10. const PF_INET6 = AF_INET6;
  11. const SOCK_DGRAM = 2; /* datagram socket */
  12. const SOCK_STREAM = 1; /* stream socket */
  13. /* eslint-enable no-unused-vars */
  14. // XXX At the time of this writing extending RTCPeerConnection using ES6 'class'
  15. // and 'extends' causes a runtime error related to the attempt to define the
  16. // onaddstream property setter. The error mentions that babelHelpers.set is
  17. // undefined which appears to be a thing inside React Native's packager. As a
  18. // workaround, extend using the pre-ES6 way.
  19. /**
  20. * The RTCPeerConnection provided by react-native-webrtc fires onaddstream
  21. * before it remembers remotedescription (and thus makes it available to API
  22. * clients). Because that appears to be a problem for lib-jitsi-meet which has
  23. * been successfully running on Chrome, Firefox, Temasys, etc. for a very long
  24. * time, attempt to meets its expectations (by extending RTCPPeerConnection).
  25. *
  26. * @class
  27. */
  28. export default function _RTCPeerConnection(...args) {
  29. /* eslint-disable indent, no-invalid-this */
  30. RTCPeerConnection.apply(this, args);
  31. this.onaddstream = (...args) => // eslint-disable-line no-shadow
  32. (this._onaddstreamQueue
  33. ? this._queueOnaddstream
  34. : this._invokeOnaddstream)
  35. .apply(this, args);
  36. // Shadow RTCPeerConnection's onaddstream but after _RTCPeerConnection has
  37. // assigned to the property in question. Defining the property on
  38. // _RTCPeerConnection's prototype may (or may not, I don't know) work but I
  39. // don't want to try because the following approach appears to work and I
  40. // understand it.
  41. Object.defineProperty(this, 'onaddstream', {
  42. configurable: true,
  43. enumerable: true,
  44. get() {
  45. return this._onaddstream;
  46. },
  47. set(value) {
  48. this._onaddstream = value;
  49. }
  50. });
  51. /* eslint-enable indent, no-invalid-this */
  52. }
  53. _RTCPeerConnection.prototype = Object.create(RTCPeerConnection.prototype);
  54. _RTCPeerConnection.prototype.constructor = _RTCPeerConnection;
  55. _RTCPeerConnection.prototype._invokeOnaddstream = function(...args) {
  56. const onaddstream = this._onaddstream;
  57. return onaddstream && onaddstream.apply(this, args);
  58. };
  59. _RTCPeerConnection.prototype._invokeQueuedOnaddstream = function(q) {
  60. q && q.forEach(args => {
  61. try {
  62. this._invokeOnaddstream(...args);
  63. } catch (e) {
  64. // TODO Determine whether the combination of the standard
  65. // setRemoteDescription and onaddstream results in a similar
  66. // swallowing of errors.
  67. _LOGE(e);
  68. }
  69. });
  70. };
  71. _RTCPeerConnection.prototype._queueOnaddstream = function(...args) {
  72. this._onaddstreamQueue.push(Array.from(args));
  73. };
  74. _RTCPeerConnection.prototype.setRemoteDescription = function(
  75. sessionDescription,
  76. successCallback,
  77. errorCallback) {
  78. // If the deprecated callback-based version is used, translate it to the
  79. // Promise-based version.
  80. if (typeof successCallback !== 'undefined'
  81. || typeof errorCallback !== 'undefined') {
  82. // XXX Returning a Promise is not necessary. But I don't see why it'd
  83. // hurt (much).
  84. return (
  85. _RTCPeerConnection.prototype.setRemoteDescription.call(
  86. this,
  87. sessionDescription)
  88. .then(successCallback, errorCallback));
  89. }
  90. return (
  91. _synthesizeIPv6Addresses(sessionDescription)
  92. .catch(reason => {
  93. reason && _LOGE(reason);
  94. return sessionDescription;
  95. })
  96. .then(value => _setRemoteDescription.bind(this)(value)));
  97. };
  98. /**
  99. * Logs at error level.
  100. *
  101. * @private
  102. * @returns {void}
  103. */
  104. function _LOGE(...args) {
  105. console && console.error && console.error(...args);
  106. }
  107. /**
  108. * Adapts react-native-webrtc's {@link RTCPeerConnection#setRemoteDescription}
  109. * implementation which uses the deprecated, callback-based version to the
  110. * {@code Promise}-based version.
  111. *
  112. * @param {RTCSessionDescription} sessionDescription - The RTCSessionDescription
  113. * which specifies the configuration of the remote end of the connection.
  114. * @private
  115. * @private
  116. * @returns {Promise}
  117. */
  118. function _setRemoteDescription(sessionDescription) {
  119. return new Promise((resolve, reject) => {
  120. /* eslint-disable no-invalid-this */
  121. // Ensure I'm not remembering onaddstream invocations from previous
  122. // setRemoteDescription calls. I shouldn't be but... anyway.
  123. this._onaddstreamQueue = [];
  124. RTCPeerConnection.prototype.setRemoteDescription.call(
  125. this,
  126. sessionDescription,
  127. (...args) => {
  128. let q;
  129. try {
  130. resolve(...args);
  131. } finally {
  132. q = this._onaddstreamQueue;
  133. this._onaddstreamQueue = undefined;
  134. }
  135. this._invokeQueuedOnaddstream(q);
  136. },
  137. (...args) => {
  138. this._onaddstreamQueue = undefined;
  139. reject(...args);
  140. });
  141. /* eslint-enable no-invalid-this */
  142. });
  143. }
  144. /**
  145. * Synthesize IPv6 addresses on iOS in order to support IPv6 NAT64 networks.
  146. *
  147. * @param {RTCSessionDescription} sdp - The RTCSessionDescription which
  148. * specifies the configuration of the remote end of the connection.
  149. * @private
  150. * @returns {Promise}
  151. */
  152. function _synthesizeIPv6Addresses(sdp) {
  153. // The synthesis of IPv6 addresses is implemented on iOS only at the time of
  154. // this writing.
  155. if (!NativeModules.POSIX) {
  156. return Promise.resolve(sdp);
  157. }
  158. return (
  159. new Promise(resolve => resolve(_synthesizeIPv6Addresses0(sdp)))
  160. .then(({ ips, lines }) =>
  161. Promise.all(Array.from(ips.values()))
  162. .then(() => _synthesizeIPv6Addresses1(sdp, ips, lines))
  163. ));
  164. }
  165. /* eslint-disable max-depth */
  166. /**
  167. * Begins the asynchronous synthesis of IPv6 addresses.
  168. *
  169. * @param {RTCSessionDescription} sessionDescription - The RTCSessionDescription
  170. * for which IPv6 addresses will be synthesized.
  171. * @private
  172. * @returns {{
  173. * ips: Map,
  174. * lines: Array
  175. * }}
  176. */
  177. function _synthesizeIPv6Addresses0(sessionDescription) {
  178. const sdp = sessionDescription.sdp;
  179. let start = 0;
  180. const lines = [];
  181. const ips = new Map();
  182. const { getaddrinfo } = NativeModules.POSIX;
  183. do {
  184. const end = sdp.indexOf('\r\n', start);
  185. let line;
  186. if (end === -1) {
  187. line = sdp.substring(start);
  188. // Break out of the loop at the end of the iteration.
  189. start = undefined;
  190. } else {
  191. line = sdp.substring(start, end);
  192. start = end + 2;
  193. }
  194. if (line.startsWith('a=candidate:')) {
  195. const candidate = line.split(' ');
  196. if (candidate.length >= 10 && candidate[6] === 'typ') {
  197. const ip4s = [ candidate[4] ];
  198. let abort = false;
  199. for (let i = 8; i < candidate.length; ++i) {
  200. if (candidate[i] === 'raddr') {
  201. ip4s.push(candidate[++i]);
  202. break;
  203. }
  204. }
  205. for (const ip of ip4s) {
  206. if (ip.indexOf(':') === -1) {
  207. ips.has(ip)
  208. || ips.set(ip, new Promise((resolve, reject) => {
  209. const v = ips.get(ip);
  210. if (v && typeof v === 'string') {
  211. resolve(v);
  212. } else {
  213. getaddrinfo(ip, undefined).then(
  214. ([ { ai_addr: value } ]) => {
  215. if (value.indexOf(':') === -1
  216. || value === ips.get(ip)) {
  217. ips.delete(ip);
  218. } else {
  219. ips.set(ip, value);
  220. }
  221. resolve(value);
  222. },
  223. reject);
  224. }
  225. }));
  226. } else {
  227. abort = true;
  228. break;
  229. }
  230. }
  231. if (abort) {
  232. ips.clear();
  233. break;
  234. }
  235. line = candidate;
  236. }
  237. }
  238. lines.push(line);
  239. } while (start);
  240. return {
  241. ips,
  242. lines
  243. };
  244. }
  245. /* eslint-enable max-depth */
  246. /**
  247. * Completes the asynchronous synthesis of IPv6 addresses.
  248. *
  249. * @param {RTCSessionDescription} sessionDescription - The RTCSessionDescription
  250. * for which IPv6 addresses are being synthesized.
  251. * @param {Map} ips - A Map of IPv4 addresses found in the specified
  252. * sessionDescription to synthesized IPv6 addresses.
  253. * @param {Array} lines - The lines of the specified sessionDescription.
  254. * @private
  255. * @returns {RTCSessionDescription} A RTCSessionDescription that represents the
  256. * result of the synthesis of IPv6 addresses.
  257. */
  258. function _synthesizeIPv6Addresses1(sessionDescription, ips, lines) {
  259. if (ips.size === 0) {
  260. return sessionDescription;
  261. }
  262. for (let l = 0; l < lines.length; ++l) {
  263. const candidate = lines[l];
  264. if (typeof candidate !== 'string') {
  265. let ip4 = candidate[4];
  266. let ip6 = ips.get(ip4);
  267. ip6 && (candidate[4] = ip6);
  268. for (let i = 8; i < candidate.length; ++i) {
  269. if (candidate[i] === 'raddr') {
  270. ip4 = candidate[++i];
  271. (ip6 = ips.get(ip4)) && (candidate[i] = ip6);
  272. break;
  273. }
  274. }
  275. lines[l] = candidate.join(' ');
  276. }
  277. }
  278. return new RTCSessionDescription({
  279. sdp: lines.join('\r\n'),
  280. type: sessionDescription.type
  281. });
  282. }