Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

xmpp.js 42KB

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