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.

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