discovery.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. /**
  6. * This implements a UDP mulitcast device discovery protocol that:
  7. * * Is optimized for mobile devices
  8. * * Doesn't require any special schema for service info
  9. *
  10. * To ensure it works well on mobile devices, there is no heartbeat or other
  11. * recurring transmission.
  12. *
  13. * Devices are typically in one of two groups: scanning for services or
  14. * providing services (though they may be in both groups as well).
  15. *
  16. * Scanning devices listen on UPDATE_PORT for UDP multicast traffic. When the
  17. * scanning device wants to force an update of the services available, it sends
  18. * a status packet to SCAN_PORT.
  19. *
  20. * Service provider devices listen on SCAN_PORT for any packets from scanning
  21. * devices. If one is recevied, the provider device sends a status packet
  22. * (listing the services it offers) to UPDATE_PORT.
  23. *
  24. * Scanning devices purge any previously known devices after REPLY_TIMEOUT ms
  25. * from that start of a scan if no reply is received during the most recent
  26. * scan.
  27. *
  28. * When a service is registered, is supplies a regular object with any details
  29. * about itself (a port number, for example) in a service-defined format, which
  30. * is then available to scanning devices.
  31. */
  32. const { Cu, CC, Cc, Ci } = require("chrome");
  33. const EventEmitter = require("devtools/shared/event-emitter");
  34. const Services = require("Services");
  35. const UDPSocket = CC("@mozilla.org/network/udp-socket;1",
  36. "nsIUDPSocket",
  37. "init");
  38. const SCAN_PORT = 50624;
  39. const UPDATE_PORT = 50625;
  40. const ADDRESS = "224.0.0.115";
  41. const REPLY_TIMEOUT = 5000;
  42. const { XPCOMUtils } = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {});
  43. XPCOMUtils.defineLazyGetter(this, "converter", () => {
  44. let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
  45. createInstance(Ci.nsIScriptableUnicodeConverter);
  46. conv.charset = "utf8";
  47. return conv;
  48. });
  49. XPCOMUtils.defineLazyGetter(this, "sysInfo", () => {
  50. return Cc["@mozilla.org/system-info;1"].getService(Ci.nsIPropertyBag2);
  51. });
  52. XPCOMUtils.defineLazyGetter(this, "libcutils", function () {
  53. let { libcutils } = Cu.import("resource://gre/modules/systemlibs.js", {});
  54. return libcutils;
  55. });
  56. var logging = Services.prefs.getBoolPref("devtools.discovery.log");
  57. function log(msg) {
  58. if (logging) {
  59. console.log("DISCOVERY: " + msg);
  60. }
  61. }
  62. /**
  63. * Each Transport instance owns a single UDPSocket.
  64. * @param port integer
  65. * The port to listen on for incoming UDP multicast packets.
  66. */
  67. function Transport(port) {
  68. EventEmitter.decorate(this);
  69. try {
  70. this.socket = new UDPSocket(port, false, Services.scriptSecurityManager.getSystemPrincipal());
  71. this.socket.joinMulticast(ADDRESS);
  72. this.socket.asyncListen(this);
  73. } catch (e) {
  74. log("Failed to start new socket: " + e);
  75. }
  76. }
  77. Transport.prototype = {
  78. /**
  79. * Send a object to some UDP port.
  80. * @param object object
  81. * Object which is the message to send
  82. * @param port integer
  83. * UDP port to send the message to
  84. */
  85. send: function (object, port) {
  86. if (logging) {
  87. log("Send to " + port + ":\n" + JSON.stringify(object, null, 2));
  88. }
  89. let message = JSON.stringify(object);
  90. let rawMessage = converter.convertToByteArray(message);
  91. try {
  92. this.socket.send(ADDRESS, port, rawMessage, rawMessage.length);
  93. } catch (e) {
  94. log("Failed to send message: " + e);
  95. }
  96. },
  97. destroy: function () {
  98. this.socket.close();
  99. },
  100. // nsIUDPSocketListener
  101. onPacketReceived: function (socket, message) {
  102. let messageData = message.data;
  103. let object = JSON.parse(messageData);
  104. object.from = message.fromAddr.address;
  105. let port = message.fromAddr.port;
  106. if (port == this.socket.port) {
  107. log("Ignoring looped message");
  108. return;
  109. }
  110. if (logging) {
  111. log("Recv on " + this.socket.port + ":\n" +
  112. JSON.stringify(object, null, 2));
  113. }
  114. this.emit("message", object);
  115. },
  116. onStopListening: function () {}
  117. };
  118. /**
  119. * Manages the local device's name. The name can be generated in serveral
  120. * platform-specific ways (see |_generate|). The aim is for each device on the
  121. * same local network to have a unique name. If the Settings API is available,
  122. * the name is saved there to persist across reboots.
  123. */
  124. function LocalDevice() {
  125. this._name = LocalDevice.UNKNOWN;
  126. if ("@mozilla.org/settingsService;1" in Cc) {
  127. this._settings =
  128. Cc["@mozilla.org/settingsService;1"].getService(Ci.nsISettingsService);
  129. Services.obs.addObserver(this, "mozsettings-changed", false);
  130. }
  131. this._get(); // Trigger |_get| to load name eagerly
  132. }
  133. LocalDevice.SETTING = "devtools.discovery.device";
  134. LocalDevice.UNKNOWN = "unknown";
  135. LocalDevice.prototype = {
  136. _get: function () {
  137. if (!this._settings) {
  138. // Without Settings API, just generate a name and stop, since the value
  139. // can't be persisted.
  140. this._generate();
  141. return;
  142. }
  143. // Initial read of setting value
  144. this._settings.createLock().get(LocalDevice.SETTING, {
  145. handle: (_, name) => {
  146. if (name && name !== LocalDevice.UNKNOWN) {
  147. this._name = name;
  148. log("Device: " + this._name);
  149. return;
  150. }
  151. // No existing name saved, so generate one.
  152. this._generate();
  153. },
  154. handleError: () => log("Failed to get device name setting")
  155. });
  156. },
  157. /**
  158. * Generate a new device name from various platform-specific properties.
  159. * Triggers the |name| setter to persist if needed.
  160. */
  161. _generate: function () {
  162. if (Services.appinfo.widgetToolkit == "android") {
  163. // For Firefox for Android, use the device's model name.
  164. // TODO: Bug 1180997: Find the right way to expose an editable name
  165. this.name = sysInfo.get("device");
  166. } else {
  167. this.name = sysInfo.get("host");
  168. }
  169. },
  170. /**
  171. * Observe any changes that might be made via the Settings app
  172. */
  173. observe: function (subject, topic, data) {
  174. if (topic !== "mozsettings-changed") {
  175. return;
  176. }
  177. if ("wrappedJSObject" in subject) {
  178. subject = subject.wrappedJSObject;
  179. }
  180. if (subject.key !== LocalDevice.SETTING) {
  181. return;
  182. }
  183. this._name = subject.value;
  184. log("Device: " + this._name);
  185. },
  186. get name() {
  187. return this._name;
  188. },
  189. set name(name) {
  190. if (!this._settings) {
  191. this._name = name;
  192. log("Device: " + this._name);
  193. return;
  194. }
  195. // Persist to Settings API
  196. // The new value will be seen and stored by the observer above
  197. this._settings.createLock().set(LocalDevice.SETTING, name, {
  198. handle: () => {},
  199. handleError: () => log("Failed to set device name setting")
  200. });
  201. }
  202. };
  203. function Discovery() {
  204. EventEmitter.decorate(this);
  205. this.localServices = {};
  206. this.remoteServices = {};
  207. this.device = new LocalDevice();
  208. this.replyTimeout = REPLY_TIMEOUT;
  209. // Defaulted to Transport, but can be altered by tests
  210. this._factories = { Transport: Transport };
  211. this._transports = {
  212. scan: null,
  213. update: null
  214. };
  215. this._expectingReplies = {
  216. from: new Set()
  217. };
  218. this._onRemoteScan = this._onRemoteScan.bind(this);
  219. this._onRemoteUpdate = this._onRemoteUpdate.bind(this);
  220. this._purgeMissingDevices = this._purgeMissingDevices.bind(this);
  221. }
  222. Discovery.prototype = {
  223. /**
  224. * Add a new service offered by this device.
  225. * @param service string
  226. * Name of the service
  227. * @param info object
  228. * Arbitrary data about the service to announce to scanning devices
  229. */
  230. addService: function (service, info) {
  231. log("ADDING LOCAL SERVICE");
  232. if (Object.keys(this.localServices).length === 0) {
  233. this._startListeningForScan();
  234. }
  235. this.localServices[service] = info;
  236. },
  237. /**
  238. * Remove a service offered by this device.
  239. * @param service string
  240. * Name of the service
  241. */
  242. removeService: function (service) {
  243. delete this.localServices[service];
  244. if (Object.keys(this.localServices).length === 0) {
  245. this._stopListeningForScan();
  246. }
  247. },
  248. /**
  249. * Scan for service updates from other devices.
  250. */
  251. scan: function () {
  252. this._startListeningForUpdate();
  253. this._waitForReplies();
  254. // TODO Bug 1027457: Use timer to debounce
  255. this._sendStatusTo(SCAN_PORT);
  256. },
  257. /**
  258. * Get a list of all remote devices currently offering some service.:w
  259. */
  260. getRemoteDevices: function () {
  261. let devices = new Set();
  262. for (let service in this.remoteServices) {
  263. for (let device in this.remoteServices[service]) {
  264. devices.add(device);
  265. }
  266. }
  267. return [...devices];
  268. },
  269. /**
  270. * Get a list of all remote devices currently offering a particular service.
  271. */
  272. getRemoteDevicesWithService: function (service) {
  273. let devicesWithService = this.remoteServices[service] || {};
  274. return Object.keys(devicesWithService);
  275. },
  276. /**
  277. * Get service info (any details registered by the remote device) for a given
  278. * service on a device.
  279. */
  280. getRemoteService: function (service, device) {
  281. let devicesWithService = this.remoteServices[service] || {};
  282. return devicesWithService[device];
  283. },
  284. _waitForReplies: function () {
  285. clearTimeout(this._expectingReplies.timer);
  286. this._expectingReplies.from = new Set(this.getRemoteDevices());
  287. this._expectingReplies.timer =
  288. setTimeout(this._purgeMissingDevices, this.replyTimeout);
  289. },
  290. get Transport() {
  291. return this._factories.Transport;
  292. },
  293. _startListeningForScan: function () {
  294. if (this._transports.scan) {
  295. return; // Already listening
  296. }
  297. log("LISTEN FOR SCAN");
  298. this._transports.scan = new this.Transport(SCAN_PORT);
  299. this._transports.scan.on("message", this._onRemoteScan);
  300. },
  301. _stopListeningForScan: function () {
  302. if (!this._transports.scan) {
  303. return; // Not listening
  304. }
  305. this._transports.scan.off("message", this._onRemoteScan);
  306. this._transports.scan.destroy();
  307. this._transports.scan = null;
  308. },
  309. _startListeningForUpdate: function () {
  310. if (this._transports.update) {
  311. return; // Already listening
  312. }
  313. log("LISTEN FOR UPDATE");
  314. this._transports.update = new this.Transport(UPDATE_PORT);
  315. this._transports.update.on("message", this._onRemoteUpdate);
  316. },
  317. _stopListeningForUpdate: function () {
  318. if (!this._transports.update) {
  319. return; // Not listening
  320. }
  321. this._transports.update.off("message", this._onRemoteUpdate);
  322. this._transports.update.destroy();
  323. this._transports.update = null;
  324. },
  325. _restartListening: function () {
  326. if (this._transports.scan) {
  327. this._stopListeningForScan();
  328. this._startListeningForScan();
  329. }
  330. if (this._transports.update) {
  331. this._stopListeningForUpdate();
  332. this._startListeningForUpdate();
  333. }
  334. },
  335. /**
  336. * When sending message, we can use either transport, so just pick the first
  337. * one currently alive.
  338. */
  339. get _outgoingTransport() {
  340. if (this._transports.scan) {
  341. return this._transports.scan;
  342. }
  343. if (this._transports.update) {
  344. return this._transports.update;
  345. }
  346. return null;
  347. },
  348. _sendStatusTo: function (port) {
  349. let status = {
  350. device: this.device.name,
  351. services: this.localServices
  352. };
  353. this._outgoingTransport.send(status, port);
  354. },
  355. _onRemoteScan: function () {
  356. // Send my own status in response
  357. log("GOT SCAN REQUEST");
  358. this._sendStatusTo(UPDATE_PORT);
  359. },
  360. _onRemoteUpdate: function (e, update) {
  361. log("GOT REMOTE UPDATE");
  362. let remoteDevice = update.device;
  363. let remoteHost = update.from;
  364. // Record the reply as received so it won't be purged as missing
  365. this._expectingReplies.from.delete(remoteDevice);
  366. // First, loop over the known services
  367. for (let service in this.remoteServices) {
  368. let devicesWithService = this.remoteServices[service];
  369. let hadServiceForDevice = !!devicesWithService[remoteDevice];
  370. let haveServiceForDevice = service in update.services;
  371. // If the remote device used to have service, but doesn't any longer, then
  372. // it was deleted, so we remove it here.
  373. if (hadServiceForDevice && !haveServiceForDevice) {
  374. delete devicesWithService[remoteDevice];
  375. log("REMOVED " + service + ", DEVICE " + remoteDevice);
  376. this.emit(service + "-device-removed", remoteDevice);
  377. }
  378. }
  379. // Second, loop over the services in the received update
  380. for (let service in update.services) {
  381. // Detect if this is a new device for this service
  382. let newDevice = !this.remoteServices[service] ||
  383. !this.remoteServices[service][remoteDevice];
  384. // Look up the service info we may have received previously from the same
  385. // remote device
  386. let devicesWithService = this.remoteServices[service] || {};
  387. let oldDeviceInfo = devicesWithService[remoteDevice];
  388. // Store the service info from the remote device
  389. let newDeviceInfo = Cu.cloneInto(update.services[service], {});
  390. newDeviceInfo.host = remoteHost;
  391. devicesWithService[remoteDevice] = newDeviceInfo;
  392. this.remoteServices[service] = devicesWithService;
  393. // If this is a new service for the remote device, announce the addition
  394. if (newDevice) {
  395. log("ADDED " + service + ", DEVICE " + remoteDevice);
  396. this.emit(service + "-device-added", remoteDevice, newDeviceInfo);
  397. }
  398. // If we've seen this service from the remote device, but the details have
  399. // changed, announce the update
  400. if (!newDevice &&
  401. JSON.stringify(oldDeviceInfo) != JSON.stringify(newDeviceInfo)) {
  402. log("UPDATED " + service + ", DEVICE " + remoteDevice);
  403. this.emit(service + "-device-updated", remoteDevice, newDeviceInfo);
  404. }
  405. }
  406. },
  407. _purgeMissingDevices: function () {
  408. log("PURGING MISSING DEVICES");
  409. for (let service in this.remoteServices) {
  410. let devicesWithService = this.remoteServices[service];
  411. for (let remoteDevice in devicesWithService) {
  412. // If we're still expecting a reply from a remote device when it's time
  413. // to purge, then the service is removed.
  414. if (this._expectingReplies.from.has(remoteDevice)) {
  415. delete devicesWithService[remoteDevice];
  416. log("REMOVED " + service + ", DEVICE " + remoteDevice);
  417. this.emit(service + "-device-removed", remoteDevice);
  418. }
  419. }
  420. }
  421. }
  422. };
  423. var discovery = new Discovery();
  424. module.exports = discovery;