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

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