modified lib-jitsi-meet dev repo
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 18KB

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