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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. /* global $, __filename */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import { $iq, Strophe } from 'strophe.js';
  4. import XMPPEvents from '../../service/xmpp/XMPPEvents';
  5. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  6. import RandomUtil from '../util/RandomUtil';
  7. import Statistics from '../statistics/statistics';
  8. import JingleSessionPC from './JingleSessionPC';
  9. import ConnectionPlugin from './ConnectionPlugin';
  10. const logger = getLogger(__filename);
  11. // XXX Strophe is build around the idea of chaining function calls so allow long
  12. // function call chains.
  13. /* eslint-disable newline-per-chained-call */
  14. /**
  15. *
  16. */
  17. class JingleConnectionPlugin extends ConnectionPlugin {
  18. /**
  19. * Creates new <tt>JingleConnectionPlugin</tt>
  20. * @param {XMPP} xmpp
  21. * @param {EventEmitter} eventEmitter
  22. * @param {Array<Object>} p2pStunServers an array which is part of the ice
  23. * config passed to the <tt>PeerConnection</tt> with the structure defined
  24. * by the WebRTC standard.
  25. */
  26. constructor(xmpp, eventEmitter, p2pStunServers) {
  27. super();
  28. this.xmpp = xmpp;
  29. this.eventEmitter = eventEmitter;
  30. this.sessions = {};
  31. this.jvbIceConfig = { iceServers: [ ] };
  32. this.p2pIceConfig = { iceServers: [ ] };
  33. if (Array.isArray(p2pStunServers)) {
  34. logger.info('Configured STUN servers: ', p2pStunServers);
  35. this.p2pIceConfig.iceServers = p2pStunServers;
  36. }
  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. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  115. switch (action) {
  116. case 'session-initiate': {
  117. logger.log('(TIME) received session-initiate:\t', now);
  118. const startMuted = $(iq).find('jingle>startmuted');
  119. if (startMuted && startMuted.length > 0) {
  120. const audioMuted = startMuted.attr('audio');
  121. const videoMuted = startMuted.attr('video');
  122. this.eventEmitter.emit(
  123. XMPPEvents.START_MUTED_FROM_FOCUS,
  124. audioMuted === 'true',
  125. videoMuted === 'true');
  126. }
  127. // FIXME that should work most of the time, but we'd have to
  128. // think how secure it is to assume that user with "focus"
  129. // nickname is Jicofo.
  130. const isP2P = Strophe.getResourceFromJid(fromJid) !== 'focus';
  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.xmpp.options);
  145. this.sessions[sess.sid] = sess;
  146. this.eventEmitter.emit(XMPPEvents.CALL_INCOMING,
  147. sess, $(iq).find('>jingle'), now);
  148. Statistics.analytics.sendEvent(
  149. 'xmpp.session-initiate', { value: now });
  150. break;
  151. }
  152. case 'session-accept': {
  153. this.eventEmitter.emit(
  154. XMPPEvents.CALL_ACCEPTED, sess, $(iq).find('>jingle'));
  155. break;
  156. }
  157. case 'content-modify': {
  158. sess.modifyContents($(iq).find('>jingle'));
  159. break;
  160. }
  161. case 'transport-info': {
  162. this.eventEmitter.emit(
  163. XMPPEvents.TRANSPORT_INFO, sess, $(iq).find('>jingle'));
  164. break;
  165. }
  166. case 'session-terminate': {
  167. logger.log('terminating...', sess.sid);
  168. let reasonCondition = null;
  169. let reasonText = null;
  170. if ($(iq).find('>jingle>reason').length) {
  171. reasonCondition
  172. = $(iq).find('>jingle>reason>:first')[0].tagName;
  173. reasonText = $(iq).find('>jingle>reason>text').text();
  174. }
  175. this.terminate(sess.sid, reasonCondition, reasonText);
  176. this.eventEmitter.emit(XMPPEvents.CALL_ENDED,
  177. sess, reasonCondition, reasonText);
  178. break;
  179. }
  180. case 'transport-replace':
  181. logger.info('(TIME) Start transport replace', now);
  182. Statistics.analytics.sendEvent(
  183. 'xmpp.transport-replace.start',
  184. { value: now });
  185. sess.replaceTransport($(iq).find('>jingle'), () => {
  186. const successTime = window.performance.now();
  187. logger.info('(TIME) Transport replace success!', successTime);
  188. Statistics.analytics.sendEvent(
  189. 'xmpp.transport-replace.success',
  190. { value: successTime });
  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.xmpp.options);
  236. this.sessions[sess.sid] = sess;
  237. return sess;
  238. }
  239. /**
  240. *
  241. * @param sid
  242. * @param reasonCondition
  243. * @param reasonText
  244. */
  245. terminate(sid, reasonCondition, reasonText) {
  246. if (this.sessions.hasOwnProperty(sid)) {
  247. if (this.sessions[sid].state !== 'ended') {
  248. this.sessions[sid].onTerminated(reasonCondition, reasonText);
  249. }
  250. delete this.sessions[sid];
  251. }
  252. }
  253. /**
  254. *
  255. */
  256. getStunAndTurnCredentials() {
  257. // get stun and turn configuration from server via xep-0215
  258. // uses time-limited credentials as described in
  259. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  260. //
  261. // See https://code.google.com/p/prosody-modules/source/browse/
  262. // mod_turncredentials/mod_turncredentials.lua
  263. // for a prosody module which implements this.
  264. //
  265. // Currently, this doesn't work with updateIce and therefore credentials
  266. // with a long validity have to be fetched before creating the
  267. // peerconnection.
  268. // TODO: implement refresh via updateIce as described in
  269. // https://code.google.com/p/webrtc/issues/detail?id=1650
  270. this.connection.sendIQ(
  271. $iq({ type: 'get',
  272. to: this.connection.domain })
  273. .c('services', { xmlns: 'urn:xmpp:extdisco:1' })
  274. .c('service', { host: `turn.${this.connection.domain}` }),
  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 && port !== '3478') {
  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. this.jvbIceConfig.iceServers = iceservers;
  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 p2pStunServers
  362. */
  363. export default function initJingle(XMPP, eventEmitter, p2pStunServers) {
  364. Strophe.addConnectionPlugin(
  365. 'jingle',
  366. new JingleConnectionPlugin(XMPP, eventEmitter, p2pStunServers));
  367. }