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

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