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

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