modified lib-jitsi-meet dev repo
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

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