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

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