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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /* global $, $iq, Strophe */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. const logger = getLogger(__filename);
  4. import JingleSessionPC from './JingleSessionPC';
  5. import XMPPEvents from '../../service/xmpp/XMPPEvents';
  6. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  7. import Statistics from '../statistics/statistics';
  8. import ConnectionPlugin from './ConnectionPlugin';
  9. // XXX Strophe is build around the idea of chaining function calls so allow long
  10. // function call chains.
  11. /* eslint-disable newline-per-chained-call */
  12. class JingleConnectionPlugin extends ConnectionPlugin {
  13. constructor(xmpp, eventEmitter) {
  14. super();
  15. this.xmpp = xmpp;
  16. this.eventEmitter = eventEmitter;
  17. this.sessions = {};
  18. this.ice_config = { iceServers: [] };
  19. this.media_constraints = {
  20. mandatory: {
  21. 'OfferToReceiveAudio': true,
  22. 'OfferToReceiveVideo': true
  23. }
  24. // MozDontOfferDataChannel: true when this is firefox
  25. };
  26. }
  27. init(connection) {
  28. super.init(connection);
  29. this.connection.addHandler(this.onJingle.bind(this),
  30. 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  31. }
  32. onJingle(iq) {
  33. const sid = $(iq).find('jingle').attr('sid');
  34. const action = $(iq).find('jingle').attr('action');
  35. const fromJid = iq.getAttribute('from');
  36. // send ack first
  37. const ack = $iq({ type: 'result',
  38. to: fromJid,
  39. id: iq.getAttribute('id')
  40. });
  41. logger.log(`on jingle ${action} from ${fromJid}`, iq);
  42. let sess = this.sessions[sid];
  43. if (action != 'session-initiate') {
  44. if (!sess) {
  45. ack.attrs({ type: 'error' });
  46. ack.c('error', { type: 'cancel' })
  47. .c('item-not-found', {
  48. xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas' }).up()
  49. .c('unknown-session', { xmlns: 'urn:xmpp:jingle:errors:1' });
  50. logger.warn('invalid session id', iq);
  51. this.connection.send(ack);
  52. return true;
  53. }
  54. // local jid is not checked
  55. if (fromJid != sess.peerjid) {
  56. logger.warn(
  57. 'jid mismatch for session id', sid, sess.peerjid, iq);
  58. ack.attrs({ type: 'error' });
  59. ack.c('error', { type: 'cancel' })
  60. .c('item-not-found', { xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas' }).up()
  61. .c('unknown-session', { xmlns: 'urn:xmpp:jingle:errors:1' });
  62. this.connection.send(ack);
  63. return true;
  64. }
  65. } else if (sess !== undefined) {
  66. // existing session with same session id
  67. // this might be out-of-order if the sess.peerjid is the same as from
  68. ack.attrs({ type: 'error' });
  69. ack.c('error', { type: 'cancel' })
  70. .c('service-unavailable', { xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas' }).up();
  71. logger.warn('duplicate session id', sid, iq);
  72. this.connection.send(ack);
  73. return true;
  74. }
  75. const now = window.performance.now();
  76. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  77. switch (action) {
  78. case 'session-initiate': {
  79. logger.log('(TIME) received session-initiate:\t', now);
  80. const startMuted = $(iq).find('jingle>startmuted');
  81. if (startMuted && startMuted.length > 0) {
  82. const audioMuted = startMuted.attr('audio');
  83. const videoMuted = startMuted.attr('video');
  84. this.eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  85. audioMuted === 'true', videoMuted === 'true');
  86. }
  87. sess = new JingleSessionPC(
  88. $(iq).find('jingle').attr('sid'),
  89. $(iq).attr('to'),
  90. fromJid,
  91. this.connection,
  92. this.media_constraints,
  93. this.ice_config, this.xmpp.options);
  94. this.sessions[sess.sid] = sess;
  95. this.eventEmitter.emit(XMPPEvents.CALL_INCOMING,
  96. sess, $(iq).find('>jingle'), now);
  97. Statistics.analytics.sendEvent(
  98. 'xmpp.session-initiate', { value: now });
  99. break;
  100. }
  101. case 'session-terminate': {
  102. logger.log('terminating...', sess.sid);
  103. let reasonCondition = null;
  104. let reasonText = null;
  105. if ($(iq).find('>jingle>reason').length) {
  106. reasonCondition
  107. = $(iq).find('>jingle>reason>:first')[0].tagName;
  108. reasonText = $(iq).find('>jingle>reason>text').text();
  109. }
  110. this.terminate(sess.sid, reasonCondition, reasonText);
  111. this.eventEmitter.emit(XMPPEvents.CALL_ENDED,
  112. sess, reasonCondition, reasonText);
  113. break;
  114. }
  115. case 'transport-replace':
  116. logger.info('(TIME) Start transport replace', now);
  117. Statistics.analytics.sendEvent(
  118. 'xmpp.transport-replace.start', { value: now });
  119. sess.replaceTransport($(iq).find('>jingle'), () => {
  120. const successTime = window.performance.now();
  121. logger.info(
  122. '(TIME) Transport replace success!', successTime);
  123. Statistics.analytics.sendEvent(
  124. 'xmpp.transport-replace.success',
  125. { value: successTime });
  126. }, error => {
  127. GlobalOnErrorHandler.callErrorHandler(error);
  128. logger.error('Transport replace failed', error);
  129. sess.sendTransportReject();
  130. });
  131. break;
  132. case 'addsource': // FIXME: proprietary, un-jingleish
  133. case 'source-add': // FIXME: proprietary
  134. sess.addRemoteStream($(iq).find('>jingle>content'));
  135. break;
  136. case 'removesource': // FIXME: proprietary, un-jingleish
  137. case 'source-remove': // FIXME: proprietary
  138. sess.removeRemoteStream($(iq).find('>jingle>content'));
  139. break;
  140. default:
  141. logger.warn('jingle action not implemented', action);
  142. ack.attrs({ type: 'error' });
  143. ack.c('error', { type: 'cancel' })
  144. .c('bad-request',
  145. { xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas' })
  146. .up();
  147. break;
  148. }
  149. this.connection.send(ack);
  150. return true;
  151. }
  152. terminate(sid, reasonCondition, reasonText) {
  153. if (this.sessions.hasOwnProperty(sid)) {
  154. if (this.sessions[sid].state != 'ended') {
  155. this.sessions[sid].onTerminated(reasonCondition, reasonText);
  156. }
  157. delete this.sessions[sid];
  158. }
  159. }
  160. getStunAndTurnCredentials() {
  161. // get stun and turn configuration from server via xep-0215
  162. // uses time-limited credentials as described in
  163. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  164. //
  165. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  166. // for a prosody module which implements this
  167. //
  168. // currently, this doesn't work with updateIce and therefore credentials with a long
  169. // validity have to be fetched before creating the peerconnection
  170. // TODO: implement refresh via updateIce as described in
  171. // https://code.google.com/p/webrtc/issues/detail?id=1650
  172. this.connection.sendIQ(
  173. $iq({ type: 'get',
  174. to: this.connection.domain })
  175. .c('services', { xmlns: 'urn:xmpp:extdisco:1' })
  176. .c('service', { host: `turn.${this.connection.domain}` }),
  177. res => {
  178. const iceservers = [];
  179. $(res).find('>services>service').each((idx, el) => {
  180. el = $(el);
  181. const dict = {};
  182. const type = el.attr('type');
  183. switch (type) {
  184. case 'stun':
  185. dict.url = `stun:${el.attr('host')}`;
  186. if (el.attr('port')) {
  187. dict.url += `:${el.attr('port')}`;
  188. }
  189. iceservers.push(dict);
  190. break;
  191. case 'turn':
  192. case 'turns': {
  193. dict.url = `${type}:`;
  194. const username = el.attr('username');
  195. // https://code.google.com/p/webrtc/issues/detail?id=1508
  196. if (username) {
  197. if (navigator.userAgent.match(
  198. /Chrom(e|ium)\/([0-9]+)\./)
  199. && parseInt(
  200. navigator.userAgent.match(
  201. /Chrom(e|ium)\/([0-9]+)\./)[2],
  202. 10) < 28) {
  203. dict.url += `${username}@`;
  204. } else {
  205. // only works in M28
  206. dict.username = username;
  207. }
  208. }
  209. dict.url += el.attr('host');
  210. const port = el.attr('port');
  211. if (port && port != '3478') {
  212. dict.url += `:${el.attr('port')}`;
  213. }
  214. const transport = el.attr('transport');
  215. if (transport && transport != 'udp') {
  216. dict.url += `?transport=${transport}`;
  217. }
  218. dict.credential = el.attr('password')
  219. || dict.credential;
  220. iceservers.push(dict);
  221. break;
  222. }
  223. }
  224. });
  225. this.ice_config.iceServers = iceservers;
  226. }, err => {
  227. logger.warn('getting turn credentials failed', err);
  228. logger.warn('is mod_turncredentials or similar installed?');
  229. });
  230. // implement push?
  231. }
  232. /**
  233. * Returns the data saved in 'updateLog' in a format to be logged.
  234. */
  235. getLog() {
  236. const data = {};
  237. Object.keys(this.sessions).forEach(sid => {
  238. const session = this.sessions[sid];
  239. const pc = session.peerconnection;
  240. if (pc && pc.updateLog) {
  241. // FIXME: should probably be a .dump call
  242. data[`jingle_${sid}`] = {
  243. updateLog: pc.updateLog,
  244. stats: pc.stats,
  245. url: window.location.href
  246. };
  247. }
  248. });
  249. return data;
  250. }
  251. }
  252. /* eslint-enable newline-per-chained-call */
  253. module.exports = function(XMPP, eventEmitter) {
  254. Strophe.addConnectionPlugin(
  255. 'jingle',
  256. new JingleConnectionPlugin(XMPP, eventEmitter));
  257. };