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

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