summaryrefslogtreecommitdiffstats
path: root/toolkit/modules/secondscreen/SimpleServiceDiscovery.jsm
blob: 4abc93ad1f80a69e97a1e2d3632d6cf7d22b31ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
// -*- Mode: js; tab-width: 2; indent-tabs-mode: nil; js2-basic-offset: 2; js2-skip-preprocessor-directives: t; -*-
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

this.EXPORTED_SYMBOLS = ["SimpleServiceDiscovery"];

const { classes: Cc, interfaces: Ci, utils: Cu } = Components;

Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Timer.jsm");

var log = Cu.reportError;

XPCOMUtils.defineLazyGetter(this, "converter", function () {
  let conv = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
  conv.charset = "utf8";
  return conv;
});

// Spec information:
// https://tools.ietf.org/html/draft-cai-ssdp-v1-03
// http://www.dial-multiscreen.org/dial-protocol-specification
const SSDP_PORT = 1900;
const SSDP_ADDRESS = "239.255.255.250";

const SSDP_DISCOVER_PACKET =
  "M-SEARCH * HTTP/1.1\r\n" +
  "HOST: " + SSDP_ADDRESS + ":" + SSDP_PORT + "\r\n" +
  "MAN: \"ssdp:discover\"\r\n" +
  "MX: 2\r\n" +
  "ST: %SEARCH_TARGET%\r\n\r\n";

const SSDP_DISCOVER_ATTEMPTS = 3;
const SSDP_DISCOVER_DELAY = 500;
const SSDP_DISCOVER_TIMEOUT_MULTIPLIER = 2;
const SSDP_TRANSMISSION_INTERVAL = 1000;

const EVENT_SERVICE_FOUND = "ssdp-service-found";
const EVENT_SERVICE_LOST = "ssdp-service-lost";

/*
 * SimpleServiceDiscovery manages any discovered SSDP services. It uses a UDP
 * broadcast to locate available services on the local network.
 */
