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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. /* global $, __filename */
  2. import {
  3. ACTION_JINGLE_TR_RECEIVED,
  4. ACTION_JINGLE_TR_SUCCESS,
  5. createJingleEvent
  6. } from '../../service/statistics/AnalyticsEvents';
  7. import { getLogger } from 'jitsi-meet-logger';
  8. import { $iq, Strophe } from 'strophe.js';
  9. import XMPPEvents from '../../service/xmpp/XMPPEvents';
  10. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  11. import RandomUtil from '../util/RandomUtil';
  12. import Statistics from '../statistics/statistics';
  13. import JingleSessionPC from './JingleSessionPC';
  14. import ConnectionPlugin from './ConnectionPlugin';
  15. const logger = getLogger(__filename);
  16. // XXX Strophe is build around the idea of chaining function calls so allow long
  17. // function call chains.
  18. /* eslint-disable newline-per-chained-call */
  19. /**
  20. *
  21. */
  22. class JingleConnectionPlugin extends ConnectionPlugin {
  23. /**
  24. * Creates new <tt>JingleConnectionPlugin</tt>
  25. * @param {XMPP} xmpp
  26. * @param {EventEmitter} eventEmitter
  27. * @param {Object} iceConfig an object that holds the iceConfig to be passed
  28. * to the p2p and the jvb <tt>PeerConnection</tt>.
  29. */
  30. constructor(xmpp, eventEmitter, iceConfig) {
  31. super();
  32. this.xmpp = xmpp;
  33. this.eventEmitter = eventEmitter;
  34. this.sessions = {};
  35. this.jvbIceConfig = iceConfig.jvb;
  36. this.p2pIceConfig = iceConfig.p2p;
  37. this.mediaConstraints = {
  38. offerToReceiveAudio: true,
  39. offerToReceiveVideo: true
  40. };
  41. }
  42. /**
  43. *
  44. * @param connection
  45. */
  46. init(connection) {
  47. super.init(connection);
  48. this.connection.addHandler(this.onJingle.bind(this),
  49. 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  50. }
  51. /**
  52. *
  53. * @param iq
  54. */
  55. onJingle(iq) {
  56. const sid = $(iq).find('jingle').attr('sid');
  57. const action = $(iq).find('jingle').attr('action');
  58. const fromJid = iq.getAttribute('from');
  59. // send ack first
  60. const ack = $iq({ type: 'result',
  61. to: fromJid,
  62. id: iq.getAttribute('id')
  63. });
  64. logger.log(`on jingle ${action} from ${fromJid}`, iq);
  65. let sess = this.sessions[sid];
  66. if (action !== 'session-initiate') {
  67. if (!sess) {
  68. ack.attrs({ type: 'error' });
  69. ack.c('error', { type: 'cancel' })
  70. .c('item-not-found', {
  71. xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'
  72. })
  73. .up()
  74. .c('unknown-session', {
  75. xmlns: 'urn:xmpp:jingle:errors:1'
  76. });
  77. logger.warn('invalid session id', iq);
  78. this.connection.send(ack);
  79. return true;
  80. }
  81. // local jid is not checked
  82. if (fromJid !== sess.remoteJid) {
  83. logger.warn(
  84. 'jid mismatch for session id', sid, sess.remoteJid, iq);
  85. ack.attrs({ type: 'error' });
  86. ack.c('error', { type: 'cancel' })
  87. .c('item-not-found', {
  88. xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'
  89. })
  90. .up()
  91. .c('unknown-session', {
  92. xmlns: 'urn:xmpp:jingle:errors:1'
  93. });
  94. this.connection.send(ack);
  95. return true;
  96. }
  97. } else if (sess !== undefined) {
  98. // Existing session with same session id. This might be out-of-order
  99. // if the sess.remoteJid is the same as from.
  100. ack.attrs({ type: 'error' });
  101. ack.c('error', { type: 'cancel' })
  102. .c('service-unavailable', {
  103. xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'
  104. })
  105. .up();
  106. logger.warn('duplicate session id', sid, iq);
  107. this.connection.send(ack);
  108. return true;
  109. }
  110. const now = window.performance.now();
  111. // FIXME that should work most of the time, but we'd have to
  112. // think how secure it is to assume that user with "focus"
  113. // nickname is Jicofo.
  114. const isP2P = Strophe.getResourceFromJid(fromJid) !== 'focus';
  115. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  116. switch (action) {
  117. case 'session-initiate': {
  118. logger.log('(TIME) received session-initiate:\t', now);
  119. const startMuted = $(iq).find('jingle>startmuted');
  120. if (startMuted && startMuted.length > 0) {
  121. const audioMuted = startMuted.attr('audio');
  122. const videoMuted = startMuted.attr('video');
  123. this.eventEmitter.emit(
  124. XMPPEvents.START_MUTED_FROM_FOCUS,
  125. audioMuted === 'true',
  126. videoMuted === 'true');
  127. }
  128. logger.info(
  129. `Marking session from ${fromJid
  130. } as ${isP2P ? '' : '*not*'} P2P`);
  131. sess
  132. = new JingleSessionPC(
  133. $(iq).find('jingle').attr('sid'),
  134. $(iq).attr('to'),
  135. fromJid,
  136. this.connection,
  137. this.mediaConstraints,
  138. isP2P ? this.p2pIceConfig : this.jvbIceConfig,
  139. isP2P,
  140. /* initiator */ false);
  141. this.sessions[sess.sid] = sess;
  142. this.eventEmitter.emit(XMPPEvents.CALL_INCOMING,
  143. sess, $(iq).find('>jingle'), now);
  144. break;
  145. }
  146. case 'session-accept': {
  147. this.eventEmitter.emit(
  148. XMPPEvents.CALL_ACCEPTED, sess, $(iq).find('>jingle'));
  149. break;
  150. }
  151. case 'content-modify': {
  152. sess.modifyContents($(iq).find('>jingle'));
  153. break;
  154. }
  155. case 'transport-info': {
  156. this.eventEmitter.emit(
  157. XMPPEvents.TRANSPORT_INFO, sess, $(iq).find('>jingle'));
  158. break;
  159. }
  160. case 'session-terminate': {
  161. logger.log('terminating...', sess.sid);
  162. let reasonCondition = null;
  163. let reasonText = null;
  164. if ($(iq).find('>jingle>reason').length) {
  165. reasonCondition
  166. = $(iq).find('>jingle>reason>:first')[0].tagName;
  167. reasonText = $(iq).find('>jingle>reason>text').text();
  168. }
  169. this.terminate(sess.sid, reasonCondition, reasonText);
  170. this.eventEmitter.emit(XMPPEvents.CALL_ENDED,
  171. sess, reasonCondition, reasonText);
  172. break;
  173. }
  174. case 'transport-replace':
  175. logger.info('(TIME) Start transport replace', now);
  176. Statistics.sendAnalytics(createJingleEvent(
  177. ACTION_JINGLE_TR_RECEIVED,
  178. {
  179. p2p: isP2P,
  180. value: now
  181. }));
  182. sess.replaceTransport($(iq).find('>jingle'), () => {
  183. const successTime = window.performance.now();
  184. logger.info('(TIME) Transport replace success!', successTime);
  185. Statistics.sendAnalytics(createJingleEvent(
  186. ACTION_JINGLE_TR_SUCCESS,
  187. {
  188. p2p: isP2P,
  189. value: successTime
  190. }));
  191. }, error => {
  192. GlobalOnErrorHandler.callErrorHandler(error);
  193. logger.error('Transport replace failed', error);
  194. sess.sendTransportReject();
  195. });
  196. break;
  197. case 'addsource': // FIXME: proprietary, un-jingleish
  198. case 'source-add': // FIXME: proprietary
  199. sess.addRemoteStream($(iq).find('>jingle>content'));
  200. break;
  201. case 'removesource': // FIXME: proprietary, un-jingleish
  202. case 'source-remove': // FIXME: proprietary
  203. sess.removeRemoteStream($(iq).find('>jingle>content'));
  204. break;
  205. default:
  206. logger.warn('jingle action not implemented', action);
  207. ack.attrs({ type: 'error' });
  208. ack.c('error', { type: 'cancel' })
  209. .c('bad-request',
  210. { xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas' })
  211. .up();
  212. break;
  213. }
  214. this.connection.send(ack);
  215. return true;
  216. }
  217. /**
  218. * Creates new <tt>JingleSessionPC</tt> meant to be used in a direct P2P
  219. * connection, configured as 'initiator'.
  220. * @param {string} me our JID
  221. * @param {string} peer remote participant's JID
  222. * @return {JingleSessionPC}
  223. */
  224. newP2PJingleSession(me, peer) {
  225. const sess
  226. = new JingleSessionPC(
  227. RandomUtil.randomHexString(12),
  228. me,
  229. peer,
  230. this.connection,
  231. this.mediaConstraints,
  232. this.p2pIceConfig,
  233. /* P2P */ true,
  234. /* initiator */ true);
  235. this.sessions[sess.sid] = sess;
  236. return sess;
  237. }
  238. /**
  239. *
  240. * @param sid
  241. * @param reasonCondition
  242. * @param reasonText
  243. */
  244. terminate(sid, reasonCondition, reasonText) {
  245. if (this.sessions.hasOwnProperty(sid)) {
  246. if (this.sessions[sid].state !== 'ended') {
  247. this.sessions[sid].onTerminated(reasonCondition, reasonText);
  248. }
  249. delete this.sessions[sid];
  250. }
  251. }
  252. /**
  253. *
  254. */
  255. getStunAndTurnCredentials() {
  256. // get stun and turn configuration from server via xep-0215
  257. // uses time-limited credentials as described in
  258. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  259. //
  260. // See https://modules.prosody.im/mod_turncredentials.html
  261. // for a prosody module which implements this.
  262. //
  263. // Currently, this doesn't work with updateIce and therefore credentials
  264. // with a long validity have to be fetched before creating the
  265. // peerconnection.
  266. // TODO: implement refresh via updateIce as described in
  267. // https://code.google.com/p/webrtc/issues/detail?id=1650
  268. this.connection.sendIQ(
  269. $iq({ type: 'get',
  270. to: this.connection.domain })
  271. .c('services', { xmlns: 'urn:xmpp:extdisco:1' }),
  272. res => {
  273. const iceservers = [];
  274. $(res).find('>services>service').each((idx, el) => {
  275. // eslint-disable-next-line no-param-reassign
  276. el = $(el);
  277. const dict = {};
  278. const type = el.attr('type');
  279. switch (type) {
  280. case 'stun':
  281. dict.url = `stun:${el.attr('host')}`;
  282. if (el.attr('port')) {
  283. dict.url += `:${el.attr('port')}`;
  284. }
  285. iceservers.push(dict);
  286. break;
  287. case 'turn':
  288. case 'turns': {
  289. dict.url = `${type}:`;
  290. const username = el.attr('username');
  291. // https://code.google.com/p/webrtc/issues/detail
  292. // ?id=1508
  293. if (username) {
  294. const match
  295. = navigator.userAgent.match(
  296. /Chrom(e|ium)\/([0-9]+)\./);
  297. if (match && parseInt(match[2], 10) < 28) {
  298. dict.url += `${username}@`;
  299. } else {
  300. // only works in M28
  301. dict.username = username;
  302. }
  303. }
  304. dict.url += el.attr('host');
  305. const port = el.attr('port');
  306. if (port) {
  307. dict.url += `:${el.attr('port')}`;
  308. }
  309. const transport = el.attr('transport');
  310. if (transport && transport !== 'udp') {
  311. dict.url += `?transport=${transport}`;
  312. }
  313. dict.credential = el.attr('password')
  314. || dict.credential;
  315. iceservers.push(dict);
  316. break;
  317. }
  318. }
  319. });
  320. const options = this.xmpp.options;
  321. if (options.useStunTurn) {
  322. // we want to filter and leave only tcp/turns candidates
  323. // which make sense for the jvb connections
  324. this.jvbIceConfig.iceServers
  325. = iceservers.filter(s => s.url.startsWith('turns'));
  326. }
  327. if (options.p2p && options.p2p.useStunTurn) {
  328. this.p2pIceConfig.iceServers = iceservers;
  329. }
  330. }, err => {
  331. logger.warn('getting turn credentials failed', err);
  332. logger.warn('is mod_turncredentials or similar installed?');
  333. });
  334. // implement push?
  335. }
  336. /**
  337. * Returns the data saved in 'updateLog' in a format to be logged.
  338. */
  339. getLog() {
  340. const data = {};
  341. Object.keys(this.sessions).forEach(sid => {
  342. const session = this.sessions[sid];
  343. const pc = session.peerconnection;
  344. if (pc && pc.updateLog) {
  345. // FIXME: should probably be a .dump call
  346. data[`jingle_${sid}`] = {
  347. updateLog: pc.updateLog,
  348. stats: pc.stats,
  349. url: window.location.href
  350. };
  351. }
  352. });
  353. return data;
  354. }
  355. }
  356. /* eslint-enable newline-per-chained-call */
  357. /**
  358. *
  359. * @param XMPP
  360. * @param eventEmitter
  361. * @param iceConfig
  362. */
  363. export default function initJingle(XMPP, eventEmitter, iceConfig) {
  364. Strophe.addConnectionPlugin(
  365. 'jingle',
  366. new JingleConnectionPlugin(XMPP, eventEmitter, iceConfig));
  367. }