Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

XmppConnection.js 21KB

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