Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

XmppConnection.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. import { getLogger } from 'jitsi-meet-logger';
  2. import { $pres, Strophe } from 'strophe.js';
  3. import 'strophejs-plugin-stream-management';
  4. import Listenable from '../util/Listenable';
  5. import ResumeTask from './ResumeTask';
  6. import LastSuccessTracker from './StropheLastSuccess';
  7. import PingConnectionPlugin from './strophe.ping';
  8. const logger = getLogger(__filename);
  9. /**
  10. * The lib-jitsi-meet layer for {@link Strophe.Connection}.
  11. */
  12. export default class XmppConnection extends Listenable {
  13. /**
  14. * The list of {@link XmppConnection} events.
  15. *
  16. * @returns {Object}
  17. */
  18. static get Events() {
  19. return {
  20. CONN_STATUS_CHANGED: 'CONN_STATUS_CHANGED',
  21. CONN_SHARD_CHANGED: 'CONN_SHARD_CHANGED'
  22. };
  23. }
  24. /**
  25. * The list of Xmpp connection statuses.
  26. *
  27. * @returns {Strophe.Status}
  28. */
  29. static get Status() {
  30. return Strophe.Status;
  31. }
  32. /**
  33. * Initializes new connection instance.
  34. *
  35. * @param {Object} options
  36. * @param {String} options.serviceUrl - The BOSH or WebSocket service URL.
  37. * @param {String} options.shard - The BOSH or WebSocket is connecting to this shard.
  38. * Useful for detecting when shard changes.
  39. * @param {String} [options.enableWebsocketResume=true] - True/false to control the stream resumption functionality.
  40. * It will enable automatically by default if supported by the XMPP server.
  41. * @param {Number} [options.websocketKeepAlive=60000] - The websocket keep alive interval.
  42. * It's the interval + a up to a minute of jitter. Pass -1 to disable.
  43. * The keep alive is HTTP GET request to {@link options.serviceUrl} or to {@link options.websocketKeepAliveUrl}.
  44. * @param {Number} [options.websocketKeepAliveUrl] - The websocket keep alive url to use if any,
  45. * if missing the serviceUrl url will be used.
  46. * @param {Object} [options.xmppPing] - The xmpp ping settings.
  47. */
  48. constructor({ enableWebsocketResume, websocketKeepAlive, websocketKeepAliveUrl, serviceUrl, shard, xmppPing }) {
  49. super();
  50. this._options = {
  51. enableWebsocketResume: typeof enableWebsocketResume === 'undefined' ? true : enableWebsocketResume,
  52. pingOptions: xmppPing,
  53. shard,
  54. websocketKeepAlive: typeof websocketKeepAlive === 'undefined' ? 60 * 1000 : Number(websocketKeepAlive),
  55. websocketKeepAliveUrl
  56. };
  57. this._stropheConn = new Strophe.Connection(serviceUrl);
  58. this._usesWebsocket = serviceUrl.startsWith('ws:') || serviceUrl.startsWith('wss:');
  59. // The default maxRetries is 5, which is too long.
  60. this._stropheConn.maxRetries = 3;
  61. this._rawInputTracker = new LastSuccessTracker();
  62. this._rawInputTracker.startTracking(this, this._stropheConn);
  63. this._resumeTask = new ResumeTask(this._stropheConn);
  64. /**
  65. * @typedef DeferredSendIQ Object
  66. * @property {Element} iq - The IQ to send.
  67. * @property {function} resolve - The resolve method of the deferred Promise.
  68. * @property {function} reject - The reject method of the deferred Promise.
  69. * @property {number} timeout - The ID of the timeout task that needs to be cleared, before sending the IQ.
  70. */
  71. /**
  72. * Deferred IQs to be sent upon reconnect.
  73. * @type {Array<DeferredSendIQ>}
  74. * @private
  75. */
  76. this._deferredIQs = [];
  77. // Ping plugin is mandatory for the Websocket mode to work correctly. It's used to detect when the connection
  78. // is broken (WebSocket/TCP connection not closed gracefully).
  79. this.addConnectionPlugin(
  80. 'ping',
  81. new PingConnectionPlugin({
  82. getTimeSinceLastServerResponse: () => this.getTimeSinceLastSuccess(),
  83. onPingThresholdExceeded: () => this._onPingErrorThresholdExceeded(),
  84. pingOptions: xmppPing
  85. }));
  86. // tracks whether this is the initial connection or a reconnect
  87. this._oneSuccessfulConnect = false;
  88. }
  89. /**
  90. * A getter for the connected state.
  91. *
  92. * @returns {boolean}
  93. */
  94. get connected() {
  95. const websocket = this._stropheConn && this._stropheConn._proto && this._stropheConn._proto.socket;
  96. return (this._status === Strophe.Status.CONNECTED || this._status === Strophe.Status.ATTACHED)
  97. && (!this.isUsingWebSocket || (websocket && websocket.readyState === WebSocket.OPEN));
  98. }
  99. /**
  100. * Retrieves the feature discovery plugin instance.
  101. *
  102. * @returns {Strophe.Connection.disco}
  103. */
  104. get disco() {
  105. return this._stropheConn.disco;
  106. }
  107. /**
  108. * A getter for the disconnecting state.
  109. *
  110. * @returns {boolean}
  111. */
  112. get disconnecting() {
  113. return this._stropheConn.disconnecting === true;
  114. }
  115. /**
  116. * A getter for the domain.
  117. *
  118. * @returns {string|null}
  119. */
  120. get domain() {
  121. return this._stropheConn.domain;
  122. }
  123. /**
  124. * Tells if Websocket is used as the transport for the current XMPP connection. Returns true for Websocket or false
  125. * for BOSH.
  126. * @returns {boolean}
  127. */
  128. get isUsingWebSocket() {
  129. return this._usesWebsocket;
  130. }
  131. /**
  132. * A getter for the JID.
  133. *
  134. * @returns {string|null}
  135. */
  136. get jid() {
  137. return this._stropheConn.jid;
  138. }
  139. /**
  140. * Returns headers for the last BOSH response received.
  141. *
  142. * @returns {string}
  143. */
  144. get lastResponseHeaders() {
  145. return this._stropheConn._proto && this._stropheConn._proto.lastResponseHeaders;
  146. }
  147. /**
  148. * A getter for the logger plugin instance.
  149. *
  150. * @returns {*}
  151. */
  152. get logger() {
  153. return this._stropheConn.logger;
  154. }
  155. /**
  156. * A getter for the connection options.
  157. *
  158. * @returns {*}
  159. */
  160. get options() {
  161. return this._stropheConn.options;
  162. }
  163. /**
  164. * A getter for the domain to be used for ping.
  165. */
  166. get pingDomain() {
  167. return this._options.pingOptions?.domain || this.domain;
  168. }
  169. /**
  170. * A getter for the service URL.
  171. *
  172. * @returns {string}
  173. */
  174. get service() {
  175. return this._stropheConn.service;
  176. }
  177. /**
  178. * Returns the current connection status.
  179. *
  180. * @returns {Strophe.Status}
  181. */
  182. get status() {
  183. return this._status;
  184. }
  185. /**
  186. * Adds a connection plugin to this instance.
  187. *
  188. * @param {string} name - The name of the plugin or rather a key under which it will be stored on this connection
  189. * instance.
  190. * @param {ConnectionPluginListenable} plugin - The plugin to add.
  191. */
  192. addConnectionPlugin(name, plugin) {
  193. this[name] = plugin;
  194. plugin.init(this);
  195. }
  196. /**
  197. * See {@link Strophe.Connection.addHandler}
  198. *
  199. * @returns {void}
  200. */
  201. addHandler(...args) {
  202. this._stropheConn.addHandler(...args);
  203. }
  204. /* eslint-disable max-params */
  205. /**
  206. * Wraps {@link Strophe.Connection.attach} method in order to intercept the connection status updates.
  207. * See {@link Strophe.Connection.attach} for the params description.
  208. *
  209. * @returns {void}
  210. */
  211. attach(jid, sid, rid, callback, ...args) {
  212. this._stropheConn.attach(jid, sid, rid, this._stropheConnectionCb.bind(this, callback), ...args);
  213. }
  214. /**
  215. * Wraps Strophe.Connection.connect method in order to intercept the connection status updates.
  216. * See {@link Strophe.Connection.connect} for the params description.
  217. *
  218. * @returns {void}
  219. */
  220. connect(jid, pass, callback, ...args) {
  221. this._stropheConn.connect(jid, pass, this._stropheConnectionCb.bind(this, callback), ...args);
  222. }
  223. /* eslint-enable max-params */
  224. /**
  225. * Handles {@link Strophe.Status} updates for the current connection.
  226. *
  227. * @param {function} targetCallback - The callback passed by the {@link XmppConnection} consumer to one of
  228. * the connect methods.
  229. * @param {Strophe.Status} status - The new connection status.
  230. * @param {*} args - The rest of the arguments passed by Strophe.
  231. * @private
  232. */
  233. _stropheConnectionCb(targetCallback, status, ...args) {
  234. this._status = status;
  235. let blockCallback = false;
  236. if (status === Strophe.Status.CONNECTED || status === Strophe.Status.ATTACHED) {
  237. this._maybeEnableStreamResume();
  238. // after connecting - immediately check whether shard changed,
  239. // we need this only when using websockets as bosh checks headers from every response
  240. if (this._usesWebsocket && this._oneSuccessfulConnect) {
  241. this._keepAliveAndCheckShard();
  242. }
  243. this._oneSuccessfulConnect = true;
  244. this._maybeStartWSKeepAlive();
  245. this._processDeferredIQs();
  246. this._resumeTask.cancel();
  247. this.ping.startInterval(this._options.pingOptions?.domain || this.domain);
  248. } else if (status === Strophe.Status.DISCONNECTED) {
  249. this.ping.stopInterval();
  250. // FIXME add RECONNECTING state instead of blocking the DISCONNECTED update
  251. blockCallback = this._tryResumingConnection();
  252. if (!blockCallback) {
  253. clearTimeout(this._wsKeepAlive);
  254. }
  255. }
  256. if (!blockCallback) {
  257. targetCallback(status, ...args);
  258. this.eventEmitter.emit(XmppConnection.Events.CONN_STATUS_CHANGED, status);
  259. }
  260. }
  261. /**
  262. * Clears the list of IQs and rejects deferred Promises with an error.
  263. *
  264. * @private
  265. */
  266. _clearDeferredIQs() {
  267. for (const deferred of this._deferredIQs) {
  268. deferred.reject(new Error('disconnect'));
  269. }
  270. this._deferredIQs = [];
  271. }
  272. /**
  273. * The method is meant to be used for testing. It's a shortcut for closing the WebSocket.
  274. *
  275. * @returns {void}
  276. */
  277. closeWebsocket() {
  278. if (this._stropheConn && this._stropheConn._proto) {
  279. this._stropheConn._proto._closeSocket();
  280. this._stropheConn._proto._onClose(null);
  281. }
  282. }
  283. /**
  284. * See {@link Strophe.Connection.disconnect}.
  285. *
  286. * @returns {void}
  287. */
  288. disconnect(...args) {
  289. this._resumeTask.cancel();
  290. clearTimeout(this._wsKeepAlive);
  291. this._clearDeferredIQs();
  292. this._stropheConn.disconnect(...args);
  293. }
  294. /**
  295. * See {@link Strophe.Connection.flush}.
  296. *
  297. * @returns {void}
  298. */
  299. flush(...args) {
  300. this._stropheConn.flush(...args);
  301. }
  302. /**
  303. * See {@link LastRequestTracker.getTimeSinceLastSuccess}.
  304. *
  305. * @returns {number|null}
  306. */
  307. getTimeSinceLastSuccess() {
  308. return this._rawInputTracker.getTimeSinceLastSuccess();
  309. }
  310. /**
  311. * See {@link LastRequestTracker.getLastFailedMessage}.
  312. *
  313. * @returns {string|null}
  314. */
  315. getLastFailedMessage() {
  316. return this._rawInputTracker.getLastFailedMessage();
  317. }
  318. /**
  319. * Requests a resume token from the server if enabled and all requirements are met.
  320. *
  321. * @private
  322. */
  323. _maybeEnableStreamResume() {
  324. if (!this._options.enableWebsocketResume) {
  325. return;
  326. }
  327. const { streamManagement } = this._stropheConn;
  328. if (!this.isUsingWebSocket) {
  329. logger.warn('Stream resume enabled, but WebSockets are not enabled');
  330. } else if (!streamManagement) {
  331. logger.warn('Stream resume enabled, but Strophe streamManagement plugin is not installed');
  332. } else if (!streamManagement.isSupported()) {
  333. logger.warn('Stream resume enabled, but XEP-0198 is not supported by the server');
  334. } else if (!streamManagement.getResumeToken()) {
  335. logger.info('Enabling XEP-0198 stream management');
  336. streamManagement.enable(/* resume */ true);
  337. }
  338. }
  339. /**
  340. * Starts the Websocket keep alive if enabled.
  341. *
  342. * @private
  343. * @returns {void}
  344. */
  345. _maybeStartWSKeepAlive() {
  346. const { websocketKeepAlive } = this._options;
  347. if (this._usesWebsocket && websocketKeepAlive > 0) {
  348. this._wsKeepAlive || logger.info(`WebSocket keep alive interval: ${websocketKeepAlive}ms`);
  349. clearTimeout(this._wsKeepAlive);
  350. const intervalWithJitter = /* base */ websocketKeepAlive + /* jitter */ (Math.random() * 60 * 1000);
  351. logger.debug(`Scheduling next WebSocket keep-alive in ${intervalWithJitter}ms`);
  352. this._wsKeepAlive = setTimeout(
  353. () => this._keepAliveAndCheckShard()
  354. .then(() => this._maybeStartWSKeepAlive()),
  355. intervalWithJitter);
  356. }
  357. }
  358. /**
  359. * Do a http GET to the shard and if shard change will throw an event.
  360. *
  361. * @private
  362. * @returns {Promise}
  363. */
  364. _keepAliveAndCheckShard() {
  365. const { shard, websocketKeepAliveUrl } = this._options;
  366. const url = websocketKeepAliveUrl ? websocketKeepAliveUrl
  367. : this.service.replace('wss://', 'https://').replace('ws://', 'http://');
  368. return fetch(url)
  369. .then(response => {
  370. // skips header checking if there is no info in options
  371. if (!shard) {
  372. return;
  373. }
  374. const responseShard = response.headers.get('x-jitsi-shard');
  375. if (responseShard !== shard) {
  376. logger.error(
  377. `Detected that shard changed from ${shard} to ${responseShard}`);
  378. this.eventEmitter.emit(XmppConnection.Events.CONN_SHARD_CHANGED);
  379. }
  380. })
  381. .catch(error => {
  382. logger.error(`Websocket Keep alive failed for url: ${url}`, { error });
  383. });
  384. }
  385. /**
  386. * Goes over the list of {@link DeferredSendIQ} tasks and sends them.
  387. *
  388. * @private
  389. * @returns {void}
  390. */
  391. _processDeferredIQs() {
  392. for (const deferred of this._deferredIQs) {
  393. if (deferred.iq) {
  394. clearTimeout(deferred.timeout);
  395. const timeLeft = Date.now() - deferred.start;
  396. this.sendIQ(
  397. deferred.iq,
  398. result => deferred.resolve(result),
  399. error => deferred.reject(error),
  400. timeLeft);
  401. }
  402. }
  403. this._deferredIQs = [];
  404. }
  405. /**
  406. * Send a stanza. This function is called to push data onto the send queue to go out over the wire.
  407. *
  408. * @param {Element|Strophe.Builder} stanza - The stanza to send.
  409. * @returns {void}
  410. */
  411. send(stanza) {
  412. if (!this.connected) {
  413. throw new Error('Not connected');
  414. }
  415. this._stropheConn.send(stanza);
  416. }
  417. /**
  418. * Helper function to send IQ stanzas.
  419. *
  420. * @param {Element} elem - The stanza to send.
  421. * @param {Function} callback - The callback function for a successful request.
  422. * @param {Function} errback - The callback function for a failed or timed out request. On timeout, the stanza will
  423. * be null.
  424. * @param {number} timeout - The time specified in milliseconds for a timeout to occur.
  425. * @returns {number} - The id used to send the IQ.
  426. */
  427. sendIQ(elem, callback, errback, timeout) {
  428. if (!this.connected) {
  429. errback('Not connected');
  430. return;
  431. }
  432. return this._stropheConn.sendIQ(elem, callback, errback, timeout);
  433. }
  434. /**
  435. * Sends an IQ immediately if connected or puts it on the send queue otherwise(in contrary to other send methods
  436. * which would fail immediately if disconnected).
  437. *
  438. * @param {Element} iq - The IQ to send.
  439. * @param {number} timeout - How long to wait for the response. The time when the connection is reconnecting is
  440. * included, which means that the IQ may never be sent and still fail with a timeout.
  441. */
  442. sendIQ2(iq, { timeout }) {
  443. return new Promise((resolve, reject) => {
  444. if (this.connected) {
  445. this.sendIQ(
  446. iq,
  447. result => resolve(result),
  448. error => reject(error),
  449. timeout);
  450. } else {
  451. const deferred = {
  452. iq,
  453. resolve,
  454. reject,
  455. start: Date.now(),
  456. timeout: setTimeout(() => {
  457. // clears the IQ on timeout and invalidates the deferred task
  458. deferred.iq = undefined;
  459. // Strophe calls with undefined on timeout
  460. reject(undefined);
  461. }, timeout)
  462. };
  463. this._deferredIQs.push(deferred);
  464. }
  465. });
  466. }
  467. /**
  468. * Called by the ping plugin when ping fails too many times.
  469. *
  470. * @returns {void}
  471. */
  472. _onPingErrorThresholdExceeded() {
  473. if (this.isUsingWebSocket) {
  474. logger.warn('Ping error threshold exceeded - killing the WebSocket');
  475. this.closeWebsocket();
  476. }
  477. }
  478. /**
  479. * Helper function to send presence stanzas. The main benefit is for sending presence stanzas for which you expect
  480. * a responding presence stanza with the same id (for example when leaving a chat room).
  481. *
  482. * @param {Element} elem - The stanza to send.
  483. * @param {Function} callback - The callback function for a successful request.
  484. * @param {Function} errback - The callback function for a failed or timed out request. On timeout, the stanza will
  485. * be null.
  486. * @param {number} timeout - The time specified in milliseconds for a timeout to occur.
  487. * @returns {number} - The id used to send the presence.
  488. */
  489. sendPresence(elem, callback, errback, timeout) {
  490. if (!this.connected) {
  491. errback('Not connected');
  492. return;
  493. }
  494. this._stropheConn.sendPresence(elem, callback, errback, timeout);
  495. }
  496. /**
  497. * The method gracefully closes the BOSH connection by using 'navigator.sendBeacon'.
  498. *
  499. * @returns {boolean} - true if the beacon was sent.
  500. */
  501. sendUnavailableBeacon() {
  502. if (!navigator.sendBeacon || this._stropheConn.disconnecting || !this._stropheConn.connected) {
  503. return false;
  504. }
  505. this._stropheConn._changeConnectStatus(Strophe.Status.DISCONNECTING);
  506. this._stropheConn.disconnecting = true;
  507. const body = this._stropheConn._proto._buildBody()
  508. .attrs({
  509. type: 'terminate'
  510. });
  511. const pres = $pres({
  512. xmlns: Strophe.NS.CLIENT,
  513. type: 'unavailable'
  514. });
  515. body.cnode(pres.tree());
  516. const res = navigator.sendBeacon(
  517. this.service.indexOf('https://') === -1 ? `https:${this.service}` : this.service,
  518. Strophe.serialize(body.tree()));
  519. logger.info(`Successfully send unavailable beacon ${res}`);
  520. this._stropheConn._proto._abortAllRequests();
  521. this._stropheConn._doDisconnect();
  522. return true;
  523. }
  524. /**
  525. * Tries to use stream management plugin to resume dropped XMPP connection. The streamManagement plugin clears
  526. * the resume token if any connection error occurs which would put it in unrecoverable state, so as long as
  527. * the token is present it means the connection can be resumed.
  528. *
  529. * @private
  530. * @returns {boolean}
  531. */
  532. _tryResumingConnection() {
  533. const { streamManagement } = this._stropheConn;
  534. const resumeToken = streamManagement && streamManagement.getResumeToken();
  535. if (resumeToken) {
  536. this._resumeTask.schedule();
  537. return true;
  538. }
  539. return false;
  540. }
  541. }