modified lib-jitsi-meet dev repo
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.

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