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

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