You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

moderator.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. /* eslint-disable newline-per-chained-call */
  2. import { getLogger } from '@jitsi/logger';
  3. import $ from 'jquery';
  4. import { $iq } from 'strophe.js';
  5. import { CONNECTION_REDIRECTED } from '../../JitsiConnectionEvents';
  6. import FeatureFlags from '../flags/FeatureFlags';
  7. import Settings from '../settings/Settings';
  8. import Listenable from '../util/Listenable';
  9. const AuthenticationEvents
  10. = require('../../service/authentication/AuthenticationEvents');
  11. const { XMPPEvents } = require('../../service/xmpp/XMPPEvents');
  12. const logger = getLogger(__filename);
  13. /**
  14. * Exponential backoff timer.
  15. * @param step the step to use.
  16. */
  17. function createExpBackoffTimer(step) {
  18. let count = 1;
  19. const maxTimeout = 120000;
  20. return function(reset) {
  21. // Reset call
  22. if (reset) {
  23. count = 1;
  24. return;
  25. }
  26. // Calculate next timeout
  27. const timeout = Math.pow(2, count - 1);
  28. count += 1;
  29. return Math.min(timeout * step, maxTimeout);
  30. };
  31. }
  32. /**
  33. * The moderator/focus responsible for direct communication with jicofo
  34. */
  35. export default class Moderator extends Listenable {
  36. /**
  37. * Constructs moderator.
  38. * @param xmpp The xmpp.
  39. */
  40. constructor(xmpp) {
  41. super();
  42. this.getNextTimeout = createExpBackoffTimer(1000);
  43. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  44. this.options = xmpp.options;
  45. // Whether SIP gateway (jigasi) support is enabled. TODO: use presence so it can be changed based on jigasi
  46. // availability.
  47. this.sipGatewayEnabled = false;
  48. this.xmpp = xmpp;
  49. this.connection = xmpp.connection;
  50. // The JID to which conference-iq requests are sent over XMPP.
  51. this.targetJid = this.options.hosts?.focus;
  52. // If not specified default to 'focus.domain'
  53. if (!this.targetJid) {
  54. this.targetJid = `focus.${this.options.hosts?.domain}`;
  55. }
  56. this.targetUrl = this.options.conferenceRequestUrl;
  57. // Whether to send conference requests over HTTP or XMPP
  58. this.mode = this.targetUrl ? 'http' : 'xmpp';
  59. logger.info(`Using ${this.mode} for conference requests.`);
  60. // The set of JIDs known to belong to jicofo. Populated from configuration
  61. // and responses from conference requests.
  62. this.focusUserJids = new Set();
  63. if (this.options.focusUserJid) {
  64. this.focusUserJids.add(this.options.focusUserJid);
  65. }
  66. // FIXME: Message listener that talks to POPUP window
  67. /**
  68. *
  69. * @param event
  70. */
  71. function listener(event) {
  72. if (event.data && event.data.sessionId) {
  73. if (event.origin !== window.location.origin) {
  74. logger.warn(`Ignoring sessionId from different origin: ${event.origin}`);
  75. return;
  76. }
  77. Settings.sessionId = event.data.sessionId;
  78. // After popup is closed we will authenticate
  79. }
  80. }
  81. // Register
  82. if (window.addEventListener) {
  83. window.addEventListener('message', listener, false);
  84. } else {
  85. window.attachEvent('onmessage', listener);
  86. }
  87. }
  88. /**
  89. * Check whether the supplied jid is a known jid for focus.
  90. * @param jid
  91. * @returns {boolean}
  92. */
  93. isFocusJid(jid) {
  94. if (!jid) {
  95. return false;
  96. }
  97. for (const focusJid of this.focusUserJids) {
  98. // jid may be a full JID, and focusUserJids may be bare JIDs
  99. if (jid.indexOf(`${focusJid}/`) === 0) {
  100. return true;
  101. }
  102. }
  103. return false;
  104. }
  105. /**
  106. * Is sip gw enabled.
  107. * @returns {boolean}
  108. */
  109. isSipGatewayEnabled() {
  110. return this.sipGatewayEnabled;
  111. }
  112. /**
  113. * Create a conference request based on the configured options and saved Settings.
  114. *
  115. * A conference request has the following format:
  116. * {
  117. * room: "room@example.com",
  118. * sessionId: "foo", // optional
  119. * machineUdi: "bar", // optional
  120. * identity: "baz", // optional
  121. * properties: { } // map string to string
  122. * }
  123. *
  124. * It can be encoded in either JSON or and IQ.
  125. *
  126. * @param roomJid - The room jid for which to send conference request.
  127. *
  128. * @returns the created conference request.
  129. */
  130. _createConferenceRequest(roomJid) {
  131. // Session Id used for authentication
  132. const { sessionId } = Settings;
  133. const config = this.options;
  134. const properties = {};
  135. if (config.startAudioMuted !== undefined) {
  136. properties.startAudioMuted = config.startAudioMuted;
  137. }
  138. if (config.startVideoMuted !== undefined) {
  139. properties.startVideoMuted = config.startVideoMuted;
  140. }
  141. // this flag determines whether the bridge will include this call in its
  142. // rtcstats reporting or not. If the site admin hasn't set the flag in
  143. // config.js, then the client defaults to false (see
  144. // react/features/rtcstats/functions.js in jitsi-meet). The server-side
  145. // components default to true to match the pre-existing behavior, so we only
  146. // signal if false.
  147. const rtcstatsEnabled = config?.analytics?.rtcstatsEnabled ?? false;
  148. if (!rtcstatsEnabled) {
  149. properties.rtcstatsEnabled = false;
  150. }
  151. const conferenceRequest = {
  152. properties,
  153. machineUid: Settings.machineId,
  154. room: roomJid
  155. };
  156. if (sessionId) {
  157. conferenceRequest.sessionId = sessionId;
  158. }
  159. if (FeatureFlags.isJoinAsVisitorSupported() && !config.iAmRecorder && !config.iAmSipGateway) {
  160. conferenceRequest.properties['visitors-version'] = 1;
  161. if (this.options.preferVisitor) {
  162. conferenceRequest.properties.visitor = true;
  163. }
  164. }
  165. return conferenceRequest;
  166. }
  167. /**
  168. * Create a conference request and encode it as an IQ.
  169. *
  170. * @param roomJid - The room jid for which to send conference request.
  171. */
  172. _createConferenceIq(roomJid) {
  173. const conferenceRequest = this._createConferenceRequest(roomJid);
  174. // Generate create conference IQ
  175. const elem = $iq({
  176. to: this.targetJid,
  177. type: 'set'
  178. });
  179. elem.c('conference', {
  180. xmlns: 'http://jitsi.org/protocol/focus',
  181. room: roomJid,
  182. 'machine-uid': conferenceRequest.machineUid
  183. });
  184. if (conferenceRequest.sessionId) {
  185. elem.attrs({ 'session-id': conferenceRequest.sessionId });
  186. }
  187. for (const k in conferenceRequest.properties) {
  188. if (conferenceRequest.properties.hasOwnProperty(k)) {
  189. elem.c(
  190. 'property', {
  191. name: k,
  192. value: conferenceRequest.properties[k]
  193. })
  194. .up();
  195. }
  196. }
  197. return elem;
  198. }
  199. /**
  200. * Parses a conference IQ.
  201. * @param resultIq the result IQ that is received.
  202. * @returns {{properties: {}}} Returns an object with the parsed properties.
  203. * @private
  204. */
  205. _parseConferenceIq(resultIq) {
  206. const conferenceRequest = { properties: {} };
  207. conferenceRequest.focusJid = $(resultIq)
  208. .find('conference')
  209. .attr('focusjid');
  210. conferenceRequest.sessionId = $(resultIq)
  211. .find('conference')
  212. .attr('session-id');
  213. conferenceRequest.identity = $(resultIq)
  214. .find('>conference')
  215. .attr('identity');
  216. conferenceRequest.ready = $(resultIq)
  217. .find('conference')
  218. .attr('ready') === 'true';
  219. conferenceRequest.vnode = $(resultIq)
  220. .find('conference')
  221. .attr('vnode');
  222. if ($(resultIq).find('>conference>property[name=\'authentication\'][value=\'true\']').length > 0) {
  223. conferenceRequest.properties.authentication = 'true';
  224. }
  225. if ($(resultIq).find('>conference>property[name=\'externalAuth\'][value=\'true\']').length > 0) {
  226. conferenceRequest.properties.externalAuth = 'true';
  227. }
  228. // Check if jicofo has jigasi support enabled.
  229. if ($(resultIq).find('>conference>property[name=\'sipGatewayEnabled\'][value=\'true\']').length > 0) {
  230. conferenceRequest.properties.sipGatewayEnabled = 'true';
  231. }
  232. return conferenceRequest;
  233. }
  234. // FIXME We need to show the fact that we're waiting for the focus to the user
  235. // (or that the focus is not available)
  236. /**
  237. * Allocates the conference focus.
  238. * @param roomJid - The room jid for which to send conference request.
  239. * @returns {Promise} - Resolved when Jicofo allows to join the room. It's never
  240. * rejected, and it'll keep on pinging Jicofo forever.
  241. */
  242. sendConferenceRequest(roomJid) {
  243. // there is no point of sending conference iq when in visitor mode (disableFocus)
  244. // when we have sent early the conference request via http
  245. // we want to skip sending it here, or visitors can loop
  246. if (this.conferenceRequestSent) {
  247. return Promise.resolve();
  248. }
  249. // to mark whether we have already sent a conference request
  250. this.conferenceRequestSent = false;
  251. return new Promise(resolve => {
  252. if (this.mode === 'xmpp') {
  253. logger.info(`Sending conference request over XMPP to ${this.targetJid}`);
  254. this.connection.sendIQ(
  255. this._createConferenceIq(roomJid),
  256. result => this._handleIqSuccess(roomJid, result, resolve),
  257. error => this._handleIqError(roomJid, error, resolve));
  258. // XXX We're pressed for time here because we're beginning a complex
  259. // and/or lengthy conference-establishment process which supposedly
  260. // involves multiple RTTs. We don't have the time to wait for Strophe to
  261. // decide to send our IQ.
  262. this.connection.flush();
  263. } else {
  264. logger.info(`Sending conference request over HTTP to ${this.targetUrl}`);
  265. fetch(this.targetUrl, {
  266. method: 'POST',
  267. body: JSON.stringify(this._createConferenceRequest(roomJid)),
  268. headers: { 'Content-Type': 'application/json' }
  269. })
  270. .then(response => {
  271. if (!response.ok) {
  272. response.text()
  273. .then(text => {
  274. logger.warn(`Received HTTP ${response.status} ${
  275. response.statusText}. Body: ${text}`);
  276. const sessionError = response.status === 400
  277. && text.indexOf('400 invalid-session') > 0;
  278. const notAuthorized = response.status === 403;
  279. this._handleError(roomJid, sessionError, notAuthorized, resolve);
  280. })
  281. .catch(error => {
  282. logger.warn(`Error: ${error}`);
  283. this._handleError(roomJid);
  284. });
  285. // _handleError has either scheduled a retry or fired an event indicating failure.
  286. return;
  287. }
  288. response.json()
  289. .then(resultJson => {
  290. this._handleSuccess(roomJid, resultJson, resolve);
  291. });
  292. })
  293. .catch(error => {
  294. logger.warn(`Error: ${error}`);
  295. this._handleError(roomJid);
  296. });
  297. }
  298. }).then(() => {
  299. this.conferenceRequestSent = true;
  300. });
  301. }
  302. /**
  303. * Handles success response for conference IQ.
  304. * @param roomJid
  305. * @param conferenceRequest
  306. * @param callback
  307. * @private
  308. */
  309. _handleSuccess(roomJid, conferenceRequest, callback) {
  310. // Reset the error timeout (because we haven't failed here).
  311. this.getNextErrorTimeout(true);
  312. if (conferenceRequest.focusJid) {
  313. logger.info(`Adding focus JID: ${conferenceRequest.focusJid}`);
  314. this.focusUserJids.add(conferenceRequest.focusJid);
  315. } else {
  316. logger.warn('Conference request response contained no focusJid.');
  317. }
  318. const authenticationEnabled = conferenceRequest.properties.authentication === 'true';
  319. logger.info(`Authentication enabled: ${authenticationEnabled}`);
  320. if (conferenceRequest.sessionId) {
  321. logger.info(`Received sessionId: ${conferenceRequest.sessionId}`);
  322. Settings.sessionId = conferenceRequest.sessionId;
  323. }
  324. this.eventEmitter.emit(
  325. AuthenticationEvents.IDENTITY_UPDATED, authenticationEnabled, conferenceRequest.identity);
  326. this.sipGatewayEnabled = conferenceRequest.properties.sipGatewayEnabled;
  327. logger.info(`Sip gateway enabled: ${this.sipGatewayEnabled}`);
  328. if (conferenceRequest.ready) {
  329. // Reset the non-error timeout (because we've succeeded here).
  330. this.getNextTimeout(true);
  331. // we want to ignore redirects when this is jibri (record/live-stream or a sip jibri)
  332. if (conferenceRequest.vnode && !this.options.iAmRecorder && !this.options.iAmSipGateway) {
  333. logger.warn(`Redirected to: ${conferenceRequest.vnode} with focusJid ${conferenceRequest.focusJid}`);
  334. this.xmpp.eventEmitter.emit(CONNECTION_REDIRECTED, conferenceRequest.vnode, conferenceRequest.focusJid);
  335. return;
  336. }
  337. logger.info('Conference-request successful, ready to join the MUC.');
  338. callback();
  339. } else {
  340. const waitMs = this.getNextTimeout();
  341. // This was a successful response, but the "ready" flag is not set. Retry after a timeout.
  342. logger.info(`Not ready yet, will retry in ${waitMs} ms.`);
  343. window.setTimeout(
  344. () => this.sendConferenceRequest(roomJid)
  345. .then(callback),
  346. waitMs);
  347. }
  348. }
  349. /**
  350. * Handles error response for conference IQ.
  351. * @param roomJid
  352. * @param sessionError
  353. * @param notAuthorized
  354. * @param callback
  355. * @private
  356. */
  357. _handleError(roomJid, sessionError, notAuthorized, callback) {
  358. // If the session is invalid, remove and try again without session ID to get
  359. // a new one
  360. if (sessionError) {
  361. logger.info('Session expired! - removing');
  362. Settings.sessionId = undefined;
  363. }
  364. // Not authorized to create new room
  365. if (notAuthorized) {
  366. logger.warn('Unauthorized to start the conference');
  367. this.eventEmitter.emit(XMPPEvents.AUTHENTICATION_REQUIRED);
  368. return;
  369. }
  370. const waitMs = this.getNextErrorTimeout();
  371. if (sessionError && waitMs < 60000) {
  372. // If the session is invalid, retry a limited number of times and then fire an error.
  373. logger.info(`Invalid session, will retry after ${waitMs} ms.`);
  374. this.getNextTimeout(true);
  375. window.setTimeout(() => this.sendConferenceRequest(roomJid)
  376. .then(callback), waitMs);
  377. } else {
  378. logger.error('Failed to get a successful response, giving up.');
  379. // This is a "fatal" error and the user of the lib should handle it accordingly.
  380. // TODO: change the event name to something accurate.
  381. this.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED);
  382. }
  383. }
  384. /**
  385. * Invoked by {@link #sendConferenceRequest} upon its request receiving an xmpp error result.
  386. *
  387. * @param roomJid - The room jid used to send conference request.
  388. * @param error - the error result of the request that {@link sendConferenceRequest} sent
  389. * @param {Function} callback - the function to be called back upon the
  390. * successful allocation of the conference focus
  391. */
  392. _handleIqError(roomJid, error, callback) {
  393. // The reservation system only works over XMPP. Handle the error separately.
  394. // Check for error returned by the reservation system
  395. const reservationErr = $(error).find('>error>reservation-error');
  396. if (reservationErr.length) {
  397. // Trigger error event
  398. const errorCode = reservationErr.attr('error-code');
  399. const errorTextNode = $(error).find('>error>text');
  400. let errorMsg;
  401. if (errorTextNode) {
  402. errorMsg = errorTextNode.text();
  403. }
  404. this.eventEmitter.emit(
  405. XMPPEvents.RESERVATION_ERROR,
  406. errorCode,
  407. errorMsg);
  408. return;
  409. }
  410. const invalidSession = Boolean($(error).find('>error>session-invalid').length
  411. || $(error).find('>error>not-acceptable').length);
  412. // Not authorized to create new room
  413. const notAuthorized = $(error).find('>error>not-authorized').length > 0;
  414. this._handleError(roomJid, invalidSession, notAuthorized, callback);
  415. }
  416. /**
  417. * Invoked by {@link #sendConferenecRequest} upon its request receiving a
  418. * success (i.e. non-error) result.
  419. *
  420. * @param roomJid - The room jid used to send conference request.
  421. * @param result - the success (i.e. non-error) result of the request that {@link #sendConferenecRequest} sent
  422. * @param {Function} callback - the function to be called back upon the
  423. * successful allocation of the conference focus
  424. */
  425. _handleIqSuccess(roomJid, result, callback) {
  426. // Setup config options
  427. const conferenceRequest = this._parseConferenceIq(result);
  428. this._handleSuccess(roomJid, conferenceRequest, callback);
  429. }
  430. /**
  431. * Authenticate by sending a conference IQ.
  432. * @param roomJid The room jid.
  433. * @returns {Promise<unknown>}
  434. */
  435. authenticate(roomJid) {
  436. return new Promise((resolve, reject) => {
  437. this.connection.sendIQ(
  438. this._createConferenceIq(roomJid),
  439. result => {
  440. const sessionId = $(result)
  441. .find('conference')
  442. .attr('session-id');
  443. if (sessionId) {
  444. logger.info(`Received sessionId: ${sessionId}`);
  445. Settings.sessionId = sessionId;
  446. } else {
  447. logger.warn('Response did not contain a session-id');
  448. }
  449. resolve();
  450. },
  451. errorIq => reject({
  452. error: $(errorIq)
  453. .find('iq>error :first')
  454. .prop('tagName'),
  455. message: $(errorIq)
  456. .find('iq>error>text')
  457. .text()
  458. })
  459. );
  460. });
  461. }
  462. /**
  463. * Logout by sending conference IQ.
  464. * @param callback
  465. */
  466. logout(callback) {
  467. const iq = $iq({
  468. to: this.targetJid,
  469. type: 'set'
  470. });
  471. const { sessionId } = Settings;
  472. if (!sessionId) {
  473. callback();
  474. return;
  475. }
  476. iq.c('logout', {
  477. xmlns: 'http://jitsi.org/protocol/focus',
  478. 'session-id': sessionId
  479. });
  480. this.connection.sendIQ(
  481. iq,
  482. result => {
  483. logger.info('Log out OK', result);
  484. Settings.sessionId = undefined;
  485. callback();
  486. },
  487. error => {
  488. logger.error('Logout error', error);
  489. }
  490. );
  491. }
  492. }