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

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