Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

XmppConnection.js 17KB

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