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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /* global $, Strophe */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. const logger = getLogger(__filename);
  4. import RandomUtil from '../util/RandomUtil';
  5. import * as JitsiConnectionErrors from '../../JitsiConnectionErrors';
  6. import * as JitsiConnectionEvents from '../../JitsiConnectionEvents';
  7. import RTCBrowserType from '../RTC/RTCBrowserType';
  8. import initEmuc from './strophe.emuc';
  9. import initJingle from './strophe.jingle';
  10. import initStropheUtil from './strophe.util';
  11. import initPing from './strophe.ping';
  12. import initRayo from './strophe.rayo';
  13. import initStropheLogger from './strophe.logger';
  14. import Listenable from '../util/Listenable';
  15. import Caps from './Caps';
  16. /**
  17. *
  18. * @param token
  19. * @param bosh
  20. */
  21. function createConnection(token, bosh = '/http-bind') {
  22. // Append token as URL param
  23. if (token) {
  24. // eslint-disable-next-line no-param-reassign
  25. bosh += `${bosh.indexOf('?') === -1 ? '?' : '&'}token=${token}`;
  26. }
  27. return new Strophe.Connection(bosh);
  28. }
  29. /**
  30. *
  31. */
  32. export default class XMPP extends Listenable {
  33. /**
  34. * FIXME describe all options
  35. * @param {Object} options
  36. * @param {Array<Object>} options.p2pStunServers see
  37. * {@link JingleConnectionPlugin} for more details.
  38. * @param token
  39. */
  40. constructor(options, token) {
  41. super();
  42. this.connection = null;
  43. this.disconnectInProgress = false;
  44. this.connectionTimes = {};
  45. this.forceMuted = false;
  46. this.options = options;
  47. this.connectParams = {};
  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. * @password {string} the password passed in connect method
  105. * @status the connection status
  106. * @msg message
  107. */
  108. connectionHandler(password, status, msg) {
  109. const now = window.performance.now();
  110. const statusStr = Strophe.getStatusString(status).toLowerCase();
  111. this.connectionTimes[statusStr] = now;
  112. logger.log(
  113. `(TIME) Strophe ${statusStr}${msg ? `[${msg}]` : ''}:\t`,
  114. now);
  115. if (status === Strophe.Status.CONNECTED
  116. || status === Strophe.Status.ATTACHED) {
  117. if (this.options.useStunTurn) {
  118. this.connection.jingle.getStunAndTurnCredentials();
  119. }
  120. logger.info(`My Jabber ID: ${this.connection.jid}`);
  121. // Schedule ping ?
  122. const pingJid = this.connection.domain;
  123. this.connection.ping.hasPingSupport(
  124. pingJid,
  125. hasPing => {
  126. if (hasPing) {
  127. this.connection.ping.startInterval(pingJid);
  128. } else {
  129. logger.warn(`Ping NOT supported by ${pingJid}`);
  130. }
  131. });
  132. if (password) {
  133. this.authenticatedUser = true;
  134. }
  135. if (this.connection && this.connection.connected
  136. && Strophe.getResourceFromJid(this.connection.jid)) {
  137. // .connected is true while connecting?
  138. // this.connection.send($pres());
  139. this.eventEmitter.emit(
  140. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  141. Strophe.getResourceFromJid(this.connection.jid));
  142. }
  143. } else if (status === Strophe.Status.CONNFAIL) {
  144. if (msg === 'x-strophe-bad-non-anon-jid') {
  145. this.anonymousConnectionFailed = true;
  146. } else {
  147. this.connectionFailed = true;
  148. }
  149. this.lastErrorMsg = msg;
  150. } else if (status === Strophe.Status.DISCONNECTED) {
  151. // Stop ping interval
  152. this.connection.ping.stopInterval();
  153. const wasIntentionalDisconnect = this.disconnectInProgress;
  154. const errMsg = msg ? msg : this.lastErrorMsg;
  155. this.disconnectInProgress = false;
  156. if (this.anonymousConnectionFailed) {
  157. // prompt user for username and password
  158. this.eventEmitter.emit(
  159. JitsiConnectionEvents.CONNECTION_FAILED,
  160. JitsiConnectionErrors.PASSWORD_REQUIRED);
  161. } else if (this.connectionFailed) {
  162. this.eventEmitter.emit(
  163. JitsiConnectionEvents.CONNECTION_FAILED,
  164. JitsiConnectionErrors.OTHER_ERROR, errMsg);
  165. } else if (wasIntentionalDisconnect) {
  166. this.eventEmitter.emit(
  167. JitsiConnectionEvents.CONNECTION_DISCONNECTED, errMsg);
  168. } else {
  169. // XXX if Strophe drops the connection while not being asked to,
  170. // it means that most likely some serious error has occurred.
  171. // One currently known case is when a BOSH request fails for
  172. // more than 4 times. The connection is dropped without
  173. // supplying a reason(error message/event) through the API.
  174. logger.error('XMPP connection dropped!');
  175. // XXX if the last request error is within 5xx range it means it
  176. // was a server failure
  177. const lastErrorStatus = Strophe.getLastErrorStatus();
  178. if (lastErrorStatus >= 500 && lastErrorStatus < 600) {
  179. this.eventEmitter.emit(
  180. JitsiConnectionEvents.CONNECTION_FAILED,
  181. JitsiConnectionErrors.SERVER_ERROR,
  182. errMsg ? errMsg : 'server-error');
  183. } else {
  184. this.eventEmitter.emit(
  185. JitsiConnectionEvents.CONNECTION_FAILED,
  186. JitsiConnectionErrors.CONNECTION_DROPPED_ERROR,
  187. errMsg ? errMsg : 'connection-dropped-error');
  188. }
  189. }
  190. } else if (status === Strophe.Status.AUTHFAIL) {
  191. // wrong password or username, prompt user
  192. this.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  193. JitsiConnectionErrors.PASSWORD_REQUIRED);
  194. }
  195. }
  196. /**
  197. *
  198. * @param jid
  199. * @param password
  200. */
  201. _connect(jid, password) {
  202. // connection.connect() starts the connection process.
  203. //
  204. // As the connection process proceeds, the user supplied callback will
  205. // be triggered multiple times with status updates. The callback should
  206. // take two arguments - the status code and the error condition.
  207. //
  208. // The status code will be one of the values in the Strophe.Status
  209. // constants. The error condition will be one of the conditions defined
  210. // in RFC 3920 or the condition ‘strophe-parsererror’.
  211. //
  212. // The Parameters wait, hold and route are optional and only relevant
  213. // for BOSH connections. Please see XEP 124 for a more detailed
  214. // explanation of the optional parameters.
  215. //
  216. // Connection status constants for use by the connection handler
  217. // callback.
  218. //
  219. // Status.ERROR - An error has occurred (websockets specific)
  220. // Status.CONNECTING - The connection is currently being made
  221. // Status.CONNFAIL - The connection attempt failed
  222. // Status.AUTHENTICATING - The connection is authenticating
  223. // Status.AUTHFAIL - The authentication attempt failed
  224. // Status.CONNECTED - The connection has succeeded
  225. // Status.DISCONNECTED - The connection has been terminated
  226. // Status.DISCONNECTING - The connection is currently being terminated
  227. // Status.ATTACHED - The connection has been attached
  228. this.anonymousConnectionFailed = false;
  229. this.connectionFailed = false;
  230. this.lastErrorMsg = undefined;
  231. this.connection.connect(jid, password,
  232. this.connectionHandler.bind(this, password));
  233. }
  234. /**
  235. * Attach to existing connection. Can be used for optimizations. For
  236. * example: if the connection is created on the server we can attach to it
  237. * and start using it.
  238. *
  239. * @param options {object} connecting options - rid, sid, jid and password.
  240. */
  241. attach(options) {
  242. const now = this.connectionTimes.attaching = window.performance.now();
  243. logger.log(`(TIME) Strophe Attaching\t:${now}`);
  244. this.connection.attach(options.jid, options.sid,
  245. parseInt(options.rid, 10) + 1,
  246. this.connectionHandler.bind(this, options.password));
  247. }
  248. /**
  249. *
  250. * @param jid
  251. * @param password
  252. */
  253. connect(jid, password) {
  254. this.connectParams = {
  255. jid,
  256. password
  257. };
  258. if (!jid) {
  259. let configDomain
  260. = this.options.hosts.anonymousdomain
  261. || this.options.hosts.domain;
  262. // Force authenticated domain if room is appended with '?login=true'
  263. // or if we're joining with the token
  264. if (this.options.hosts.anonymousdomain
  265. && (window.location.search.indexOf('login=true') !== -1
  266. || this.token)) {
  267. configDomain = this.options.hosts.domain;
  268. }
  269. // eslint-disable-next-line no-param-reassign
  270. jid = configDomain || window.location.hostname;
  271. }
  272. return this._connect(jid, password);
  273. }
  274. /**
  275. *
  276. * @param roomName
  277. * @param options
  278. */
  279. createRoom(roomName, options) {
  280. // By default MUC nickname is the resource part of the JID
  281. let mucNickname = Strophe.getNodeFromJid(this.connection.jid);
  282. let roomjid = `${roomName}@${this.options.hosts.muc}/`;
  283. const cfgNickname
  284. = options.useNicks && options.nick ? options.nick : null;
  285. if (cfgNickname) {
  286. // Use nick if it's defined
  287. mucNickname = options.nick;
  288. } else if (!this.authenticatedUser) {
  289. // node of the anonymous JID is very long - here we trim it a bit
  290. mucNickname = mucNickname.substr(0, 8);
  291. }
  292. // Constant JIDs need some random part to be appended in order to be
  293. // able to join the MUC more than once.
  294. if (this.authenticatedUser || cfgNickname !== null) {
  295. mucNickname += `-${RandomUtil.randomHexString(6)}`;
  296. }
  297. roomjid += mucNickname;
  298. return this.connection.emuc.createRoom(roomjid, null, options);
  299. }
  300. /**
  301. * Returns the logs from strophe.jingle.
  302. * @returns {Object}
  303. */
  304. getJingleLog() {
  305. const jingle = this.connection.jingle;
  306. return jingle ? jingle.getLog() : {};
  307. }
  308. /**
  309. * Returns the logs from strophe.
  310. */
  311. getXmppLog() {
  312. return (this.connection.logger || {}).log || null;
  313. }
  314. /**
  315. *
  316. */
  317. dial(...args) {
  318. this.connection.rayo.dial(...args);
  319. }
  320. /**
  321. *
  322. * @param jid
  323. * @param mute
  324. */
  325. setMute(jid, mute) {
  326. this.connection.moderate.setMute(jid, mute);
  327. }
  328. /**
  329. *
  330. * @param jid
  331. */
  332. eject(jid) {
  333. this.connection.moderate.eject(jid);
  334. }
  335. /**
  336. *
  337. */
  338. getSessions() {
  339. return this.connection.jingle.sessions;
  340. }
  341. /**
  342. * Disconnects this from the XMPP server (if this is connected).
  343. *
  344. * @param ev optionally, the event which triggered the necessity to
  345. * disconnect from the XMPP server (e.g. beforeunload, unload).
  346. */
  347. disconnect(ev) {
  348. if (this.disconnectInProgress
  349. || !this.connection
  350. || !this.connection.connected) {
  351. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  352. return;
  353. }
  354. this.disconnectInProgress = true;
  355. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  356. // means that there may not be enough time to send an unavailable
  357. // presence or disconnect at all. Switching Strophe to synchronous
  358. // sending is not much of an option because it may lead to a noticeable
  359. // delay in navigating away from the current location. As a compromise,
  360. // we will try to increase the chances of sending an unavailable
  361. // presence and/or disconecting within the short time span that we have
  362. // upon unloading by invoking flush() on the connection. We flush() once
  363. // before disconnect() in order to attemtp to have its unavailable
  364. // presence at the top of the send queue. We flush() once more after
  365. // disconnect() in order to attempt to have its unavailable presence
  366. // sent as soon as possible.
  367. this.connection.flush();
  368. if (ev !== null && typeof ev !== 'undefined') {
  369. const evType = ev.type;
  370. if (evType === 'beforeunload' || evType === 'unload') {
  371. // XXX Whatever we said above, synchronous sending is the best
  372. // (known) way to properly disconnect from the XMPP server.
  373. // Consequently, it may be fine to have the source code and
  374. // comment it in or out depending on whether we want to run with
  375. // it for some time.
  376. this.connection.options.sync = true;
  377. }
  378. }
  379. this.connection.disconnect();
  380. if (this.connection.options.sync !== true) {
  381. this.connection.flush();
  382. }
  383. }
  384. /**
  385. *
  386. */
  387. _initStrophePlugins() {
  388. // FIXME: remove once we have a default config template. -saghul
  389. const defaultStunServers = [
  390. { urls: 'stun:stun.l.google.com:19302' },
  391. { urls: 'stun:stun1.l.google.com:19302' },
  392. { urls: 'stun:stun2.l.google.com:19302' }
  393. ];
  394. const p2pStunServers = (this.options.p2p
  395. && this.options.p2p.stunServers) || defaultStunServers;
  396. initEmuc(this);
  397. initJingle(this, this.eventEmitter, p2pStunServers);
  398. initStropheUtil();
  399. initPing(this);
  400. initRayo();
  401. initStropheLogger();
  402. }
  403. }