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

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