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

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