您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

xmpp.js 42KB

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