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

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