Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

XmppConnection.js 18KB

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