blob: 1cac09b79134eefe63a2124093cd6061d5c305af [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 Thompson4eb992a2013-03-09 21:05:53 -080019function 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 Thompson4eb992a2013-03-09 21:05:53 -080085 NdnProtocolInfo.ndn.expressInterest(name, new ExponentialReExpressClosure
86 (new ContentClosure(NdnProtocolInfo.ndn, contentListener, name,
Jeff Thompson52843b12013-02-18 17:53:18 -080087 aURI, searchWithoutNdn + uriParts.hash, segmentTemplate)),
Jeff Thompson5fc9b672012-11-24 10:00:56 -080088 template);
Jeff Thompson9e6dff02012-11-04 09:20:47 -080089 };
Jeff Thompson57d07382012-10-29 23:25:54 -070090
Jeff Thompson5fc9b672012-11-24 10:00:56 -080091 return new ContentChannel(aURI, requestContent);
Jeff Thompson9e6dff02012-11-04 09:20:47 -080092 } catch (ex) {
Jeff Thompsonbd829262012-11-30 22:28:37 -080093 dump("NdnProtocol.newChannel exception: " + ex + "\n" + ex.stack);
Jeff Thompson9e6dff02012-11-04 09:20:47 -080094 }
95 },
Jeff Thompson08ab3cd2012-10-08 02:56:20 -070096
Jeff Thompsonbd829262012-11-30 22:28:37 -080097 classDescription: "ndn Protocol Handler",
98 contractID: "@mozilla.org/network/protocol;1?name=" + "ndn",
Jeff Thompson9e6dff02012-11-04 09:20:47 -080099 classID: Components.ID('{8122e660-1012-11e2-892e-0800200c9a66}'),
100 QueryInterface: XPCOMUtils.generateQI([Ci.nsIProtocolHandler])
Jeff Thompson3d6ce942012-12-16 12:11:42 -0800101};
Jeff Thompson08ab3cd2012-10-08 02:56:20 -0700102
103if (XPCOMUtils.generateNSGetFactory)
Jeff Thompsonbd829262012-11-30 22:28:37 -0800104 var NSGetFactory = XPCOMUtils.generateNSGetFactory([NdnProtocol]);
Jeff Thompson08ab3cd2012-10-08 02:56:20 -0700105else
Jeff Thompsonbd829262012-11-30 22:28:37 -0800106 var NSGetModule = XPCOMUtils.generateNSGetModule([NdnProtocol]);
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800107
108/*
109 * Create a closure for calling expressInterest.
110 * contentListener is from the call to requestContent.
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800111 * uriName is the name in the URI passed to newChannel (used in part to determine whether to request
112 * only that segment number and for updating the URL bar).
Jeff Thompson3663c672013-02-04 23:22:11 -0800113 * aURI is the URI passed to newChannel.
Jeff Thompson1eea6322012-11-23 16:56:18 -0800114 * uriSearchAndHash is the search and hash part of the URI passed to newChannel, including the '?'
115 * and/or '#' but without the interest selector fields.
Jeff Thompsone5a88282013-01-05 21:02:06 -0800116 * segmentTemplate is the template used in expressInterest to fetch further segments.
Jeff Thompson52843b12013-02-18 17:53:18 -0800117 * The uses ExponentialReExpressClosure in expressInterest to re-express if fetching a segment times out.
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800118 */
119var ContentClosure = function ContentClosure
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800120 (ndn, contentListener, uriName, aURI, uriSearchAndHash, segmentTemplate) {
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800121 // Inherit from Closure.
122 Closure.call(this);
123
124 this.ndn = ndn;
125 this.contentListener = contentListener;
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800126 this.uriName = uriName;
Jeff Thompson3663c672013-02-04 23:22:11 -0800127 this.aURI = aURI;
Jeff Thompson1eea6322012-11-23 16:56:18 -0800128 this.uriSearchAndHash = uriSearchAndHash;
Jeff Thompsone5a88282013-01-05 21:02:06 -0800129 this.segmentTemplate = segmentTemplate;
Jeff Thompson1eea6322012-11-23 16:56:18 -0800130
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800131 this.segmentStore = new SegmentStore();
Jeff Thompson1ac86ce2013-01-21 21:51:07 -0800132 this.contentSha256 = new Sha256();
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800133 this.didRequestFinalSegment = false;
134 this.finalSegmentNumber = null;
Jeff Thompson52843b12013-02-18 17:53:18 -0800135 this.didOnStart = false;
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800136 this.uriEndsWithSegmentNumber = endsWithSegmentNumber(uriName);
Jeff Thompson3d6ce942012-12-16 12:11:42 -0800137};
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800138
139ContentClosure.prototype.upcall = function(kind, upcallInfo) {
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800140 try {
Jeff Thompson52843b12013-02-18 17:53:18 -0800141 // Assume this is only called once we're connected, report the host and port.
142 NdnProtocolInfo.setConnectedNdnHub(this.ndn.host, this.ndn.port);
143
Jeff Thompson3663c672013-02-04 23:22:11 -0800144 if (this.contentListener.done)
145 // We are getting unexpected extra results.
146 return Closure.RESULT_ERR;
147
148 if (kind == Closure.UPCALL_INTEREST_TIMED_OUT) {
Jeff Thompson152342b2013-02-18 20:36:53 -0800149 if (!this.didOnStart) {
150 // 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 -0800151 this.contentListener.onStart("text/plain", "utf-8", this.aURI);
152 this.contentListener.onReceivedContent
Jeff Thompson152342b2013-02-18 20:36:53 -0800153 ("The latest interest timed out after " + upcallInfo.interest.interestLifetime + " milliseconds.");
Jeff Thompson3663c672013-02-04 23:22:11 -0800154 this.contentListener.onStop();
155 return Closure.RESULT_OK;
156 }
157 else
Jeff Thompson52843b12013-02-18 17:53:18 -0800158 // ExponentialReExpressClosure already tried to re-express, so quit.
Jeff Thompson3663c672013-02-04 23:22:11 -0800159 return Closure.RESULT_ERR;
160 }
161
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800162 if (!(kind == Closure.UPCALL_CONTENT ||
163 kind == Closure.UPCALL_CONTENT_UNVERIFIED))
164 // The upcall is not for us.
165 return Closure.RESULT_ERR;
166
167 var contentObject = upcallInfo.contentObject;
168 if (contentObject.content == null) {
Jeff Thompsonbd829262012-11-30 22:28:37 -0800169 dump("NdnProtocol.ContentClosure: contentObject.content is null\n");
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800170 return Closure.RESULT_ERR;
171 }
Jeff Thompson6ad5c362012-12-27 17:57:02 -0800172
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800173 // If !this.uriEndsWithSegmentNumber, we use the segmentNumber to load multiple segments.
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800174 // If this.uriEndsWithSegmentNumber, then we leave segmentNumber null.
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800175 var segmentNumber = null;
176 if (!this.uriEndsWithSegmentNumber && endsWithSegmentNumber(contentObject.name)) {
177 segmentNumber = DataUtils.bigEndianToUnsignedInt
178 (contentObject.name.components[contentObject.name.components.length - 1]);
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800179 this.segmentStore.storeContent(segmentNumber, contentObject);
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800180 }
181
Jeff Thompson52843b12013-02-18 17:53:18 -0800182 if ((segmentNumber == null || segmentNumber == 0) && !this.didOnStart) {
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800183 // This is the first or only segment.
184 /* TODO: Finish implementing check for META.
185 var iMetaComponent = getIndexOfMetaComponent(contentObject.name);
186 if (!this.uriEndsWithSegmentNumber && iMetaComponent >= 0 &&
187 getIndexOfMetaComponent(this.uriName) < 0) {
188 // The matched content name has a META component that wasn't requiested in the original
189 // URI. Try to exclude the META component to get the "real" content.
190 var nameWithoutMeta = new Name(contentObject.name.components.slice(0, iMetaComponent));
191 var excludeMetaTemplate = this.segmentTemplate.clone();
192 excludeMetaTemplate.exclude = new Exclude([MetaComponentPrefix, Exclude.ANY]);
193
194 this.ndn.expressInterest
195 (nameWithoutMeta, new ExponentialReExpressClosure(this), excludeMetaTemplate);
196 }
197 */
198
Jeff Thompson52843b12013-02-18 17:53:18 -0800199 this.didOnStart = true;
200
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800201 // Get the URI from the ContentObject including the version.
202 var contentUriSpec;
203 if (!this.uriEndsWithSegmentNumber && endsWithSegmentNumber(contentObject.name)) {
204 var nameWithoutSegmentNumber = new Name
Jeff Thompson963d2da2012-12-02 23:31:22 -0800205 (contentObject.name.components.slice(0, contentObject.name.components.length - 1));
Jeff Thompsonbd829262012-11-30 22:28:37 -0800206 contentUriSpec = "ndn:" + nameWithoutSegmentNumber.to_uri();
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800207 }
208 else
Jeff Thompsonbd829262012-11-30 22:28:37 -0800209 contentUriSpec = "ndn:" + contentObject.name.to_uri();
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800210
Jeff Thompson1eea6322012-11-23 16:56:18 -0800211 // Include the search and hash.
212 contentUriSpec += this.uriSearchAndHash;
213
Jeff Thompsone769c512012-11-04 17:25:07 -0800214 var contentTypeEtc = getNameContentTypeAndCharset(contentObject.name);
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800215 var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
216 this.contentListener.onStart(contentTypeEtc.contentType, contentTypeEtc.contentCharset,
Jeff Thompson3663c672013-02-04 23:22:11 -0800217 ioService.newURI(contentUriSpec, this.aURI.originCharset, null));
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800218 }
219
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800220 if (segmentNumber == null) {
221 // We are not doing segments, so just finish.
222 this.contentListener.onReceivedContent(DataUtils.toString(contentObject.content));
Jeff Thompson869e8192012-12-16 12:18:24 -0800223 this.contentSha256.update(contentObject.content);
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800224 this.contentListener.onStop();
225
226 if (!this.uriEndsWithSegmentNumber) {
227 var nameContentDigest = contentObject.name.getContentDigestValue();
228 if (nameContentDigest != null &&
229 !DataUtils.arraysEqual(nameContentDigest, this.contentSha256.finalize()))
230 // TODO: How to show the user an error for invalid digest?
231 dump("Content does not match digest in name " + contentObject.name.to_uri());
232 }
233 return Closure.RESULT_OK;
234 }
235
236 if (contentObject.signedInfo != null && contentObject.signedInfo.finalBlockID != null)
237 this.finalSegmentNumber = DataUtils.bigEndianToUnsignedInt(contentObject.signedInfo.finalBlockID);
238
239 // The content was already put in the store. Retrieve as much as possible.
240 var entry;
241 while ((entry = this.segmentStore.maybeRetrieveNextEntry()) != null) {
242 segmentNumber = entry.key;
243 contentObject = entry.value;
244 this.contentListener.onReceivedContent(DataUtils.toString(contentObject.content));
245 this.contentSha256.update(contentObject.content);
246
247 if (this.finalSegmentNumber != null && segmentNumber == this.finalSegmentNumber) {
248 // Finished.
249 this.contentListener.onStop();
250 var nameContentDigest = contentObject.name.getContentDigestValue();
251 if (nameContentDigest != null &&
252 !DataUtils.arraysEqual(nameContentDigest, this.contentSha256.finalize()))
253 // TODO: How to show the user an error for invalid digest?
254 dump("Content does not match digest in name " + contentObject.name.to_uri());
255
256 return Closure.RESULT_OK;
257 }
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800258 }
259
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800260 if (this.finalSegmentNumber == null && !this.didRequestFinalSegment) {
Jeff Thompsonb083c8e2013-01-23 21:27:32 -0800261 this.didRequestFinalSegment = true;
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800262 // Try to determine the final segment now.
263 var components = contentObject.name.components.slice
264 (0, contentObject.name.components.length - 1);
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800265
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800266 // Clone the template to set the childSelector.
267 var childSelectorTemplate = this.segmentTemplate.clone();
268 childSelectorTemplate.childSelector = 1;
Jeff Thompson52843b12013-02-18 17:53:18 -0800269 this.ndn.expressInterest
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800270 (new Name(components), new ExponentialReExpressClosure(this), childSelectorTemplate);
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800271 }
272
273 // Request new segments.
274 var toRequest = this.segmentStore.requestSegmentNumbers(2);
275 for (var i = 0; i < toRequest.length; ++i) {
276 if (this.finalSegmentNumber != null && toRequest[i] > this.finalSegmentNumber)
277 continue;
278
Jeff Thompson52843b12013-02-18 17:53:18 -0800279 this.ndn.expressInterest
Jeff Thompsonca2535c2013-02-28 22:26:13 -0800280 (new Name(contentObject.name.components.slice
281 (0, contentObject.name.components.length - 1)).addSegment(toRequest[i]),
282 new ExponentialReExpressClosure(this), this.segmentTemplate);
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800283 }
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800284
285 return Closure.RESULT_OK;
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800286 } catch (ex) {
287 dump("ContentClosure.upcall exception: " + ex + "\n" + ex.stack);
288 return Closure.RESULT_ERR;
289 }
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800290};
Jeff Thompsonf6995b52013-01-23 21:21:16 -0800291
292/*
293 * A SegmentStore stores segments until they are retrieved in order starting with segment 0.
294 */
295var SegmentStore = function SegmentStore() {
296 // Each entry is an object where the key is the segment number and value is null if
297 // the segment number is requested or the contentObject if received.
298 this.store = new SortedArray();
299 this.maxRetrievedSegmentNumber = -1;
300};
301
302SegmentStore.prototype.storeContent = function(segmentNumber, contentObject) {
303 // We don't expect to try to store a segment that has already been retrieved, but check anyway.
304 if (segmentNumber > this.maxRetrievedSegmentNumber)
305 this.store.set(segmentNumber, contentObject);
306};
307
308/*
309 * If the min segment number is this.maxRetrievedSegmentNumber + 1 and its value is not null,
310 * then delete from the store, return the entry with key and value, and update maxRetrievedSegmentNumber.
311 * Otherwise return null.
312 */
313SegmentStore.prototype.maybeRetrieveNextEntry = function() {
314 if (this.store.entries.length > 0 && this.store.entries[0].value != null &&
315 this.store.entries[0].key == this.maxRetrievedSegmentNumber + 1) {
316 var entry = this.store.entries[0];
317 this.store.removeAt(0);
318 ++this.maxRetrievedSegmentNumber;
319 return entry;
320 }
321 else
322 return null;
323};
324
325/*
326 * Return an array of the next segment numbers that need to be requested so that the total
327 * requested segments is totalRequestedSegments. If a segment store entry value is null, it is
328 * already requested and is not returned. If a segment number is returned, create a
329 * entry in the segment store with a null value.
330 */
331SegmentStore.prototype.requestSegmentNumbers = function(totalRequestedSegments) {
332 // First, count how many are already requested.
333 var nRequestedSegments = 0;
334 for (var i = 0; i < this.store.entries.length; ++i) {
335 if (this.store.entries[i].value == null) {
336 ++nRequestedSegments;
337 if (nRequestedSegments >= totalRequestedSegments)
338 // Already maxed out on requests.
339 return [];
340 }
341 }
342
343 var toRequest = [];
344 var nextSegmentNumber = this.maxRetrievedSegmentNumber + 1;
345 for (var i = 0; i < this.store.entries.length; ++i) {
346 var entry = this.store.entries[i];
347 // Fill in the gap before the segment number in the entry.
348 while (nextSegmentNumber < entry.key) {
349 toRequest.push(nextSegmentNumber);
350 ++nextSegmentNumber;
351 ++nRequestedSegments;
352 if (nRequestedSegments >= totalRequestedSegments)
353 break;
354 }
355 if (nRequestedSegments >= totalRequestedSegments)
356 break;
357
358 nextSegmentNumber = entry.key + 1;
359 }
360
361 // We already filled in the gaps for the segments in the store. Continue after the last.
362 while (nRequestedSegments < totalRequestedSegments) {
363 toRequest.push(nextSegmentNumber);
364 ++nextSegmentNumber;
365 ++nRequestedSegments;
366 }
367
368 // Mark the new segment numbers as requested.
369 for (var i = 0; i < toRequest.length; ++i)
370 this.store.set(toRequest[i], null);
371 return toRequest;
372}
373
374/*
375 * A SortedArray is an array of objects with key and value, where the key is an integer.
376 */
377var SortedArray = function SortedArray() {
378 this.entries = [];
379}
380
381SortedArray.prototype.sortEntries = function() {
382 this.entries.sort(function(a, b) { return a.key - b.key; });
383};
384
385SortedArray.prototype.indexOfKey = function(key) {
386 for (var i = 0; i < this.entries.length; ++i) {
387 if (this.entries[i].key == key)
388 return i;
389 }
390
391 return -1;
392}
393
394SortedArray.prototype.set = function(key, value) {
395 var i = this.indexOfKey(key);
396 if (i >= 0) {
397 this.entries[i].value = value;
398 return;
399 }
400
401 this.entries.push({ key: key, value: value});
402 this.sortEntries();
403}
404
405SortedArray.prototype.removeAt = function(index) {
406 this.entries.splice(index, 1);
407}
408
Jeff Thompsondf0a6f72012-10-21 15:58:58 -0700409/*
Jeff Thompsonbd829262012-11-30 22:28:37 -0800410 * Scan the name from the last component to the first (skipping special name components)
Jeff Thompson25b06412012-10-21 20:07:57 -0700411 * for a recognized file name extension, and return an object with properties contentType and charset.
Jeff Thompsondf0a6f72012-10-21 15:58:58 -0700412 */
Jeff Thompsone769c512012-11-04 17:25:07 -0800413function getNameContentTypeAndCharset(name) {
Jeff Thompson16a35f72012-11-25 08:07:33 -0800414 var iFileName = name.indexOfFileName();
415 if (iFileName < 0)
416 // Get the default mime type.
417 return MimeTypes.getContentTypeAndCharset("");
Jeff Thompsondf0a6f72012-10-21 15:58:58 -0700418
Jeff Thompson16a35f72012-11-25 08:07:33 -0800419 return MimeTypes.getContentTypeAndCharset
420 (DataUtils.toString(name.components[iFileName]).toLowerCase());
Jeff Thompsondf0a6f72012-10-21 15:58:58 -0700421}
Jeff Thompson10de4592012-10-21 23:54:18 -0700422
423/*
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800424 * Return true if the last component in the name is a segment number..
Jeff Thompson10de4592012-10-21 23:54:18 -0700425 */
Jeff Thompson9e6dff02012-11-04 09:20:47 -0800426function endsWithSegmentNumber(name) {
Jeff Thompson10de4592012-10-21 23:54:18 -0700427 return name.components != null && name.components.length >= 1 &&
428 name.components[name.components.length - 1].length >= 1 &&
429 name.components[name.components.length - 1][0] == 0;
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800430}
431
432/*
Jeff Thompsonbd829262012-11-30 22:28:37 -0800433 * Find all search keys starting with "ndn." and set the attribute in template.
434 * Return the search string including the starting "?" but with the "ndn." keys removed,
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800435 * or return "" if there are no search terms left.
436 */
Jeff Thompsonbd829262012-11-30 22:28:37 -0800437function extractNdnSearch(search, template) {
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800438 if (!(search.length >= 1 && search[0] == '?'))
439 return search;
440
441 var terms = search.substr(1).split('&');
442 var i = 0;
443 while (i < terms.length) {
444 var keyValue = terms[i].split('=');
445 var key = keyValue[0].trim();
Jeff Thompsonbd829262012-11-30 22:28:37 -0800446 if (key.substr(0, 4) == "ndn.") {
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800447 if (keyValue.length >= 1) {
Jeff Thompson754652d2012-11-24 16:23:43 -0800448 var value = keyValue[1].trim();
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800449 var nonNegativeInt = parseInt(value);
450
Jeff Thompsonbd829262012-11-30 22:28:37 -0800451 if (key == "ndn.MinSuffixComponents" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800452 template.minSuffixComponents = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800453 else if (key == "ndn.MaxSuffixComponents" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800454 template.maxSuffixComponents = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800455 else if (key == "ndn.ChildSelector" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800456 template.childSelector = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800457 else if (key == "ndn.AnswerOriginKind" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800458 template.answerOriginKind = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800459 else if (key == "ndn.Scope" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800460 template.scope = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800461 else if (key == "ndn.InterestLifetime" && nonNegativeInt >= 0)
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800462 template.interestLifetime = nonNegativeInt;
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800463 else if (key == "ndn.PublisherPublicKeyDigest")
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800464 template.publisherPublicKeyDigest = DataUtils.toNumbersFromString(unescape(value));
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800465 else if (key == "ndn.Nonce")
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800466 template.nonce = DataUtils.toNumbersFromString(unescape(value));
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800467 else if (key == "ndn.Exclude")
468 template.exclude = parseExclude(value);
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800469 }
470
Jeff Thompsonbd829262012-11-30 22:28:37 -0800471 // Remove the "ndn." term and don't advance i.
Jeff Thompson5fc9b672012-11-24 10:00:56 -0800472 terms.splice(i, 1);
473 }
474 else
475 ++i;
476 }
477
478 if (terms.length == 0)
479 return "";
480 else
481 return "?" + terms.join('&');
Jeff Thompson963d2da2012-12-02 23:31:22 -0800482}
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800483
484/*
485 * Parse the comma-separated list of exclude components and return an Exclude.
486 */
487function parseExclude(value) {
488 var excludeValues = [];
489
490 var splitValue = value.split(',');
491 for (var i = 0; i < splitValue.length; ++i) {
492 var element = splitValue[i].trim();
493 if (element == "*")
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800494 excludeValues.push(Exclude.ANY)
Jeff Thompson6ac75d22013-02-04 22:41:34 -0800495 else
496 excludeValues.push(Name.fromEscapedString(element));
497 }
498
499 return new Exclude(excludeValues);
500}
Jeff Thompson4a4caba2013-02-28 21:31:33 -0800501
502/*
503 * Return the index of the first compoment that starts with %C1.META, or -1 if not found.
504 */
505function getIndexOfMetaComponent(name) {
506 for (var i = 0; i < name.components.length; ++i) {
507 var component = name.components[i];
508 if (component.length >= MetaComponentPrefix.length &&
509 DataUtils.arraysEqual(component.subarray(0, MetaComponentPrefix.length),
510 MetaComponentPrefix))
511 return i;
512 }
513
514 return -1;
515}
516
517var MetaComponentPrefix = new Uint8Array([0xc1, 0x2e, 0x4d, 0x45, 0x54, 0x41]);