Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

xmpp.js 42KB

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