NetworkGeolocationProvider.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
  6. Components.utils.import("resource://gre/modules/Services.jsm");
  7. const Ci = Components.interfaces;
  8. const Cc = Components.classes;
  9. const Cu = Components.utils;
  10. const POSITION_UNAVAILABLE = Ci.nsIDOMGeoPositionError.POSITION_UNAVAILABLE;
  11. const SETTINGS_DEBUG_ENABLED = "geolocation.debugging.enabled";
  12. const SETTINGS_CHANGED_TOPIC = "mozsettings-changed";
  13. const SETTINGS_WIFI_ENABLED = "wifi.enabled";
  14. var gLoggingEnabled = false;
  15. /*
  16. The gLocationRequestTimeout controls how long we wait on receiving an update
  17. from the Wifi subsystem. If this timer fires, we believe the Wifi scan has
  18. had a problem and we no longer can use Wifi to position the user this time
  19. around (we will continue to be hopeful that Wifi will recover).
  20. This timeout value is also used when Wifi scanning is disabled (see
  21. gWifiScanningEnabled). In this case, we use this timer to collect cell/ip
  22. data and xhr it to the location server.
  23. */
  24. var gLocationRequestTimeout = 5000;
  25. var gWifiScanningEnabled = true;
  26. function LOG(aMsg) {
  27. if (gLoggingEnabled) {
  28. aMsg = "*** WIFI GEO: " + aMsg + "\n";
  29. Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService).logStringMessage(aMsg);
  30. dump(aMsg);
  31. }
  32. }
  33. function CachedRequest(loc, cellInfo, wifiList) {
  34. this.location = loc;
  35. let wifis = new Set();
  36. if (wifiList) {
  37. for (let i = 0; i < wifiList.length; i++) {
  38. wifis.add(wifiList[i].macAddress);
  39. }
  40. }
  41. // Use only these values for equality
  42. // (the JSON will contain additional values in future)
  43. function makeCellKey(cell) {
  44. return "" + cell.radio + ":" + cell.mobileCountryCode + ":" +
  45. cell.mobileNetworkCode + ":" + cell.locationAreaCode + ":" +
  46. cell.cellId;
  47. }
  48. let cells = new Set();
  49. if (cellInfo) {
  50. for (let i = 0; i < cellInfo.length; i++) {
  51. cells.add(makeCellKey(cellInfo[i]));
  52. }
  53. }
  54. this.hasCells = () => cells.size > 0;
  55. this.hasWifis = () => wifis.size > 0;
  56. // if fields match
  57. this.isCellEqual = function(cellInfo) {
  58. if (!this.hasCells()) {
  59. return false;
  60. }
  61. let len1 = cells.size;
  62. let len2 = cellInfo.length;
  63. if (len1 != len2) {
  64. LOG("cells not equal len");
  65. return false;
  66. }
  67. for (let i = 0; i < len2; i++) {
  68. if (!cells.has(makeCellKey(cellInfo[i]))) {
  69. return false;
  70. }
  71. }
  72. return true;
  73. };
  74. // if 50% of the SSIDS match
  75. this.isWifiApproxEqual = function(wifiList) {
  76. if (!this.hasWifis()) {
  77. return false;
  78. }
  79. // if either list is a 50% subset of the other, they are equal
  80. let common = 0;
  81. for (let i = 0; i < wifiList.length; i++) {
  82. if (wifis.has(wifiList[i].macAddress)) {
  83. common++;
  84. }
  85. }
  86. let kPercentMatch = 0.5;
  87. return common >= (Math.max(wifis.size, wifiList.length) * kPercentMatch);
  88. };
  89. this.isGeoip = function() {
  90. return !this.hasCells() && !this.hasWifis();
  91. };
  92. this.isCellAndWifi = function() {
  93. return this.hasCells() && this.hasWifis();
  94. };
  95. this.isCellOnly = function() {
  96. return this.hasCells() && !this.hasWifis();
  97. };
  98. this.isWifiOnly = function() {
  99. return this.hasWifis() && !this.hasCells();
  100. };
  101. }
  102. var gCachedRequest = null;
  103. var gDebugCacheReasoning = ""; // for logging the caching logic
  104. // This function serves two purposes:
  105. // 1) do we have a cached request
  106. // 2) is the cached request better than what newCell and newWifiList will obtain
  107. // If the cached request exists, and we know it to have greater accuracy
  108. // by the nature of its origin (wifi/cell/geoip), use its cached location.
  109. //
  110. // If there is more source info than the cached request had, return false
  111. // In other cases, MLS is known to produce better/worse accuracy based on the
  112. // inputs, so base the decision on that.
  113. function isCachedRequestMoreAccurateThanServerRequest(newCell, newWifiList)
  114. {
  115. gDebugCacheReasoning = "";
  116. let isNetworkRequestCacheEnabled = true;
  117. try {
  118. // Mochitest needs this pref to simulate request failure
  119. isNetworkRequestCacheEnabled = Services.prefs.getBoolPref("geo.wifi.debug.requestCache.enabled");
  120. if (!isNetworkRequestCacheEnabled) {
  121. gCachedRequest = null;
  122. }
  123. } catch (e) {}
  124. if (!gCachedRequest || !isNetworkRequestCacheEnabled) {
  125. gDebugCacheReasoning = "No cached data";
  126. return false;
  127. }
  128. if (!newCell && !newWifiList) {
  129. gDebugCacheReasoning = "New req. is GeoIP.";
  130. return true;
  131. }
  132. if (newCell && newWifiList && (gCachedRequest.isCellOnly() || gCachedRequest.isWifiOnly())) {
  133. gDebugCacheReasoning = "New req. is cell+wifi, cache only cell or wifi.";
  134. return false;
  135. }
  136. if (newCell && gCachedRequest.isWifiOnly()) {
  137. // In order to know if a cell-only request should trump a wifi-only request
  138. // need to know if wifi is low accuracy. >5km would be VERY low accuracy,
  139. // it is worth trying the cell
  140. var isHighAccuracyWifi = gCachedRequest.location.coords.accuracy < 5000;
  141. gDebugCacheReasoning = "Req. is cell, cache is wifi, isHigh:" + isHighAccuracyWifi;
  142. return isHighAccuracyWifi;
  143. }
  144. let hasEqualCells = false;
  145. if (newCell) {
  146. hasEqualCells = gCachedRequest.isCellEqual(newCell);
  147. }
  148. let hasEqualWifis = false;
  149. if (newWifiList) {
  150. hasEqualWifis = gCachedRequest.isWifiApproxEqual(newWifiList);
  151. }
  152. gDebugCacheReasoning = "EqualCells:" + hasEqualCells + " EqualWifis:" + hasEqualWifis;
  153. if (gCachedRequest.isCellOnly()) {
  154. gDebugCacheReasoning += ", Cell only.";
  155. if (hasEqualCells) {
  156. return true;
  157. }
  158. } else if (gCachedRequest.isWifiOnly() && hasEqualWifis) {
  159. gDebugCacheReasoning +=", Wifi only."
  160. return true;
  161. } else if (gCachedRequest.isCellAndWifi()) {
  162. gDebugCacheReasoning += ", Cache has Cell+Wifi.";
  163. if ((hasEqualCells && hasEqualWifis) ||
  164. (!newWifiList && hasEqualCells) ||
  165. (!newCell && hasEqualWifis))
  166. {
  167. return true;
  168. }
  169. }
  170. return false;
  171. }
  172. function WifiGeoCoordsObject(lat, lon, acc, alt, altacc) {
  173. this.latitude = lat;
  174. this.longitude = lon;
  175. this.accuracy = acc;
  176. this.altitude = alt;
  177. this.altitudeAccuracy = altacc;
  178. }
  179. WifiGeoCoordsObject.prototype = {
  180. QueryInterface: XPCOMUtils.generateQI([Ci.nsIDOMGeoPositionCoords])
  181. };
  182. function WifiGeoPositionObject(lat, lng, acc, cc, tz, zip, city, rc, region, country, isp, org, as) {
  183. this.coords = new WifiGeoCoordsObject(lat, lng, acc, 0, 0);
  184. this.address = null;
  185. this.countrycode = cc;
  186. this.timezone = tz;
  187. this.zipcode = zip;
  188. this.postalcode = zip;
  189. this.city = city;
  190. this.regioncode = rc;
  191. this.region = region;
  192. this.country = country;
  193. this.isp = isp;
  194. this.org = org;
  195. this.as = as;
  196. this.timestamp = Date.now();
  197. }
  198. WifiGeoPositionObject.prototype = {
  199. QueryInterface: XPCOMUtils.generateQI([Ci.nsIDOMGeoPosition])
  200. };
  201. function WifiGeoPositionProvider() {
  202. try {
  203. gLoggingEnabled = Services.prefs.getBoolPref("geo.wifi.logging.enabled");
  204. } catch (e) {}
  205. try {
  206. gLocationRequestTimeout = Services.prefs.getIntPref("geo.wifi.timeToWaitBeforeSending");
  207. } catch (e) {}
  208. try {
  209. gWifiScanningEnabled = Services.prefs.getBoolPref("geo.wifi.scan");
  210. } catch (e) {}
  211. this.wifiService = null;
  212. this.timer = null;
  213. this.started = false;
  214. }
  215. WifiGeoPositionProvider.prototype = {
  216. classID: Components.ID("{77DA64D3-7458-4920-9491-86CC9914F904}"),
  217. QueryInterface: XPCOMUtils.generateQI([Ci.nsIGeolocationProvider,
  218. Ci.nsIWifiListener,
  219. Ci.nsITimerCallback,
  220. Ci.nsIObserver]),
  221. listener: null,
  222. observe: function(aSubject, aTopic, aData) {
  223. if (aTopic != SETTINGS_CHANGED_TOPIC) {
  224. return;
  225. }
  226. try {
  227. if ("wrappedJSObject" in aSubject) {
  228. aSubject = aSubject.wrappedJSObject;
  229. }
  230. if (aSubject.key == SETTINGS_DEBUG_ENABLED) {
  231. gLoggingEnabled = aSubject.value;
  232. } else if (aSubject.key == SETTINGS_WIFI_ENABLED) {
  233. gWifiScanningEnabled = aSubject.value;
  234. }
  235. } catch (e) {
  236. }
  237. },
  238. resetTimer: function() {
  239. if (this.timer) {
  240. this.timer.cancel();
  241. this.timer = null;
  242. }
  243. // wifi thread triggers WifiGeoPositionProvider to proceed, with no wifi, do manual timeout
  244. this.timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  245. this.timer.initWithCallback(this,
  246. gLocationRequestTimeout,
  247. this.timer.TYPE_REPEATING_SLACK);
  248. },
  249. startup: function() {
  250. if (this.started)
  251. return;
  252. this.started = true;
  253. let self = this;
  254. let settingsCallback = {
  255. handle: function(name, result) {
  256. // Stop the B2G UI setting from overriding the js prefs setting, and turning off logging
  257. // If gLoggingEnabled is already on during startup, that means it was set in js prefs.
  258. if (name == SETTINGS_DEBUG_ENABLED && !gLoggingEnabled) {
  259. gLoggingEnabled = result;
  260. } else if (name == SETTINGS_WIFI_ENABLED) {
  261. gWifiScanningEnabled = result;
  262. if (self.wifiService) {
  263. self.wifiService.stopWatching(self);
  264. }
  265. if (gWifiScanningEnabled) {
  266. self.wifiService = Cc["@mozilla.org/wifi/monitor;1"].getService(Ci.nsIWifiMonitor);
  267. self.wifiService.startWatching(self);
  268. }
  269. }
  270. },
  271. handleError: function(message) {
  272. gLoggingEnabled = false;
  273. LOG("settings callback threw an exception, dropping");
  274. }
  275. };
  276. Services.obs.addObserver(this, SETTINGS_CHANGED_TOPIC, false);
  277. let settingsService = Cc["@mozilla.org/settingsService;1"];
  278. if (settingsService) {
  279. let settings = settingsService.getService(Ci.nsISettingsService);
  280. settings.createLock().get(SETTINGS_WIFI_ENABLED, settingsCallback);
  281. settings.createLock().get(SETTINGS_DEBUG_ENABLED, settingsCallback);
  282. }
  283. if (gWifiScanningEnabled && Cc["@mozilla.org/wifi/monitor;1"]) {
  284. if (this.wifiService) {
  285. this.wifiService.stopWatching(this);
  286. }
  287. this.wifiService = Cc["@mozilla.org/wifi/monitor;1"].getService(Ci.nsIWifiMonitor);
  288. this.wifiService.startWatching(this);
  289. }
  290. this.resetTimer();
  291. LOG("startup called.");
  292. },
  293. watch: function(c) {
  294. this.listener = c;
  295. },
  296. shutdown: function() {
  297. LOG("shutdown called");
  298. if (this.started == false) {
  299. return;
  300. }
  301. // Without clearing this, we could end up using the cache almost indefinitely
  302. // TODO: add logic for cache lifespan, for now just be safe and clear it
  303. gCachedRequest = null;
  304. if (this.timer) {
  305. this.timer.cancel();
  306. this.timer = null;
  307. }
  308. if(this.wifiService) {
  309. this.wifiService.stopWatching(this);
  310. this.wifiService = null;
  311. }
  312. Services.obs.removeObserver(this, SETTINGS_CHANGED_TOPIC);
  313. this.listener = null;
  314. this.started = false;
  315. },
  316. setHighAccuracy: function(enable) {
  317. },
  318. onChange: function(accessPoints) {
  319. // we got some wifi data, rearm the timer.
  320. this.resetTimer();
  321. function isPublic(ap) {
  322. let mask = "_nomap"
  323. let result = ap.ssid.indexOf(mask, ap.ssid.length - mask.length);
  324. if (result != -1) {
  325. LOG("Filtering out " + ap.ssid + " " + result);
  326. return false;
  327. }
  328. return true;
  329. };
  330. function sort(a, b) {
  331. return b.signal - a.signal;
  332. };
  333. function encode(ap) {
  334. return { 'macAddress': ap.mac, 'signalStrength': ap.signal };
  335. };
  336. let wifiData = null;
  337. if (accessPoints) {
  338. wifiData = accessPoints.filter(isPublic).sort(sort).map(encode);
  339. }
  340. this.sendLocationRequest(wifiData);
  341. },
  342. onError: function (code) {
  343. LOG("wifi error: " + code);
  344. this.sendLocationRequest(null);
  345. },
  346. notify: function (timer) {
  347. this.sendLocationRequest(null);
  348. },
  349. sendLocationRequest: function (wifiData) {
  350. let data = { cellTowers: undefined, wifiAccessPoints: undefined };
  351. if (wifiData && wifiData.length >= 2) {
  352. data.wifiAccessPoints = wifiData;
  353. }
  354. let useCached = isCachedRequestMoreAccurateThanServerRequest(data.cellTowers,
  355. data.wifiAccessPoints);
  356. LOG("Use request cache:" + useCached + " reason:" + gDebugCacheReasoning);
  357. if (useCached) {
  358. gCachedRequest.location.timestamp = Date.now();
  359. this.notifyListener("update", [gCachedRequest.location]);
  360. return;
  361. }
  362. // From here on, do a network geolocation request //
  363. let url = Services.urlFormatter.formatURLPref("geo.wifi.uri");
  364. LOG("Sending request");
  365. let xhr = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
  366. .createInstance(Ci.nsIXMLHttpRequest);
  367. // XXX: Dead code?
  368. // this.notifyListener("locationUpdatePending");
  369. try {
  370. xhr.open("GET", url, true);
  371. xhr.channel.loadFlags = Ci.nsIChannel.LOAD_ANONYMOUS;
  372. } catch (e) {
  373. this.notifyListener("notifyError",
  374. [POSITION_UNAVAILABLE]);
  375. return;
  376. }
  377. xhr.responseType = "json";
  378. xhr.mozBackgroundRequest = true;
  379. xhr.timeout = Services.prefs.getIntPref("geo.wifi.xhr.timeout");
  380. xhr.ontimeout = (function() {
  381. LOG("Location request XHR timed out.")
  382. this.notifyListener("notifyError",
  383. [POSITION_UNAVAILABLE]);
  384. }).bind(this);
  385. xhr.onerror = (function() {
  386. this.notifyListener("notifyError",
  387. [POSITION_UNAVAILABLE]);
  388. }).bind(this);
  389. xhr.onload = (function() {
  390. LOG("server returned status: " + xhr.status + " --> " + JSON.stringify(xhr.response));
  391. if ((xhr.channel instanceof Ci.nsIHttpChannel && xhr.status != 200) ||
  392. !xhr.response || xhr.response.status == 'fail') {
  393. this.notifyListener("notifyError",
  394. [POSITION_UNAVAILABLE]);
  395. return;
  396. }
  397. let newLocation = new WifiGeoPositionObject(xhr.response.lat,
  398. xhr.response.lon,
  399. null, //accuracy not provided
  400. xhr.response.countryCode,
  401. xhr.response.timezone,
  402. xhr.response.zip,
  403. xhr.response.city,
  404. xhr.response.region,
  405. xhr.response.regionName,
  406. xhr.response.country,
  407. xhr.response.isp,
  408. xhr.response.org,
  409. xhr.response.as);
  410. this.notifyListener("update", [newLocation]);
  411. gCachedRequest = new CachedRequest(newLocation, data.cellTowers, data.wifiAccessPoints);
  412. }).bind(this);
  413. var requestData = JSON.stringify(data);
  414. LOG("sending " + requestData);
  415. xhr.send(requestData);
  416. },
  417. notifyListener: function(listenerFunc, args) {
  418. args = args || [];
  419. LOG("Notify listener " + listenerFunc);
  420. try {
  421. this.listener[listenerFunc].apply(this.listener, args);
  422. } catch(e) {
  423. Cu.reportError(e);
  424. }
  425. }
  426. };
  427. this.NSGetFactory = XPCOMUtils.generateNSGetFactory([WifiGeoPositionProvider]);