Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

XmppConnection.js 17KB

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