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.

xmpp.js 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /* global $ */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import { Strophe } from 'strophe.js';
  4. import 'strophejs-plugin-disco';
  5. import RandomUtil from '../util/RandomUtil';
  6. import * as JitsiConnectionErrors from '../../JitsiConnectionErrors';
  7. import * as JitsiConnectionEvents from '../../JitsiConnectionEvents';
  8. import RTCBrowserType from '../RTC/RTCBrowserType';
  9. import initEmuc from './strophe.emuc';
  10. import initJingle from './strophe.jingle';
  11. import initStropheUtil from './strophe.util';
  12. import initPing from './strophe.ping';
  13. import initRayo from './strophe.rayo';
  14. import initStropheLogger from './strophe.logger';
  15. import Listenable from '../util/Listenable';
  16. import Caps from './Caps';
  17. const logger = getLogger(__filename);
  18. /**
  19. *
  20. * @param token
  21. * @param bosh
  22. */
  23. function createConnection(token, bosh = '/http-bind') {
  24. // Append token as URL param
  25. if (token) {
  26. // eslint-disable-next-line no-param-reassign
  27. bosh += `${bosh.indexOf('?') === -1 ? '?' : '&'}token=${token}`;
  28. }
  29. return new Strophe.Connection(bosh);
  30. }
  31. /**
  32. *
  33. */
  34. export default class XMPP extends Listenable {
  35. /**
  36. * FIXME describe all options
  37. * @param {Object} options
  38. * @param {Array<Object>} options.p2pStunServers see
  39. * {@link JingleConnectionPlugin} for more details.
  40. * @param token
  41. */
  42. constructor(options, token) {
  43. super();
  44. this.connection = null;
  45. this.disconnectInProgress = false;
  46. this.connectionTimes = {};
  47. this.options = options;
  48. this.token = token;
  49. this.authenticatedUser = false;
  50. this._initStrophePlugins(this);
  51. this.connection = createConnection(token, options.bosh);
  52. this.caps = new Caps(this.connection, this.options.clientNode);
  53. // Initialize features advertised in disco-info
  54. this.initFeaturesList();
  55. // Setup a disconnect on unload as a way to facilitate API consumers. It
  56. // sounds like they would want that. A problem for them though may be if
  57. // they wanted to utilize the connected connection in an unload handler
  58. // of their own. However, it should be fairly easy for them to do that
  59. // by registering their unload handler before us.
  60. $(window).on('beforeunload unload', this.disconnect.bind(this));
  61. }
  62. /**
  63. * Initializes the list of feature advertised through the disco-info
  64. * mechanism.
  65. */
  66. initFeaturesList() {
  67. // http://xmpp.org/extensions/xep-0167.html#support
  68. // http://xmpp.org/extensions/xep-0176.html#support
  69. this.caps.addFeature('urn:xmpp:jingle:1');
  70. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:1');
  71. this.caps.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  72. this.caps.addFeature('urn:xmpp:jingle:apps:dtls:0');
  73. this.caps.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  74. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  75. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:video');
  76. if (!this.options.disableRtx && RTCBrowserType.supportsRtx()) {
  77. this.caps.addFeature('urn:ietf:rfc:4588');
  78. }
  79. // this is dealt with by SDP O/A so we don't need to announce this
  80. // XEP-0293
  81. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0');
  82. // XEP-0294
  83. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0');
  84. this.caps.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  85. this.caps.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  86. // this.caps.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  87. // Enable Lipsync ?
  88. if (RTCBrowserType.isChrome() && this.options.enableLipSync !== false) {
  89. logger.info('Lip-sync enabled !');
  90. this.caps.addFeature('http://jitsi.org/meet/lipsync');
  91. }
  92. if (this.connection.rayo) {
  93. this.caps.addFeature('urn:xmpp:rayo:client:1');
  94. }
  95. }
  96. /**
  97. *
  98. */
  99. getConnection() {
  100. return this.connection;
  101. }
  102. /**
  103. * Receive connection status changes and handles them.
  104. *
  105. * @param {Object} credentials
  106. * @param {string} credentials.jid - The user's XMPP ID passed to the
  107. * connect method. For example, 'user@xmpp.com'.
  108. * @param {string} credentials.password - The password passed to the connect
  109. * method.
  110. * @param {string} status - One of Strophe's connection status strings.
  111. * @param {string} [msg] - The connection error message provided by Strophe.
  112. */
  113. connectionHandler(credentials = {}, status, msg) {
  114. const now = window.performance.now();
  115. const statusStr = Strophe.getStatusString(status).toLowerCase();
  116. this.connectionTimes[statusStr] = now;
  117. logger.log(
  118. `(TIME) Strophe ${statusStr}${msg ? `[${msg}]` : ''}:\t`,
  119. now);
  120. if (status === Strophe.Status.CONNECTED
  121. || status === Strophe.Status.ATTACHED) {
  122. if (this.options.useStunTurn
  123. || (this.options.p2p && this.options.p2p.useStunTurn)) {
  124. this.connection.jingle.getStunAndTurnCredentials();
  125. }
  126. logger.info(`My Jabber ID: ${this.connection.jid}`);
  127. // Schedule ping ?
  128. const pingJid = this.connection.domain;
  129. this.connection.ping.hasPingSupport(
  130. pingJid,
  131. hasPing => {
  132. if (hasPing) {
  133. this.connection.ping.startInterval(pingJid);
  134. } else {
  135. logger.warn(`Ping NOT supported by ${pingJid}`);
  136. }
  137. });
  138. if (credentials.password) {
  139. this.authenticatedUser = true;
  140. }
  141. if (this.connection && this.connection.connected
  142. && Strophe.getResourceFromJid(this.connection.jid)) {
  143. // .connected is true while connecting?
  144. // this.connection.send($pres());
  145. this.eventEmitter.emit(
  146. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  147. Strophe.getResourceFromJid(this.connection.jid));
  148. }
  149. } else if (status === Strophe.Status.CONNFAIL) {
  150. if (msg === 'x-strophe-bad-non-anon-jid') {
  151. this.anonymousConnectionFailed = true;
  152. } else {
  153. this.connectionFailed = true;
  154. }
  155. this.lastErrorMsg = msg;
  156. if (msg === 'giving-up') {
  157. this.eventEmitter.emit(
  158. JitsiConnectionEvents.CONNECTION_FAILED,
  159. JitsiConnectionErrors.OTHER_ERROR, msg);
  160. }
  161. } else if (status === Strophe.Status.DISCONNECTED) {
  162. // Stop ping interval
  163. this.connection.ping.stopInterval();
  164. const wasIntentionalDisconnect = this.disconnectInProgress;
  165. const errMsg = msg || this.lastErrorMsg;
  166. this.disconnectInProgress = false;
  167. if (this.anonymousConnectionFailed) {
  168. // prompt user for username and password
  169. this.eventEmitter.emit(
  170. JitsiConnectionEvents.CONNECTION_FAILED,
  171. JitsiConnectionErrors.PASSWORD_REQUIRED);
  172. } else if (this.connectionFailed) {
  173. this.eventEmitter.emit(
  174. JitsiConnectionEvents.CONNECTION_FAILED,
  175. JitsiConnectionErrors.OTHER_ERROR, errMsg);
  176. } else if (wasIntentionalDisconnect) {
  177. this.eventEmitter.emit(
  178. JitsiConnectionEvents.CONNECTION_DISCONNECTED, errMsg);
  179. } else {
  180. // XXX if Strophe drops the connection while not being asked to,
  181. // it means that most likely some serious error has occurred.
  182. // One currently known case is when a BOSH request fails for
  183. // more than 4 times. The connection is dropped without
  184. // supplying a reason(error message/event) through the API.
  185. logger.error('XMPP connection dropped!');
  186. // XXX if the last request error is within 5xx range it means it
  187. // was a server failure
  188. const lastErrorStatus = Strophe.getLastErrorStatus();
  189. if (lastErrorStatus >= 500 && lastErrorStatus < 600) {
  190. this.eventEmitter.emit(
  191. JitsiConnectionEvents.CONNECTION_FAILED,
  192. JitsiConnectionErrors.SERVER_ERROR,
  193. errMsg || 'server-error');
  194. } else {
  195. this.eventEmitter.emit(
  196. JitsiConnectionEvents.CONNECTION_FAILED,
  197. JitsiConnectionErrors.CONNECTION_DROPPED_ERROR,
  198. errMsg || 'connection-dropped-error');
  199. }
  200. }
  201. } else if (status === Strophe.Status.AUTHFAIL) {
  202. // wrong password or username, prompt user
  203. this.eventEmitter.emit(
  204. JitsiConnectionEvents.CONNECTION_FAILED,
  205. JitsiConnectionErrors.PASSWORD_REQUIRED,
  206. msg,
  207. credentials);
  208. }
  209. }
  210. /**
  211. *
  212. * @param jid
  213. * @param password
  214. */
  215. _connect(jid, password) {
  216. // connection.connect() starts the connection process.
  217. //
  218. // As the connection process proceeds, the user supplied callback will
  219. // be triggered multiple times with status updates. The callback should
  220. // take two arguments - the status code and the error condition.
  221. //
  222. // The status code will be one of the values in the Strophe.Status
  223. // constants. The error condition will be one of the conditions defined
  224. // in RFC 3920 or the condition ‘strophe-parsererror’.
  225. //
  226. // The Parameters wait, hold and route are optional and only relevant
  227. // for BOSH connections. Please see XEP 124 for a more detailed
  228. // explanation of the optional parameters.
  229. //
  230. // Connection status constants for use by the connection handler
  231. // callback.
  232. //
  233. // Status.ERROR - An error has occurred (websockets specific)
  234. // Status.CONNECTING - The connection is currently being made
  235. // Status.CONNFAIL - The connection attempt failed
  236. // Status.AUTHENTICATING - The connection is authenticating
  237. // Status.AUTHFAIL - The authentication attempt failed
  238. // Status.CONNECTED - The connection has succeeded
  239. // Status.DISCONNECTED - The connection has been terminated
  240. // Status.DISCONNECTING - The connection is currently being terminated
  241. // Status.ATTACHED - The connection has been attached
  242. this.anonymousConnectionFailed = false;
  243. this.connectionFailed = false;
  244. this.lastErrorMsg = undefined;
  245. this.connection.connect(
  246. jid,
  247. password,
  248. this.connectionHandler.bind(this, {
  249. jid,
  250. password
  251. }));
  252. }
  253. /**
  254. * Attach to existing connection. Can be used for optimizations. For
  255. * example: if the connection is created on the server we can attach to it
  256. * and start using it.
  257. *
  258. * @param options {object} connecting options - rid, sid, jid and password.
  259. */
  260. attach(options) {
  261. const now = this.connectionTimes.attaching = window.performance.now();
  262. logger.log(`(TIME) Strophe Attaching\t:${now}`);
  263. this.connection.attach(options.jid, options.sid,
  264. parseInt(options.rid, 10) + 1,
  265. this.connectionHandler.bind(this, {
  266. jid: options.jid,
  267. password: options.password
  268. }));
  269. }
  270. /**
  271. *
  272. * @param jid
  273. * @param password
  274. */
  275. connect(jid, password) {
  276. if (!jid) {
  277. const { anonymousdomain, domain } = this.options.hosts;
  278. let configDomain = anonymousdomain || domain;
  279. // Force authenticated domain if room is appended with '?login=true'
  280. // or if we're joining with the token
  281. // FIXME Do not rely on window.location because (1) React Native
  282. // does not have a window.location by default and (2) here we cannot
  283. // know for sure that query/search has not be stripped from
  284. // window.location by the time the following executes.
  285. const { location } = window;
  286. if (anonymousdomain) {
  287. const search = location && location.search;
  288. if ((search && search.indexOf('login=true') !== -1)
  289. || this.token) {
  290. configDomain = domain;
  291. }
  292. }
  293. // eslint-disable-next-line no-param-reassign
  294. jid = configDomain || (location && location.hostname);
  295. }
  296. return this._connect(jid, password);
  297. }
  298. /**
  299. *
  300. * @param roomName
  301. * @param options
  302. */
  303. createRoom(roomName, options) {
  304. // By default MUC nickname is the resource part of the JID
  305. let mucNickname = Strophe.getNodeFromJid(this.connection.jid);
  306. let roomjid = `${roomName}@${this.options.hosts.muc}/`;
  307. const cfgNickname
  308. = options.useNicks && options.nick ? options.nick : null;
  309. if (cfgNickname) {
  310. // Use nick if it's defined
  311. mucNickname = options.nick;
  312. } else if (!this.authenticatedUser) {
  313. // node of the anonymous JID is very long - here we trim it a bit
  314. mucNickname = mucNickname.substr(0, 8);
  315. }
  316. // Constant JIDs need some random part to be appended in order to be
  317. // able to join the MUC more than once.
  318. if (this.authenticatedUser || cfgNickname !== null) {
  319. mucNickname += `-${RandomUtil.randomHexString(6)}`;
  320. }
  321. roomjid += mucNickname;
  322. return this.connection.emuc.createRoom(roomjid, null, options);
  323. }
  324. /**
  325. * Returns the logs from strophe.jingle.
  326. * @returns {Object}
  327. */
  328. getJingleLog() {
  329. const jingle = this.connection.jingle;
  330. return jingle ? jingle.getLog() : {};
  331. }
  332. /**
  333. * Returns the logs from strophe.
  334. */
  335. getXmppLog() {
  336. return (this.connection.logger || {}).log || null;
  337. }
  338. /**
  339. *
  340. */
  341. dial(...args) {
  342. this.connection.rayo.dial(...args);
  343. }
  344. /**
  345. *
  346. * @param jid
  347. * @param mute
  348. */
  349. setMute(jid, mute) {
  350. this.connection.moderate.setMute(jid, mute);
  351. }
  352. /**
  353. *
  354. * @param jid
  355. */
  356. eject(jid) {
  357. this.connection.moderate.eject(jid);
  358. }
  359. /**
  360. *
  361. */
  362. getSessions() {
  363. return this.connection.jingle.sessions;
  364. }
  365. /**
  366. * Disconnects this from the XMPP server (if this is connected).
  367. *
  368. * @param ev optionally, the event which triggered the necessity to
  369. * disconnect from the XMPP server (e.g. beforeunload, unload).
  370. */
  371. disconnect(ev) {
  372. if (this.disconnectInProgress
  373. || !this.connection
  374. || !this.connection.connected) {
  375. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  376. return;
  377. }
  378. this.disconnectInProgress = true;
  379. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  380. // means that there may not be enough time to send an unavailable
  381. // presence or disconnect at all. Switching Strophe to synchronous
  382. // sending is not much of an option because it may lead to a noticeable
  383. // delay in navigating away from the current location. As a compromise,
  384. // we will try to increase the chances of sending an unavailable
  385. // presence and/or disconecting within the short time span that we have
  386. // upon unloading by invoking flush() on the connection. We flush() once
  387. // before disconnect() in order to attemtp to have its unavailable
  388. // presence at the top of the send queue. We flush() once more after
  389. // disconnect() in order to attempt to have its unavailable presence
  390. // sent as soon as possible.
  391. this.connection.flush();
  392. if (ev !== null && typeof ev !== 'undefined') {
  393. const evType = ev.type;
  394. if (evType === 'beforeunload' || evType === 'unload') {
  395. // XXX Whatever we said above, synchronous sending is the best
  396. // (known) way to properly disconnect from the XMPP server.
  397. // Consequently, it may be fine to have the source code and
  398. // comment it in or out depending on whether we want to run with
  399. // it for some time.
  400. this.connection.options.sync = true;
  401. }
  402. }
  403. this.connection.disconnect();
  404. if (this.connection.options.sync !== true) {
  405. this.connection.flush();
  406. }
  407. }
  408. /**
  409. *
  410. */
  411. _initStrophePlugins() {
  412. const iceConfig = {
  413. jvb: { iceServers: [ ] },
  414. p2p: { iceServers: [ ] }
  415. };
  416. // FIXME: remove once we have a default config template. -saghul
  417. const defaultStunServers = [
  418. { urls: 'stun:stun.l.google.com:19302' },
  419. { urls: 'stun:stun1.l.google.com:19302' },
  420. { urls: 'stun:stun2.l.google.com:19302' }
  421. ];
  422. const p2pStunServers = (this.options.p2p
  423. && this.options.p2p.stunServers) || defaultStunServers;
  424. if (Array.isArray(p2pStunServers)) {
  425. logger.info('P2P STUN servers: ', p2pStunServers);
  426. iceConfig.p2p.iceServers = p2pStunServers;
  427. }
  428. if (this.options.p2p && this.options.p2p.iceTransportPolicy) {
  429. logger.info('P2P ICE transport policy: ',
  430. this.options.p2p.iceTransportPolicy);
  431. iceConfig.p2p.iceTransportPolicy
  432. = this.options.p2p.iceTransportPolicy;
  433. }
  434. initEmuc(this);
  435. initJingle(this, this.eventEmitter, iceConfig);
  436. initStropheUtil();
  437. initPing(this);
  438. initRayo();
  439. initStropheLogger();
  440. }
  441. }