You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RTCPeerConnection.js 10.0KB

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