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

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