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

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