Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

xmpp.js 39KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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. if (identity.type === 'breakout_rooms') {
  398. this.breakoutRoomsComponentAddress = identity.name;
  399. }
  400. });
  401. this._maybeSendDeploymentInfoStat(true);
  402. if (this.avModerationComponentAddress
  403. || this.speakerStatsComponentAddress
  404. || this.conferenceDurationComponentAddress) {
  405. this.connection.addHandler(this._onPrivateMessage.bind(this), null, 'message', null, null);
  406. }
  407. }
  408. /**
  409. * Parses a raw failure xmpp xml message received on auth failed.
  410. *
  411. * @param {string} msg - The raw failure message from xmpp.
  412. * @returns {string|null} - The parsed message from the raw xmpp message.
  413. */
  414. _parseConnectionFailedMessage(msg) {
  415. if (!msg) {
  416. return null;
  417. }
  418. const matches = FAILURE_REGEX.exec(msg);
  419. return matches ? matches[1] : null;
  420. }
  421. /**
  422. *
  423. * @param jid
  424. * @param password
  425. */
  426. _connect(jid, password) {
  427. // connection.connect() starts the connection process.
  428. //
  429. // As the connection process proceeds, the user supplied callback will
  430. // be triggered multiple times with status updates. The callback should
  431. // take two arguments - the status code and the error condition.
  432. //
  433. // The status code will be one of the values in the Strophe.Status
  434. // constants. The error condition will be one of the conditions defined
  435. // in RFC 3920 or the condition ‘strophe-parsererror’.
  436. //
  437. // The Parameters wait, hold and route are optional and only relevant
  438. // for BOSH connections. Please see XEP 124 for a more detailed
  439. // explanation of the optional parameters.
  440. //
  441. // Connection status constants for use by the connection handler
  442. // callback.
  443. //
  444. // Status.ERROR - An error has occurred (websockets specific)
  445. // Status.CONNECTING - The connection is currently being made
  446. // Status.CONNFAIL - The connection attempt failed
  447. // Status.AUTHENTICATING - The connection is authenticating
  448. // Status.AUTHFAIL - The authentication attempt failed
  449. // Status.CONNECTED - The connection has succeeded
  450. // Status.DISCONNECTED - The connection has been terminated
  451. // Status.DISCONNECTING - The connection is currently being terminated
  452. // Status.ATTACHED - The connection has been attached
  453. this._resetState();
  454. // we want to send this only on the initial connect
  455. this.sendDiscoInfo = true;
  456. this.sendDeploymentInfo = true;
  457. if (this.connection._stropheConn && this.connection._stropheConn._addSysHandler) {
  458. this._sysMessageHandler = this.connection._stropheConn._addSysHandler(
  459. this._onSystemMessage.bind(this),
  460. null,
  461. 'message'
  462. );
  463. } else {
  464. logger.warn('Cannot attach strophe system handler, jiconop cannot operate');
  465. }
  466. this.connection.connect(
  467. jid,
  468. password,
  469. this.connectionHandler.bind(this, {
  470. jid,
  471. password
  472. }));
  473. }
  474. /**
  475. * Receives system messages during the connect/login process and checks for services or
  476. * @param msg The received message.
  477. * @returns {void}
  478. * @private
  479. */
  480. _onSystemMessage(msg) {
  481. // proceed only if the message has any of the expected information
  482. if ($(msg).find('>services').length === 0 && $(msg).find('>query').length === 0) {
  483. return;
  484. }
  485. this.sendDiscoInfo = false;
  486. const foundIceServers = this.connection.jingle.onReceiveStunAndTurnCredentials(msg);
  487. const { features, identities } = parseDiscoInfo(msg);
  488. this._processDiscoInfoIdentities(identities, features);
  489. if (foundIceServers || identities.size > 0 || features.size > 0) {
  490. this.connection._stropheConn.deleteHandler(this._sysMessageHandler);
  491. this._sysMessageHandler = null;
  492. }
  493. }
  494. /**
  495. * Attach to existing connection. Can be used for optimizations. For
  496. * example: if the connection is created on the server we can attach to it
  497. * and start using it.
  498. *
  499. * @param options {object} connecting options - rid, sid, jid and password.
  500. */
  501. attach(options) {
  502. this._resetState();
  503. // we want to send this only on the initial connect
  504. this.sendDiscoInfo = true;
  505. const now = this.connectionTimes.attaching = window.performance.now();
  506. logger.log('(TIME) Strophe Attaching:\t', now);
  507. this.connection.attach(options.jid, options.sid,
  508. parseInt(options.rid, 10) + 1,
  509. this.connectionHandler.bind(this, {
  510. jid: options.jid,
  511. password: options.password
  512. }));
  513. }
  514. /**
  515. * Resets any state/flag before starting a new connection.
  516. * @private
  517. */
  518. _resetState() {
  519. this.anonymousConnectionFailed = false;
  520. this.connectionFailed = false;
  521. this.lastErrorMsg = undefined;
  522. this.disconnectInProgress = undefined;
  523. }
  524. /**
  525. *
  526. * @param jid
  527. * @param password
  528. */
  529. connect(jid, password) {
  530. if (!jid) {
  531. const { anonymousdomain, domain } = this.options.hosts;
  532. let configDomain = anonymousdomain || domain;
  533. // Force authenticated domain if room is appended with '?login=true'
  534. // or if we're joining with the token
  535. // FIXME Do not rely on window.location because (1) React Native
  536. // does not have a window.location by default and (2) here we cannot
  537. // know for sure that query/search has not be stripped from
  538. // window.location by the time the following executes.
  539. const { location } = window;
  540. if (anonymousdomain) {
  541. const search = location && location.search;
  542. if ((search && search.indexOf('login=true') !== -1)
  543. || this.token) {
  544. configDomain = domain;
  545. }
  546. }
  547. // eslint-disable-next-line no-param-reassign
  548. jid = configDomain || (location && location.hostname);
  549. }
  550. return this._connect(jid, password);
  551. }
  552. /**
  553. * Joins or creates a muc with the provided jid, created from the passed
  554. * in room name and muc host and onCreateResource result.
  555. *
  556. * @param {string} roomName - The name of the muc to join.
  557. * @param {Object} options - Configuration for how to join the muc.
  558. * @param {Function} [onCreateResource] - Callback to invoke when a resource
  559. * is to be added to the jid.
  560. * @returns {Promise} Resolves with an instance of a strophe muc.
  561. */
  562. createRoom(roomName, options, onCreateResource) {
  563. // Support passing the domain in a String object as part of the room name.
  564. const domain = roomName.domain || options.customDomain;
  565. // There are cases (when using subdomain) where muc can hold an uppercase part
  566. let roomjid = `${this.getRoomJid(roomName, domain)}/`;
  567. const mucNickname = onCreateResource
  568. ? onCreateResource(this.connection.jid, this.authenticatedUser)
  569. : RandomUtil.randomHexString(8).toLowerCase();
  570. logger.info(`JID ${this.connection.jid} using MUC nickname ${mucNickname}`);
  571. roomjid += mucNickname;
  572. return this.connection.emuc.createRoom(roomjid, null, options);
  573. }
  574. /**
  575. * Returns the room JID based on the passed room name and domain.
  576. *
  577. * @param {string} roomName - The room name.
  578. * @param {string} domain - The domain.
  579. * @returns {string} - The room JID.
  580. */
  581. getRoomJid(roomName, domain) {
  582. return `${roomName}@${domain ? domain : this.options.hosts.muc.toLowerCase()}`;
  583. }
  584. /**
  585. * Check if a room with the passed JID is already created.
  586. *
  587. * @param {string} roomJid - The JID of the room.
  588. * @returns {boolean}
  589. */
  590. isRoomCreated(roomName, domain) {
  591. return this.connection.emuc.isRoomCreated(this.getRoomJid(roomName, domain));
  592. }
  593. /**
  594. * Returns the jid of the participant associated with the Strophe connection.
  595. *
  596. * @returns {string} The jid of the participant.
  597. */
  598. getJid() {
  599. return this.connection.jid;
  600. }
  601. /**
  602. * Returns the logs from strophe.jingle.
  603. * @returns {Object}
  604. */
  605. getJingleLog() {
  606. const jingle = this.connection.jingle;
  607. return jingle ? jingle.getLog() : {};
  608. }
  609. /**
  610. * Returns the logs from strophe.
  611. */
  612. getXmppLog() {
  613. return (this.connection.logger || {}).log || null;
  614. }
  615. /**
  616. *
  617. */
  618. dial(...args) {
  619. this.connection.rayo.dial(...args);
  620. }
  621. /**
  622. * Pings the server.
  623. * @param timeout how many ms before a timeout should occur.
  624. * @returns {Promise} resolved on ping success and reject on an error or
  625. * a timeout.
  626. */
  627. ping(timeout) {
  628. return new Promise((resolve, reject) => {
  629. this.connection.ping.ping(this.connection.pingDomain, resolve, reject, timeout);
  630. });
  631. }
  632. /**
  633. *
  634. */
  635. getSessions() {
  636. return this.connection.jingle.sessions;
  637. }
  638. /**
  639. * Disconnects this from the XMPP server (if this is connected).
  640. *
  641. * @param {Object} ev - Optionally, the event which triggered the necessity to
  642. * disconnect from the XMPP server (e.g. beforeunload, unload).
  643. * @returns {Promise} - Resolves when the disconnect process is finished or rejects with an error.
  644. */
  645. disconnect(ev) {
  646. if (this.disconnectInProgress) {
  647. return this.disconnectInProgress;
  648. } else if (!this.connection) {
  649. return Promise.resolve();
  650. }
  651. this.disconnectInProgress = new Promise(resolve => {
  652. const disconnectListener = (credentials, status) => {
  653. if (status === Strophe.Status.DISCONNECTED) {
  654. resolve();
  655. this.eventEmitter.removeListener(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  656. }
  657. };
  658. this.eventEmitter.on(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  659. });
  660. this._cleanupXmppConnection(ev);
  661. return this.disconnectInProgress;
  662. }
  663. /**
  664. * The method is supposed to gracefully close the XMPP connection and the main goal is to make sure that the current
  665. * participant will be removed from the conference XMPP MUC, so that it doesn't leave a "ghost" participant behind.
  666. *
  667. * @param {Object} ev - Optionally, the event which triggered the necessity to disconnect from the XMPP server
  668. * (e.g. beforeunload, unload).
  669. * @private
  670. * @returns {void}
  671. */
  672. _cleanupXmppConnection(ev) {
  673. // XXX Strophe is asynchronously sending by default. Unfortunately, that means that there may not be enough time
  674. // to send an unavailable presence or disconnect at all. Switching Strophe to synchronous sending is not much of
  675. // an option because it may lead to a noticeable delay in navigating away from the current location. As
  676. // a compromise, we will try to increase the chances of sending an unavailable presence and/or disconnecting
  677. // within the short time span that we have upon unloading by invoking flush() on the connection. We flush() once
  678. // before disconnect() in order to attempt to have its unavailable presence at the top of the send queue. We
  679. // flush() once more after disconnect() in order to attempt to have its unavailable presence sent as soon as
  680. // possible.
  681. !this.connection.isUsingWebSocket && this.connection.flush();
  682. if (!this.connection.isUsingWebSocket && ev !== null && typeof ev !== 'undefined') {
  683. const evType = ev.type;
  684. if (evType === 'beforeunload' || evType === 'unload') {
  685. // XXX Whatever we said above, synchronous sending is the best (known) way to properly disconnect from
  686. // the XMPP server. Consequently, it may be fine to have the source code and comment it in or out
  687. // depending on whether we want to run with it for some time.
  688. this.connection.options.sync = true;
  689. // This is needed in some browsers where sync xhr sending is disabled by default on unload.
  690. if (this.connection.sendUnavailableBeacon()) {
  691. return;
  692. }
  693. }
  694. }
  695. this.connection.disconnect();
  696. if (this.connection.options.sync !== true) {
  697. this.connection.flush();
  698. }
  699. }
  700. /**
  701. *
  702. */
  703. _initStrophePlugins() {
  704. const iceConfig = {
  705. jvb: { iceServers: [ ] },
  706. p2p: { iceServers: [ ] }
  707. };
  708. const p2pStunServers = (this.options.p2p
  709. && this.options.p2p.stunServers) || DEFAULT_STUN_SERVERS;
  710. if (Array.isArray(p2pStunServers)) {
  711. logger.info('P2P STUN servers: ', p2pStunServers);
  712. iceConfig.p2p.iceServers = p2pStunServers;
  713. }
  714. if (this.options.p2p && this.options.p2p.iceTransportPolicy) {
  715. logger.info('P2P ICE transport policy: ',
  716. this.options.p2p.iceTransportPolicy);
  717. iceConfig.p2p.iceTransportPolicy
  718. = this.options.p2p.iceTransportPolicy;
  719. }
  720. this.connection.addConnectionPlugin('emuc', new MucConnectionPlugin(this));
  721. this.connection.addConnectionPlugin('jingle', new JingleConnectionPlugin(this, this.eventEmitter, iceConfig));
  722. this.connection.addConnectionPlugin('rayo', new RayoConnectionPlugin());
  723. }
  724. /**
  725. * Returns details about connection failure. Shard change or is it after
  726. * suspend.
  727. * @returns {object} contains details about a connection failure.
  728. * @private
  729. */
  730. _getConnectionFailedReasonDetails() {
  731. const details = {};
  732. // check for moving between shard if information is available
  733. if (this.options.deploymentInfo
  734. && this.options.deploymentInfo.shard
  735. && this.connection.lastResponseHeaders) {
  736. // split headers by line
  737. const headersArr = this.connection.lastResponseHeaders
  738. .trim().split(/[\r\n]+/);
  739. const headers = {};
  740. headersArr.forEach(line => {
  741. const parts = line.split(': ');
  742. const header = parts.shift();
  743. const value = parts.join(': ');
  744. headers[header] = value;
  745. });
  746. /* eslint-disable camelcase */
  747. details.shard_changed
  748. = this.options.deploymentInfo.shard
  749. !== headers['x-jitsi-shard'];
  750. /* eslint-enable camelcase */
  751. }
  752. /* eslint-disable camelcase */
  753. // check for possible suspend
  754. details.suspend_time = this.connection.ping.getPingSuspendTime();
  755. details.time_since_last_success = this.connection.getTimeSinceLastSuccess();
  756. /* eslint-enable camelcase */
  757. return details;
  758. }
  759. /**
  760. * Notifies speaker stats component if available that we are the new
  761. * dominant speaker in the conference.
  762. * @param {String} roomJid - The room jid where the speaker event occurred.
  763. */
  764. sendDominantSpeakerEvent(roomJid) {
  765. // no speaker stats component advertised
  766. if (!this.speakerStatsComponentAddress || !roomJid) {
  767. return;
  768. }
  769. const msg = $msg({ to: this.speakerStatsComponentAddress });
  770. msg.c('speakerstats', {
  771. xmlns: 'http://jitsi.org/jitmeet',
  772. room: roomJid })
  773. .up();
  774. this.connection.send(msg);
  775. }
  776. /**
  777. * Sends facial expression to speaker stats component.
  778. * @param {String} roomJid - The room jid where the speaker event occurred.
  779. * @param {Object} payload - The expression to be sent to the speaker stats.
  780. */
  781. sendFacialExpressionEvent(roomJid, payload) {
  782. // no speaker stats component advertised
  783. if (!this.speakerStatsComponentAddress || !roomJid) {
  784. return;
  785. }
  786. const msg = $msg({ to: this.speakerStatsComponentAddress });
  787. msg.c('facialExpression', {
  788. xmlns: 'http://jitsi.org/jitmeet',
  789. room: roomJid,
  790. expression: payload.facialExpression,
  791. duration: payload.duration
  792. }).up();
  793. this.connection.send(msg);
  794. }
  795. /**
  796. * Check if the given argument is a valid JSON ENDPOINT_MESSAGE string by
  797. * parsing it and checking if it has a field called 'type'.
  798. *
  799. * @param {string} jsonString check if this string is a valid json string
  800. * and contains the special structure.
  801. * @returns {boolean, object} if given object is a valid JSON string, return
  802. * the json object. Otherwise, returns false.
  803. */
  804. tryParseJSONAndVerify(jsonString) {
  805. // ignore empty strings, like message errors
  806. if (!jsonString) {
  807. return false;
  808. }
  809. try {
  810. const json = JSON.parse(jsonString);
  811. // Handle non-exception-throwing cases:
  812. // Neither JSON.parse(false) or JSON.parse(1234) throw errors,
  813. // hence the type-checking,
  814. // but... JSON.parse(null) returns null, and
  815. // typeof null === "object",
  816. // so we must check for that, too.
  817. // Thankfully, null is falsey, so this suffices:
  818. if (json && typeof json === 'object') {
  819. const type = json[JITSI_MEET_MUC_TYPE];
  820. if (typeof type !== 'undefined') {
  821. return json;
  822. }
  823. logger.debug('parsing valid json but does not have correct '
  824. + 'structure', 'topic: ', type);
  825. }
  826. } catch (e) {
  827. logger.error(`Error parsing json ${jsonString}`, e);
  828. return false;
  829. }
  830. return false;
  831. }
  832. /**
  833. * A private message is received, message that is not addressed to the muc.
  834. * We expect private message coming from plugins component if it is
  835. * enabled and running.
  836. *
  837. * @param {string} msg - The message.
  838. */
  839. _onPrivateMessage(msg) {
  840. const from = msg.getAttribute('from');
  841. if (!(from === this.speakerStatsComponentAddress
  842. || from === this.conferenceDurationComponentAddress
  843. || from === this.avModerationComponentAddress
  844. || from === this.breakoutRoomsComponentAddress)) {
  845. return true;
  846. }
  847. const jsonMessage = $(msg).find('>json-message')
  848. .text();
  849. const parsedJson = this.tryParseJSONAndVerify(jsonMessage);
  850. if (!parsedJson) {
  851. return true;
  852. }
  853. if (parsedJson[JITSI_MEET_MUC_TYPE] === 'speakerstats' && parsedJson.users) {
  854. this.eventEmitter.emit(XMPPEvents.SPEAKER_STATS_RECEIVED, parsedJson.users);
  855. } else if (parsedJson[JITSI_MEET_MUC_TYPE] === 'conference_duration' && parsedJson.created_timestamp) {
  856. this.eventEmitter.emit(XMPPEvents.CONFERENCE_TIMESTAMP_RECEIVED, parsedJson.created_timestamp);
  857. } else if (parsedJson[JITSI_MEET_MUC_TYPE] === 'av_moderation') {
  858. this.eventEmitter.emit(XMPPEvents.AV_MODERATION_RECEIVED, parsedJson);
  859. } else if (parsedJson[JITSI_MEET_MUC_TYPE] === 'breakout_rooms') {
  860. this.eventEmitter.emit(XMPPEvents.BREAKOUT_ROOMS_EVENT, parsedJson);
  861. }
  862. return true;
  863. }
  864. /**
  865. * Sends deployment info to stats if not sent already.
  866. * We want to try sending it on failure to connect
  867. * or when we get a sys message(from jiconop2)
  868. * or after success or failure of disco-info
  869. * @param force Whether to force sending without checking anything.
  870. * @private
  871. */
  872. _maybeSendDeploymentInfoStat(force) {
  873. const acceptedStatuses = [
  874. Strophe.Status.ERROR,
  875. Strophe.Status.CONNFAIL,
  876. Strophe.Status.AUTHFAIL,
  877. Strophe.Status.DISCONNECTED,
  878. Strophe.Status.CONNTIMEOUT
  879. ];
  880. if (!force && !(acceptedStatuses.includes(this.connection.status) && this.sendDeploymentInfo)) {
  881. return;
  882. }
  883. // Log deployment-specific information, if available. Defined outside
  884. // the application by individual deployments
  885. const aprops = this.options.deploymentInfo;
  886. if (aprops && Object.keys(aprops).length > 0) {
  887. const logObject = {};
  888. logObject.id = 'deployment_info';
  889. for (const attr in aprops) {
  890. if (aprops.hasOwnProperty(attr)) {
  891. logObject[attr] = aprops[attr];
  892. }
  893. }
  894. Statistics.sendLog(JSON.stringify(logObject));
  895. }
  896. this.sendDeploymentInfo = false;
  897. }
  898. }