Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

xmpp.js 43KB

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