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.

xmpp.js 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. /* global $ */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import { Strophe } from 'strophe.js';
  4. import 'strophejs-plugin-disco';
  5. import RandomUtil from '../util/RandomUtil';
  6. import * as JitsiConnectionErrors from '../../JitsiConnectionErrors';
  7. import * as JitsiConnectionEvents from '../../JitsiConnectionEvents';
  8. import browser from '../browser';
  9. import initEmuc from './strophe.emuc';
  10. import initJingle from './strophe.jingle';
  11. import initStropheUtil from './strophe.util';
  12. import initPing from './strophe.ping';
  13. import initRayo from './strophe.rayo';
  14. import initStropheLogger from './strophe.logger';
  15. import Listenable from '../util/Listenable';
  16. import Caps from './Caps';
  17. const logger = getLogger(__filename);
  18. /**
  19. *
  20. * @param token
  21. * @param bosh
  22. */
  23. function createConnection(token, bosh = '/http-bind') {
  24. // Append token as URL param
  25. if (token) {
  26. // eslint-disable-next-line no-param-reassign
  27. bosh += `${bosh.indexOf('?') === -1 ? '?' : '&'}token=${token}`;
  28. }
  29. const conn = new Strophe.Connection(bosh);
  30. // The default maxRetries is 5, which is too long.
  31. conn.maxRetries = 3;
  32. return conn;
  33. }
  34. /**
  35. *
  36. */
  37. export default class XMPP extends Listenable {
  38. /**
  39. * FIXME describe all options
  40. * @param {Object} options
  41. * @param {Array<Object>} options.p2pStunServers see
  42. * {@link JingleConnectionPlugin} for more details.
  43. * @param token
  44. */
  45. constructor(options, token) {
  46. super();
  47. this.connection = null;
  48. this.disconnectInProgress = false;
  49. this.connectionTimes = {};
  50. this.options = options;
  51. this.token = token;
  52. this.authenticatedUser = false;
  53. this._initStrophePlugins(this);
  54. this.connection = createConnection(token, options.bosh);
  55. this.caps = new Caps(this.connection, this.options.clientNode);
  56. // Initialize features advertised in disco-info
  57. this.initFeaturesList();
  58. // Setup a disconnect on unload as a way to facilitate API consumers. It
  59. // sounds like they would want that. A problem for them though may be if
  60. // they wanted to utilize the connected connection in an unload handler
  61. // of their own. However, it should be fairly easy for them to do that
  62. // by registering their unload handler before us.
  63. $(window).on('beforeunload unload', this.disconnect.bind(this));
  64. }
  65. /**
  66. * Initializes the list of feature advertised through the disco-info
  67. * mechanism.
  68. */
  69. initFeaturesList() {
  70. // http://xmpp.org/extensions/xep-0167.html#support
  71. // http://xmpp.org/extensions/xep-0176.html#support
  72. this.caps.addFeature('urn:xmpp:jingle:1');
  73. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:1');
  74. this.caps.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  75. this.caps.addFeature('urn:xmpp:jingle:apps:dtls:0');
  76. this.caps.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  77. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  78. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:video');
  79. if (!this.options.disableRtx && browser.supportsRtx()) {
  80. this.caps.addFeature('urn:ietf:rfc:4588');
  81. }
  82. // this is dealt with by SDP O/A so we don't need to announce this
  83. // XEP-0293
  84. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0');
  85. // XEP-0294
  86. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0');
  87. this.caps.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  88. this.caps.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  89. // this.caps.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  90. // Enable Lipsync ?
  91. if (browser.isChrome() && this.options.enableLipSync !== false) {
  92. logger.info('Lip-sync enabled !');
  93. this.caps.addFeature('http://jitsi.org/meet/lipsync');
  94. }
  95. if (this.connection.rayo) {
  96. this.caps.addFeature('urn:xmpp:rayo:client:1');
  97. }
  98. }
  99. /**
  100. *
  101. */
  102. getConnection() {
  103. return this.connection;
  104. }
  105. /**
  106. * Receive connection status changes and handles them.
  107. *
  108. * @param {Object} credentials
  109. * @param {string} credentials.jid - The user's XMPP ID passed to the
  110. * connect method. For example, 'user@xmpp.com'.
  111. * @param {string} credentials.password - The password passed to the connect
  112. * method.
  113. * @param {string} status - One of Strophe's connection status strings.
  114. * @param {string} [msg] - The connection error message provided by Strophe.
  115. */
  116. connectionHandler(credentials = {}, status, msg) {
  117. const now = window.performance.now();
  118. const statusStr = Strophe.getStatusString(status).toLowerCase();
  119. this.connectionTimes[statusStr] = now;
  120. logger.log(
  121. `(TIME) Strophe ${statusStr}${msg ? `[${msg}]` : ''}:\t`,
  122. now);
  123. if (status === Strophe.Status.CONNECTED
  124. || status === Strophe.Status.ATTACHED) {
  125. if (this.options.useStunTurn
  126. || (this.options.p2p && this.options.p2p.useStunTurn)) {
  127. this.connection.jingle.getStunAndTurnCredentials();
  128. }
  129. logger.info(`My Jabber ID: ${this.connection.jid}`);
  130. // Schedule ping ?
  131. const pingJid = this.connection.domain;
  132. this.connection.ping.hasPingSupport(
  133. pingJid,
  134. hasPing => {
  135. if (hasPing) {
  136. this.connection.ping.startInterval(pingJid);
  137. } else {
  138. logger.warn(`Ping NOT supported by ${pingJid}`);
  139. }
  140. });
  141. if (credentials.password) {
  142. this.authenticatedUser = true;
  143. }
  144. if (this.connection && this.connection.connected
  145. && Strophe.getResourceFromJid(this.connection.jid)) {
  146. // .connected is true while connecting?
  147. // this.connection.send($pres());
  148. this.eventEmitter.emit(
  149. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  150. Strophe.getResourceFromJid(this.connection.jid));
  151. }
  152. } else if (status === Strophe.Status.CONNFAIL) {
  153. if (msg === 'x-strophe-bad-non-anon-jid') {
  154. this.anonymousConnectionFailed = true;
  155. } else {
  156. this.connectionFailed = true;
  157. }
  158. this.lastErrorMsg = msg;
  159. if (msg === 'giving-up') {
  160. this.eventEmitter.emit(
  161. JitsiConnectionEvents.CONNECTION_FAILED,
  162. JitsiConnectionErrors.OTHER_ERROR, msg);
  163. }
  164. } else if (status === Strophe.Status.DISCONNECTED) {
  165. // Stop ping interval
  166. this.connection.ping.stopInterval();
  167. const wasIntentionalDisconnect = this.disconnectInProgress;
  168. const errMsg = msg || this.lastErrorMsg;
  169. this.disconnectInProgress = false;
  170. if (this.anonymousConnectionFailed) {
  171. // prompt user for username and password
  172. this.eventEmitter.emit(
  173. JitsiConnectionEvents.CONNECTION_FAILED,
  174. JitsiConnectionErrors.PASSWORD_REQUIRED);
  175. } else if (this.connectionFailed) {
  176. this.eventEmitter.emit(
  177. JitsiConnectionEvents.CONNECTION_FAILED,
  178. JitsiConnectionErrors.OTHER_ERROR,
  179. errMsg,
  180. undefined, /* credentials */
  181. this._getConnectionFailedReasonDetails());
  182. } else if (wasIntentionalDisconnect) {
  183. this.eventEmitter.emit(
  184. JitsiConnectionEvents.CONNECTION_DISCONNECTED, errMsg);
  185. } else {
  186. // XXX if Strophe drops the connection while not being asked to,
  187. // it means that most likely some serious error has occurred.
  188. // One currently known case is when a BOSH request fails for
  189. // more than 4 times. The connection is dropped without
  190. // supplying a reason(error message/event) through the API.
  191. logger.error('XMPP connection dropped!');
  192. // XXX if the last request error is within 5xx range it means it
  193. // was a server failure
  194. const lastErrorStatus = Strophe.getLastErrorStatus();
  195. if (lastErrorStatus >= 500 && lastErrorStatus < 600) {
  196. this.eventEmitter.emit(
  197. JitsiConnectionEvents.CONNECTION_FAILED,
  198. JitsiConnectionErrors.SERVER_ERROR,
  199. errMsg || 'server-error');
  200. } else {
  201. this.eventEmitter.emit(
  202. JitsiConnectionEvents.CONNECTION_FAILED,
  203. JitsiConnectionErrors.CONNECTION_DROPPED_ERROR,
  204. errMsg || 'connection-dropped-error');
  205. }
  206. }
  207. } else if (status === Strophe.Status.AUTHFAIL) {
  208. // wrong password or username, prompt user
  209. this.eventEmitter.emit(
  210. JitsiConnectionEvents.CONNECTION_FAILED,
  211. JitsiConnectionErrors.PASSWORD_REQUIRED,
  212. msg,
  213. credentials);
  214. }
  215. }
  216. /**
  217. *
  218. * @param jid
  219. * @param password
  220. */
  221. _connect(jid, password) {
  222. // connection.connect() starts the connection process.
  223. //
  224. // As the connection process proceeds, the user supplied callback will
  225. // be triggered multiple times with status updates. The callback should
  226. // take two arguments - the status code and the error condition.
  227. //
  228. // The status code will be one of the values in the Strophe.Status
  229. // constants. The error condition will be one of the conditions defined
  230. // in RFC 3920 or the condition ‘strophe-parsererror’.
  231. //
  232. // The Parameters wait, hold and route are optional and only relevant
  233. // for BOSH connections. Please see XEP 124 for a more detailed
  234. // explanation of the optional parameters.
  235. //
  236. // Connection status constants for use by the connection handler
  237. // callback.
  238. //
  239. // Status.ERROR - An error has occurred (websockets specific)
  240. // Status.CONNECTING - The connection is currently being made
  241. // Status.CONNFAIL - The connection attempt failed
  242. // Status.AUTHENTICATING - The connection is authenticating
  243. // Status.AUTHFAIL - The authentication attempt failed
  244. // Status.CONNECTED - The connection has succeeded
  245. // Status.DISCONNECTED - The connection has been terminated
  246. // Status.DISCONNECTING - The connection is currently being terminated
  247. // Status.ATTACHED - The connection has been attached
  248. this.anonymousConnectionFailed = false;
  249. this.connectionFailed = false;
  250. this.lastErrorMsg = undefined;
  251. this.connection.connect(
  252. jid,
  253. password,
  254. this.connectionHandler.bind(this, {
  255. jid,
  256. password
  257. }));
  258. }
  259. /**
  260. * Attach to existing connection. Can be used for optimizations. For
  261. * example: if the connection is created on the server we can attach to it
  262. * and start using it.
  263. *
  264. * @param options {object} connecting options - rid, sid, jid and password.
  265. */
  266. attach(options) {
  267. const now = this.connectionTimes.attaching = window.performance.now();
  268. logger.log(`(TIME) Strophe Attaching\t:${now}`);
  269. this.connection.attach(options.jid, options.sid,
  270. parseInt(options.rid, 10) + 1,
  271. this.connectionHandler.bind(this, {
  272. jid: options.jid,
  273. password: options.password
  274. }));
  275. }
  276. /**
  277. *
  278. * @param jid
  279. * @param password
  280. */
  281. connect(jid, password) {
  282. if (!jid) {
  283. const { anonymousdomain, domain } = this.options.hosts;
  284. let configDomain = anonymousdomain || domain;
  285. // Force authenticated domain if room is appended with '?login=true'
  286. // or if we're joining with the token
  287. // FIXME Do not rely on window.location because (1) React Native
  288. // does not have a window.location by default and (2) here we cannot
  289. // know for sure that query/search has not be stripped from
  290. // window.location by the time the following executes.
  291. const { location } = window;
  292. if (anonymousdomain) {
  293. const search = location && location.search;
  294. if ((search && search.indexOf('login=true') !== -1)
  295. || this.token) {
  296. configDomain = domain;
  297. }
  298. }
  299. // eslint-disable-next-line no-param-reassign
  300. jid = configDomain || (location && location.hostname);
  301. }
  302. return this._connect(jid, password);
  303. }
  304. /**
  305. *
  306. * @param roomName
  307. * @param options
  308. */
  309. createRoom(roomName, options) {
  310. // By default MUC nickname is the resource part of the JID
  311. let mucNickname = Strophe.getNodeFromJid(this.connection.jid);
  312. let roomjid = `${roomName}@${this.options.hosts.muc}/`;
  313. const cfgNickname
  314. = options.useNicks && options.nick ? options.nick : null;
  315. if (cfgNickname) {
  316. // Use nick if it's defined
  317. mucNickname = options.nick;
  318. } else if (!this.authenticatedUser) {
  319. // node of the anonymous JID is very long - here we trim it a bit
  320. mucNickname = mucNickname.substr(0, 8);
  321. }
  322. // Constant JIDs need some random part to be appended in order to be
  323. // able to join the MUC more than once.
  324. if (this.authenticatedUser || cfgNickname !== null) {
  325. mucNickname += `-${RandomUtil.randomHexString(6)}`;
  326. }
  327. roomjid += mucNickname;
  328. return this.connection.emuc.createRoom(roomjid, null, options);
  329. }
  330. /**
  331. * Returns the logs from strophe.jingle.
  332. * @returns {Object}
  333. */
  334. getJingleLog() {
  335. const jingle = this.connection.jingle;
  336. return jingle ? jingle.getLog() : {};
  337. }
  338. /**
  339. * Returns the logs from strophe.
  340. */
  341. getXmppLog() {
  342. return (this.connection.logger || {}).log || null;
  343. }
  344. /**
  345. *
  346. */
  347. dial(...args) {
  348. this.connection.rayo.dial(...args);
  349. }
  350. /**
  351. *
  352. * @param jid
  353. * @param mute
  354. */
  355. setMute(jid, mute) {
  356. this.connection.moderate.setMute(jid, mute);
  357. }
  358. /**
  359. *
  360. * @param jid
  361. */
  362. eject(jid) {
  363. this.connection.moderate.eject(jid);
  364. }
  365. /**
  366. *
  367. */
  368. getSessions() {
  369. return this.connection.jingle.sessions;
  370. }
  371. /**
  372. * Disconnects this from the XMPP server (if this is connected).
  373. *
  374. * @param ev optionally, the event which triggered the necessity to
  375. * disconnect from the XMPP server (e.g. beforeunload, unload).
  376. */
  377. disconnect(ev) {
  378. if (this.disconnectInProgress
  379. || !this.connection
  380. || !this.connection.connected) {
  381. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  382. return;
  383. }
  384. this.disconnectInProgress = true;
  385. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  386. // means that there may not be enough time to send an unavailable
  387. // presence or disconnect at all. Switching Strophe to synchronous
  388. // sending is not much of an option because it may lead to a noticeable
  389. // delay in navigating away from the current location. As a compromise,
  390. // we will try to increase the chances of sending an unavailable
  391. // presence and/or disconecting within the short time span that we have
  392. // upon unloading by invoking flush() on the connection. We flush() once
  393. // before disconnect() in order to attemtp to have its unavailable
  394. // presence at the top of the send queue. We flush() once more after
  395. // disconnect() in order to attempt to have its unavailable presence
  396. // sent as soon as possible.
  397. this.connection.flush();
  398. if (ev !== null && typeof ev !== 'undefined') {
  399. const evType = ev.type;
  400. if (evType === 'beforeunload' || evType === 'unload') {
  401. // XXX Whatever we said above, synchronous sending is the best
  402. // (known) way to properly disconnect from the XMPP server.
  403. // Consequently, it may be fine to have the source code and
  404. // comment it in or out depending on whether we want to run with
  405. // it for some time.
  406. this.connection.options.sync = true;
  407. }
  408. }
  409. this.connection.disconnect();
  410. if (this.connection.options.sync !== true) {
  411. this.connection.flush();
  412. }
  413. }
  414. /**
  415. *
  416. */
  417. _initStrophePlugins() {
  418. const iceConfig = {
  419. jvb: { iceServers: [ ] },
  420. p2p: { iceServers: [ ] }
  421. };
  422. // FIXME: remove once we have a default config template. -saghul
  423. const defaultStunServers = [
  424. { urls: 'stun:stun.l.google.com:19302' },
  425. { urls: 'stun:stun1.l.google.com:19302' },
  426. { urls: 'stun:stun2.l.google.com:19302' }
  427. ];
  428. const p2pStunServers = (this.options.p2p
  429. && this.options.p2p.stunServers) || defaultStunServers;
  430. if (Array.isArray(p2pStunServers)) {
  431. logger.info('P2P STUN servers: ', p2pStunServers);
  432. iceConfig.p2p.iceServers = p2pStunServers;
  433. }
  434. if (this.options.p2p && this.options.p2p.iceTransportPolicy) {
  435. logger.info('P2P ICE transport policy: ',
  436. this.options.p2p.iceTransportPolicy);
  437. iceConfig.p2p.iceTransportPolicy
  438. = this.options.p2p.iceTransportPolicy;
  439. }
  440. initEmuc(this);
  441. initJingle(this, this.eventEmitter, iceConfig);
  442. initStropheUtil();
  443. initPing(this);
  444. initRayo();
  445. initStropheLogger();
  446. }
  447. /**
  448. * Returns details about connection failure. Shard change or is it after
  449. * suspend.
  450. * @returns {object} contains details about a connection failure.
  451. * @private
  452. */
  453. _getConnectionFailedReasonDetails() {
  454. const details = {};
  455. // check for moving between shard if information is available
  456. if (this.options.deploymentInfo
  457. && this.options.deploymentInfo.shard
  458. && this.connection._proto
  459. && this.connection._proto.lastResponseHeaders) {
  460. // split headers by line
  461. const headersArr = this.connection._proto.lastResponseHeaders
  462. .trim().split(/[\r\n]+/);
  463. const headers = {};
  464. headersArr.forEach(line => {
  465. const parts = line.split(': ');
  466. const header = parts.shift();
  467. const value = parts.join(': ');
  468. headers[header] = value;
  469. });
  470. /* eslint-disable camelcase */
  471. details.shard_changed
  472. = this.options.deploymentInfo.shard
  473. !== headers['x-jitsi-shard'];
  474. /* eslint-enable camelcase */
  475. }
  476. /* eslint-disable camelcase */
  477. // check for possible suspend
  478. details.suspend_time = this.connection.ping.getPingSuspendTime();
  479. /* eslint-enable camelcase */
  480. return details;
  481. }
  482. }