Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

XmppConnection.js 17KB

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