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

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