blob: 4b254c371f97ad54b879ccbfadb6cb4dc798839c [file] [log] [blame]
Jeff Thompson08ab3cd2012-10-08 02:56:20 -07001/*
Jeff Thompson17a9da82012-11-12 01:11:01 -08002 * @author: Jeff Thompson
Jeff Thompson745026e2012-10-13 12:49:20 -07003 * See COPYING for copyright and distribution information.
Jeff Thompsonbd829262012-11-30 22:28:37 -08004 * This is the ndn protocol handler.
Jeff Thompson08ab3cd2012-10-08 02:56:20 -07005 * Protocol handling code derived from http://mike.kaply.com/2011/01/18/writing-a-firefox-protocol-handler/
6 */
7
8const Cc = Components.classes;
9const Ci = Components.interfaces;
10const Cr = Components.results;
11
12const nsIProtocolHandler = Ci.nsIProtocolHandler;
13
14Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
15Components.utils.import("chrome://modules/content/ndn-js.jsm");
16Components.utils.import("chrome://modules/content/ContentChannel.jsm");
Jeff Thompson6ad5c362012-12-27 17:57:02 -080017Components.utils.import("chrome://modules/content/NdnProtocolInfo.jsm");
Jeff Thompson08ab3cd2012-10-08 02:56:20 -070018
Jeff Thompson74d38e32013-03-18 21:44:07 -070019function NdnProtocol() {
Jeff Thompson08ab3cd2012-10-08 02:56:20 -070020}
21
Jeff Thompsonbd829262012-11-30 22:28:37 -080022NdnProtocol.prototype = {
23 scheme: "ndn",
Jeff Thompson9e6dff02012-11-04 09:20:47 -080024 protocolFlags: nsIProtocolHandler.URI_NORELATIVE |
Jeff Thompson08ab3cd2012-10-08 02:56:20 -070025 nsIProtocolHandler.URI_NOAUTH |
26 nsIProtocolHandler.URI_LOADABLE_BY_ANYONE,
27
Jeff Thompson9e6dff02012-11-04 09:20:47 -080028 newURI: function(aSpec, aOriginCharset, aBaseURI)
29 {
Jeff Thompson2cc54b42013-01-12 23:11:12 -080030 var uri = Cc["@mozilla.org/network/simple-uri;1"].createInstance(Ci.nsIURI);
31
Jeff Thompsond6b61e42012-11-24 12:10:35 -080032 // We have to trim now because nsIURI converts spaces to %20 and we can't trim in newChannel.
Jeff Thompsonb2f91ea2013-01-13 15:59:26 -080033 var uriParts = NdnProtocolInfo.splitUri(aSpec);
Jeff Thompson2cc54b42013-01-12 23:11:12 -080034 if (aBaseURI == null || uriParts.name.length < 1 || uriParts.name[0] == '/')
35 // Just reconstruct the trimmed URI.
36 uri.spec = "ndn:" + uriParts.name + uriParts.search + uriParts.hash;
37 else {
38 // Make a URI relative to the base name up to the file name component.
Jeff Thompsonb2f91ea2013-01-13 15:59:26 -080039 var baseUriParts = NdnProtocolInfo.splitUri(aBaseURI.spec);
Jeff Thompson2cc54b42013-01-12 23:11:12 -080040 var baseName = new Name(baseUriParts.name);
41 var iFileName = baseName.indexOfFileName();
42
43 var relativeName = uriParts.name;
44 // Handle ../
45 while (true) {
46 if (relativeName.substr(0, 2) == "./")
47 relativeName = relativeName.substr(2);
48 else if (relativeName.substr(0, 3) == "../") {
49 relativeName = relativeName.substr(3);
50 if (iFileName > 0)
51 --iFileName;
52 }
53 else
54 break;
55 }
56
57 var prefixUri = "/";
58 if (iFileName > 0)
59 prefixUri = new Name(baseName.components.slice(0, iFileName)).to_uri() + "/";
60 uri.spec = "ndn:" + prefixUri + relativeName + uriParts.search + uriParts.hash;
61 }
62
Jeff Thompson9e6dff02012-11-04 09:20:47 -080063 return uri;
64 },
Jeff Thompson08ab3cd2012-10-08 02:56:20 -070065
Jeff Thompson9e6dff02012-11-04 09:20:47 -080066 newChannel: function(aURI)
67 {
Jeff Thompson1eea6322012-11-23 16:56:18 -080068 try {
Jeff Thompsonb2f91ea2013-01-13 15:59:26 -080069 var uriParts = NdnProtocolInfo.splitUri(aURI.spec);
Jeff Thompsondf0a6f72012-10-21 15:58:58 -070070
Jeff Thompson5fc9b672012-11-24 10:00:56 -080071 var template = new Interest(new Name([]));
72 // Use the same default as NDN.expressInterest.
Jeff Thompson42806a12012-12-29 18:19:39 -080073 template.interestLifetime = 4000; // milliseconds
Jeff Thompson8107ec82013-01-12 21:53:27 -080074 var searchWithoutNdn = extractNdnSearch(uriParts.search, template);
Jeff Thompsone5a88282013-01-05 21:02:06 -080075
76 var segmentTemplate = new Interest(new Name([]));
77 // Only use the interest selectors which make sense for fetching further segments.
78 segmentTemplate.publisherPublicKeyDigest = template.publisherPublicKeyDigest;
79 segmentTemplate.scope = template.scope;
80 segmentTemplate.interestLifetime = template.interestLifetime;
Jeff Thompson5fc9b672012-11-24 10:00:56 -080081
Jeff Thompson1eea6322012-11-23 16:56:18 -080082 var requestContent = function(contentListener) {
Jeff Thompson8107ec82013-01-12 21:53:27 -080083 var name = new Name(uriParts.name);
Jeff Thompson3d6ce942012-12-16 12:11:42 -080084 // Use the same NDN object each time.
Jeff Thompson4f912272013-03-31 15:24:39 -070085 var closure = new ContentClosure(NdnProtocolInfo.ndn, contentListener, name,
86 aURI, searchWithoutNdn + uriParts.hash, segmentTemplate);
87
Jeff Thompsonfacbb842013-03-31 15:30:58 -070088 /* Disable until bug is fixed for opening multiple tabs.
Jeff Thompson4f912272013-03-31 15:24:39 -070089 if (contentChannel.loadFlags & (1<<19))
90 // Load flags bit 19 means this channel is for the main window with the URL bar.
91 ContentClosure.setClosureForWindow(contentChannel.mostRecentWindow, closure);
Jeff Thompsonfacbb842013-03-31 15:30:58 -070092 */
Jeff Thompson4f912272013-03-31 15:24:39 -070093
94 NdnProtocolInfo.ndn.expressInterest
95 (name, new ExponentialReExpressClosure(closure), template);
Jeff Thompson9e6dff02012-11-04 09:20:47 -080096 };
Jeff Thompson57d07382012-10-29 23:25:54 -070097
Jeff Thompsonf998ef12013-03-31 14:44:58 -070098 var contentChannel = new ContentChannel(aURI, requestContent);
99 return contentChannel;
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800100 } catch (ex) {
Jeff Thompsonbd829262012-11-30 22:28:37 -0800101 dump("NdnProtocol.newChannel exception: " + ex + "\n" + ex.stack);
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800102 }
103 },
Jeff Thompson08ab3cd2012-10-08 02:56:20 -0700104
Jeff Thompsonbd829262012-11-30 22:28:37 -0800105 classDescription: "ndn Protocol Handler",
106 contractID: "@mozilla.org/network/protocol;1?name=" + "ndn",
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800107 classID: Components.ID('{8122e660-1012-11e2-892e-0800200c9a66}'),
108 QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler])
Jeff Thompson3d6ce942012-12-16 12:11:42 -0800109};
Jeff Thompson08ab3cd2012-10-08 02:56:20 -0700110
111if (XPCOMUtils.generateNSGetFactory)
Jeff Thompsonbd829262012-11-30 22:28:37 -0800112 var NSGetFactory = XPCOMUtils.generateNSGetFactory([NdnProtocol]);
Jeff Thompson08ab3cd2012-10-08 02:56:20 -0700113else
Jeff Thompsonbd829262012-11-30 22:28:37 -0800114 var NSGetModule = XPCOMUtils.generateNSGetModule([NdnProtocol]);
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800115
116/*
117 * Create a closure for calling expressInterest.
118 * contentListener is from the call to requestContent.
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800119 * uriName is the name in the URI passed to newChannel (used in part to determine whether to request
120 * only that segment number and for updating the URL bar).
Jeff Thompson3663c672013-02-04 23:22:11 -0800121 * aURI is the URI passed to newChannel.
Jeff Thompson1eea6322012-11-23 16:56:18 -0800122 * uriSearchAndHash is the search and hash part of the URI passed to newChannel, including the '?'
123 * and/or '#' but without the interest selector fields.
Jeff Thompsone5a88282013-01-05 21:02:06 -0800124 * segmentTemplate is the template used in expressInterest to fetch further segments.
Jeff Thompson52843b12013-02-18 17:53:18 -0800125 * The uses ExponentialReExpressClosure in expressInterest to re-express if fetching a segment times out.
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800126 */
127var ContentClosure = function ContentClosure
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800128 (ndn, contentListener, uriName, aURI, uriSearchAndHash, segmentTemplate) {
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800129 // Inherit from Closure.
130 Closure.call(this);
131
132 this.ndn = ndn;
133 this.contentListener = contentListener;
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800134 this.uriName = uriName;
Jeff Thompson3663c672013-02-04 23:22:11 -0800135 this.aURI = aURI;
Jeff Thompson1eea6322012-11-23 16:56:18 -0800136 this.uriSearchAndHash = uriSearchAndHash;
Jeff Thompsone5a88282013-01-05 21:02:06 -0800137 this.segmentTemplate = segmentTemplate;
Jeff Thompson1eea6322012-11-23 16:56:18 -0800138
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800139 this.segmentStore = new SegmentStore();
Jeff Thompson74d38e32013-03-18 21:44:07 -0700140 this.contentSha256 = Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);
141 this.contentSha256.init(this.contentSha256.SHA256);
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800142 this.didRequestFinalSegment = false;
143 this.finalSegmentNumber = null;
Jeff Thompson52843b12013-02-18 17:53:18 -0800144 this.didOnStart = false;
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800145 this.uriEndsWithSegmentNumber = endsWithSegmentNumber(uriName);
Jeff Thompson7fb08bf2013-03-15 00:13:10 -0700146 this.nameWithoutSegment = null;
Jeff Thompson9c7d6912013-03-15 00:53:27 -0700147 this.excludedMetaComponents = [];
148 this.iMetaComponent = null;
Jeff Thompson3d6ce942012-12-16 12:11:42 -0800149};
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800150
151ContentClosure.prototype.upcall = function(kind, upcallInfo) {
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800152 try {
Jeff Thompsonf998ef12013-03-31 14:44:58 -0700153 if (this.contentListener.isDone())
Jeff Thompson3663c672013-02-04 23:22:11 -0800154 // We are getting unexpected extra results.
155 return Closure.RESULT_ERR;
156
157 if (kind == Closure.UPCALL_INTEREST_TIMED_OUT) {
Jeff Thompson152342b2013-02-18 20:36:53 -0800158 if (!this.didOnStart) {
Jeff Thompson7e2e2e22013-03-10 16:41:37 -0700159 // We have not received a segment to start the content yet, so assume the URI can't be fetched.
Jeff Thompson3663c672013-02-04 23:22:11 -0800160 this.contentListener.onStart("text/plain", "utf-8", this.aURI);
161 this.contentListener.onReceivedContent
Jeff Thompson152342b2013-02-18 20:36:53 -0800162 ("The latest interest timed out after " + upcallInfo.interest.interestLifetime + " milliseconds.");
Jeff Thompson3663c672013-02-04 23:22:11 -0800163 this.contentListener.onStop();
164 return Closure.RESULT_OK;
165 }
166 else
Jeff Thompson52843b12013-02-18 17:53:18 -0800167 // ExponentialReExpressClosure already tried to re-express, so quit.
Jeff Thompson3663c672013-02-04 23:22:11 -0800168 return Closure.RESULT_ERR;
169 }
170
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800171 if (!(kind == Closure.UPCALL_CONTENT ||
172 kind == Closure.UPCALL_CONTENT_UNVERIFIED))
173 // The upcall is not for us.
174 return Closure.RESULT_ERR;
175
176 var contentObject = upcallInfo.contentObject;
177 if (contentObject.content == null) {
Jeff Thompsonbd829262012-11-30 22:28:37 -0800178 dump("NdnProtocol.ContentClosure: contentObject.content is null\n");
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800179 return Closure.RESULT_ERR;
180 }
Jeff Thompson6ad5c362012-12-27 17:57:02 -0800181
Jeff Thompson7e2e2e22013-03-10 16:41:37 -0700182 // Assume this is only called once we're connected, report the host and port.
183 NdnProtocolInfo.setConnectedNdnHub(this.ndn.host, this.ndn.port);
184
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800185 // If !this.uriEndsWithSegmentNumber, we use the segmentNumber to load multiple segments.
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800186 // If this.uriEndsWithSegmentNumber, then we leave segmentNumber null.
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800187 var segmentNumber = null;
Jeff Thompson7fb08bf2013-03-15 00:13:10 -0700188 if (!this.uriEndsWithSegmentNumber && endsWithSegmentNumber(contentObject.name))
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800189 segmentNumber = DataUtils.bigEndianToUnsignedInt
190 (contentObject.name.components[contentObject.name.components.length - 1]);
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800191
Jeff Thompson52843b12013-02-18 17:53:18 -0800192 if ((segmentNumber == null || segmentNumber == 0) && !this.didOnStart) {
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800193 // This is the first or only segment.
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800194 var iMetaComponent = getIndexOfMetaComponent(contentObject.name);
195 if (!this.uriEndsWithSegmentNumber && iMetaComponent >= 0 &&
196 getIndexOfMetaComponent(this.uriName) < 0) {
Jeff Thompson7fb08bf2013-03-15 00:13:10 -0700197 // The matched content name has a META component that wasn't requested in the original
198 // URI. Add this to the excluded META components to try to get the "real" content.
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800199 var nameWithoutMeta = new Name(contentObject.name.components.slice(0, iMetaComponent));
Jeff Thompson9c7d6912013-03-15 00:53:27 -0700200 if (this.excludedMetaComponents.length > 0 && iMetaComponent != this.iMetaComponent)
201 // We are excluding META components at a new position in the name, so start over.
202 this.excludedMetaComponents = [];
203 this.iMetaComponent = iMetaComponent;
204 this.excludedMetaComponents.push(contentObject.name.components[iMetaComponent]);
205 // Exclude components are required to be sorted.
206 this.excludedMetaComponents.sort(Exclude.compareComponents);
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800207
Jeff Thompson9c7d6912013-03-15 00:53:27 -0700208 var excludeMetaTemplate = this.segmentTemplate.clone();
209 excludeMetaTemplate.exclude = new Exclude(this.excludedMetaComponents);
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800210 this.ndn.expressInterest
211 (nameWithoutMeta, new ExponentialReExpressClosure(this), excludeMetaTemplate);
Jeff Thompson7fb08bf2013-03-15 00:13:10 -0700212 return Closure.RESULT_OK;
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800213 }
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800214
Jeff Thompson52843b12013-02-18 17:53:18 -0800215 this.didOnStart = true;
216
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800217 // Get the URI from the ContentObject including the version.
218 var contentUriSpec;
219 if (!this.uriEndsWithSegmentNumber && endsWithSegmentNumber(contentObject.name)) {
220 var nameWithoutSegmentNumber = new Name
Jeff Thompson963d2da2012-12-02 23:31:22 -0800221 (contentObject.name.components.slice(0, contentObject.name.components.length - 1));
Jeff Thompsonbd829262012-11-30 22:28:37 -0800222 contentUriSpec = "ndn:" + nameWithoutSegmentNumber.to_uri();
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800223 }
224 else
Jeff Thompsonbd829262012-11-30 22:28:37 -0800225 contentUriSpec = "ndn:" + contentObject.name.to_uri();
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800226
Jeff Thompson1eea6322012-11-23 16:56:18 -0800227 // Include the search and hash.
228 contentUriSpec += this.uriSearchAndHash;
229
Jeff Thompsone769c512012-11-04 17:25:07 -0800230 var contentTypeEtc = getNameContentTypeAndCharset(contentObject.name);
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800231 var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
232 this.contentListener.onStart(contentTypeEtc.contentType, contentTypeEtc.contentCharset,
Jeff Thompson3663c672013-02-04 23:22:11 -0800233 ioService.newURI(contentUriSpec, this.aURI.originCharset, null));
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800234
Jeff Thompson7fb08bf2013-03-15 00:13:10 -0700235 if (segmentNumber == null) {
236 // We are not doing segments, so just finish.
237 this.contentListener.onReceivedContent(DataUtils.toString(contentObject.content));
Jeff Thompson74d38e32013-03-18 21:44:07 -0700238 this.contentSha256.update(contentObject.content, contentObject.content.length);
Jeff Thompson7fb08bf2013-03-15 00:13:10 -0700239 this.contentListener.onStop();
Jeff Thompson4f912272013-03-31 15:24:39 -0700240 ContentClosure.removeClosureForWindow(this);
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800241
Jeff Thompson7fb08bf2013-03-15 00:13:10 -0700242 if (!this.uriEndsWithSegmentNumber) {
243 var nameContentDigest = contentObject.name.getContentDigestValue();
Jeff Thompsondd038fc2013-03-16 16:29:47 -0700244 if (nameContentDigest != null && this.contentSha256 != null &&
Jeff Thompson74d38e32013-03-18 21:44:07 -0700245 !DataUtils.arraysEqual(nameContentDigest,
246 DataUtils.toNumbersFromString(this.contentSha256.finish(false))))
Jeff Thompson7fb08bf2013-03-15 00:13:10 -0700247 // TODO: How to show the user an error for invalid digest?
Jeff Thompson74d38e32013-03-18 21:44:07 -0700248 dump("Content does not match digest in name " + contentObject.name.to_uri() + "\n");
Jeff Thompson7fb08bf2013-03-15 00:13:10 -0700249 }
250 return Closure.RESULT_OK;
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800251 }
Jeff Thompson7fb08bf2013-03-15 00:13:10 -0700252 else
253 // We are doing segments. Make sure we always request the same base name.
254 this.nameWithoutSegment = new Name(contentObject.name.components.slice
255 (0, contentObject.name.components.length - 1));
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800256 }
257
Jeff Thompson7fb08bf2013-03-15 00:13:10 -0700258 if (segmentNumber == null)
259 // We should be doing segments at this point.
260 return Closure.RESULT_ERR;
261
262 if (!(contentObject.name.components.length == this.nameWithoutSegment.components.length + 1 &&
263 this.nameWithoutSegment.match(contentObject.name)))
264 // The content object name is not part of our sequence of segments.
265 return Closure.RESULT_ERR;
266
267 this.segmentStore.storeContent(segmentNumber, contentObject);
268
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800269 if (contentObject.signedInfo != null && contentObject.signedInfo.finalBlockID != null)
270 this.finalSegmentNumber = DataUtils.bigEndianToUnsignedInt(contentObject.signedInfo.finalBlockID);
271
272 // The content was already put in the store. Retrieve as much as possible.
273 var entry;
274 while ((entry = this.segmentStore.maybeRetrieveNextEntry()) != null) {
275 segmentNumber = entry.key;
276 contentObject = entry.value;
277 this.contentListener.onReceivedContent(DataUtils.toString(contentObject.content));
Jeff Thompson74d38e32013-03-18 21:44:07 -0700278 this.contentSha256.update(contentObject.content, contentObject.content.length);
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800279
280 if (this.finalSegmentNumber != null && segmentNumber == this.finalSegmentNumber) {
281 // Finished.
282 this.contentListener.onStop();
Jeff Thompson4f912272013-03-31 15:24:39 -0700283 ContentClosure.removeClosureForWindow(this);
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800284 var nameContentDigest = contentObject.name.getContentDigestValue();
Jeff Thompsondd038fc2013-03-16 16:29:47 -0700285 if (nameContentDigest != null && this.contentSha256 != null &&
Jeff Thompson74d38e32013-03-18 21:44:07 -0700286 !DataUtils.arraysEqual(nameContentDigest,
287 DataUtils.toNumbersFromString(this.contentSha256.finish(false))))
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800288 // TODO: How to show the user an error for invalid digest?
Jeff Thompson74d38e32013-03-18 21:44:07 -0700289 dump("Content does not match digest in name " + contentObject.name.to_uri() + "\n");
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800290
291 return Closure.RESULT_OK;
292 }
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800293 }
294
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800295 if (this.finalSegmentNumber == null && !this.didRequestFinalSegment) {
Jeff Thompsonb083c8e2013-01-23 21:27:32 -0800296 this.didRequestFinalSegment = true;
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800297 // Try to determine the final segment now.
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800298 // Clone the template to set the childSelector.
299 var childSelectorTemplate = this.segmentTemplate.clone();
300 childSelectorTemplate.childSelector = 1;
Jeff Thompson52843b12013-02-18 17:53:18 -0800301 this.ndn.expressInterest
Jeff Thompson7fb08bf2013-03-15 00:13:10 -0700302 (this.nameWithoutSegment, new ExponentialReExpressClosure(this), childSelectorTemplate);
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800303 }
304
305 // Request new segments.
306 var toRequest = this.segmentStore.requestSegmentNumbers(2);
307 for (var i = 0; i < toRequest.length; ++i) {
308 if (this.finalSegmentNumber != null && toRequest[i] > this.finalSegmentNumber)
309 continue;
310
Jeff Thompson52843b12013-02-18 17:53:18 -0800311 this.ndn.expressInterest
Jeff Thompson7fb08bf2013-03-15 00:13:10 -0700312 (new Name(this.nameWithoutSegment).addSegment(toRequest[i]),
Jeff Thompsonca2535c2013-02-28 22:26:13 -0800313 new ExponentialReExpressClosure(this), this.segmentTemplate);
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800314 }
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800315
316 return Closure.RESULT_OK;
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800317 } catch (ex) {
318 dump("ContentClosure.upcall exception: " + ex + "\n" + ex.stack);
319 return Closure.RESULT_ERR;
320 }
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800321};
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800322
Jeff Thompson4f912272013-03-31 15:24:39 -0700323ContentClosure.closureForWindowList = [];
324
325/*
326 * We use closureForWindowList to keep only one closure for each document window.
327 * window is the window with the URL bar.
328 * closure is the ContentClosure to associate with it.
329 * If there is already another closure for window, callits contentListener.onStop(); so
330 * that further calls to upcall will do nothing.
331 */
332ContentClosure.setClosureForWindow = function(window, closure) {
333 for (var i = 0; i < ContentClosure.closureForWindowList.length; ++i) {
334 var entry = ContentClosure.closureForWindowList[i];
335 if (entry.window == window) {
336 try {
337 entry.closure.contentListener.onStop();
338 } catch (ex) {
339 // Ignore any errors when stopping.
340 }
341 entry.closure = closure;
342 return;
343 }
344 }
345
346 ContentClosure.closureForWindowList.push({ window: window, closure: closure });
347};
348
349/*
350 * Remove any entry in closureForWindowList for closure. This is called when the closure is done.
351 */
352ContentClosure.removeClosureForWindow = function(closure) {
353 for (var i = ContentClosure.closureForWindowList.length - 1; i >= 0; --i) {
354 if (ContentClosure.closureForWindowList[i].closure == closure)
355 ContentClosure.closureForWindowList.splice(i, 1);
356 }
357}
358
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800359/*
360 * A SegmentStore stores segments until they are retrieved in order starting with segment 0.
361 */
362var SegmentStore = function SegmentStore() {
363 // Each entry is an object where the key is the segment number and value is null if
364 // the segment number is requested or the contentObject if received.
365 this.store = new SortedArray();
366 this.maxRetrievedSegmentNumber = -1;
367};
368
369SegmentStore.prototype.storeContent = function(segmentNumber, contentObject) {
370 // We don't expect to try to store a segment that has already been retrieved, but check anyway.
371 if (segmentNumber > this.maxRetrievedSegmentNumber)
372 this.store.set(segmentNumber, contentObject);
373};
374
375/*
376 * If the min segment number is this.maxRetrievedSegmentNumber + 1 and its value is not null,
377 * then delete from the store, return the entry with key and value, and update maxRetrievedSegmentNumber.
378 * Otherwise return null.
379 */
380SegmentStore.prototype.maybeRetrieveNextEntry = function() {
381 if (this.store.entries.length > 0 && this.store.entries[0].value != null &&
382 this.store.entries[0].key == this.maxRetrievedSegmentNumber + 1) {
383 var entry = this.store.entries[0];
384 this.store.removeAt(0);
385 ++this.maxRetrievedSegmentNumber;
386 return entry;
387 }
388 else
389 return null;
390};
391
392/*
393 * Return an array of the next segment numbers that need to be requested so that the total
394 * requested segments is totalRequestedSegments. If a segment store entry value is null, it is
395 * already requested and is not returned. If a segment number is returned, create a
396 * entry in the segment store with a null value.
397 */
398SegmentStore.prototype.requestSegmentNumbers = function(totalRequestedSegments) {
399 // First, count how many are already requested.
400 var nRequestedSegments = 0;
401 for (var i = 0; i < this.store.entries.length; ++i) {
402 if (this.store.entries[i].value == null) {
403 ++nRequestedSegments;
404 if (nRequestedSegments >= totalRequestedSegments)
405 // Already maxed out on requests.
406 return [];
407 }
408 }
409
410 var toRequest = [];
411 var nextSegmentNumber = this.maxRetrievedSegmentNumber + 1;
412 for (var i = 0; i < this.store.entries.length; ++i) {
413 var entry = this.store.entries[i];
414 // Fill in the gap before the segment number in the entry.
415 while (nextSegmentNumber < entry.key) {
416 toRequest.push(nextSegmentNumber);
417 ++nextSegmentNumber;
418 ++nRequestedSegments;
419 if (nRequestedSegments >= totalRequestedSegments)
420 break;
421 }
422 if (nRequestedSegments >= totalRequestedSegments)
423 break;
424
425 nextSegmentNumber = entry.key + 1;
426 }
427
428 // We already filled in the gaps for the segments in the store. Continue after the last.
429 while (nRequestedSegments < totalRequestedSegments) {
430 toRequest.push(nextSegmentNumber);
431 ++nextSegmentNumber;
432 ++nRequestedSegments;
433 }
434
435 // Mark the new segment numbers as requested.
436 for (var i = 0; i < toRequest.length; ++i)
437 this.store.set(toRequest[i], null);
438 return toRequest;
439}
440
441/*
442 * A SortedArray is an array of objects with key and value, where the key is an integer.
443 */
444var SortedArray = function SortedArray() {
445 this.entries = [];
446}
447
448SortedArray.prototype.sortEntries = function() {
449 this.entries.sort(function(a, b) { return a.key - b.key; });
450};
451
452SortedArray.prototype.indexOfKey = function(key) {
453 for (var i = 0; i < this.entries.length; ++i) {
454 if (this.entries[i].key == key)
455 return i;
456 }
457
458 return -1;
459}
460
461SortedArray.prototype.set = function(key, value) {
462 var i = this.indexOfKey(key);
463 if (i >= 0) {
464 this.entries[i].value = value;
465 return;
466 }
467
468 this.entries.push({ key: key, value: value});
469 this.sortEntries();
470}
471
472SortedArray.prototype.removeAt = function(index) {
473 this.entries.splice(index, 1);
474}
475
Jeff Thompsondf0a6f72012-10-21 15:58:58 -0700476/*
Jeff Thompsonbd829262012-11-30 22:28:37 -0800477 * Scan the name from the last component to the first (skipping special name components)
Jeff Thompson25b06412012-10-21 20:07:57 -0700478 * for a recognized file name extension, and return an object with properties contentType and charset.
Jeff Thompsondf0a6f72012-10-21 15:58:58 -0700479 */
Jeff Thompsone769c512012-11-04 17:25:07 -0800480function getNameContentTypeAndCharset(name) {
Jeff Thompson16a35f72012-11-25 08:07:33 -0800481 var iFileName = name.indexOfFileName();
482 if (iFileName < 0)
483 // Get the default mime type.
484 return MimeTypes.getContentTypeAndCharset("");
Jeff Thompsondf0a6f72012-10-21 15:58:58 -0700485
Jeff Thompson16a35f72012-11-25 08:07:33 -0800486 return MimeTypes.getContentTypeAndCharset
487 (DataUtils.toString(name.components[iFileName]).toLowerCase());
Jeff Thompsondf0a6f72012-10-21 15:58:58 -0700488}
Jeff Thompson10de4592012-10-21 23:54:18 -0700489
490/*
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800491 * Return true if the last component in the name is a segment number..
Jeff Thompson10de4592012-10-21 23:54:18 -0700492 */
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800493function endsWithSegmentNumber(name) {
Jeff Thompson10de4592012-10-21 23:54:18 -0700494 return name.components != null && name.components.length >= 1 &&
495 name.components[name.components.length - 1].length >= 1 &&
496 name.components[name.components.length - 1][0] == 0;
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800497}
498
499/*
Jeff Thompsonbd829262012-11-30 22:28:37 -0800500 * Find all search keys starting with "ndn." and set the attribute in template.
501 * Return the search string including the starting "?" but with the "ndn." keys removed,
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800502 * or return "" if there are no search terms left.
503 */
Jeff Thompsonbd829262012-11-30 22:28:37 -0800504function extractNdnSearch(search, template) {
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800505 if (!(search.length >= 1 && search[0] == '?'))
506 return search;
507
508 var terms = search.substr(1).split('&');
509 var i = 0;
510 while (i < terms.length) {
511 var keyValue = terms[i].split('=');
512 var key = keyValue[0].trim();
Jeff Thompsonbd829262012-11-30 22:28:37 -0800513 if (key.substr(0, 4) == "ndn.") {
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800514 if (keyValue.length >= 1) {
Jeff Thompson754652d2012-11-24 16:23:43 -0800515 var value = keyValue[1].trim();
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800516 var nonNegativeInt = parseInt(value);
517
Jeff Thompsonbd829262012-11-30 22:28:37 -0800518 if (key == "ndn.MinSuffixComponents" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800519 template.minSuffixComponents = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800520 else if (key == "ndn.MaxSuffixComponents" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800521 template.maxSuffixComponents = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800522 else if (key == "ndn.ChildSelector" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800523 template.childSelector = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800524 else if (key == "ndn.AnswerOriginKind" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800525 template.answerOriginKind = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800526 else if (key == "ndn.Scope" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800527 template.scope = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800528 else if (key == "ndn.InterestLifetime" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800529 template.interestLifetime = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800530 else if (key == "ndn.PublisherPublicKeyDigest")
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800531 template.publisherPublicKeyDigest = DataUtils.toNumbersFromString(unescape(value));
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800532 else if (key == "ndn.Nonce")
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800533 template.nonce = DataUtils.toNumbersFromString(unescape(value));
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800534 else if (key == "ndn.Exclude")
535 template.exclude = parseExclude(value);
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800536 }
537
Jeff Thompsonbd829262012-11-30 22:28:37 -0800538 // Remove the "ndn." term and don't advance i.
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800539 terms.splice(i, 1);
540 }
541 else
542 ++i;
543 }
544
545 if (terms.length == 0)
546 return "";
547 else
548 return "?" + terms.join('&');
Jeff Thompson963d2da2012-12-02 23:31:22 -0800549}
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800550
551/*
552 * Parse the comma-separated list of exclude components and return an Exclude.
553 */
554function parseExclude(value) {
555 var excludeValues = [];
556
557 var splitValue = value.split(',');
558 for (var i = 0; i < splitValue.length; ++i) {
559 var element = splitValue[i].trim();
560 if (element == "*")
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800561 excludeValues.push(Exclude.ANY)
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800562 else
563 excludeValues.push(Name.fromEscapedString(element));
564 }
565
566 return new Exclude(excludeValues);
567}
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800568
569/*
570 * Return the index of the first compoment that starts with %C1.META, or -1 if not found.
571 */
572function getIndexOfMetaComponent(name) {
573 for (var i = 0; i < name.components.length; ++i) {
574 var component = name.components[i];
575 if (component.length >= MetaComponentPrefix.length &&
576 DataUtils.arraysEqual(component.subarray(0, MetaComponentPrefix.length),
577 MetaComponentPrefix))
578 return i;
579 }
580
581 return -1;
582}
583
584var MetaComponentPrefix = new Uint8Array([0xc1, 0x2e, 0x4d, 0x45, 0x54, 0x41]);