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

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