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.

xmpp.js 38KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. /* global $ */
  2. import { getLogger } from '@jitsi/logger';
  3. import { $msg, Strophe } from 'strophe.js';
  4. import 'strophejs-plugin-disco';
  5. import * as JitsiConnectionErrors from '../../JitsiConnectionErrors';
  6. import * as JitsiConnectionEvents from '../../JitsiConnectionEvents';
  7. import XMPPEvents from '../../service/xmpp/XMPPEvents';
  8. import browser from '../browser';
  9. import { E2EEncryption } from '../e2ee/E2EEncryption';
  10. import Statistics from '../statistics/statistics';
  11. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  12. import Listenable from '../util/Listenable';
  13. import RandomUtil from '../util/RandomUtil';
  14. import Caps, { parseDiscoInfo } from './Caps';
  15. import XmppConnection from './XmppConnection';
  16. import MucConnectionPlugin from './strophe.emuc';
  17. import JingleConnectionPlugin from './strophe.jingle';
  18. import initStropheLogger from './strophe.logger';
  19. import RayoConnectionPlugin from './strophe.rayo';
  20. import initStropheUtil from './strophe.util';
  21. const logger = getLogger(__filename);
  22. /**
  23. * Regex to extract exact error message on jwt error.
  24. */
  25. const FAILURE_REGEX = /<failure.*><not-allowed\/><text>(.*)<\/text><\/failure>/gi;
  26. /**
  27. * Creates XMPP connection.
  28. *
  29. * @param {Object} options
  30. * @param {string} [options.token] - JWT token used for authentication(JWT authentication module must be enabled in
  31. * Prosody).
  32. * @param {string} options.serviceUrl - The service URL for XMPP connection.
  33. * @param {string} options.shard - The shard where XMPP connection initially landed.
  34. * @param {string} options.enableWebsocketResume - True to enable stream resumption.
  35. * @param {number} [options.websocketKeepAlive] - See {@link XmppConnection} constructor.
  36. * @param {number} [options.websocketKeepAliveUrl] - See {@link XmppConnection} constructor.
  37. * @param {Object} [options.xmppPing] - See {@link XmppConnection} constructor.
  38. * @returns {XmppConnection}
  39. */
  40. function createConnection({
  41. enableWebsocketResume,
  42. serviceUrl = '/http-bind',
  43. shard,
  44. token,
  45. websocketKeepAlive,
  46. websocketKeepAliveUrl,
  47. xmppPing }) {
  48. // Append token as URL param
  49. if (token) {
  50. // eslint-disable-next-line no-param-reassign
  51. serviceUrl += `${serviceUrl.indexOf('?') === -1 ? '?' : '&'}token=${token}`;
  52. }
  53. return new XmppConnection({
  54. enableWebsocketResume,
  55. serviceUrl,
  56. websocketKeepAlive,
  57. websocketKeepAliveUrl,
  58. xmppPing,
  59. shard
  60. });
  61. }
  62. /**
  63. * Initializes Strophe plugins that need to work with Strophe.Connection directly rather than the lib-jitsi-meet's
  64. * {@link XmppConnection} wrapper.
  65. *
  66. * @returns {void}
  67. */
  68. function initStropheNativePlugins() {
  69. initStropheUtil();
  70. initStropheLogger();
  71. }
  72. // FIXME: remove once we have a default config template. -saghul
  73. /**
  74. * A list of ice servers to use by default for P2P.
  75. */
  76. export const DEFAULT_STUN_SERVERS = [
  77. { urls: 'stun:meet-jit-si-turnrelay.jitsi.net:443' }
  78. ];
  79. /**
  80. * The name of the field used to recognize a chat message as carrying a JSON
  81. * payload from another endpoint.
  82. * If the json-message of a chat message contains a valid JSON object, and
  83. * the JSON has this key, then it is a valid json-message to be sent.
  84. */
  85. export const JITSI_MEET_MUC_TYPE = 'type';
  86. /**
  87. * The feature used by jigasi participants.
  88. * @type {string}
  89. */
  90. export const FEATURE_JIGASI = 'http://jitsi.org/protocol/jigasi';
  91. /**
  92. * The feature used by the lib to mark support for e2ee. We use the feature by putting it in the presence
  93. * to avoid additional signaling (disco-info).
  94. * @type {string}
  95. */
  96. export const FEATURE_E2EE = 'https://jitsi.org/meet/e2ee';
  97. /**
  98. *
  99. */
  100. export default class XMPP extends Listenable {
  101. /**
  102. * FIXME describe all options
  103. * @param {Object} options
  104. * @param {String} options.serviceUrl - URL passed to the XMPP client which will be used to establish XMPP
  105. * connection with the server.
  106. * @param {String} options.bosh - Deprecated, use {@code serviceUrl}.
  107. * @param {boolean} options.enableWebsocketResume - Enables XEP-0198 stream management which will make the XMPP
  108. * module try to resume the session in case the Websocket connection breaks.
  109. * @param {number} [options.websocketKeepAlive] - The websocket keep alive interval. See {@link XmppConnection}
  110. * constructor for more details.
  111. * @param {number} [options.websocketKeepAliveUrl] - The websocket keep alive url. See {@link XmppConnection}
  112. * constructor for more details.
  113. * @param {Object} [options.xmppPing] - The xmpp ping settings.
  114. * @param {Array<Object>} options.p2pStunServers see {@link JingleConnectionPlugin} for more details.
  115. * @param token
  116. */
  117. constructor(options, token) {
  118. super();
  119. this.connection = null;
  120. this.disconnectInProgress = false;
  121. this.connectionTimes = {};
  122. this.options = options;
  123. this.token = token;
  124. this.authenticatedUser = false;
  125. initStropheNativePlugins();
  126. const xmppPing = options.xmppPing || {};
  127. // let's ping the main domain (in case a guest one is used for the connection)
  128. xmppPing.domain = options.hosts.domain;
  129. this.connection = createConnection({
  130. enableWebsocketResume: options.enableWebsocketResume,
  131. // FIXME remove deprecated bosh option at some point
  132. serviceUrl: options.serviceUrl || options.bosh,
  133. token,
  134. websocketKeepAlive: options.websocketKeepAlive,
  135. websocketKeepAliveUrl: options.websocketKeepAliveUrl,
  136. xmppPing,
  137. shard: options.deploymentInfo?.shard
  138. });
  139. // forwards the shard changed event
  140. this.connection.on(XmppConnection.Events.CONN_SHARD_CHANGED, () => {
  141. /* eslint-disable camelcase */
  142. const details = {
  143. shard_changed: true,
  144. suspend_time: this.connection.ping.getPingSuspendTime(),
  145. time_since_last_success: this.connection.getTimeSinceLastSuccess()
  146. };
  147. /* eslint-enable camelcase */
  148. this.eventEmitter.emit(
  149. JitsiConnectionEvents.CONNECTION_FAILED,
  150. JitsiConnectionErrors.OTHER_ERROR,
  151. undefined,
  152. undefined,
  153. details);
  154. });
  155. this._initStrophePlugins();
  156. this.caps = new Caps(this.connection, /* clientNode */ 'https://jitsi.org/jitsi-meet');
  157. // Initialize features advertised in disco-info
  158. this.initFeaturesList();
  159. // Setup a disconnect on unload as a way to facilitate API consumers. It
  160. // sounds like they would want that. A problem for them though may be if
  161. // they wanted to utilize the connected connection in an unload handler
  162. // of their own. However, it should be fairly easy for them to do that
  163. // by registering their unload handler before us.
  164. $(window).on('beforeunload unload', ev => {
  165. this.disconnect(ev).catch(() => {
  166. // ignore errors in order to not brake the unload.
  167. });
  168. });
  169. }
  170. /**
  171. * Initializes the list of feature advertised through the disco-info
  172. * mechanism.
  173. */
  174. initFeaturesList() {
  175. // http://xmpp.org/extensions/xep-0167.html#support
  176. // http://xmpp.org/extensions/xep-0176.html#support
  177. this.caps.addFeature('urn:xmpp:jingle:1');
  178. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:1');
  179. this.caps.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  180. this.caps.addFeature('urn:xmpp:jingle:apps:dtls:0');
  181. this.caps.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  182. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  183. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:video');
  184. this.caps.addFeature('http://jitsi.org/json-encoded-sources');
  185. if (!(this.options.disableRtx || !browser.supportsRTX())) {
  186. this.caps.addFeature('urn:ietf:rfc:4588');
  187. }
  188. if (this.options.enableOpusRed === true && browser.supportsAudioRed()) {
  189. this.caps.addFeature('http://jitsi.org/opus-red');
  190. }
  191. if (typeof this.options.enableRemb === 'undefined' || this.options.enableRemb) {
  192. this.caps.addFeature('http://jitsi.org/remb');
  193. }
  194. // Disable TCC on Firefox because of a known issue where BWE is halved on every renegotiation.
  195. if (!browser.isFirefox() && (typeof this.options.enableTcc === 'undefined' || this.options.enableTcc)) {
  196. this.caps.addFeature('http://jitsi.org/tcc');
  197. }
  198. // this is dealt with by SDP O/A so we don't need to announce this
  199. // XEP-0293
  200. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0');
  201. // XEP-0294
  202. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0');
  203. this.caps.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  204. this.caps.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  205. // this.caps.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  206. // Enable Lipsync ?
  207. if (browser.isChromiumBased() && this.options.enableLipSync === true) {
  208. logger.info('Lip-sync enabled !');
  209. this.caps.addFeature('http://jitsi.org/meet/lipsync');
  210. }
  211. if (this.connection.rayo) {
  212. this.caps.addFeature('urn:xmpp:rayo:client:1');
  213. }
  214. if (E2EEncryption.isSupported(this.options)) {
  215. this.caps.addFeature(FEATURE_E2EE, false, true);
  216. }
  217. }
  218. /**
  219. *
  220. */
  221. getConnection() {
  222. return this.connection;
  223. }
  224. /**
  225. * Receive connection status changes and handles them.
  226. *
  227. * @param {Object} credentials
  228. * @param {string} credentials.jid - The user's XMPP ID passed to the
  229. * connect method. For example, 'user@xmpp.com'.
  230. * @param {string} credentials.password - The password passed to the connect
  231. * method.
  232. * @param {string} status - One of Strophe's connection status strings.
  233. * @param {string} [msg] - The connection error message provided by Strophe.
  234. */
  235. connectionHandler(credentials = {}, status, msg) {
  236. const now = window.performance.now();
  237. const statusStr = Strophe.getStatusString(status).toLowerCase();
  238. this.connectionTimes[statusStr] = now;
  239. logger.log(
  240. `(TIME) Strophe ${statusStr}${msg ? `[${msg}]` : ''}:\t`,
  241. now);
  242. this.eventEmitter.emit(XMPPEvents.CONNECTION_STATUS_CHANGED, credentials, status, msg);
  243. this._maybeSendDeploymentInfoStat();
  244. if (status === Strophe.Status.CONNECTED || status === Strophe.Status.ATTACHED) {
  245. // once connected or attached we no longer need this handle, drop it if it exist
  246. if (this._sysMessageHandler) {
  247. this.connection._stropheConn.deleteHandler(this._sysMessageHandler);
  248. this._sysMessageHandler = null;
  249. }
  250. this.sendDiscoInfo && this.connection.jingle.getStunAndTurnCredentials();
  251. logger.info(`My Jabber ID: ${this.connection.jid}`);
  252. // XmppConnection emits CONNECTED again on reconnect - a good opportunity to clear any "last error" flags
  253. this._resetState();
  254. // make sure we will send the info after the features request succeeds or fails
  255. this.sendDeploymentInfo = false;
  256. this.sendDiscoInfo && this.caps.getFeaturesAndIdentities(this.options.hosts.domain)
  257. .then(({ features, identities }) => {
  258. if (!features.has(Strophe.NS.PING)) {
  259. logger.error(`Ping NOT supported by ${
  260. this.options.hosts.domain} - please enable ping in your XMPP server config`);
  261. }
  262. this._processDiscoInfoIdentities(
  263. identities, undefined /* when querying we will query for features */);
  264. })
  265. .catch(error => {
  266. const errmsg = 'Feature discovery error';
  267. GlobalOnErrorHandler.callErrorHandler(
  268. new Error(`${errmsg}: ${error}`));
  269. logger.error(errmsg, error);
  270. this._maybeSendDeploymentInfoStat(true);
  271. });
  272. // make sure we don't query again
  273. this.sendDiscoInfo = false;
  274. if (credentials.password) {
  275. this.authenticatedUser = true;
  276. }
  277. if (this.connection && this.connection.connected
  278. && Strophe.getResourceFromJid(this.connection.jid)) {
  279. // .connected is true while connecting?
  280. // this.connection.send($pres());
  281. this.eventEmitter.emit(
  282. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  283. Strophe.getResourceFromJid(this.connection.jid));
  284. }
  285. } else if (status === Strophe.Status.CONNFAIL) {
  286. if (msg === 'x-strophe-bad-non-anon-jid') {
  287. this.anonymousConnectionFailed = true;
  288. } else {
  289. this.connectionFailed = true;
  290. }
  291. this.lastErrorMsg = msg;
  292. if (msg === 'giving-up') {
  293. this.eventEmitter.emit(
  294. JitsiConnectionEvents.CONNECTION_FAILED,
  295. JitsiConnectionErrors.OTHER_ERROR, msg);
  296. }
  297. } else if (status === Strophe.Status.ERROR) {
  298. this.lastErrorMsg = msg;
  299. } else if (status === Strophe.Status.DISCONNECTED) {
  300. // Stop ping interval
  301. this.connection.ping.stopInterval();
  302. const wasIntentionalDisconnect = Boolean(this.disconnectInProgress);
  303. const errMsg = msg || this.lastErrorMsg;
  304. if (this.anonymousConnectionFailed) {
  305. // prompt user for username and password
  306. this.eventEmitter.emit(
  307. JitsiConnectionEvents.CONNECTION_FAILED,
  308. JitsiConnectionErrors.PASSWORD_REQUIRED);
  309. } else if (this.connectionFailed) {
  310. this.eventEmitter.emit(
  311. JitsiConnectionEvents.CONNECTION_FAILED,
  312. JitsiConnectionErrors.OTHER_ERROR,
  313. errMsg,
  314. undefined, /* credentials */
  315. this._getConnectionFailedReasonDetails());
  316. } else if (wasIntentionalDisconnect) {
  317. this.eventEmitter.emit(
  318. JitsiConnectionEvents.CONNECTION_DISCONNECTED, errMsg);
  319. } else {
  320. // XXX if Strophe drops the connection while not being asked to,
  321. // it means that most likely some serious error has occurred.
  322. // One currently known case is when a BOSH request fails for
  323. // more than 4 times. The connection is dropped without
  324. // supplying a reason(error message/event) through the API.
  325. logger.error('XMPP connection dropped!');
  326. // XXX if the last request error is within 5xx range it means it
  327. // was a server failure
  328. const lastErrorStatus = Strophe.getLastErrorStatus();
  329. if (lastErrorStatus >= 500 && lastErrorStatus < 600) {
  330. this.eventEmitter.emit(
  331. JitsiConnectionEvents.CONNECTION_FAILED,
  332. JitsiConnectionErrors.SERVER_ERROR,
  333. errMsg || 'server-error',
  334. /* credentials */ undefined,
  335. this._getConnectionFailedReasonDetails());
  336. } else {
  337. this.eventEmitter.emit(
  338. JitsiConnectionEvents.CONNECTION_FAILED,
  339. JitsiConnectionErrors.CONNECTION_DROPPED_ERROR,
  340. errMsg || 'connection-dropped-error',
  341. /* credentials */ undefined,
  342. this._getConnectionFailedReasonDetails());
  343. }
  344. }
  345. } else if (status === Strophe.Status.AUTHFAIL) {
  346. const lastFailedRawMessage = this.getConnection().getLastFailedMessage();
  347. // wrong password or username, prompt user
  348. this.eventEmitter.emit(
  349. JitsiConnectionEvents.CONNECTION_FAILED,
  350. JitsiConnectionErrors.PASSWORD_REQUIRED,
  351. msg || this._parseConnectionFailedMessage(lastFailedRawMessage),
  352. credentials);
  353. }
  354. }
  355. /**
  356. * Process received identities.
  357. * @param {Set<String>} identities The identities to process.
  358. * @param {Set<String>} features The features to process, optional. If missing lobby component will be queried
  359. * for more features.
  360. * @private
  361. */
  362. _processDiscoInfoIdentities(identities, features) {
  363. // check for speakerstats
  364. identities.forEach(identity => {
  365. if (identity.type === 'av_moderation') {
  366. this.avModerationComponentAddress = identity.name;
  367. }
  368. if (identity.type === 'speakerstats') {
  369. this.speakerStatsComponentAddress = identity.name;
  370. }
  371. if (identity.type === 'conference_duration') {
  372. this.conferenceDurationComponentAddress = identity.name;
  373. }
  374. if (identity.type === 'lobbyrooms') {
  375. this.lobbySupported = true;
  376. const processLobbyFeatures = f => {
  377. f.forEach(fr => {
  378. if (fr.endsWith('#displayname_required')) {
  379. this.eventEmitter.emit(JitsiConnectionEvents.DISPLAY_NAME_REQUIRED);
  380. }
  381. });
  382. };
  383. if (features) {
  384. processLobbyFeatures(features);
  385. } else {
  386. identity.name && this.caps.getFeaturesAndIdentities(identity.name, identity.type)
  387. .then(({ features: f }) => processLobbyFeatures(f))
  388. .catch(e => logger.warn('Error getting features from lobby.', e && e.message));
  389. }
  390. }
  391. if (identity.type === 'shard') {
  392. this.options.deploymentInfo.shard = this.connection.shard = identity.name;
  393. }
  394. if (identity.type === 'region') {
  395. this.options.deploymentInfo.region = this.connection.region = identity.name;
  396. }
  397. });
  398. this._maybeSendDeploymentInfoStat(true);
  399. if (this.avModerationComponentAddress
  400. || this.speakerStatsComponentAddress
  401. || this.conferenceDurationComponentAddress) {
  402. this.connection.addHandler(this._onPrivateMessage.bind(this), null, 'message', null, null);
  403. }
  404. }
  405. /**
  406. * Parses a raw failure xmpp xml message received on auth failed.
  407. *
  408. * @param {string} msg - The raw failure message from xmpp.
  409. * @returns {string|null} - The parsed message from the raw xmpp message.
  410. */
  411. _parseConnectionFailedMessage(msg) {
  412. if (!msg) {
  413. return null;
  414. }
  415. const matches = FAILURE_REGEX.exec(msg);
  416. return matches ? matches[1] : null;
  417. }
  418. /**
  419. *
  420. * @param jid
  421. * @param password
  422. */
  423. _connect(jid, password) {
  424. // connection.connect() starts the connection process.
  425. //
  426. // As the connection process proceeds, the user supplied callback will
  427. // be triggered multiple times with status updates. The callback should
  428. // take two arguments - the status code and the error condition.
  429. //
  430. // The status code will be one of the values in the Strophe.Status
  431. // constants. The error condition will be one of the conditions defined
  432. // in RFC 3920 or the condition ‘strophe-parsererror’.
  433. //
  434. // The Parameters wait, hold and route are optional and only relevant
  435. // for BOSH connections. Please see XEP 124 for a more detailed
  436. // explanation of the optional parameters.
  437. //
  438. // Connection status constants for use by the connection handler
  439. // callback.
  440. //
  441. // Status.ERROR - An error has occurred (websockets specific)
  442. // Status.CONNECTING - The connection is currently being made
  443. // Status.CONNFAIL - The connection attempt failed
  444. // Status.AUTHENTICATING - The connection is authenticating
  445. // Status.AUTHFAIL - The authentication attempt failed
  446. // Status.CONNECTED - The connection has succeeded
  447. // Status.DISCONNECTED - The connection has been terminated
  448. // Status.DISCONNECTING - The connection is currently being terminated
  449. // Status.ATTACHED - The connection has been attached
  450. this._resetState();
  451. // we want to send this only on the initial connect
  452. this.sendDiscoInfo = true;
  453. this.sendDeploymentInfo = true;
  454. if (this.connection._stropheConn && this.connection._stropheConn._addSysHandler) {
  455. this._sysMessageHandler = this.connection._stropheConn._addSysHandler(
  456. this._onSystemMessage.bind(this),
  457. null,
  458. 'message'
  459. );
  460. } else {
  461. logger.warn('Cannot attach strophe system handler, jiconop cannot operate');
  462. }
  463. this.connection.connect(
  464. jid,
  465. password,
  466. this.connectionHandler.bind(this, {
  467. jid,
  468. password
  469. }));
  470. }
  471. /**
  472. * Receives system messages during the connect/login process and checks for services or
  473. * @param msg The received message.
  474. * @returns {void}
  475. * @private
  476. */
  477. _onSystemMessage(msg) {
  478. // proceed only if the message has any of the expected information
  479. if ($(msg).find('>services').length === 0 && $(msg).find('>query').length === 0) {
  480. return;
  481. }
  482. this.sendDiscoInfo = false;
  483. const foundIceServers = this.connection.jingle.onReceiveStunAndTurnCredentials(msg);
  484. const { features, identities } = parseDiscoInfo(msg);
  485. this._processDiscoInfoIdentities(identities, features);
  486. if (foundIceServers || identities.size > 0 || features.size > 0) {
  487. this.connection._stropheConn.deleteHandler(this._sysMessageHandler);
  488. this._sysMessageHandler = null;
  489. }
  490. }
  491. /**
  492. * Attach to existing connection. Can be used for optimizations. For
  493. * example: if the connection is created on the server we can attach to it
  494. * and start using it.
  495. *
  496. * @param options {object} connecting options - rid, sid, jid and password.
  497. */
  498. attach(options) {
  499. this._resetState();
  500. // we want to send this only on the initial connect
  501. this.sendDiscoInfo = true;
  502. const now = this.connectionTimes.attaching = window.performance.now();
  503. logger.log('(TIME) Strophe Attaching:\t', now);
  504. this.connection.attach(options.jid, options.sid,
  505. parseInt(options.rid, 10) + 1,
  506. this.connectionHandler.bind(this, {
  507. jid: options.jid,
  508. password: options.password
  509. }));
  510. }
  511. /**
  512. * Resets any state/flag before starting a new connection.
  513. * @private
  514. */
  515. _resetState() {
  516. this.anonymousConnectionFailed = false;
  517. this.connectionFailed = false;
  518. this.lastErrorMsg = undefined;
  519. this.disconnectInProgress = undefined;
  520. }
  521. /**
  522. *
  523. * @param jid
  524. * @param password
  525. */
  526. connect(jid, password) {
  527. if (!jid) {
  528. const { anonymousdomain, domain } = this.options.hosts;
  529. let configDomain = anonymousdomain || domain;
  530. // Force authenticated domain if room is appended with '?login=true'
  531. // or if we're joining with the token
  532. // FIXME Do not rely on window.location because (1) React Native
  533. // does not have a window.location by default and (2) here we cannot
  534. // know for sure that query/search has not be stripped from
  535. // window.location by the time the following executes.
  536. const { location } = window;
  537. if (anonymousdomain) {
  538. const search = location && location.search;
  539. if ((search && search.indexOf('login=true') !== -1)
  540. || this.token) {
  541. configDomain = domain;
  542. }
  543. }
  544. // eslint-disable-next-line no-param-reassign
  545. jid = configDomain || (location && location.hostname);
  546. }
  547. return this._connect(jid, password);
  548. }
  549. /**
  550. * Joins or creates a muc with the provided jid, created from the passed
  551. * in room name and muc host and onCreateResource result.
  552. *
  553. * @param {string} roomName - The name of the muc to join.
  554. * @param {Object} options - Configuration for how to join the muc.
  555. * @param {Function} [onCreateResource] - Callback to invoke when a resource
  556. * is to be added to the jid.
  557. * @returns {Promise} Resolves with an instance of a strophe muc.
  558. */
  559. createRoom(roomName, options, onCreateResource) {
  560. // There are cases (when using subdomain) where muc can hold an uppercase part
  561. let roomjid = `${this.getRoomJid(roomName, options.customDomain)}/`;
  562. const mucNickname = onCreateResource
  563. ? onCreateResource(this.connection.jid, this.authenticatedUser)
  564. : RandomUtil.randomHexString(8).toLowerCase();
  565. logger.info(`JID ${this.connection.jid} using MUC nickname ${mucNickname}`);
  566. roomjid += mucNickname;
  567. return this.connection.emuc.createRoom(roomjid, null, options);
  568. }
  569. /**
  570. * Returns the room JID based on the passed room name and domain.
  571. *
  572. * @param {string} roomName - The room name.
  573. * @param {string} domain - The domain.
  574. * @returns {string} - The room JID.
  575. */
  576. getRoomJid(roomName, domain) {
  577. return `${roomName}@${domain ? domain : this.options.hosts.muc.toLowerCase()}`;
  578. }
  579. /**
  580. * Check if a room with the passed JID is already created.
  581. *
  582. * @param {string} roomJid - The JID of the room.
  583. * @returns {boolean}
  584. */
  585. isRoomCreated(roomName, domain) {
  586. return this.connection.emuc.isRoomCreated(this.getRoomJid(roomName, domain));
  587. }
  588. /**
  589. * Returns the jid of the participant associated with the Strophe connection.
  590. *
  591. * @returns {string} The jid of the participant.
  592. */
  593. getJid() {
  594. return this.connection.jid;
  595. }
  596. /**
  597. * Returns the logs from strophe.jingle.
  598. * @returns {Object}
  599. */
  600. getJingleLog() {
  601. const jingle = this.connection.jingle;
  602. return jingle ? jingle.getLog() : {};
  603. }
  604. /**
  605. * Returns the logs from strophe.
  606. */
  607. getXmppLog() {
  608. return (this.connection.logger || {}).log || null;
  609. }
  610. /**
  611. *
  612. */
  613. dial(...args) {
  614. this.connection.rayo.dial(...args);
  615. }
  616. /**
  617. * Pings the server.
  618. * @param timeout how many ms before a timeout should occur.
  619. * @returns {Promise} resolved on ping success and reject on an error or
  620. * a timeout.
  621. */
  622. ping(timeout) {
  623. return new Promise((resolve, reject) => {
  624. this.connection.ping.ping(this.connection.pingDomain, resolve, reject, timeout);
  625. });
  626. }
  627. /**
  628. *
  629. */
  630. getSessions() {
  631. return this.connection.jingle.sessions;
  632. }
  633. /**
  634. * Disconnects this from the XMPP server (if this is connected).
  635. *
  636. * @param {Object} ev - Optionally, the event which triggered the necessity to
  637. * disconnect from the XMPP server (e.g. beforeunload, unload).
  638. * @returns {Promise} - Resolves when the disconnect process is finished or rejects with an error.
  639. */
  640. disconnect(ev) {
  641. if (this.disconnectInProgress) {
  642. return this.disconnectInProgress;
  643. } else if (!this.connection) {
  644. return Promise.resolve();
  645. }
  646. this.disconnectInProgress = new Promise(resolve => {
  647. const disconnectListener = (credentials, status) => {
  648. if (status === Strophe.Status.DISCONNECTED) {
  649. resolve();
  650. this.eventEmitter.removeListener(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  651. }
  652. };
  653. this.eventEmitter.on(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  654. });
  655. this._cleanupXmppConnection(ev);
  656. return this.disconnectInProgress;
  657. }
  658. /**
  659. * The method is supposed to gracefully close the XMPP connection and the main goal is to make sure that the current
  660. * participant will be removed from the conference XMPP MUC, so that it doesn't leave a "ghost" participant behind.
  661. *
  662. * @param {Object} ev - Optionally, the event which triggered the necessity to disconnect from the XMPP server
  663. * (e.g. beforeunload, unload).
  664. * @private
  665. * @returns {void}
  666. */
  667. _cleanupXmppConnection(ev) {
  668. // XXX Strophe is asynchronously sending by default. Unfortunately, that means that there may not be enough time
  669. // to send an unavailable presence or disconnect at all. Switching Strophe to synchronous sending is not much of
  670. // an option because it may lead to a noticeable delay in navigating away from the current location. As
  671. // a compromise, we will try to increase the chances of sending an unavailable presence and/or disconnecting
  672. // within the short time span that we have upon unloading by invoking flush() on the connection. We flush() once
  673. // before disconnect() in order to attempt to have its unavailable presence at the top of the send queue. We
  674. // flush() once more after disconnect() in order to attempt to have its unavailable presence sent as soon as
  675. // possible.
  676. !this.connection.isUsingWebSocket && this.connection.flush();
  677. if (!this.connection.isUsingWebSocket && ev !== null && typeof ev !== 'undefined') {
  678. const evType = ev.type;
  679. if (evType === 'beforeunload' || evType === 'unload') {
  680. // XXX Whatever we said above, synchronous sending is the best (known) way to properly disconnect from
  681. // the XMPP server. Consequently, it may be fine to have the source code and comment it in or out
  682. // depending on whether we want to run with it for some time.
  683. this.connection.options.sync = true;
  684. // This is needed in some browsers where sync xhr sending is disabled by default on unload.
  685. if (this.connection.sendUnavailableBeacon()) {
  686. return;
  687. }
  688. }
  689. }
  690. this.connection.disconnect();
  691. if (this.connection.options.sync !== true) {
  692. this.connection.flush();
  693. }
  694. }
  695. /**
  696. *
  697. */
  698. _initStrophePlugins() {
  699. const iceConfig = {
  700. jvb: { iceServers: [ ] },
  701. p2p: { iceServers: [ ] }
  702. };
  703. const p2pStunServers = (this.options.p2p
  704. && this.options.p2p.stunServers) || DEFAULT_STUN_SERVERS;
  705. if (Array.isArray(p2pStunServers)) {
  706. logger.info('P2P STUN servers: ', p2pStunServers);
  707. iceConfig.p2p.iceServers = p2pStunServers;
  708. }
  709. if (this.options.p2p && this.options.p2p.iceTransportPolicy) {
  710. logger.info('P2P ICE transport policy: ',
  711. this.options.p2p.iceTransportPolicy);
  712. iceConfig.p2p.iceTransportPolicy
  713. = this.options.p2p.iceTransportPolicy;
  714. }
  715. this.connection.addConnectionPlugin('emuc', new MucConnectionPlugin(this));
  716. this.connection.addConnectionPlugin('jingle', new JingleConnectionPlugin(this, this.eventEmitter, iceConfig));
  717. this.connection.addConnectionPlugin('rayo', new RayoConnectionPlugin());
  718. }
  719. /**
  720. * Returns details about connection failure. Shard change or is it after
  721. * suspend.
  722. * @returns {object} contains details about a connection failure.
  723. * @private
  724. */
  725. _getConnectionFailedReasonDetails() {
  726. const details = {};
  727. // check for moving between shard if information is available
  728. if (this.options.deploymentInfo
  729. && this.options.deploymentInfo.shard
  730. && this.connection.lastResponseHeaders) {
  731. // split headers by line
  732. const headersArr = this.connection.lastResponseHeaders
  733. .trim().split(/[\r\n]+/);
  734. const headers = {};
  735. headersArr.forEach(line => {
  736. const parts = line.split(': ');
  737. const header = parts.shift();
  738. const value = parts.join(': ');
  739. headers[header] = value;
  740. });
  741. /* eslint-disable camelcase */
  742. details.shard_changed
  743. = this.options.deploymentInfo.shard
  744. !== headers['x-jitsi-shard'];
  745. /* eslint-enable camelcase */
  746. }
  747. /* eslint-disable camelcase */
  748. // check for possible suspend
  749. details.suspend_time = this.connection.ping.getPingSuspendTime();
  750. details.time_since_last_success = this.connection.getTimeSinceLastSuccess();
  751. /* eslint-enable camelcase */
  752. return details;
  753. }
  754. /**
  755. * Notifies speaker stats component if available that we are the new
  756. * dominant speaker in the conference.
  757. * @param {String} roomJid - The room jid where the speaker event occurred.
  758. */
  759. sendDominantSpeakerEvent(roomJid) {
  760. // no speaker stats component advertised
  761. if (!this.speakerStatsComponentAddress || !roomJid) {
  762. return;
  763. }
  764. const msg = $msg({ to: this.speakerStatsComponentAddress });
  765. msg.c('speakerstats', {
  766. xmlns: 'http://jitsi.org/jitmeet',
  767. room: roomJid })
  768. .up();
  769. this.connection.send(msg);
  770. }
  771. /**
  772. * Check if the given argument is a valid JSON ENDPOINT_MESSAGE string by
  773. * parsing it and checking if it has a field called 'type'.
  774. *
  775. * @param {string} jsonString check if this string is a valid json string
  776. * and contains the special structure.
  777. * @returns {boolean, object} if given object is a valid JSON string, return
  778. * the json object. Otherwise, returns false.
  779. */
  780. tryParseJSONAndVerify(jsonString) {
  781. // ignore empty strings, like message errors
  782. if (!jsonString) {
  783. return false;
  784. }
  785. try {
  786. const json = JSON.parse(jsonString);
  787. // Handle non-exception-throwing cases:
  788. // Neither JSON.parse(false) or JSON.parse(1234) throw errors,
  789. // hence the type-checking,
  790. // but... JSON.parse(null) returns null, and
  791. // typeof null === "object",
  792. // so we must check for that, too.
  793. // Thankfully, null is falsey, so this suffices:
  794. if (json && typeof json === 'object') {
  795. const type = json[JITSI_MEET_MUC_TYPE];
  796. if (typeof type !== 'undefined') {
  797. return json;
  798. }
  799. logger.debug('parsing valid json but does not have correct '
  800. + 'structure', 'topic: ', type);
  801. }
  802. } catch (e) {
  803. logger.error(`Error parsing json ${jsonString}`, e);
  804. return false;
  805. }
  806. return false;
  807. }
  808. /**
  809. * A private message is received, message that is not addressed to the muc.
  810. * We expect private message coming from plugins component if it is
  811. * enabled and running.
  812. *
  813. * @param {string} msg - The message.
  814. */
  815. _onPrivateMessage(msg) {
  816. const from = msg.getAttribute('from');
  817. if (!(from === this.speakerStatsComponentAddress
  818. || from === this.conferenceDurationComponentAddress
  819. || from === this.avModerationComponentAddress)) {
  820. return true;
  821. }
  822. const jsonMessage = $(msg).find('>json-message')
  823. .text();
  824. const parsedJson = this.tryParseJSONAndVerify(jsonMessage);
  825. if (!parsedJson) {
  826. return true;
  827. }
  828. if (parsedJson[JITSI_MEET_MUC_TYPE] === 'speakerstats' && parsedJson.users) {
  829. this.eventEmitter.emit(XMPPEvents.SPEAKER_STATS_RECEIVED, parsedJson.users);
  830. } else if (parsedJson[JITSI_MEET_MUC_TYPE] === 'conference_duration' && parsedJson.created_timestamp) {
  831. this.eventEmitter.emit(XMPPEvents.CONFERENCE_TIMESTAMP_RECEIVED, parsedJson.created_timestamp);
  832. } else if (parsedJson[JITSI_MEET_MUC_TYPE] === 'av_moderation') {
  833. this.eventEmitter.emit(XMPPEvents.AV_MODERATION_RECEIVED, parsedJson);
  834. }
  835. return true;
  836. }
  837. /**
  838. * Sends deployment info to stats if not sent already.
  839. * We want to try sending it on failure to connect
  840. * or when we get a sys message(from jiconop2)
  841. * or after success or failure of disco-info
  842. * @param force Whether to force sending without checking anything.
  843. * @private
  844. */
  845. _maybeSendDeploymentInfoStat(force) {
  846. const acceptedStatuses = [
  847. Strophe.Status.ERROR,
  848. Strophe.Status.CONNFAIL,
  849. Strophe.Status.AUTHFAIL,
  850. Strophe.Status.DISCONNECTED,
  851. Strophe.Status.CONNTIMEOUT
  852. ];
  853. if (!force && !(acceptedStatuses.includes(this.connection.status) && this.sendDeploymentInfo)) {
  854. return;
  855. }
  856. // Log deployment-specific information, if available. Defined outside
  857. // the application by individual deployments
  858. const aprops = this.options.deploymentInfo;
  859. if (aprops && Object.keys(aprops).length > 0) {
  860. const logObject = {};
  861. logObject.id = 'deployment_info';
  862. for (const attr in aprops) {
  863. if (aprops.hasOwnProperty(attr)) {
  864. logObject[attr] = aprops[attr];
  865. }
  866. }
  867. Statistics.sendLog(JSON.stringify(logObject));
  868. }
  869. this.sendDeploymentInfo = false;
  870. }
  871. }