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.

strophe.jingle.js 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. import { getLogger } from '@jitsi/logger';
  2. import $ from 'jquery';
  3. import clonedeep from 'lodash.clonedeep';
  4. import { $iq, Strophe } from 'strophe.js';
  5. import { MediaType } from '../../service/RTC/MediaType';
  6. import {
  7. ACTION_JINGLE_TR_RECEIVED,
  8. ACTION_JINGLE_TR_SUCCESS,
  9. createJingleEvent
  10. } from '../../service/statistics/AnalyticsEvents';
  11. import { XMPPEvents } from '../../service/xmpp/XMPPEvents';
  12. import Statistics from '../statistics/statistics';
  13. import RandomUtil from '../util/RandomUtil';
  14. import ConnectionPlugin from './ConnectionPlugin';
  15. import { expandSourcesFromJson } from './JingleHelperFunctions';
  16. import JingleSessionPC from './JingleSessionPC';
  17. const logger = getLogger(__filename);
  18. // XXX Strophe is build around the idea of chaining function calls so allow long
  19. // function call chains.
  20. /* eslint-disable newline-per-chained-call */
  21. /**
  22. * Parses the transport XML element and returns the list of ICE candidates formatted as text.
  23. *
  24. * @param {*} transport Transport XML element extracted from the IQ.
  25. * @returns {Array<string>}
  26. */
  27. function _parseIceCandidates(transport) {
  28. const candidates = $(transport).find('>candidate');
  29. const parseCandidates = [];
  30. // Extract the candidate information from the IQ.
  31. candidates.each((_, candidate) => {
  32. const attributes = candidate.attributes;
  33. const candidateAttrs = [];
  34. for (let i = 0; i < attributes.length; i++) {
  35. const attr = attributes[i];
  36. candidateAttrs.push(`${attr.name}: ${attr.value}`);
  37. }
  38. parseCandidates.push(candidateAttrs.join(' '));
  39. });
  40. return parseCandidates;
  41. }
  42. /**
  43. *
  44. */
  45. export default class JingleConnectionPlugin extends ConnectionPlugin {
  46. /**
  47. * Creates new <tt>JingleConnectionPlugin</tt>
  48. * @param {XMPP} xmpp
  49. * @param {EventEmitter} eventEmitter
  50. * @param {Object} iceConfig an object that holds the iceConfig to be passed
  51. * to the p2p and the jvb <tt>PeerConnection</tt>.
  52. */
  53. constructor(xmpp, eventEmitter, iceConfig) {
  54. super();
  55. this.xmpp = xmpp;
  56. this.eventEmitter = eventEmitter;
  57. this.sessions = {};
  58. this.jvbIceConfig = iceConfig.jvb;
  59. this.p2pIceConfig = iceConfig.p2p;
  60. this.mediaConstraints = {
  61. offerToReceiveAudio: true,
  62. offerToReceiveVideo: true
  63. };
  64. }
  65. /**
  66. *
  67. * @param connection
  68. */
  69. init(connection) {
  70. super.init(connection);
  71. this.connection.addHandler(this.onJingle.bind(this),
  72. 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  73. }
  74. /**
  75. *
  76. * @param iq
  77. */
  78. onJingle(iq) {
  79. const sid = $(iq).find('jingle').attr('sid');
  80. const action = $(iq).find('jingle').attr('action');
  81. const fromJid = iq.getAttribute('from');
  82. // send ack first
  83. const ack = $iq({ type: 'result',
  84. to: fromJid,
  85. id: iq.getAttribute('id')
  86. });
  87. let sess = this.sessions[sid];
  88. if (action !== 'session-initiate') {
  89. if (!sess) {
  90. ack.attrs({ type: 'error' });
  91. ack.c('error', { type: 'cancel' })
  92. .c('item-not-found', {
  93. xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'
  94. })
  95. .up()
  96. .c('unknown-session', {
  97. xmlns: 'urn:xmpp:jingle:errors:1'
  98. });
  99. logger.warn(`invalid session id: ${sid}`);
  100. logger.debug(iq);
  101. this.connection.send(ack);
  102. return true;
  103. }
  104. // local jid is not checked
  105. if (fromJid !== sess.remoteJid) {
  106. logger.warn(
  107. 'jid mismatch for session id', sid, sess.remoteJid, iq);
  108. ack.attrs({ type: 'error' });
  109. ack.c('error', { type: 'cancel' })
  110. .c('item-not-found', {
  111. xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'
  112. })
  113. .up()
  114. .c('unknown-session', {
  115. xmlns: 'urn:xmpp:jingle:errors:1'
  116. });
  117. this.connection.send(ack);
  118. return true;
  119. }
  120. } else if (sess !== undefined) {
  121. // Existing session with same session id. This might be out-of-order
  122. // if the sess.remoteJid is the same as from.
  123. ack.attrs({ type: 'error' });
  124. ack.c('error', { type: 'cancel' })
  125. .c('service-unavailable', {
  126. xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'
  127. })
  128. .up();
  129. logger.warn('duplicate session id', sid, iq);
  130. this.connection.send(ack);
  131. return true;
  132. }
  133. const now = window.performance.now();
  134. // FIXME that should work most of the time, but we'd have to
  135. // think how secure it is to assume that user with "focus"
  136. // nickname is Jicofo.
  137. const isP2P = Strophe.getResourceFromJid(fromJid) !== 'focus';
  138. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  139. const jsonMessages = $(iq).find('jingle>json-message');
  140. if (jsonMessages?.length) {
  141. let audioVideoSsrcs;
  142. logger.info(`Found a JSON-encoded element in ${action}, translating to standard Jingle.`);
  143. for (let i = 0; i < jsonMessages.length; i++) {
  144. // Currently there is always a single json-message in the IQ with the source information.
  145. audioVideoSsrcs = expandSourcesFromJson(iq, jsonMessages[i]);
  146. }
  147. if (audioVideoSsrcs?.size) {
  148. const logMessage = [];
  149. for (const endpoint of audioVideoSsrcs.keys()) {
  150. logMessage.push(`${endpoint}:[${audioVideoSsrcs.get(endpoint)}]`);
  151. }
  152. logger.debug(`Received ${action} from ${fromJid} with sources=${logMessage.join(', ')}`);
  153. }
  154. // TODO: is there a way to remove the json-message elements once we've extracted the information?
  155. // removeChild doesn't seem to work.
  156. }
  157. switch (action) {
  158. case 'session-initiate': {
  159. logger.log('(TIME) received session-initiate:\t', now);
  160. const startMuted = $(iq).find('jingle>startmuted');
  161. isP2P && logger.debug(`Received ${action} from ${fromJid}`);
  162. if (startMuted?.length) {
  163. const audioMuted = startMuted.attr(MediaType.AUDIO);
  164. const videoMuted = startMuted.attr(MediaType.VIDEO);
  165. this.eventEmitter.emit(
  166. XMPPEvents.START_MUTED_FROM_FOCUS,
  167. audioMuted === 'true',
  168. videoMuted === 'true');
  169. }
  170. const pcConfig = isP2P ? this.p2pIceConfig : this.jvbIceConfig;
  171. sess
  172. = new JingleSessionPC(
  173. $(iq).find('jingle').attr('sid'),
  174. $(iq).attr('to'),
  175. fromJid,
  176. this.connection,
  177. this.mediaConstraints,
  178. clonedeep(pcConfig),
  179. isP2P,
  180. /* initiator */ false);
  181. this.sessions[sess.sid] = sess;
  182. this.eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess, $(iq).find('>jingle'), now);
  183. break;
  184. }
  185. case 'session-accept': {
  186. const ssrcs = [];
  187. const contents = $(iq).find('jingle>content');
  188. // Extract the SSRCs from the session-accept received from a p2p peer.
  189. for (const content of contents) {
  190. const ssrc = $(content).find('description').attr('ssrc');
  191. ssrc && ssrcs.push(ssrc);
  192. }
  193. logger.debug(`Received ${action} from ${fromJid} with ssrcs=${ssrcs}`);
  194. this.eventEmitter.emit(XMPPEvents.CALL_ACCEPTED, sess, $(iq).find('>jingle'));
  195. break;
  196. }
  197. case 'content-modify': {
  198. logger.debug(`Received ${action} from ${fromJid}`);
  199. sess.modifyContents($(iq).find('>jingle'));
  200. break;
  201. }
  202. case 'transport-info': {
  203. const candidates = _parseIceCandidates($(iq).find('jingle>content>transport'));
  204. logger.debug(`Received ${action} from ${fromJid} for candidates=${candidates.join(', ')}`);
  205. this.eventEmitter.emit(XMPPEvents.TRANSPORT_INFO, sess, $(iq).find('>jingle'));
  206. break;
  207. }
  208. case 'session-terminate': {
  209. logger.log('terminating...', sess.sid);
  210. let reasonCondition = null;
  211. let reasonText = null;
  212. if ($(iq).find('>jingle>reason').length) {
  213. reasonCondition
  214. = $(iq).find('>jingle>reason>:first')[0].tagName;
  215. reasonText = $(iq).find('>jingle>reason>text').text();
  216. }
  217. logger.debug(`Received ${action} from ${fromJid} disconnect reason=${reasonText}`);
  218. this.terminate(sess.sid, reasonCondition, reasonText);
  219. this.eventEmitter.emit(XMPPEvents.CALL_ENDED, sess, reasonCondition, reasonText);
  220. break;
  221. }
  222. case 'transport-replace': {
  223. logger.info('(TIME) Start transport replace:\t', now);
  224. const transport = $(iq).find('jingle>content>transport');
  225. const candidates = _parseIceCandidates(transport);
  226. const iceUfrag = $(transport).attr('ufrag');
  227. const icePwd = $(transport).attr('pwd');
  228. const dtlsFingerprint = $(transport).find('>fingerprint')?.text();
  229. logger.debug(`Received ${action} from ${fromJid} with iceUfrag=${iceUfrag},`
  230. + ` icePwd=${icePwd}, DTLS fingerprint=${dtlsFingerprint}, candidates=${candidates.join(', ')}`);
  231. Statistics.sendAnalytics(createJingleEvent(
  232. ACTION_JINGLE_TR_RECEIVED,
  233. {
  234. p2p: isP2P,
  235. value: now
  236. }));
  237. sess.replaceTransport($(iq).find('>jingle'), () => {
  238. const successTime = window.performance.now();
  239. logger.info('(TIME) Transport replace success:\t', successTime);
  240. Statistics.sendAnalytics(createJingleEvent(
  241. ACTION_JINGLE_TR_SUCCESS,
  242. {
  243. p2p: isP2P,
  244. value: successTime
  245. }));
  246. }, error => {
  247. logger.error('Transport replace failed', error);
  248. sess.sendTransportReject();
  249. });
  250. break;
  251. }
  252. case 'source-add':
  253. sess.addRemoteStream($(iq).find('>jingle>content'));
  254. break;
  255. case 'source-remove':
  256. sess.removeRemoteStream($(iq).find('>jingle>content'));
  257. break;
  258. default:
  259. logger.warn('jingle action not implemented', action);
  260. ack.attrs({ type: 'error' });
  261. ack.c('error', { type: 'cancel' })
  262. .c('bad-request',
  263. { xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas' })
  264. .up();
  265. break;
  266. }
  267. this.connection.send(ack);
  268. return true;
  269. }
  270. /**
  271. * Creates new <tt>JingleSessionPC</tt> meant to be used in a direct P2P
  272. * connection, configured as 'initiator'.
  273. * @param {string} me our JID
  274. * @param {string} peer remote participant's JID
  275. * @return {JingleSessionPC}
  276. */
  277. newP2PJingleSession(me, peer) {
  278. const sess
  279. = new JingleSessionPC(
  280. RandomUtil.randomHexString(12),
  281. me,
  282. peer,
  283. this.connection,
  284. this.mediaConstraints,
  285. this.p2pIceConfig,
  286. /* P2P */ true,
  287. /* initiator */ true);
  288. this.sessions[sess.sid] = sess;
  289. return sess;
  290. }
  291. /**
  292. *
  293. * @param sid
  294. * @param reasonCondition
  295. * @param reasonText
  296. */
  297. terminate(sid, reasonCondition, reasonText) {
  298. if (this.sessions.hasOwnProperty(sid)) {
  299. if (this.sessions[sid].state !== 'ended') {
  300. this.sessions[sid].onTerminated(reasonCondition, reasonText);
  301. }
  302. delete this.sessions[sid];
  303. }
  304. }
  305. /**
  306. *
  307. */
  308. getStunAndTurnCredentials() {
  309. // get stun and turn configuration from server via xep-0215
  310. // uses time-limited credentials as described in
  311. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  312. //
  313. // See https://modules.prosody.im/mod_turncredentials.html
  314. // for a prosody module which implements this.
  315. // Or the new implementation https://modules.prosody.im/mod_external_services which will be in prosody 0.12
  316. //
  317. // Currently, this doesn't work with updateIce and therefore credentials
  318. // with a long validity have to be fetched before creating the
  319. // peerconnection.
  320. // TODO: implement refresh via updateIce as described in
  321. // https://code.google.com/p/webrtc/issues/detail?id=1650
  322. this.connection.sendIQ(
  323. $iq({ type: 'get',
  324. to: this.xmpp.options.hosts.domain })
  325. .c('services', { xmlns: 'urn:xmpp:extdisco:2' }),
  326. v2Res => this.onReceiveStunAndTurnCredentials(v2Res),
  327. () => {
  328. logger.warn('getting turn credentials with extdisco:2 failed, trying extdisco:1');
  329. this.connection.sendIQ(
  330. $iq({ type: 'get',
  331. to: this.xmpp.options.hosts.domain })
  332. .c('services', { xmlns: 'urn:xmpp:extdisco:1' }),
  333. v1Res => this.onReceiveStunAndTurnCredentials(v1Res),
  334. () => {
  335. logger.warn('getting turn credentials failed');
  336. logger.warn('is mod_turncredentials or similar installed and configured?');
  337. }
  338. );
  339. });
  340. }
  341. /**
  342. * Parses response when querying for services using urn:xmpp:extdisco:1 or urn:xmpp:extdisco:2.
  343. * Stores results in jvbIceConfig and p2pIceConfig.
  344. * @param res The response iq.
  345. * @return {boolean} Whether something was processed from the supplied message.
  346. */
  347. onReceiveStunAndTurnCredentials(res) {
  348. let iceservers = [];
  349. $(res).find('>services>service').each((idx, el) => {
  350. // eslint-disable-next-line no-param-reassign
  351. el = $(el);
  352. const dict = {};
  353. const type = el.attr('type');
  354. switch (type) {
  355. case 'stun':
  356. dict.urls = `stun:${el.attr('host')}`;
  357. if (el.attr('port')) {
  358. dict.urls += `:${el.attr('port')}`;
  359. }
  360. iceservers.push(dict);
  361. break;
  362. case 'turn':
  363. case 'turns': {
  364. dict.urls = `${type}:`;
  365. dict.username = el.attr('username');
  366. dict.urls += el.attr('host');
  367. const port = el.attr('port');
  368. if (port) {
  369. dict.urls += `:${port}`;
  370. }
  371. const transport = el.attr('transport');
  372. if (transport && transport !== 'udp') {
  373. dict.urls += `?transport=${transport}`;
  374. }
  375. dict.credential = el.attr('password') || dict.credential;
  376. iceservers.push(dict);
  377. break;
  378. }
  379. }
  380. });
  381. const options = this.xmpp.options;
  382. const { iceServersOverride = [] } = options;
  383. iceServersOverride.forEach(({ targetType, urls, username, credential }) => {
  384. if (![ 'turn', 'turns', 'stun' ].includes(targetType)) {
  385. return;
  386. }
  387. const pattern = `${targetType}:`;
  388. if (typeof urls === 'undefined'
  389. && typeof username === 'undefined'
  390. && typeof credential === 'undefined') {
  391. return;
  392. }
  393. if (urls === null) { // remove this type of ice server
  394. iceservers = iceservers.filter(server => !server.urls.startsWith(pattern));
  395. }
  396. iceservers.forEach(server => {
  397. if (!server.urls.startsWith(pattern)) {
  398. return;
  399. }
  400. server.urls = urls ?? server.urls;
  401. if (username === null) {
  402. delete server.username;
  403. } else {
  404. server.username = username ?? server.username;
  405. }
  406. if (credential === null) {
  407. delete server.credential;
  408. } else {
  409. server.credential = credential ?? server.credential;
  410. }
  411. });
  412. });
  413. // Shuffle ICEServers for loadbalancing
  414. for (let i = iceservers.length - 1; i > 0; i--) {
  415. const j = Math.floor(Math.random() * (i + 1));
  416. const temp = iceservers[i];
  417. iceservers[i] = iceservers[j];
  418. iceservers[j] = temp;
  419. }
  420. let filter;
  421. if (options.useTurnUdp) {
  422. filter = s => s.urls.startsWith('turn');
  423. } else {
  424. // By default we filter out STUN and TURN/UDP and leave only TURN/TCP.
  425. filter = s => s.urls.startsWith('turn') && (s.urls.indexOf('transport=tcp') >= 0);
  426. }
  427. this.jvbIceConfig.iceServers = iceservers.filter(filter);
  428. this.p2pIceConfig.iceServers = iceservers;
  429. return iceservers.length > 0;
  430. }
  431. /**
  432. * Returns the data saved in 'updateLog' in a format to be logged.
  433. */
  434. getLog() {
  435. const data = {};
  436. Object.keys(this.sessions).forEach(sid => {
  437. const session = this.sessions[sid];
  438. const pc = session.peerconnection;
  439. if (pc && pc.updateLog) {
  440. // FIXME: should probably be a .dump call
  441. data[`jingle_${sid}`] = {
  442. updateLog: pc.updateLog,
  443. stats: pc.stats,
  444. url: window.location.href
  445. };
  446. }
  447. });
  448. return data;
  449. }
  450. }
  451. /* eslint-enable newline-per-chained-call */