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.

XmppConnection.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. import { getLogger } from '@jitsi/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. * Sets new value for shard.
  179. * @param value the new shard value.
  180. */
  181. set shard(value) {
  182. this._options.shard = value;
  183. // shard setting changed so let's schedule a new keep-alive check if connected
  184. if (this._oneSuccessfulConnect) {
  185. this._maybeStartWSKeepAlive();
  186. }
  187. }
  188. /**
  189. * Returns the current connection status.
  190. *
  191. * @returns {Strophe.Status}
  192. */
  193. get status() {
  194. return this._status;
  195. }
  196. /**
  197. * Adds a connection plugin to this instance.
  198. *
  199. * @param {string} name - The name of the plugin or rather a key under which it will be stored on this connection
  200. * instance.
  201. * @param {ConnectionPluginListenable} plugin - The plugin to add.
  202. */
  203. addConnectionPlugin(name, plugin) {
  204. this[name] = plugin;
  205. plugin.init(this);
  206. }
  207. /**
  208. * See {@link Strophe.Connection.addHandler}
  209. *
  210. * @returns {Object} - handler for the connection.
  211. */
  212. addHandler(...args) {
  213. return this._stropheConn.addHandler(...args);
  214. }
  215. /**
  216. * See {@link Strophe.Connection.deleteHandler}
  217. *
  218. * @returns {void}
  219. */
  220. deleteHandler(...args) {
  221. this._stropheConn.deleteHandler(...args);
  222. }
  223. /* eslint-disable max-params */
  224. /**
  225. * Wraps {@link Strophe.Connection.attach} method in order to intercept the connection status updates.
  226. * See {@link Strophe.Connection.attach} for the params description.
  227. *
  228. * @returns {void}
  229. */
  230. attach(jid, sid, rid, callback, ...args) {
  231. this._stropheConn.attach(jid, sid, rid, this._stropheConnectionCb.bind(this, callback), ...args);
  232. }
  233. /**
  234. * Wraps Strophe.Connection.connect method in order to intercept the connection status updates.
  235. * See {@link Strophe.Connection.connect} for the params description.
  236. *
  237. * @returns {void}
  238. */
  239. connect(jid, pass, callback, ...args) {
  240. this._stropheConn.connect(jid, pass, this._stropheConnectionCb.bind(this, callback), ...args);
  241. }
  242. /* eslint-enable max-params */
  243. /**
  244. * Handles {@link Strophe.Status} updates for the current connection.
  245. *
  246. * @param {function} targetCallback - The callback passed by the {@link XmppConnection} consumer to one of
  247. * the connect methods.
  248. * @param {Strophe.Status} status - The new connection status.
  249. * @param {*} args - The rest of the arguments passed by Strophe.
  250. * @private
  251. */
  252. _stropheConnectionCb(targetCallback, status, ...args) {
  253. this._status = status;
  254. let blockCallback = false;
  255. if (status === Strophe.Status.CONNECTED || status === Strophe.Status.ATTACHED) {
  256. this._maybeEnableStreamResume();
  257. // after connecting - immediately check whether shard changed,
  258. // we need this only when using websockets as bosh checks headers from every response
  259. if (this._usesWebsocket && this._oneSuccessfulConnect) {
  260. this._keepAliveAndCheckShard();
  261. }
  262. this._oneSuccessfulConnect = true;
  263. this._maybeStartWSKeepAlive();
  264. this._processDeferredIQs();
  265. this._resumeTask.cancel();
  266. this.ping.startInterval(this._options.pingOptions?.domain || this.domain);
  267. } else if (status === Strophe.Status.DISCONNECTED) {
  268. this.ping.stopInterval();
  269. // FIXME add RECONNECTING state instead of blocking the DISCONNECTED update
  270. blockCallback = this._tryResumingConnection();
  271. if (!blockCallback) {
  272. clearTimeout(this._wsKeepAlive);
  273. }
  274. }
  275. if (!blockCallback) {
  276. targetCallback(status, ...args);
  277. this.eventEmitter.emit(XmppConnection.Events.CONN_STATUS_CHANGED, status);
  278. }
  279. }
  280. /**
  281. * Clears the list of IQs and rejects deferred Promises with an error.
  282. *
  283. * @private
  284. */
  285. _clearDeferredIQs() {
  286. for (const deferred of this._deferredIQs) {
  287. deferred.reject(new Error('disconnect'));
  288. }
  289. this._deferredIQs = [];
  290. }
  291. /**
  292. * The method is meant to be used for testing. It's a shortcut for closing the WebSocket.
  293. *
  294. * @returns {void}
  295. */
  296. closeWebsocket() {
  297. if (this._stropheConn && this._stropheConn._proto) {
  298. this._stropheConn._proto._closeSocket();
  299. this._stropheConn._proto._onClose(null);
  300. }
  301. }
  302. /**
  303. * See {@link Strophe.Connection.disconnect}.
  304. *
  305. * @returns {void}
  306. */
  307. disconnect(...args) {
  308. this._resumeTask.cancel();
  309. clearTimeout(this._wsKeepAlive);
  310. this._clearDeferredIQs();
  311. this._stropheConn.disconnect(...args);
  312. }
  313. /**
  314. * See {@link Strophe.Connection.flush}.
  315. *
  316. * @returns {void}
  317. */
  318. flush(...args) {
  319. this._stropheConn.flush(...args);
  320. }
  321. /**
  322. * See {@link LastRequestTracker.getTimeSinceLastSuccess}.
  323. *
  324. * @returns {number|null}
  325. */
  326. getTimeSinceLastSuccess() {
  327. return this._rawInputTracker.getTimeSinceLastSuccess();
  328. }
  329. /**
  330. * See {@link LastRequestTracker.getLastFailedMessage}.
  331. *
  332. * @returns {string|null}
  333. */
  334. getLastFailedMessage() {
  335. return this._rawInputTracker.getLastFailedMessage();
  336. }
  337. /**
  338. * Requests a resume token from the server if enabled and all requirements are met.
  339. *
  340. * @private
  341. */
  342. _maybeEnableStreamResume() {
  343. if (!this._options.enableWebsocketResume) {
  344. return;
  345. }
  346. const { streamManagement } = this._stropheConn;
  347. if (!this.isUsingWebSocket) {
  348. logger.warn('Stream resume enabled, but WebSockets are not enabled');
  349. } else if (!streamManagement) {
  350. logger.warn('Stream resume enabled, but Strophe streamManagement plugin is not installed');
  351. } else if (!streamManagement.isSupported()) {
  352. logger.warn('Stream resume enabled, but XEP-0198 is not supported by the server');
  353. } else if (!streamManagement.getResumeToken()) {
  354. logger.info('Enabling XEP-0198 stream management');
  355. streamManagement.enable(/* resume */ true);
  356. }
  357. }
  358. /**
  359. * Starts the Websocket keep alive if enabled.
  360. *
  361. * @private
  362. * @returns {void}
  363. */
  364. _maybeStartWSKeepAlive() {
  365. const { websocketKeepAlive } = this._options;
  366. if (this._usesWebsocket && websocketKeepAlive > 0) {
  367. this._wsKeepAlive || logger.info(`WebSocket keep alive interval: ${websocketKeepAlive}ms`);
  368. clearTimeout(this._wsKeepAlive);
  369. const intervalWithJitter = /* base */ websocketKeepAlive + /* jitter */ (Math.random() * 60 * 1000);
  370. logger.debug(`Scheduling next WebSocket keep-alive in ${intervalWithJitter}ms`);
  371. this._wsKeepAlive = setTimeout(
  372. () => this._keepAliveAndCheckShard()
  373. .then(() => this._maybeStartWSKeepAlive()),
  374. intervalWithJitter);
  375. }
  376. }
  377. /**
  378. * Do a http GET to the shard and if shard change will throw an event.
  379. *
  380. * @private
  381. * @returns {Promise}
  382. */
  383. _keepAliveAndCheckShard() {
  384. const { shard, websocketKeepAliveUrl } = this._options;
  385. const url = websocketKeepAliveUrl ? websocketKeepAliveUrl
  386. : this.service.replace('wss://', 'https://').replace('ws://', 'http://');
  387. return fetch(url)
  388. .then(response => {
  389. // skips header checking if there is no info in options
  390. if (!shard) {
  391. return;
  392. }
  393. const responseShard = response.headers.get('x-jitsi-shard');
  394. if (responseShard !== shard) {
  395. logger.error(
  396. `Detected that shard changed from ${shard} to ${responseShard}`);
  397. this.eventEmitter.emit(XmppConnection.Events.CONN_SHARD_CHANGED);
  398. }
  399. })
  400. .catch(error => {
  401. logger.error(`Websocket Keep alive failed for url: ${url}`, { error });
  402. });
  403. }
  404. /**
  405. * Goes over the list of {@link DeferredSendIQ} tasks and sends them.
  406. *
  407. * @private
  408. * @returns {void}
  409. */
  410. _processDeferredIQs() {
  411. for (const deferred of this._deferredIQs) {
  412. if (deferred.iq) {
  413. clearTimeout(deferred.timeout);
  414. const timeLeft = Date.now() - deferred.start;
  415. this.sendIQ(
  416. deferred.iq,
  417. result => deferred.resolve(result),
  418. error => deferred.reject(error),
  419. timeLeft);
  420. }
  421. }
  422. this._deferredIQs = [];
  423. }
  424. /**
  425. * Send a stanza. This function is called to push data onto the send queue to go out over the wire.
  426. *
  427. * @param {Element|Strophe.Builder} stanza - The stanza to send.
  428. * @returns {void}
  429. */
  430. send(stanza) {
  431. if (!this.connected) {
  432. logger.error(`Trying to send stanza while not connected. Status:${this._status} Proto:${
  433. this.isUsingWebSocket ? this._stropheConn?._proto?.socket?.readyState : 'bosh'
  434. }`);
  435. throw new Error('Not connected');
  436. }
  437. this._stropheConn.send(stanza);
  438. }
  439. /**
  440. * Helper function to send IQ stanzas.
  441. *
  442. * @param {Element} elem - The stanza to send.
  443. * @param {Function} callback - The callback function for a successful request.
  444. * @param {Function} errback - The callback function for a failed or timed out request. On timeout, the stanza will
  445. * be null.
  446. * @param {number} timeout - The time specified in milliseconds for a timeout to occur.
  447. * @returns {number} - The id used to send the IQ.
  448. */
  449. sendIQ(elem, callback, errback, timeout) {
  450. if (!this.connected) {
  451. errback('Not connected');
  452. return;
  453. }
  454. return this._stropheConn.sendIQ(elem, callback, errback, timeout);
  455. }
  456. /**
  457. * Sends an IQ immediately if connected or puts it on the send queue otherwise(in contrary to other send methods
  458. * which would fail immediately if disconnected).
  459. *
  460. * @param {Element} iq - The IQ to send.
  461. * @param {number} timeout - How long to wait for the response. The time when the connection is reconnecting is
  462. * included, which means that the IQ may never be sent and still fail with a timeout.
  463. */
  464. sendIQ2(iq, { timeout }) {
  465. return new Promise((resolve, reject) => {
  466. if (this.connected) {
  467. this.sendIQ(
  468. iq,
  469. result => resolve(result),
  470. error => reject(error),
  471. timeout);
  472. } else {
  473. const deferred = {
  474. iq,
  475. resolve,
  476. reject,
  477. start: Date.now(),
  478. timeout: setTimeout(() => {
  479. // clears the IQ on timeout and invalidates the deferred task
  480. deferred.iq = undefined;
  481. // Strophe calls with undefined on timeout
  482. reject(undefined);
  483. }, timeout)
  484. };
  485. this._deferredIQs.push(deferred);
  486. }
  487. });
  488. }
  489. /**
  490. * Called by the ping plugin when ping fails too many times.
  491. *
  492. * @returns {void}
  493. */
  494. _onPingErrorThresholdExceeded() {
  495. if (this.isUsingWebSocket) {
  496. logger.warn('Ping error threshold exceeded - killing the WebSocket');
  497. this.closeWebsocket();
  498. }
  499. }
  500. /**
  501. * Helper function to send presence stanzas. The main benefit is for sending presence stanzas for which you expect
  502. * a responding presence stanza with the same id (for example when leaving a chat room).
  503. *
  504. * @param {Element} elem - The stanza to send.
  505. * @param {Function} callback - The callback function for a successful request.
  506. * @param {Function} errback - The callback function for a failed or timed out request. On timeout, the stanza will
  507. * be null.
  508. * @param {number} timeout - The time specified in milliseconds for a timeout to occur.
  509. * @returns {number} - The id used to send the presence.
  510. */
  511. sendPresence(elem, callback, errback, timeout) {
  512. if (!this.connected) {
  513. errback('Not connected');
  514. return;
  515. }
  516. this._stropheConn.sendPresence(elem, callback, errback, timeout);
  517. }
  518. /**
  519. * The method gracefully closes the BOSH connection by using 'navigator.sendBeacon'.
  520. *
  521. * @returns {boolean} - true if the beacon was sent.
  522. */
  523. sendUnavailableBeacon() {
  524. if (!navigator.sendBeacon || this._stropheConn.disconnecting || !this._stropheConn.connected) {
  525. return false;
  526. }
  527. this._stropheConn._changeConnectStatus(Strophe.Status.DISCONNECTING);
  528. this._stropheConn.disconnecting = true;
  529. const body = this._stropheConn._proto._buildBody()
  530. .attrs({
  531. type: 'terminate'
  532. });
  533. const pres = $pres({
  534. xmlns: Strophe.NS.CLIENT,
  535. type: 'unavailable'
  536. });
  537. body.cnode(pres.tree());
  538. const res = navigator.sendBeacon(
  539. this.service.indexOf('https://') === -1 ? `https:${this.service}` : this.service,
  540. Strophe.serialize(body.tree()));
  541. logger.info(`Successfully send unavailable beacon ${res}`);
  542. this._stropheConn._proto._abortAllRequests();
  543. this._stropheConn._doDisconnect();
  544. return true;
  545. }
  546. /**
  547. * Tries to use stream management plugin to resume dropped XMPP connection. The streamManagement plugin clears
  548. * the resume token if any connection error occurs which would put it in unrecoverable state, so as long as
  549. * the token is present it means the connection can be resumed.
  550. *
  551. * @private
  552. * @returns {boolean}
  553. */
  554. _tryResumingConnection() {
  555. const { streamManagement } = this._stropheConn;
  556. const resumeToken = streamManagement && streamManagement.getResumeToken();
  557. if (resumeToken) {
  558. this._resumeTask.schedule();
  559. return true;
  560. }
  561. return false;
  562. }
  563. }