Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

xmpp.js 42KB

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