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 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. /* eslint-disable newline-per-chained-call */
  2. import { getLogger } from '@jitsi/logger';
  3. import { $iq } from 'strophe.js';
  4. import { CONFERENCE_REQUEST_FAILED, NOT_LIVE_ERROR } from '../../JitsiConnectionErrors';
  5. import { CONNECTION_FAILED, CONNECTION_REDIRECTED } from '../../JitsiConnectionEvents';
  6. import Settings from '../settings/Settings';
  7. import Listenable from '../util/Listenable';
  8. import $ from '../util/XMLParser';
  9. const AuthenticationEvents
  10. = require('../../service/authentication/AuthenticationEvents');
  11. const { XMPPEvents } = require('../../service/xmpp/XMPPEvents');
  12. const logger = getLogger('modules/xmpp/moderator');
  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 (!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. token: this.xmpp.token
  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. // check for explicit false, all other cases is considered live
  234. if ($(resultIq).find('>conference>property[name=\'live\'][value=\'false\']').length > 0) {
  235. conferenceRequest.properties.live = 'false';
  236. }
  237. return conferenceRequest;
  238. }
  239. // FIXME We need to show the fact that we're waiting for the focus to the user
  240. // (or that the focus is not available)
  241. /**
  242. * Allocates the conference focus.
  243. * @param roomJid - The room jid for which to send conference request.
  244. * @returns {Promise} - Resolved when Jicofo allows to join the room. It's never
  245. * rejected, and it'll keep on pinging Jicofo forever.
  246. */
  247. sendConferenceRequest(roomJid) {
  248. // there is no point of sending conference iq when in visitor mode (disableFocus)
  249. // when we have sent early the conference request via http
  250. // we want to skip sending it here, or visitors can loop
  251. if (this.conferenceRequestSent) {
  252. return Promise.resolve();
  253. }
  254. // to mark whether we have already sent a conference request
  255. this.conferenceRequestSent = false;
  256. return new Promise((resolve, reject) => {
  257. if (this.mode === 'xmpp') {
  258. logger.info(`Sending conference request over XMPP to ${this.targetJid}`);
  259. this.connection.sendIQ(
  260. this._createConferenceIq(roomJid),
  261. result => this._handleIqSuccess(roomJid, result, resolve, reject),
  262. error => this._handleIqError(roomJid, error, resolve, reject));
  263. // XXX We're pressed for time here because we're beginning a complex
  264. // and/or lengthy conference-establishment process which supposedly
  265. // involves multiple RTTs. We don't have the time to wait for Strophe to
  266. // decide to send our IQ.
  267. this.connection.flush();
  268. } else {
  269. logger.info(`Sending conference request over HTTP to ${this.targetUrl}`);
  270. fetch(this.targetUrl, {
  271. method: 'POST',
  272. body: JSON.stringify(this._createConferenceRequest(roomJid)),
  273. headers: {
  274. 'Content-Type': 'application/json',
  275. ...this.xmpp.token ? { 'Authorization': `Bearer ${this.xmpp.token}` } : {}
  276. }
  277. })
  278. .then(response => {
  279. if (!response.ok) {
  280. response.text()
  281. .then(text => {
  282. logger.warn(`Received HTTP ${response.status} ${
  283. response.statusText}. Body: ${text}`);
  284. const sessionError = response.status === 400
  285. && text.indexOf('400 invalid-session') > 0;
  286. const notAuthorized = response.status === 403;
  287. this._handleError(roomJid, sessionError, notAuthorized, resolve, reject);
  288. })
  289. .catch(error => {
  290. logger.warn(`Error: ${error}`);
  291. this._handleError(roomJid, undefined, undefined, resolve, () => reject(error));
  292. });
  293. // _handleError has either scheduled a retry or fired an event indicating failure.
  294. return;
  295. }
  296. response.json()
  297. .then(resultJson => {
  298. this._handleSuccess(roomJid, resultJson, resolve, reject);
  299. });
  300. })
  301. .catch(error => {
  302. logger.warn(`Error: ${error}`);
  303. this._handleError(roomJid, undefined, undefined, resolve, () => reject(error));
  304. });
  305. }
  306. }).then(() => {
  307. this.conferenceRequestSent = true;
  308. })
  309. .finally(() => {
  310. this.xmpp.connection._breakoutMovingToMain = undefined;
  311. });
  312. }
  313. /**
  314. * Handles success response for conference IQ.
  315. * @param roomJid
  316. * @param conferenceRequest
  317. * @param callback
  318. * @param errorCallback
  319. * @private
  320. */
  321. _handleSuccess(roomJid, conferenceRequest, callback, errorCallback) {
  322. // Reset the error timeout (because we haven't failed here).
  323. this.getNextErrorTimeout(true);
  324. if (conferenceRequest.focusJid) {
  325. logger.info(`Adding focus JID: ${conferenceRequest.focusJid}`);
  326. this.focusUserJids.add(conferenceRequest.focusJid);
  327. } else {
  328. logger.warn('Conference request response contained no focusJid.');
  329. }
  330. const authenticationEnabled = conferenceRequest.properties.authentication === 'true';
  331. logger.info(`Authentication enabled: ${authenticationEnabled}`);
  332. if (conferenceRequest.sessionId) {
  333. logger.info(`Received sessionId: ${conferenceRequest.sessionId}`);
  334. Settings.sessionId = conferenceRequest.sessionId;
  335. }
  336. this.eventEmitter.emit(
  337. AuthenticationEvents.IDENTITY_UPDATED, authenticationEnabled, conferenceRequest.identity);
  338. this.sipGatewayEnabled = conferenceRequest.properties.sipGatewayEnabled;
  339. logger.info(`Sip gateway enabled: ${this.sipGatewayEnabled}`);
  340. if (conferenceRequest.properties.live === 'false' && this.options.preferVisitor) {
  341. this.getNextTimeout(true);
  342. logger.info('Conference is not live.');
  343. this.xmpp.eventEmitter.emit(CONNECTION_FAILED, NOT_LIVE_ERROR);
  344. errorCallback();
  345. return;
  346. }
  347. if (conferenceRequest.ready) {
  348. // Reset the non-error timeout (because we've succeeded here).
  349. this.getNextTimeout(true);
  350. // we want to ignore redirects when this is jibri (record/live-stream or a sip jibri)
  351. // we ignore redirects when moving from a breakout room to the main room
  352. if (conferenceRequest.vnode && !this.options.iAmRecorder && !this.options.iAmSipGateway) {
  353. if (this.connection._breakoutMovingToMain === roomJid) {
  354. logger.info('Skipping redirect as we are moving from breakout to main.');
  355. callback();
  356. return;
  357. }
  358. logger.warn(`Redirected to: ${conferenceRequest.vnode} with focusJid ${conferenceRequest.focusJid}`);
  359. this.xmpp.eventEmitter.emit(CONNECTION_REDIRECTED, conferenceRequest.vnode, conferenceRequest.focusJid);
  360. errorCallback();
  361. return;
  362. }
  363. logger.info('Conference-request successful, ready to join the MUC.');
  364. callback();
  365. } else {
  366. const waitMs = this.getNextTimeout();
  367. // This was a successful response, but the "ready" flag is not set. Retry after a timeout.
  368. logger.info(`Not ready yet, will retry in ${waitMs} ms.`);
  369. window.setTimeout(
  370. () => this.sendConferenceRequest(roomJid)
  371. .then(callback).catch(errorCallback),
  372. waitMs);
  373. }
  374. }
  375. /**
  376. * Handles error response for conference IQ.
  377. * @param roomJid
  378. * @param sessionError
  379. * @param notAuthorized
  380. * @param callback
  381. * @param errorCallback
  382. * @private
  383. */
  384. _handleError(roomJid, sessionError, notAuthorized, callback, errorCallback) { // eslint-disable-line max-params
  385. // If the session is invalid, remove and try again without session ID to get
  386. // a new one
  387. if (sessionError) {
  388. logger.info('Session expired! - removing');
  389. Settings.sessionId = undefined;
  390. }
  391. // Not authorized to create new room
  392. if (notAuthorized) {
  393. logger.warn('Unauthorized to start the conference');
  394. this.eventEmitter.emit(XMPPEvents.AUTHENTICATION_REQUIRED);
  395. errorCallback();
  396. return;
  397. }
  398. const waitMs = this.getNextErrorTimeout();
  399. if (sessionError && waitMs < 60000) {
  400. // If the session is invalid, retry a limited number of times and then fire an error.
  401. logger.info(`Invalid session, will retry after ${waitMs} ms.`);
  402. this.getNextTimeout(true);
  403. window.setTimeout(() => this.sendConferenceRequest(roomJid)
  404. .then(callback)
  405. .catch(errorCallback), waitMs);
  406. } else {
  407. logger.error('Failed to get a successful response, giving up.');
  408. // This is a "fatal" error and the user of the lib should handle it accordingly.
  409. this.xmpp.eventEmitter.emit(CONNECTION_FAILED, CONFERENCE_REQUEST_FAILED);
  410. errorCallback();
  411. }
  412. }
  413. /**
  414. * Invoked by {@link #sendConferenceRequest} upon its request receiving an xmpp error result.
  415. *
  416. * @param roomJid - The room jid used to send conference request.
  417. * @param error - the error result of the request that {@link sendConferenceRequest} sent
  418. * @param {Function} callback - the function to be called back upon the
  419. * successful allocation of the conference focus
  420. * @param errorCallback
  421. */
  422. _handleIqError(roomJid, error, callback, errorCallback) {
  423. // The reservation system only works over XMPP. Handle the error separately.
  424. // Check for error returned by the reservation system
  425. const reservationErr = $(error).find('>error>reservation-error');
  426. if (reservationErr.length) {
  427. // Trigger error event
  428. const errorCode = reservationErr.attr('error-code');
  429. const errorTextNode = $(error).find('>error>text');
  430. let errorMsg;
  431. if (errorTextNode) {
  432. errorMsg = errorTextNode.text();
  433. }
  434. this.eventEmitter.emit(
  435. XMPPEvents.RESERVATION_ERROR,
  436. errorCode,
  437. errorMsg);
  438. errorCallback();
  439. return;
  440. }
  441. const invalidSession = Boolean($(error).find('>error>session-invalid').length
  442. || $(error).find('>error>not-acceptable').length);
  443. // Not authorized to create new room
  444. const notAuthorized = $(error).find('>error>not-authorized').length > 0;
  445. this._handleError(roomJid, invalidSession, notAuthorized, callback, errorCallback);
  446. }
  447. /**
  448. * Invoked by {@link #sendConferenecRequest} upon its request receiving a
  449. * success (i.e. non-error) result.
  450. *
  451. * @param roomJid - The room jid used to send conference request.
  452. * @param result - the success (i.e. non-error) result of the request that {@link #sendConferenecRequest} sent
  453. * @param {Function} callback - the function to be called back upon the
  454. * successful allocation of the conference focus
  455. * @param errorCallback
  456. */
  457. _handleIqSuccess(roomJid, result, callback, errorCallback) {
  458. // Setup config options
  459. const conferenceRequest = this._parseConferenceIq(result);
  460. this._handleSuccess(roomJid, conferenceRequest, callback, errorCallback);
  461. }
  462. /**
  463. * Authenticate by sending a conference IQ.
  464. * @param roomJid The room jid.
  465. * @returns {Promise<unknown>}
  466. */
  467. authenticate(roomJid) {
  468. return new Promise((resolve, reject) => {
  469. this.connection.sendIQ(
  470. this._createConferenceIq(roomJid),
  471. result => {
  472. const sessionId = $(result)
  473. .find('conference')
  474. .attr('session-id');
  475. if (sessionId) {
  476. logger.info(`Received sessionId: ${sessionId}`);
  477. Settings.sessionId = sessionId;
  478. } else {
  479. logger.warn('Response did not contain a session-id');
  480. }
  481. resolve();
  482. },
  483. errorIq => reject({
  484. error: $(errorIq)
  485. .find('iq>error :first')
  486. .prop('tagName'),
  487. message: $(errorIq)
  488. .find('iq>error>text')
  489. .text()
  490. })
  491. );
  492. });
  493. }
  494. /**
  495. * Logout by sending conference IQ.
  496. * @param callback
  497. */
  498. logout(callback) {
  499. const iq = $iq({
  500. to: this.targetJid,
  501. type: 'set'
  502. });
  503. const { sessionId } = Settings;
  504. if (!sessionId) {
  505. callback();
  506. return;
  507. }
  508. iq.c('logout', {
  509. xmlns: 'http://jitsi.org/protocol/focus',
  510. 'session-id': sessionId
  511. });
  512. this.connection.sendIQ(
  513. iq,
  514. result => {
  515. logger.info('Log out OK', result);
  516. Settings.sessionId = undefined;
  517. callback();
  518. },
  519. error => {
  520. logger.error('Logout error', error);
  521. }
  522. );
  523. }
  524. }