blob: 0e08795989ecfc3789bd8e1cea05a9f72a8fa5b8 [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 Thompsonbd829262012-11-30 22:28:37 -080019function NdnProtocol() {
Jeff Thompson6b3d81a2013-01-26 15:45:21 -080020 this.ndn = new NDN({ getTransport: function() { return new XpcomTransport(); },
Jeff Thompson49f37882013-01-26 19:08:11 -080021 verify: false });
Jeff Thompson08ab3cd2012-10-08 02:56:20 -070022}
23
Jeff Thompsonbd829262012-11-30 22:28:37 -080024NdnProtocol.prototype = {
25 scheme: "ndn",
Jeff Thompson9e6dff02012-11-04 09:20:47 -080026 protocolFlags: nsIProtocolHandler.URI_NORELATIVE |
Jeff Thompson08ab3cd2012-10-08 02:56:20 -070027 nsIProtocolHandler.URI_NOAUTH |
28 nsIProtocolHandler.URI_LOADABLE_BY_ANYONE,
29
Jeff Thompson9e6dff02012-11-04 09:20:47 -080030 newURI: function(aSpec, aOriginCharset, aBaseURI)
31 {
Jeff Thompson2cc54b42013-01-12 23:11:12 -080032 var uri = Cc["@mozilla.org/network/simple-uri;1"].createInstance(Ci.nsIURI);
33
Jeff Thompsond6b61e42012-11-24 12:10:35 -080034 // 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 -080035 var uriParts = NdnProtocolInfo.splitUri(aSpec);
Jeff Thompson2cc54b42013-01-12 23:11:12 -080036 if (aBaseURI == null || uriParts.name.length < 1 || uriParts.name[0] == '/')
37 // Just reconstruct the trimmed URI.
38 uri.spec = "ndn:" + uriParts.name + uriParts.search + uriParts.hash;
39 else {
40 // Make a URI relative to the base name up to the file name component.
Jeff Thompsonb2f91ea2013-01-13 15:59:26 -080041 var baseUriParts = NdnProtocolInfo.splitUri(aBaseURI.spec);
Jeff Thompson2cc54b42013-01-12 23:11:12 -080042 var baseName = new Name(baseUriParts.name);
43 var iFileName = baseName.indexOfFileName();
44
45 var relativeName = uriParts.name;
46 // Handle ../
47 while (true) {
48 if (relativeName.substr(0, 2) == "./")
49 relativeName = relativeName.substr(2);
50 else if (relativeName.substr(0, 3) == "../") {
51 relativeName = relativeName.substr(3);
52 if (iFileName > 0)
53 --iFileName;
54 }
55 else
56 break;
57 }
58
59 var prefixUri = "/";
60 if (iFileName > 0)
61 prefixUri = new Name(baseName.components.slice(0, iFileName)).to_uri() + "/";
62 uri.spec = "ndn:" + prefixUri + relativeName + uriParts.search + uriParts.hash;
63 }
64
Jeff Thompson9e6dff02012-11-04 09:20:47 -080065 return uri;
66 },
Jeff Thompson08ab3cd2012-10-08 02:56:20 -070067
Jeff Thompson9e6dff02012-11-04 09:20:47 -080068 newChannel: function(aURI)
69 {
Jeff Thompsonbd829262012-11-30 22:28:37 -080070 var thisNdnProtocol = this;
Jeff Thompson17a9da82012-11-12 01:11:01 -080071
Jeff Thompson1eea6322012-11-23 16:56:18 -080072 try {
Jeff Thompsonb2f91ea2013-01-13 15:59:26 -080073 var uriParts = NdnProtocolInfo.splitUri(aURI.spec);
Jeff Thompsondf0a6f72012-10-21 15:58:58 -070074
Jeff Thompson5fc9b672012-11-24 10:00:56 -080075 var template = new Interest(new Name([]));
76 // Use the same default as NDN.expressInterest.
Jeff Thompson42806a12012-12-29 18:19:39 -080077 template.interestLifetime = 4000; // milliseconds
Jeff Thompson8107ec82013-01-12 21:53:27 -080078 var searchWithoutNdn = extractNdnSearch(uriParts.search, template);
Jeff Thompsone5a88282013-01-05 21:02:06 -080079
80 var segmentTemplate = new Interest(new Name([]));
81 // Only use the interest selectors which make sense for fetching further segments.
82 segmentTemplate.publisherPublicKeyDigest = template.publisherPublicKeyDigest;
83 segmentTemplate.scope = template.scope;
84 segmentTemplate.interestLifetime = template.interestLifetime;
Jeff Thompson5fc9b672012-11-24 10:00:56 -080085
Jeff Thompson1eea6322012-11-23 16:56:18 -080086 var requestContent = function(contentListener) {
Jeff Thompson8107ec82013-01-12 21:53:27 -080087 var name = new Name(uriParts.name);
Jeff Thompson3d6ce942012-12-16 12:11:42 -080088 // Use the same NDN object each time.
Jeff Thompson52843b12013-02-18 17:53:18 -080089 thisNdnProtocol.ndn.expressInterest(name, new ExponentialReExpressClosure
Jeff Thompson4a4caba2013-02-28 21:31:33 -080090 (new ContentClosure(thisNdnProtocol.ndn, contentListener, name,
Jeff Thompson52843b12013-02-18 17:53:18 -080091 aURI, searchWithoutNdn + uriParts.hash, segmentTemplate)),
Jeff Thompson5fc9b672012-11-24 10:00:56 -080092 template);
Jeff Thompson9e6dff02012-11-04 09:20:47 -080093 };
Jeff Thompson57d07382012-10-29 23:25:54 -070094
Jeff Thompson5fc9b672012-11-24 10:00:56 -080095 return new ContentChannel(aURI, requestContent);
Jeff Thompson9e6dff02012-11-04 09:20:47 -080096 } catch (ex) {
Jeff Thompsonbd829262012-11-30 22:28:37 -080097 dump("NdnProtocol.newChannel exception: " + ex + "\n" + ex.stack);
Jeff Thompson9e6dff02012-11-04 09:20:47 -080098 }
99 },
Jeff Thompson08ab3cd2012-10-08 02:56:20 -0700100
Jeff Thompsonbd829262012-11-30 22:28:37 -0800101 classDescription: "ndn Protocol Handler",
102 contractID: "@mozilla.org/network/protocol;1?name=" + "ndn",
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800103 classID: Components.ID('{8122e660-1012-11e2-892e-0800200c9a66}'),
104 QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler])
Jeff Thompson3d6ce942012-12-16 12:11:42 -0800105};
Jeff Thompson08ab3cd2012-10-08 02:56:20 -0700106
107if (XPCOMUtils.generateNSGetFactory)
Jeff Thompsonbd829262012-11-30 22:28:37 -0800108 var NSGetFactory = XPCOMUtils.generateNSGetFactory([NdnProtocol]);
Jeff Thompson08ab3cd2012-10-08 02:56:20 -0700109else
Jeff Thompsonbd829262012-11-30 22:28:37 -0800110 var NSGetModule = XPCOMUtils.generateNSGetModule([NdnProtocol]);
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800111
112/*
113 * Create a closure for calling expressInterest.
114 * contentListener is from the call to requestContent.
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800115 * uriName is the name in the URI passed to newChannel (used in part to determine whether to request
116 * only that segment number and for updating the URL bar).
Jeff Thompson3663c672013-02-04 23:22:11 -0800117 * aURI is the URI passed to newChannel.
Jeff Thompson1eea6322012-11-23 16:56:18 -0800118 * uriSearchAndHash is the search and hash part of the URI passed to newChannel, including the '?'
119 * and/or '#' but without the interest selector fields.
Jeff Thompsone5a88282013-01-05 21:02:06 -0800120 * segmentTemplate is the template used in expressInterest to fetch further segments.
Jeff Thompson52843b12013-02-18 17:53:18 -0800121 * The uses ExponentialReExpressClosure in expressInterest to re-express if fetching a segment times out.
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800122 */
123var ContentClosure = function ContentClosure
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800124 (ndn, contentListener, uriName, aURI, uriSearchAndHash, segmentTemplate) {
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800125 // Inherit from Closure.
126 Closure.call(this);
127
128 this.ndn = ndn;
129 this.contentListener = contentListener;
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800130 this.uriName = uriName;
Jeff Thompson3663c672013-02-04 23:22:11 -0800131 this.aURI = aURI;
Jeff Thompson1eea6322012-11-23 16:56:18 -0800132 this.uriSearchAndHash = uriSearchAndHash;
Jeff Thompsone5a88282013-01-05 21:02:06 -0800133 this.segmentTemplate = segmentTemplate;
Jeff Thompson1eea6322012-11-23 16:56:18 -0800134
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800135 this.segmentStore = new SegmentStore();
Jeff Thompson1ac86ce2013-01-21 21:51:07 -0800136 this.contentSha256 = new Sha256();
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800137 this.didRequestFinalSegment = false;
138 this.finalSegmentNumber = null;
Jeff Thompson52843b12013-02-18 17:53:18 -0800139 this.didOnStart = false;
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800140 this.uriEndsWithSegmentNumber = endsWithSegmentNumber(uriName);
Jeff Thompson3d6ce942012-12-16 12:11:42 -0800141};
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800142
143ContentClosure.prototype.upcall = function(kind, upcallInfo) {
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800144 try {
Jeff Thompson52843b12013-02-18 17:53:18 -0800145 // Assume this is only called once we're connected, report the host and port.
146 NdnProtocolInfo.setConnectedNdnHub(this.ndn.host, this.ndn.port);
147
Jeff Thompson3663c672013-02-04 23:22:11 -0800148 if (this.contentListener.done)
149 // We are getting unexpected extra results.
150 return Closure.RESULT_ERR;
151
152 if (kind == Closure.UPCALL_INTEREST_TIMED_OUT) {
Jeff Thompson152342b2013-02-18 20:36:53 -0800153 if (!this.didOnStart) {
154 // We have not received a segments to start the content yet, so assume the URI can't be fetched.
Jeff Thompson3663c672013-02-04 23:22:11 -0800155 this.contentListener.onStart("text/plain", "utf-8", this.aURI);
156 this.contentListener.onReceivedContent
Jeff Thompson152342b2013-02-18 20:36:53 -0800157 ("The latest interest timed out after " + upcallInfo.interest.interestLifetime + " milliseconds.");
Jeff Thompson3663c672013-02-04 23:22:11 -0800158 this.contentListener.onStop();
159 return Closure.RESULT_OK;
160 }
161 else
Jeff Thompson52843b12013-02-18 17:53:18 -0800162 // ExponentialReExpressClosure already tried to re-express, so quit.
Jeff Thompson3663c672013-02-04 23:22:11 -0800163 return Closure.RESULT_ERR;
164 }
165
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800166 if (!(kind == Closure.UPCALL_CONTENT ||
167 kind == Closure.UPCALL_CONTENT_UNVERIFIED))
168 // The upcall is not for us.
169 return Closure.RESULT_ERR;
170
171 var contentObject = upcallInfo.contentObject;
172 if (contentObject.content == null) {
Jeff Thompsonbd829262012-11-30 22:28:37 -0800173 dump("NdnProtocol.ContentClosure: contentObject.content is null\n");
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800174 return Closure.RESULT_ERR;
175 }
Jeff Thompson6ad5c362012-12-27 17:57:02 -0800176
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800177 // If !this.uriEndsWithSegmentNumber, we use the segmentNumber to load multiple segments.
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800178 // If this.uriEndsWithSegmentNumber, then we leave segmentNumber null.
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800179 var segmentNumber = null;
180 if (!this.uriEndsWithSegmentNumber && endsWithSegmentNumber(contentObject.name)) {
181 segmentNumber = DataUtils.bigEndianToUnsignedInt
182 (contentObject.name.components[contentObject.name.components.length - 1]);
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800183 this.segmentStore.storeContent(segmentNumber, contentObject);
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800184 }
185
Jeff Thompson52843b12013-02-18 17:53:18 -0800186 if ((segmentNumber == null || segmentNumber == 0) && !this.didOnStart) {
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800187 // This is the first or only segment.
188 /* TODO: Finish implementing check for META.
189 var iMetaComponent = getIndexOfMetaComponent(contentObject.name);
190 if (!this.uriEndsWithSegmentNumber && iMetaComponent >= 0 &&
191 getIndexOfMetaComponent(this.uriName) < 0) {
192 // The matched content name has a META component that wasn't requiested in the original
193 // URI. Try to exclude the META component to get the "real" content.
194 var nameWithoutMeta = new Name(contentObject.name.components.slice(0, iMetaComponent));
195 var excludeMetaTemplate = this.segmentTemplate.clone();
196 excludeMetaTemplate.exclude = new Exclude([MetaComponentPrefix, Exclude.ANY]);
197
198 this.ndn.expressInterest
199 (nameWithoutMeta, new ExponentialReExpressClosure(this), excludeMetaTemplate);
200 }
201 */
202
Jeff Thompson52843b12013-02-18 17:53:18 -0800203 this.didOnStart = true;
204
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800205 // Get the URI from the ContentObject including the version.
206 var contentUriSpec;
207 if (!this.uriEndsWithSegmentNumber && endsWithSegmentNumber(contentObject.name)) {
208 var nameWithoutSegmentNumber = new Name
Jeff Thompson963d2da2012-12-02 23:31:22 -0800209 (contentObject.name.components.slice(0, contentObject.name.components.length - 1));
Jeff Thompsonbd829262012-11-30 22:28:37 -0800210 contentUriSpec = "ndn:" + nameWithoutSegmentNumber.to_uri();
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800211 }
212 else
Jeff Thompsonbd829262012-11-30 22:28:37 -0800213 contentUriSpec = "ndn:" + contentObject.name.to_uri();
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800214
Jeff Thompson1eea6322012-11-23 16:56:18 -0800215 // Include the search and hash.
216 contentUriSpec += this.uriSearchAndHash;
217
Jeff Thompsone769c512012-11-04 17:25:07 -0800218 var contentTypeEtc = getNameContentTypeAndCharset(contentObject.name);
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800219 var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
220 this.contentListener.onStart(contentTypeEtc.contentType, contentTypeEtc.contentCharset,
Jeff Thompson3663c672013-02-04 23:22:11 -0800221 ioService.newURI(contentUriSpec, this.aURI.originCharset, null));
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800222 }
223
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800224 if (segmentNumber == null) {
225 // We are not doing segments, so just finish.
226 this.contentListener.onReceivedContent(DataUtils.toString(contentObject.content));
Jeff Thompson869e8192012-12-16 12:18:24 -0800227 this.contentSha256.update(contentObject.content);
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800228 this.contentListener.onStop();
229
230 if (!this.uriEndsWithSegmentNumber) {
231 var nameContentDigest = contentObject.name.getContentDigestValue();
232 if (nameContentDigest != null &&
233 !DataUtils.arraysEqual(nameContentDigest, this.contentSha256.finalize()))
234 // TODO: How to show the user an error for invalid digest?
235 dump("Content does not match digest in name " + contentObject.name.to_uri());
236 }
237 return Closure.RESULT_OK;
238 }
239
240 if (contentObject.signedInfo != null && contentObject.signedInfo.finalBlockID != null)
241 this.finalSegmentNumber = DataUtils.bigEndianToUnsignedInt(contentObject.signedInfo.finalBlockID);
242
243 // The content was already put in the store. Retrieve as much as possible.
244 var entry;
245 while ((entry = this.segmentStore.maybeRetrieveNextEntry()) != null) {
246 segmentNumber = entry.key;
247 contentObject = entry.value;
248 this.contentListener.onReceivedContent(DataUtils.toString(contentObject.content));
249 this.contentSha256.update(contentObject.content);
250
251 if (this.finalSegmentNumber != null && segmentNumber == this.finalSegmentNumber) {
252 // Finished.
253 this.contentListener.onStop();
254 var nameContentDigest = contentObject.name.getContentDigestValue();
255 if (nameContentDigest != null &&
256 !DataUtils.arraysEqual(nameContentDigest, this.contentSha256.finalize()))
257 // TODO: How to show the user an error for invalid digest?
258 dump("Content does not match digest in name " + contentObject.name.to_uri());
259
260 return Closure.RESULT_OK;
261 }
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800262 }
263
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800264 if (this.finalSegmentNumber == null && !this.didRequestFinalSegment) {
Jeff Thompsonb083c8e2013-01-23 21:27:32 -0800265 this.didRequestFinalSegment = true;
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800266 // Try to determine the final segment now.
267 var components = contentObject.name.components.slice
268 (0, contentObject.name.components.length - 1);
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800269
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800270 // Clone the template to set the childSelector.
271 var childSelectorTemplate = this.segmentTemplate.clone();
272 childSelectorTemplate.childSelector = 1;
Jeff Thompson52843b12013-02-18 17:53:18 -0800273 this.ndn.expressInterest
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800274 (new Name(components), new ExponentialReExpressClosure(this), childSelectorTemplate);
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800275 }
276
277 // Request new segments.
278 var toRequest = this.segmentStore.requestSegmentNumbers(2);
279 for (var i = 0; i < toRequest.length; ++i) {
280 if (this.finalSegmentNumber != null && toRequest[i] > this.finalSegmentNumber)
281 continue;
282
283 // Make a name for the segment and get it.
284 var segmentNumberBigEndian = DataUtils.nonNegativeIntToBigEndian(toRequest[i]);
Jeff Thompsond0327ff2012-11-11 20:30:12 -0800285 // Put a 0 byte in front.
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800286 var segmentNumberComponent = new Uint8Array(segmentNumberBigEndian.length + 1);
287 segmentNumberComponent.set(segmentNumberBigEndian, 1);
Jeff Thompsond0327ff2012-11-11 20:30:12 -0800288
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800289 var components = contentObject.name.components.slice
290 (0, contentObject.name.components.length - 1);
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800291 components.push(segmentNumberComponent);
Jeff Thompson52843b12013-02-18 17:53:18 -0800292 this.ndn.expressInterest
293 (new Name(components), new ExponentialReExpressClosure(this), this.segmentTemplate);
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800294 }
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800295
296 return Closure.RESULT_OK;
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800297 } catch (ex) {
298 dump("ContentClosure.upcall exception: " + ex + "\n" + ex.stack);
299 return Closure.RESULT_ERR;
300 }
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800301};
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800302
303/*
304 * A SegmentStore stores segments until they are retrieved in order starting with segment 0.
305 */
306var SegmentStore = function SegmentStore() {
307 // Each entry is an object where the key is the segment number and value is null if
308 // the segment number is requested or the contentObject if received.
309 this.store = new SortedArray();
310 this.maxRetrievedSegmentNumber = -1;
311};
312
313SegmentStore.prototype.storeContent = function(segmentNumber, contentObject) {
314 // We don't expect to try to store a segment that has already been retrieved, but check anyway.
315 if (segmentNumber > this.maxRetrievedSegmentNumber)
316 this.store.set(segmentNumber, contentObject);
317};
318
319/*
320 * If the min segment number is this.maxRetrievedSegmentNumber + 1 and its value is not null,
321 * then delete from the store, return the entry with key and value, and update maxRetrievedSegmentNumber.
322 * Otherwise return null.
323 */
324SegmentStore.prototype.maybeRetrieveNextEntry = function() {
325 if (this.store.entries.length > 0 && this.store.entries[0].value != null &&
326 this.store.entries[0].key == this.maxRetrievedSegmentNumber + 1) {
327 var entry = this.store.entries[0];
328 this.store.removeAt(0);
329 ++this.maxRetrievedSegmentNumber;
330 return entry;
331 }
332 else
333 return null;
334};
335
336/*
337 * Return an array of the next segment numbers that need to be requested so that the total
338 * requested segments is totalRequestedSegments. If a segment store entry value is null, it is
339 * already requested and is not returned. If a segment number is returned, create a
340 * entry in the segment store with a null value.
341 */
342SegmentStore.prototype.requestSegmentNumbers = function(totalRequestedSegments) {
343 // First, count how many are already requested.
344 var nRequestedSegments = 0;
345 for (var i = 0; i < this.store.entries.length; ++i) {
346 if (this.store.entries[i].value == null) {
347 ++nRequestedSegments;
348 if (nRequestedSegments >= totalRequestedSegments)
349 // Already maxed out on requests.
350 return [];
351 }
352 }
353
354 var toRequest = [];
355 var nextSegmentNumber = this.maxRetrievedSegmentNumber + 1;
356 for (var i = 0; i < this.store.entries.length; ++i) {
357 var entry = this.store.entries[i];
358 // Fill in the gap before the segment number in the entry.
359 while (nextSegmentNumber < entry.key) {
360 toRequest.push(nextSegmentNumber);
361 ++nextSegmentNumber;
362 ++nRequestedSegments;
363 if (nRequestedSegments >= totalRequestedSegments)
364 break;
365 }
366 if (nRequestedSegments >= totalRequestedSegments)
367 break;
368
369 nextSegmentNumber = entry.key + 1;
370 }
371
372 // We already filled in the gaps for the segments in the store. Continue after the last.
373 while (nRequestedSegments < totalRequestedSegments) {
374 toRequest.push(nextSegmentNumber);
375 ++nextSegmentNumber;
376 ++nRequestedSegments;
377 }
378
379 // Mark the new segment numbers as requested.
380 for (var i = 0; i < toRequest.length; ++i)
381 this.store.set(toRequest[i], null);
382 return toRequest;
383}
384
385/*
386 * A SortedArray is an array of objects with key and value, where the key is an integer.
387 */
388var SortedArray = function SortedArray() {
389 this.entries = [];
390}
391
392SortedArray.prototype.sortEntries = function() {
393 this.entries.sort(function(a, b) { return a.key - b.key; });
394};
395
396SortedArray.prototype.indexOfKey = function(key) {
397 for (var i = 0; i < this.entries.length; ++i) {
398 if (this.entries[i].key == key)
399 return i;
400 }
401
402 return -1;
403}
404
405SortedArray.prototype.set = function(key, value) {
406 var i = this.indexOfKey(key);
407 if (i >= 0) {
408 this.entries[i].value = value;
409 return;
410 }
411
412 this.entries.push({ key: key, value: value});
413 this.sortEntries();
414}
415
416SortedArray.prototype.removeAt = function(index) {
417 this.entries.splice(index, 1);
418}
419
Jeff Thompsondf0a6f72012-10-21 15:58:58 -0700420/*
Jeff Thompsonbd829262012-11-30 22:28:37 -0800421 * Scan the name from the last component to the first (skipping special name components)
Jeff Thompson25b06412012-10-21 20:07:57 -0700422 * for a recognized file name extension, and return an object with properties contentType and charset.
Jeff Thompsondf0a6f72012-10-21 15:58:58 -0700423 */
Jeff Thompsone769c512012-11-04 17:25:07 -0800424function getNameContentTypeAndCharset(name) {
Jeff Thompson16a35f72012-11-25 08:07:33 -0800425 var iFileName = name.indexOfFileName();
426 if (iFileName < 0)
427 // Get the default mime type.
428 return MimeTypes.getContentTypeAndCharset("");
Jeff Thompsondf0a6f72012-10-21 15:58:58 -0700429
Jeff Thompson16a35f72012-11-25 08:07:33 -0800430 return MimeTypes.getContentTypeAndCharset
431 (DataUtils.toString(name.components[iFileName]).toLowerCase());
Jeff Thompsondf0a6f72012-10-21 15:58:58 -0700432}
Jeff Thompson10de4592012-10-21 23:54:18 -0700433
434/*
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800435 * Return true if the last component in the name is a segment number..
Jeff Thompson10de4592012-10-21 23:54:18 -0700436 */
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800437function endsWithSegmentNumber(name) {
Jeff Thompson10de4592012-10-21 23:54:18 -0700438 return name.components != null && name.components.length >= 1 &&
439 name.components[name.components.length - 1].length >= 1 &&
440 name.components[name.components.length - 1][0] == 0;
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800441}
442
443/*
Jeff Thompsonbd829262012-11-30 22:28:37 -0800444 * Find all search keys starting with "ndn." and set the attribute in template.
445 * Return the search string including the starting "?" but with the "ndn." keys removed,
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800446 * or return "" if there are no search terms left.
447 */
Jeff Thompsonbd829262012-11-30 22:28:37 -0800448function extractNdnSearch(search, template) {
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800449 if (!(search.length >= 1 && search[0] == '?'))
450 return search;
451
452 var terms = search.substr(1).split('&');
453 var i = 0;
454 while (i < terms.length) {
455 var keyValue = terms[i].split('=');
456 var key = keyValue[0].trim();
Jeff Thompsonbd829262012-11-30 22:28:37 -0800457 if (key.substr(0, 4) == "ndn.") {
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800458 if (keyValue.length >= 1) {
Jeff Thompson754652d2012-11-24 16:23:43 -0800459 var value = keyValue[1].trim();
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800460 var nonNegativeInt = parseInt(value);
461
Jeff Thompsonbd829262012-11-30 22:28:37 -0800462 if (key == "ndn.MinSuffixComponents" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800463 template.minSuffixComponents = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800464 else if (key == "ndn.MaxSuffixComponents" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800465 template.maxSuffixComponents = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800466 else if (key == "ndn.ChildSelector" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800467 template.childSelector = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800468 else if (key == "ndn.AnswerOriginKind" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800469 template.answerOriginKind = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800470 else if (key == "ndn.Scope" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800471 template.scope = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800472 else if (key == "ndn.InterestLifetime" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800473 template.interestLifetime = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800474 else if (key == "ndn.PublisherPublicKeyDigest")
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800475 template.publisherPublicKeyDigest = DataUtils.toNumbersFromString(unescape(value));
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800476 else if (key == "ndn.Nonce")
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800477 template.nonce = DataUtils.toNumbersFromString(unescape(value));
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800478 else if (key == "ndn.Exclude")
479 template.exclude = parseExclude(value);
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800480 }
481
Jeff Thompsonbd829262012-11-30 22:28:37 -0800482 // Remove the "ndn." term and don't advance i.
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800483 terms.splice(i, 1);
484 }
485 else
486 ++i;
487 }
488
489 if (terms.length == 0)
490 return "";
491 else
492 return "?" + terms.join('&');
Jeff Thompson963d2da2012-12-02 23:31:22 -0800493}
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800494
495/*
496 * Parse the comma-separated list of exclude components and return an Exclude.
497 */
498function parseExclude(value) {
499 var excludeValues = [];
500
501 var splitValue = value.split(',');
502 for (var i = 0; i < splitValue.length; ++i) {
503 var element = splitValue[i].trim();
504 if (element == "*")
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800505 excludeValues.push(Exclude.ANY)
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800506 else
507 excludeValues.push(Name.fromEscapedString(element));
508 }
509
510 return new Exclude(excludeValues);
511}
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800512
513/*
514 * Return the index of the first compoment that starts with %C1.META, or -1 if not found.
515 */
516function getIndexOfMetaComponent(name) {
517 for (var i = 0; i < name.components.length; ++i) {
518 var component = name.components[i];
519 if (component.length >= MetaComponentPrefix.length &&
520 DataUtils.arraysEqual(component.subarray(0, MetaComponentPrefix.length),
521 MetaComponentPrefix))
522 return i;
523 }
524
525 return -1;
526}
527
528var MetaComponentPrefix = new Uint8Array([0xc1, 0x2e, 0x4d, 0x45, 0x54, 0x41]);