選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

xmpp.js 42KB

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