url.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. module.metadata = {
  6. "stability": "experimental"
  7. };
  8. const { Cc, Ci, Cr } = require("chrome");
  9. const { Class } = require("./core/heritage");
  10. const base64 = require("./base64");
  11. var tlds = Cc["@mozilla.org/network/effective-tld-service;1"]
  12. .getService(Ci.nsIEffectiveTLDService);
  13. var ios = Cc['@mozilla.org/network/io-service;1']
  14. .getService(Ci.nsIIOService);
  15. var resProt = ios.getProtocolHandler("resource")
  16. .QueryInterface(Ci.nsIResProtocolHandler);
  17. var URLParser = Cc["@mozilla.org/network/url-parser;1?auth=no"]
  18. .getService(Ci.nsIURLParser);
  19. function newURI(uriStr, base) {
  20. try {
  21. let baseURI = base ? ios.newURI(base, null, null) : null;
  22. return ios.newURI(uriStr, null, baseURI);
  23. }
  24. catch (e if e.result == Cr.NS_ERROR_MALFORMED_URI) {
  25. throw new Error("malformed URI: " + uriStr);
  26. }
  27. catch (e if (e.result == Cr.NS_ERROR_FAILURE ||
  28. e.result == Cr.NS_ERROR_ILLEGAL_VALUE)) {
  29. throw new Error("invalid URI: " + uriStr);
  30. }
  31. }
  32. function resolveResourceURI(uri) {
  33. var resolved;
  34. try {
  35. resolved = resProt.resolveURI(uri);
  36. } catch (e if e.result == Cr.NS_ERROR_NOT_AVAILABLE) {
  37. throw new Error("resource does not exist: " + uri.spec);
  38. };
  39. return resolved;
  40. }
  41. let fromFilename = exports.fromFilename = function fromFilename(path) {
  42. var file = Cc['@mozilla.org/file/local;1']
  43. .createInstance(Ci.nsILocalFile);
  44. file.initWithPath(path);
  45. return ios.newFileURI(file).spec;
  46. };
  47. let toFilename = exports.toFilename = function toFilename(url) {
  48. var uri = newURI(url);
  49. if (uri.scheme == "resource")
  50. uri = newURI(resolveResourceURI(uri));
  51. if (uri.scheme == "chrome") {
  52. var channel = ios.newChannelFromURI(uri);
  53. try {
  54. channel = channel.QueryInterface(Ci.nsIFileChannel);
  55. return channel.file.path;
  56. } catch (e if e.result == Cr.NS_NOINTERFACE) {
  57. throw new Error("chrome url isn't on filesystem: " + url);
  58. }
  59. }
  60. if (uri.scheme == "file") {
  61. var file = uri.QueryInterface(Ci.nsIFileURL).file;
  62. return file.path;
  63. }
  64. throw new Error("cannot map to filename: " + url);
  65. };
  66. function URL(url, base) {
  67. if (!(this instanceof URL)) {
  68. return new URL(url, base);
  69. }
  70. var uri = newURI(url, base);
  71. var userPass = null;
  72. try {
  73. userPass = uri.userPass ? uri.userPass : null;
  74. } catch (e if e.result == Cr.NS_ERROR_FAILURE) {}
  75. var host = null;
  76. try {
  77. host = uri.host;
  78. } catch (e if e.result == Cr.NS_ERROR_FAILURE) {}
  79. var port = null;
  80. try {
  81. port = uri.port == -1 ? null : uri.port;
  82. } catch (e if e.result == Cr.NS_ERROR_FAILURE) {}
  83. let uriData = [uri.path, uri.path.length, {}, {}, {}, {}, {}, {}];
  84. URLParser.parsePath.apply(URLParser, uriData);
  85. let [{ value: filepathPos }, { value: filepathLen },
  86. { value: queryPos }, { value: queryLen },
  87. { value: refPos }, { value: refLen }] = uriData.slice(2);
  88. let hash = uri.ref ? "#" + uri.ref : "";
  89. let pathname = uri.path.substr(filepathPos, filepathLen);
  90. let search = uri.path.substr(queryPos, queryLen);
  91. search = search ? "?" + search : "";
  92. this.__defineGetter__("scheme", function() uri.scheme);
  93. this.__defineGetter__("userPass", function() userPass);
  94. this.__defineGetter__("host", function() host);
  95. this.__defineGetter__("hostname", function() host);
  96. this.__defineGetter__("port", function() port);
  97. this.__defineGetter__("path", function() uri.path);
  98. this.__defineGetter__("pathname", function() pathname);
  99. this.__defineGetter__("hash", function() hash);
  100. this.__defineGetter__("href", function() uri.spec);
  101. this.__defineGetter__("origin", function() uri.prePath);
  102. this.__defineGetter__("protocol", function() uri.scheme + ":");
  103. this.__defineGetter__("search", function() search);
  104. Object.defineProperties(this, {
  105. toString: {
  106. value: function URL_toString() new String(uri.spec).toString(),
  107. enumerable: false
  108. },
  109. valueOf: {
  110. value: function() new String(uri.spec).valueOf(),
  111. enumerable: false
  112. },
  113. toSource: {
  114. value: function() new String(uri.spec).toSource(),
  115. enumerable: false
  116. }
  117. });
  118. return this;
  119. };
  120. URL.prototype = Object.create(String.prototype);
  121. exports.URL = URL;
  122. /**
  123. * Parse and serialize a Data URL.
  124. *
  125. * See: http://tools.ietf.org/html/rfc2397
  126. *
  127. * Note: Could be extended in the future to decode / encode automatically binary
  128. * data.
  129. */
  130. const DataURL = Class({
  131. get base64 () {
  132. return "base64" in this.parameters;
  133. },
  134. set base64 (value) {
  135. if (value)
  136. this.parameters["base64"] = "";
  137. else
  138. delete this.parameters["base64"];
  139. },
  140. /**
  141. * Initialize the Data URL object. If a uri is given, it will be parsed.
  142. *
  143. * @param {String} [uri] The uri to parse
  144. *
  145. * @throws {URIError} if the Data URL is malformed
  146. */
  147. initialize: function(uri) {
  148. // Due to bug 751834 it is not possible document and define these
  149. // properties in the prototype.
  150. /**
  151. * An hashmap that contains the parameters of the Data URL. By default is
  152. * empty, that accordingly to RFC is equivalent to {"charset" : "US-ASCII"}
  153. */
  154. this.parameters = {};
  155. /**
  156. * The MIME type of the data. By default is empty, that accordingly to RFC
  157. * is equivalent to "text/plain"
  158. */
  159. this.mimeType = "";
  160. /**
  161. * The string that represent the data in the Data URL
  162. */
  163. this.data = "";
  164. if (typeof uri === "undefined")
  165. return;
  166. uri = String(uri);
  167. let matches = uri.match(/^data:([^,]*),(.*)$/i);
  168. if (!matches)
  169. throw new URIError("Malformed Data URL: " + uri);
  170. let mediaType = matches[1].trim();
  171. this.data = decodeURIComponent(matches[2].trim());
  172. if (!mediaType)
  173. return;
  174. let parametersList = mediaType.split(";");
  175. this.mimeType = parametersList.shift().trim();
  176. for (let parameter, i = 0; parameter = parametersList[i++];) {
  177. let pairs = parameter.split("=");
  178. let name = pairs[0].trim();
  179. let value = pairs.length > 1 ? decodeURIComponent(pairs[1].trim()) : "";
  180. this.parameters[name] = value;
  181. }
  182. if (this.base64)
  183. this.data = base64.decode(this.data);
  184. },
  185. /**
  186. * Returns the object as a valid Data URL string
  187. *
  188. * @returns {String} The Data URL
  189. */
  190. toString : function() {
  191. let parametersList = [];
  192. for (let name in this.parameters) {
  193. let encodedParameter = encodeURIComponent(name);
  194. let value = this.parameters[name];
  195. if (value)
  196. encodedParameter += "=" + encodeURIComponent(value);
  197. parametersList.push(encodedParameter);
  198. }
  199. // If there is at least a parameter, add an empty string in order
  200. // to start with a `;` on join call.
  201. if (parametersList.length > 0)
  202. parametersList.unshift("");
  203. let data = this.base64 ? base64.encode(this.data) : this.data;
  204. return "data:" +
  205. this.mimeType +
  206. parametersList.join(";") + "," +
  207. encodeURIComponent(data);
  208. }
  209. });
  210. exports.DataURL = DataURL;
  211. let getTLD = exports.getTLD = function getTLD (url) {
  212. let uri = newURI(url.toString());
  213. let tld = null;
  214. try {
  215. tld = tlds.getPublicSuffix(uri);
  216. } catch (e if
  217. e.result == Cr.NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS ||
  218. e.result == Cr.NS_ERROR_HOST_IS_IP_ADDRESS) {}
  219. return tld;
  220. };
  221. let isValidURI = exports.isValidURI = function (uri) {
  222. try {
  223. newURI(uri);
  224. } catch(e) {
  225. return false;
  226. }
  227. return true;
  228. }
  229. function isLocalURL(url) {
  230. if (String.indexOf(url, './') === 0)
  231. return true;
  232. try {
  233. return ['resource', 'data', 'chrome'].indexOf(URL(url).scheme) > -1;
  234. }
  235. catch(e) {}
  236. return false;
  237. }
  238. exports.isLocalURL = isLocalURL;