modified lib-jitsi-meet dev repo
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

xmpp.js 40KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  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: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 === 'speakerstats') {
  384. this.speakerStatsComponentAddress = identity.name;
  385. }
  386. if (identity.type === 'conference_duration') {
  387. this.conferenceDurationComponentAddress = identity.name;
  388. }
  389. if (identity.type === 'lobbyrooms') {
  390. this.lobbySupported = true;
  391. const processLobbyFeatures = f => {
  392. f.forEach(fr => {
  393. if (fr.endsWith('#displayname_required')) {
  394. this.eventEmitter.emit(JitsiConnectionEvents.DISPLAY_NAME_REQUIRED);
  395. }
  396. });
  397. };
  398. if (features) {
  399. processLobbyFeatures(features);
  400. } else {
  401. identity.name && this.caps.getFeaturesAndIdentities(identity.name, identity.type)
  402. .then(({ features: f }) => processLobbyFeatures(f))
  403. .catch(e => logger.warn('Error getting features from lobby.', e && e.message));
  404. }
  405. }
  406. if (identity.type === 'shard') {
  407. this.options.deploymentInfo.shard = this.connection.shard = identity.name;
  408. }
  409. if (identity.type === 'region') {
  410. this.options.deploymentInfo.region = this.connection.region = identity.name;
  411. }
  412. if (identity.type === 'release') {
  413. this.options.deploymentInfo.backendRelease = identity.name;
  414. }
  415. if (identity.type === 'breakout_rooms') {
  416. this.breakoutRoomsComponentAddress = identity.name;
  417. }
  418. });
  419. this._maybeSendDeploymentInfoStat(true);
  420. if (this.avModerationComponentAddress
  421. || this.speakerStatsComponentAddress
  422. || this.conferenceDurationComponentAddress
  423. || this.breakoutRoomsComponentAddress) {
  424. this.connection.addHandler(this._onPrivateMessage.bind(this), null, 'message', null, null);
  425. }
  426. }
  427. /**
  428. * Parses a raw failure xmpp xml message received on auth failed.
  429. *
  430. * @param {string} msg - The raw failure message from xmpp.
  431. * @returns {string|null} - The parsed message from the raw xmpp message.
  432. */
  433. _parseConnectionFailedMessage(msg) {
  434. if (!msg) {
  435. return null;
  436. }
  437. const matches = FAILURE_REGEX.exec(msg);
  438. return matches ? matches[1] : null;
  439. }
  440. /**
  441. *
  442. * @param jid
  443. * @param password
  444. */
  445. _connect(jid, password) {
  446. // connection.connect() starts the connection process.
  447. //
  448. // As the connection process proceeds, the user supplied callback will
  449. // be triggered multiple times with status updates. The callback should
  450. // take two arguments - the status code and the error condition.
  451. //
  452. // The status code will be one of the values in the Strophe.Status
  453. // constants. The error condition will be one of the conditions defined
  454. // in RFC 3920 or the condition ‘strophe-parsererror’.
  455. //
  456. // The Parameters wait, hold and route are optional and only relevant
  457. // for BOSH connections. Please see XEP 124 for a more detailed
  458. // explanation of the optional parameters.
  459. //
  460. // Connection status constants for use by the connection handler
  461. // callback.
  462. //
  463. // Status.ERROR - An error has occurred (websockets specific)
  464. // Status.CONNECTING - The connection is currently being made
  465. // Status.CONNFAIL - The connection attempt failed
  466. // Status.AUTHENTICATING - The connection is authenticating
  467. // Status.AUTHFAIL - The authentication attempt failed
  468. // Status.CONNECTED - The connection has succeeded
  469. // Status.DISCONNECTED - The connection has been terminated
  470. // Status.DISCONNECTING - The connection is currently being terminated
  471. // Status.ATTACHED - The connection has been attached
  472. this._resetState();
  473. // we want to send this only on the initial connect
  474. this.sendDiscoInfo = true;
  475. this.sendDeploymentInfo = true;
  476. if (this.connection._stropheConn && this.connection._stropheConn._addSysHandler) {
  477. this._sysMessageHandler = this.connection._stropheConn._addSysHandler(
  478. this._onSystemMessage.bind(this),
  479. null,
  480. 'message'
  481. );
  482. } else {
  483. logger.warn('Cannot attach strophe system handler, jiconop cannot operate');
  484. }
  485. this.connection.connect(
  486. jid,
  487. password,
  488. this.connectionHandler.bind(this, {
  489. jid,
  490. password
  491. }));
  492. }
  493. /**
  494. * Receives system messages during the connect/login process and checks for services or
  495. * @param msg The received message.
  496. * @returns {void}
  497. * @private
  498. */
  499. _onSystemMessage(msg) {
  500. // proceed only if the message has any of the expected information
  501. if ($(msg).find('>services').length === 0 && $(msg).find('>query').length === 0) {
  502. return;
  503. }
  504. this.sendDiscoInfo = false;
  505. const foundIceServers = this.connection.jingle.onReceiveStunAndTurnCredentials(msg);
  506. const { features, identities } = parseDiscoInfo(msg);
  507. this._processDiscoInfoIdentities(identities, features);
  508. if (foundIceServers || identities.size > 0 || features.size > 0) {
  509. this.connection._stropheConn.deleteHandler(this._sysMessageHandler);
  510. this._sysMessageHandler = null;
  511. }
  512. }
  513. /**
  514. * Attach to existing connection. Can be used for optimizations. For
  515. * example: if the connection is created on the server we can attach to it
  516. * and start using it.
  517. *
  518. * @param options {object} connecting options - rid, sid, jid and password.
  519. */
  520. attach(options) {
  521. this._resetState();
  522. // we want to send this only on the initial connect
  523. this.sendDiscoInfo = true;
  524. const now = this.connectionTimes.attaching = window.performance.now();
  525. logger.log('(TIME) Strophe Attaching:\t', now);
  526. this.connection.attach(options.jid, options.sid,
  527. parseInt(options.rid, 10) + 1,
  528. this.connectionHandler.bind(this, {
  529. jid: options.jid,
  530. password: options.password
  531. }));
  532. }
  533. /**
  534. * Resets any state/flag before starting a new connection.
  535. * @private
  536. */
  537. _resetState() {
  538. this.anonymousConnectionFailed = false;
  539. this.connectionFailed = false;
  540. this.lastErrorMsg = undefined;
  541. this.disconnectInProgress = undefined;
  542. }
  543. /**
  544. *
  545. * @param jid
  546. * @param password
  547. */
  548. connect(jid, password) {
  549. if (!jid) {
  550. const { anonymousdomain, domain } = this.options.hosts;
  551. let configDomain = anonymousdomain || domain;
  552. // Force authenticated domain if room is appended with '?login=true'
  553. // or if we're joining with the token
  554. // FIXME Do not rely on window.location because (1) React Native
  555. // does not have a window.location by default and (2) here we cannot
  556. // know for sure that query/search has not be stripped from
  557. // window.location by the time the following executes.
  558. const { location } = window;
  559. if (anonymousdomain) {
  560. const search = location && location.search;
  561. if ((search && search.indexOf('login=true') !== -1)
  562. || this.token) {
  563. configDomain = domain;
  564. }
  565. }
  566. // eslint-disable-next-line no-param-reassign
  567. jid = configDomain || (location && location.hostname);
  568. }
  569. return this._connect(jid, password);
  570. }
  571. /**
  572. * Joins or creates a muc with the provided jid, created from the passed
  573. * in room name and muc host and onCreateResource result.
  574. *
  575. * @param {string} roomName - The name of the muc to join.
  576. * @param {Object} options - Configuration for how to join the muc.
  577. * @param {Function} [onCreateResource] - Callback to invoke when a resource
  578. * is to be added to the jid.
  579. * @returns {Promise} Resolves with an instance of a strophe muc.
  580. */
  581. createRoom(roomName, options, onCreateResource) {
  582. // Support passing the domain in a String object as part of the room name.
  583. const domain = roomName.domain || options.customDomain;
  584. // There are cases (when using subdomain) where muc can hold an uppercase part
  585. let roomjid = `${this.getRoomJid(roomName, domain)}/`;
  586. const mucNickname = onCreateResource
  587. ? onCreateResource(this.connection.jid, this.authenticatedUser)
  588. : RandomUtil.randomHexString(8).toLowerCase();
  589. logger.info(`JID ${this.connection.jid} using MUC nickname ${mucNickname}`);
  590. roomjid += mucNickname;
  591. return this.connection.emuc.createRoom(roomjid, null, options);
  592. }
  593. /**
  594. * Returns the room JID based on the passed room name and domain.
  595. *
  596. * @param {string} roomName - The room name.
  597. * @param {string} domain - The domain.
  598. * @returns {string} - The room JID.
  599. */
  600. getRoomJid(roomName, domain) {
  601. return `${roomName}@${domain ? domain : this.options.hosts.muc.toLowerCase()}`;
  602. }
  603. /**
  604. * Check if a room with the passed JID is already created.
  605. *
  606. * @param {string} roomJid - The JID of the room.
  607. * @returns {boolean}
  608. */
  609. isRoomCreated(roomName, domain) {
  610. return this.connection.emuc.isRoomCreated(this.getRoomJid(roomName, domain));
  611. }
  612. /**
  613. * Returns the jid of the participant associated with the Strophe connection.
  614. *
  615. * @returns {string} The jid of the participant.
  616. */
  617. getJid() {
  618. return this.connection.jid;
  619. }
  620. /**
  621. * Returns the logs from strophe.jingle.
  622. * @returns {Object}
  623. */
  624. getJingleLog() {
  625. const jingle = this.connection.jingle;
  626. return jingle ? jingle.getLog() : {};
  627. }
  628. /**
  629. * Returns the logs from strophe.
  630. */
  631. getXmppLog() {
  632. return (this.connection.logger || {}).log || null;
  633. }
  634. /**
  635. *
  636. */
  637. dial(...args) {
  638. this.connection.rayo.dial(...args);
  639. }
  640. /**
  641. * Pings the server.
  642. * @param timeout how many ms before a timeout should occur.
  643. * @returns {Promise} resolved on ping success and reject on an error or
  644. * a timeout.
  645. */
  646. ping(timeout) {
  647. return new Promise((resolve, reject) => {
  648. this.connection.ping.ping(this.connection.pingDomain, resolve, reject, timeout);
  649. });
  650. }
  651. /**
  652. *
  653. */
  654. getSessions() {
  655. return this.connection.jingle.sessions;
  656. }
  657. /**
  658. * Disconnects this from the XMPP server (if this is connected).
  659. *
  660. * @param {Object} ev - Optionally, the event which triggered the necessity to
  661. * disconnect from the XMPP server (e.g. beforeunload, unload).
  662. * @returns {Promise} - Resolves when the disconnect process is finished or rejects with an error.
  663. */
  664. disconnect(ev) {
  665. if (this.disconnectInProgress) {
  666. return this.disconnectInProgress;
  667. } else if (!this.connection) {
  668. return Promise.resolve();
  669. }
  670. this.disconnectInProgress = new Promise(resolve => {
  671. const disconnectListener = (credentials, status) => {
  672. if (status === Strophe.Status.DISCONNECTED) {
  673. resolve();
  674. this.eventEmitter.removeListener(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  675. }
  676. };
  677. this.eventEmitter.on(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  678. });
  679. this._cleanupXmppConnection(ev);
  680. return this.disconnectInProgress;
  681. }
  682. /**
  683. * The method is supposed to gracefully close the XMPP connection and the main goal is to make sure that the current
  684. * participant will be removed from the conference XMPP MUC, so that it doesn't leave a "ghost" participant behind.
  685. *
  686. * @param {Object} ev - Optionally, the event which triggered the necessity to disconnect from the XMPP server
  687. * (e.g. beforeunload, unload).
  688. * @private
  689. * @returns {void}
  690. */
  691. _cleanupXmppConnection(ev) {
  692. // XXX Strophe is asynchronously sending by default. Unfortunately, that means that there may not be enough time
  693. // to send an unavailable presence or disconnect at all. Switching Strophe to synchronous sending is not much of
  694. // an option because it may lead to a noticeable delay in navigating away from the current location. As
  695. // a compromise, we will try to increase the chances of sending an unavailable presence and/or disconnecting
  696. // within the short time span that we have upon unloading by invoking flush() on the connection. We flush() once
  697. // before disconnect() in order to attempt to have its unavailable presence at the top of the send queue. We
  698. // flush() once more after disconnect() in order to attempt to have its unavailable presence sent as soon as
  699. // possible.
  700. !this.connection.isUsingWebSocket && this.connection.flush();
  701. if (!this.connection.isUsingWebSocket && ev !== null && typeof ev !== 'undefined') {
  702. const evType = ev.type;
  703. if (evType === 'beforeunload' || evType === 'unload') {
  704. // XXX Whatever we said above, synchronous sending is the best (known) way to properly disconnect from
  705. // the XMPP server. Consequently, it may be fine to have the source code and comment it in or out
  706. // depending on whether we want to run with it for some time.
  707. this.connection.options.sync = true;
  708. // This is needed in some browsers where sync xhr sending is disabled by default on unload.
  709. if (this.connection.sendUnavailableBeacon()) {
  710. return;
  711. }
  712. }
  713. }
  714. this.connection.disconnect();
  715. if (this.connection.options.sync !== true) {
  716. this.connection.flush();
  717. }
  718. }
  719. /**
  720. *
  721. */
  722. _initStrophePlugins() {
  723. const iceConfig = {
  724. jvb: { iceServers: [ ] },
  725. p2p: { iceServers: [ ] }
  726. };
  727. const p2pStunServers = (this.options.p2p
  728. && this.options.p2p.stunServers) || DEFAULT_STUN_SERVERS;
  729. if (Array.isArray(p2pStunServers)) {
  730. logger.info('P2P STUN servers: ', p2pStunServers);
  731. iceConfig.p2p.iceServers = p2pStunServers;
  732. }
  733. if (this.options.p2p && this.options.p2p.iceTransportPolicy) {
  734. logger.info('P2P ICE transport policy: ',
  735. this.options.p2p.iceTransportPolicy);
  736. iceConfig.p2p.iceTransportPolicy
  737. = this.options.p2p.iceTransportPolicy;
  738. }
  739. this.connection.addConnectionPlugin('emuc', new MucConnectionPlugin(this));
  740. this.connection.addConnectionPlugin('jingle', new JingleConnectionPlugin(this, this.eventEmitter, iceConfig));
  741. this.connection.addConnectionPlugin('rayo', new RayoConnectionPlugin());
  742. }
  743. /**
  744. * Returns details about connection failure. Shard change or is it after
  745. * suspend.
  746. * @returns {object} contains details about a connection failure.
  747. * @private
  748. */
  749. _getConnectionFailedReasonDetails() {
  750. const details = {};
  751. // check for moving between shard if information is available
  752. if (this.options.deploymentInfo
  753. && this.options.deploymentInfo.shard
  754. && this.connection.lastResponseHeaders) {
  755. // split headers by line
  756. const headersArr = this.connection.lastResponseHeaders
  757. .trim().split(/[\r\n]+/);
  758. const headers = {};
  759. headersArr.forEach(line => {
  760. const parts = line.split(': ');
  761. const header = parts.shift();
  762. const value = parts.join(': ');
  763. headers[header] = value;
  764. });
  765. /* eslint-disable camelcase */
  766. details.shard_changed
  767. = this.options.deploymentInfo.shard
  768. !== headers['x-jitsi-shard'];
  769. /* eslint-enable camelcase */
  770. }
  771. /* eslint-disable camelcase */
  772. // check for possible suspend
  773. details.suspend_time = this.connection.ping.getPingSuspendTime();
  774. details.time_since_last_success = this.connection.getTimeSinceLastSuccess();
  775. /* eslint-enable camelcase */
  776. return details;
  777. }
  778. /**
  779. * Notifies speaker stats component if available that we are the new
  780. * dominant speaker in the conference.
  781. * @param {String} roomJid - The room jid where the speaker event occurred.
  782. */
  783. sendDominantSpeakerEvent(roomJid) {
  784. // no speaker stats component advertised
  785. if (!this.speakerStatsComponentAddress || !roomJid) {
  786. return;
  787. }
  788. const msg = $msg({ to: this.speakerStatsComponentAddress });
  789. msg.c('speakerstats', {
  790. xmlns: 'http://jitsi.org/jitmeet',
  791. room: roomJid })
  792. .up();
  793. this.connection.send(msg);
  794. }
  795. /**
  796. * Sends face expressions to speaker stats component.
  797. * @param {String} roomJid - The room jid where the speaker event occurred.
  798. * @param {Object} payload - The expression to be sent to the speaker stats.
  799. */
  800. sendFaceExpressionEvent(roomJid, payload) {
  801. // no speaker stats component advertised
  802. if (!this.speakerStatsComponentAddress || !roomJid) {
  803. return;
  804. }
  805. const msg = $msg({ to: this.speakerStatsComponentAddress });
  806. msg.c('faceExpression', {
  807. xmlns: 'http://jitsi.org/jitmeet',
  808. room: roomJid,
  809. expression: payload.faceExpression,
  810. duration: payload.duration
  811. }).up();
  812. this.connection.send(msg);
  813. }
  814. /**
  815. * Check if the given argument is a valid JSON ENDPOINT_MESSAGE string by
  816. * parsing it and checking if it has a field called 'type'.
  817. *
  818. * @param {string} jsonString check if this string is a valid json string
  819. * and contains the special structure.
  820. * @returns {boolean, object} if given object is a valid JSON string, return
  821. * the json object. Otherwise, returns false.
  822. */
  823. tryParseJSONAndVerify(jsonString) {
  824. // ignore empty strings, like message errors
  825. if (!jsonString) {
  826. return false;
  827. }
  828. try {
  829. const json = JSON.parse(jsonString);
  830. // Handle non-exception-throwing cases:
  831. // Neither JSON.parse(false) or JSON.parse(1234) throw errors,
  832. // hence the type-checking,
  833. // but... JSON.parse(null) returns null, and
  834. // typeof null === "object",
  835. // so we must check for that, too.
  836. // Thankfully, null is falsey, so this suffices:
  837. if (json && typeof json === 'object') {
  838. const type = json[JITSI_MEET_MUC_TYPE];
  839. if (typeof type !== 'undefined') {
  840. return json;
  841. }
  842. logger.debug('parsing valid json but does not have correct '
  843. + 'structure', 'topic: ', type);
  844. }
  845. } catch (e) {
  846. logger.error(`Error parsing json ${jsonString}`, e);
  847. return false;
  848. }
  849. return false;
  850. }
  851. /**
  852. * A private message is received, message that is not addressed to the muc.
  853. * We expect private message coming from plugins component if it is
  854. * enabled and running.
  855. *
  856. * @param {string} msg - The message.
  857. */
  858. _onPrivateMessage(msg) {
  859. const from = msg.getAttribute('from');
  860. if (!(from === this.speakerStatsComponentAddress
  861. || from === this.conferenceDurationComponentAddress
  862. || from === this.avModerationComponentAddress
  863. || from === this.breakoutRoomsComponentAddress)) {
  864. return true;
  865. }
  866. const jsonMessage = $(msg).find('>json-message')
  867. .text();
  868. const parsedJson = this.tryParseJSONAndVerify(jsonMessage);
  869. if (!parsedJson) {
  870. return true;
  871. }
  872. if (parsedJson[JITSI_MEET_MUC_TYPE] === 'speakerstats' && parsedJson.users) {
  873. this.eventEmitter.emit(XMPPEvents.SPEAKER_STATS_RECEIVED, parsedJson.users);
  874. } else if (parsedJson[JITSI_MEET_MUC_TYPE] === 'conference_duration' && parsedJson.created_timestamp) {
  875. this.eventEmitter.emit(XMPPEvents.CONFERENCE_TIMESTAMP_RECEIVED, parsedJson.created_timestamp);
  876. } else if (parsedJson[JITSI_MEET_MUC_TYPE] === 'av_moderation') {
  877. this.eventEmitter.emit(XMPPEvents.AV_MODERATION_RECEIVED, parsedJson);
  878. } else if (parsedJson[JITSI_MEET_MUC_TYPE] === 'breakout_rooms') {
  879. this.eventEmitter.emit(XMPPEvents.BREAKOUT_ROOMS_EVENT, parsedJson);
  880. }
  881. return true;
  882. }
  883. /**
  884. * Sends deployment info to stats if not sent already.
  885. * We want to try sending it on failure to connect
  886. * or when we get a sys message(from jiconop2)
  887. * or after success or failure of disco-info
  888. * @param force Whether to force sending without checking anything.
  889. * @private
  890. */
  891. _maybeSendDeploymentInfoStat(force) {
  892. const acceptedStatuses = [
  893. Strophe.Status.ERROR,
  894. Strophe.Status.CONNFAIL,
  895. Strophe.Status.AUTHFAIL,
  896. Strophe.Status.DISCONNECTED,
  897. Strophe.Status.CONNTIMEOUT
  898. ];
  899. if (!force && !(acceptedStatuses.includes(this.connection.status) && this.sendDeploymentInfo)) {
  900. return;
  901. }
  902. // Log deployment-specific information, if available. Defined outside
  903. // the application by individual deployments
  904. const aprops = this.options.deploymentInfo;
  905. if (aprops && Object.keys(aprops).length > 0) {
  906. const logObject = {};
  907. for (const attr in aprops) {
  908. if (aprops.hasOwnProperty(attr)) {
  909. logObject[attr] = aprops[attr];
  910. }
  911. }
  912. // Let's push to analytics any updates that may have come from the backend
  913. Statistics.analytics.addPermanentProperties({ ...logObject });
  914. logObject.id = 'deployment_info';
  915. Statistics.sendLog(JSON.stringify(logObject));
  916. }
  917. this.sendDeploymentInfo = false;
  918. }
  919. }