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 41KB

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