var SimpleServiceDiscovery = {
  get EVENT_SERVICE_FOUND() { return EVENT_SERVICE_FOUND; },
  get EVENT_SERVICE_LOST() { return EVENT_SERVICE_LOST; },

  _devices: new Map(),
  _services: new Map(),
  _searchSocket: null,
  _searchInterval: 0,
  _searchTimestamp: 0,
  _searchTimeout: Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer),
  _searchRepeat: Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer),
  _discoveryMethods: [],

  _forceTrailingSlash: function(aURL) {
    // Cleanup the URL to make it consistent across devices
    try {
      aURL = Services.io.newURI(aURL, null, null).spec;
    } catch (e) {}
    return aURL;
  },

  // nsIUDPSocketListener implementation
  onPacketReceived: function(aSocket, aMessage) {
    // Listen for responses from specific devices. There could be more than one
    // available.
    let response = aMessage.data.split("\n");
    let service = {};
    response.forEach(function(row) {
      let name = row.toUpperCase();
      if (name.startsWith("LOCATION")) {
        service.location = row.substr(10).trim();
      } else if (name.startsWith("ST")) {
        service.target = row.substr(4).trim();
      }
    }.bind(this));

    if (service.location && service.target) {
      service.location = this._forceTrailingSlash(service.location);

      // When we find a valid response, package up the service information
      // and pass it on.
      try {
        this._processService(service);
      } catch (e) {}
    }
  },

  onStopListening: function(aSocket, aStatus) {
    // This is fired when the socket is closed expectedly or unexpectedly.
    // nsITimer.cancel() is a no-op if the timer is not active.
    this._searchTimeout.cancel();
    this._searchSocket = null;
  },

  // Start a search. Make it continuous by passing an interval (in milliseconds).
  // This will stop a current search loop because the timer resets itself.
  // Returns the existing search interval.
  search: function search(aInterval) {
    let existingSearchInterval = this._searchInterval;
    if (aInterval > 0) {
      this._searchInterval = aInterval || 0;
      this._searchRepeat.initWithCallback(this._search.bind(this), this._searchInterval, Ci.nsITimer.TYPE_REPEATING_SLACK);
    }
    this._search();
    return existingSearchInterval;
  },

  // Stop the current continuous search
  stopSearch: function stopSearch() {
    this._searchRepeat.cancel();
  },

  _usingLAN: function() {
    let network = Cc["@mozilla.org/network/network-link-service;1"].getService(Ci.nsINetworkLinkService);
    return (network.linkType == Ci.nsINetworkLinkService.LINK_TYPE_WIFI ||
            network.linkType == Ci.nsINetworkLinkService.LINK_TYPE_ETHERNET ||
            network.linkType == Ci.nsINetworkLinkService.LINK_TYPE_UNKNOWN);
  },

  _search: function _search() {
    // If a search is already active, shut it down.
    this._searchShutdown();

    // We only search if on local network
    if (!this._usingLAN()) {
      return;
    }

    // Update the timestamp so we can use it to clean out stale services the
    // next time we search.
    this._searchTimestamp = Date.now();

    // Look for any fixed IP devices. Some routers might be configured to block
    // UDP broadcasts, so this is a way to skip discovery.
    this._searchFixedDevices();

    // Look for any devices via registered external discovery mechanism.
    this._startExternalDiscovery();

    // Perform a UDP broadcast to search for SSDP devices
    let socket = Cc["@mozilla.org/network/udp-socket;1"].createInstance(Ci.nsIUDPSocket);
    try {
      socket.init(SSDP_PORT, false, Services.scriptSecurityManager.getSystemPrincipal());
      socket.joinMulticast(SSDP_ADDRESS);
      socket.asyncListen(this);
    } catch (e) {
      // We were unable to create the broadcast socket. Just return, but don't
      // kill the interval timer. This might work next time.
      log("failed to start socket: " + e);
      return;
    }

    // Make the timeout SSDP_DISCOVER_TIMEOUT_MULTIPLIER times as long as the time needed to send out the discovery packets.
    const SSDP_DISCOVER_TIMEOUT = this._devices.size * SSDP_DISCOVER_ATTEMPTS * SSDP_TRANSMISSION_INTERVAL * SSDP_DISCOVER_TIMEOUT_MULTIPLIER;
    this._searchSocket = socket;
    this._searchTimeout.initWithCallback(this._searchShutdown.bind(this), SSDP_DISCOVER_TIMEOUT, Ci.nsITimer.TYPE_ONE_SHOT);

    let data = SSDP_DISCOVER_PACKET;

    // Send discovery packets out at 1 per SSDP_TRANSMISSION_INTERVAL and send each SSDP_DISCOVER_ATTEMPTS times
    // to allow for packet loss on noisy networks.
    let timeout = SSDP_DISCOVER_DELAY;
    for (let attempts = 0; attempts < SSDP_DISCOVER_ATTEMPTS; attempts++) {
      for (let [key, device] of this._devices) {
        let target = device.target;
        setTimeout(function() {
          let msgData = data.replace("%SEARCH_TARGET%", target);
          try {
            let msgRaw = converter.convertToByteArray(msgData);
            socket.send(SSDP_ADDRESS, SSDP_PORT, msgRaw, msgRaw.length);
          } catch (e) {
            log("failed to convert to byte array: " + e);
          }
        }, timeout);
        timeout += SSDP_TRANSMISSION_INTERVAL;
      }
    }
  },

  _searchFixedDevices: function _searchFixedDevices() {
    let fixedDevices = Services.prefs.getCharPref("browser.casting.fixedDevices", "");

    if (!fixedDevices) {
      return;
    }

    fixedDevices = JSON.parse(fixedDevices);
    for (let fixedDevice of fixedDevices) {
      // Verify we have the right data
      if (!("location" in fixedDevice) || !("target" in fixedDevice)) {
        continue;
      }

      fixedDevice.location = this._forceTrailingSlash(fixedDevice.location);

      let service = {
        location: fixedDevice.location,
        target: fixedDevice.target
      };

      // We don't assume the fixed target is ready. We still need to ping it.
      try {
        this._processService(service);
      } catch (e) {}
    }
  },

  // Called when the search timeout is hit. We use it to cleanup the socket and
  // perform some post-processing on the services list.
  _searchShutdown: function _searchShutdown() {
    if (this._searchSocket) {
      // This will call onStopListening.
      this._searchSocket.close();

      // Clean out any stale services
      for (let [key, service] of this._services) {
        if (service.lastPing != this._searchTimestamp) {
          this.removeService(service.uuid);
        }
      }
    }

    this._stopExternalDiscovery();
  },

  getSupportedExtensions: function() {
    let extensions = [];
    this.services.forEach(function(service) {
        extensions = extensions.concat(service.extensions);
      }, this);
    return extensions.filter(function(extension, pos) {
      return extensions.indexOf(extension) == pos;
    });
  },

  getSupportedMimeTypes: function() {
    let types = [];
    this.services.forEach(function(service) {
        types = types.concat(service.types);
      }, this);
    return types.filter(function(type, pos) {
      return types.indexOf(type) == pos;
    });
  },

  registerDevice: function registerDevice(aDevice) {
    // We must have "id", "target" and "factory" defined
    if (!("id" in aDevice) || !("target" in aDevice) || !("factory" in aDevice)) {
      // Fatal for registration
      throw "Registration requires an id, a target and a location";
    }

    // Only add if we don't already know about this device
    if (!this._devices.has(aDevice.id)) {
      this._devices.set(aDevice.id, aDevice);
    } else {
      log("device was already registered: " + aDevice.id);
    }
  },

  unregisterDevice: function unregisterDevice(aDevice) {
    // We must have "id", "target" and "factory" defined
    if (!("id" in aDevice) || !("target" in aDevice) || !("factory" in aDevice)) {
      return;
    }

    // Only remove if we know about this device
    if (this._devices.has(aDevice.id)) {
      this._devices.delete(aDevice.id);
    } else {
      log("device was not registered: " + aDevice.id);
    }
  },

  findAppForService: function findAppForService(aService) {
    if (!aService || !aService.deviceID) {
      return null;
    }

    // Find the registration for the device
    if (this._devices.has(aService.deviceID)) {
      return this._devices.get(aService.deviceID).factory(aService);
    }
    return null;
  },

  findServiceForID: function findServiceForID(aUUID) {
    if (this._services.has(aUUID)) {
      return this._services.get(aUUID);
    }
    return null;
  },

  // Returns an array copy of the active services
  get services() {
    let array = [];
    for (let [key, service] of this._services) {
      let target = this._devices.get(service.deviceID);
      service.extensions = target.extensions;
      service.types = target.types;
      array.push(service);
    }
    return array;
  },

  // Returns false if the service does not match the device's filters
  _filterService: function _filterService(aService) {
    // Loop over all the devices, looking for one that matches the service
    for (let [key, device] of this._devices) {
      // First level of match is on the target itself
      if (device.target != aService.target) {
        continue;
      }

      // If we have no filter, everything passes
      if (!("filters" in device)) {
        aService.deviceID = device.id;
        return true;
      }

      // If all the filters pass, we have a match
      let failed = false;
      let filters = device.filters;
      for (let filter in filters) {
        if (filter in aService && aService[filter] != filters[filter]) {
          failed = true;
        }
      }

      // We found a match, so link the service to the device
      if (!failed) {
        aService.deviceID = device.id;
        return true;
      }
    }

    // We didn't find any matches
    return false;
  },

  _processService: function _processService(aService) {
    // Use the REST api to request more information about this service
    let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
    xhr.open("GET", aService.location, true);
    xhr.channel.loadFlags |= Ci.nsIRequest.INHIBIT_CACHING;
    xhr.overrideMimeType("text/xml");

    xhr.addEventListener("load", (function() {
      if (xhr.status == 200) {
        let doc = xhr.responseXML;
        aService.appsURL = xhr.getResponseHeader("Application-URL");
        if (aService.appsURL && !aService.appsURL.endsWith("/"))
          aService.appsURL += "/";
        aService.friendlyName = doc.querySelector("friendlyName").textContent;
        aService.uuid = doc.querySelector("UDN").textContent;
        aService.manufacturer = doc.querySelector("manufacturer").textContent;
        aService.modelName = doc.querySelector("modelName").textContent;

        this.addService(aService);
      }
    }).bind(this), false);

    xhr.send(null);
  },

  // Add a service to the WeakMap, even if one already exists with this id.
  // Returns true if this succeeded or false if it failed
  _addService: function(service) {
    // Filter out services that do not match the device filter
    if (!this._filterService(service)) {
      return false;
    }

    let device = this._devices.get(service.target);
    if (device && device.mirror) {
      service.mirror = true;
    }
    this._services.set(service.uuid, service);
    return true;
  },

  addService: function(service) {
    // Only add and notify if we don't already know about this service
    if (!this._services.has(service.uuid)) {
      if (!this._addService(service)) {
        return;
      }
      Services.obs.notifyObservers(null, EVENT_SERVICE_FOUND, service.uuid);
    }

    // Make sure we remember this service is not stale
    this._services.get(service.uuid).lastPing = this._searchTimestamp;
  },

  removeService: function(uuid) {
    Services.obs.notifyObservers(null, EVENT_SERVICE_LOST, uuid);
    this._services.delete(uuid);
  },

  updateService: function(service) {
    if (!this._addService(service)) {
      return;
    }

    // Make sure we remember this service is not stale
    this._services.get(service.uuid).lastPing = this._searchTimestamp;
  },

  addExternalDiscovery: function(discovery) {
    this._discoveryMethods.push(discovery);
  },

  _startExternalDiscovery: function() {
    for (let discovery of this._discoveryMethods) {
      discovery.startDiscovery();
    }
  },

  _stopExternalDiscovery: function() {
    for (let discovery of this._discoveryMethods) {
      discovery.stopDiscovery();
    }
  },
}