選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

XmppConnection.js 19KB

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