blob: edc4d84449d491088017a74a5102fd7ada7bf35d [file] [log] [blame]
Wentao Shangc0311e52012-12-03 10:38:23 -08001/**
Jeff Thompson5b265a72012-11-12 01:13:08 -08002 * @author: Meki Cherkaoui, Jeff Thompson, Wentao Shang
Jeff Thompson745026e2012-10-13 12:49:20 -07003 * See COPYING for copyright and distribution information.
4 * This class represents the top-level object for communicating with an NDN host.
5 */
Meki Cherkaoui8f173612012-06-06 01:05:40 -07006
Jeff Thompson3c263812012-12-01 17:20:28 -08007var LOG = 0;
Jeff Thompson5b265a72012-11-12 01:13:08 -08008
Jeff Thompsone06b31e2012-09-30 17:19:19 -07009/**
Jeff Thompson5b265a72012-11-12 01:13:08 -080010 * settings is an associative array with the following defaults:
11 * {
Jeff Thompson5b265a72012-11-12 01:13:08 -080012 * getTransport: function() { return new WebSocketTransport(); }
Jeff Thompsond3a80dc2012-12-16 17:52:43 -080013 * getHostAndPort: transport.defaultGetHostAndPort,
Jeff Thompsond771b122013-01-26 19:04:41 -080014 * host: null, // If null, use getHostAndPort when connecting.
Jeff Thompsond3a80dc2012-12-16 17:52:43 -080015 * port: 9696,
Wentao Shangc0311e52012-12-03 10:38:23 -080016 * onopen: function() { if (LOG > 3) console.log("NDN connection established."); }
17 * onclose: function() { if (LOG > 3) console.log("NDN connection closed."); }
Jeff Thompson5b265a72012-11-12 01:13:08 -080018 * }
Jeff Thompsond3a80dc2012-12-16 17:52:43 -080019 *
20 * getHostAndPort is a function, on each call it returns a new { host: host, port: port } or
21 * null if there are no more hosts.
Jeff Thompsone06b31e2012-09-30 17:19:19 -070022 */
Jeff Thompson5b265a72012-11-12 01:13:08 -080023var NDN = function NDN(settings) {
24 settings = (settings || {});
Jeff Thompson5b265a72012-11-12 01:13:08 -080025 var getTransport = (settings.getTransport || function() { return new WebSocketTransport(); });
Wentao Shang0e291c82012-12-02 23:36:29 -080026 this.transport = getTransport();
Jeff Thompsond3a80dc2012-12-16 17:52:43 -080027 this.getHostAndPort = (settings.getHostAndPort || this.transport.defaultGetHostAndPort);
Jeff Thompsond771b122013-01-26 19:04:41 -080028 this.host = (settings.host !== undefined ? settings.host : null);
Jeff Thompsond3a80dc2012-12-16 17:52:43 -080029 this.port = (settings.port || 9696);
Wentao Shang0e291c82012-12-02 23:36:29 -080030 this.readyStatus = NDN.UNOPEN;
Wentao Shangd4607392013-01-24 23:08:49 -080031 this.verify = (settings.verify !== undefined ? settings.verify : true);
Wentao Shang0e291c82012-12-02 23:36:29 -080032 // Event handler
Wentao Shangc0311e52012-12-03 10:38:23 -080033 this.onopen = (settings.onopen || function() { if (LOG > 3) console.log("NDN connection established."); });
34 this.onclose = (settings.onclose || function() { if (LOG > 3) console.log("NDN connection closed."); });
Jeff Thompson75771cb2013-01-20 23:27:38 -080035 this.ccndid = null;
Meki Cherkaoui8f173612012-06-06 01:05:40 -070036};
37
Wentao Shang0e291c82012-12-02 23:36:29 -080038NDN.UNOPEN = 0; // created but not opened yet
39NDN.OPENED = 1; // connection to ccnd opened
40NDN.CLOSED = 2; // connection to ccnd closed
Jeff Thompson5b265a72012-11-12 01:13:08 -080041
Wentao Shangb42483a2013-01-03 15:32:32 -080042NDN.ccndIdFetcher = new Name('/%C1.M.S.localhost/%C1.M.SRV/ccnd/KEY');
Jeff Thompson5b265a72012-11-12 01:13:08 -080043
Wentao Shangb42483a2013-01-03 15:32:32 -080044NDN.prototype.createRoute = function(host, port) {
Meki Cherkaoui8f173612012-06-06 01:05:40 -070045 this.host=host;
46 this.port=port;
Wentao Shangb42483a2013-01-03 15:32:32 -080047};
Meki Cherkaoui8f173612012-06-06 01:05:40 -070048
Wentao Shang82854bd2012-12-27 14:14:41 -080049
50NDN.KeyStore = new Array();
51
Wentao Shangb5d0c3e2012-12-30 11:12:03 -080052var KeyStoreEntry = function KeyStoreEntry(name, rsa, time) {
Wentao Shang82854bd2012-12-27 14:14:41 -080053 this.keyName = name; // KeyName
Wentao Shang82854bd2012-12-27 14:14:41 -080054 this.rsaKey = rsa; // RSA key
Wentao Shangb5d0c3e2012-12-30 11:12:03 -080055 this.timeStamp = time; // Time Stamp
56};
57
58NDN.addKeyEntry = function(/* KeyStoreEntry */ keyEntry) {
59 var result = NDN.getKeyByName(keyEntry.keyName);
60 if (result == null)
61 NDN.KeyStore.push(keyEntry);
62 else
63 result = keyEntry;
Wentao Shang82854bd2012-12-27 14:14:41 -080064};
65
66NDN.getKeyByName = function(/* KeyName */ name) {
67 var result = null;
68
69 for (var i = 0; i < NDN.KeyStore.length; i++) {
Wentao Shangb42483a2013-01-03 15:32:32 -080070 if (NDN.KeyStore[i].keyName.contentName.match(name.contentName)) {
Wentao Shang82854bd2012-12-27 14:14:41 -080071 if (result == null ||
72 NDN.KeyStore[i].keyName.contentName.components.length > result.keyName.contentName.components.length)
73 result = NDN.KeyStore[i];
74 }
75 }
76
77 return result;
78};
79
Jeff Thompsonbe85be62012-12-13 22:32:01 -080080// For fetching data
81NDN.PITTable = new Array();
82
83var PITEntry = function PITEntry(interest, closure) {
84 this.interest = interest; // Interest
85 this.closure = closure; // Closure
Wentao Shangfcb16262013-01-20 14:42:46 -080086 this.timerID = -1; // Timer ID
Jeff Thompsonbe85be62012-12-13 22:32:01 -080087};
88
89// Return the longest entry from NDN.PITTable that matches name.
90NDN.getEntryForExpressedInterest = function(/*Name*/ name) {
91 // TODO: handle multiple matches? Maybe not from registerPrefix because multiple ContentObject
92 // could be sent for one Interest?
93 var result = null;
94
95 for (var i = 0; i < NDN.PITTable.length; i++) {
96 if (NDN.PITTable[i].interest.matches_name(name)) {
97 if (result == null ||
98 NDN.PITTable[i].interest.name.components.length > result.interest.name.components.length)
99 result = NDN.PITTable[i];
100 }
101 }
102
103 return result;
104};
105
Jeff Thompson75771cb2013-01-20 23:27:38 -0800106// For publishing data
107NDN.CSTable = new Array();
108
109var CSEntry = function CSEntry(name, closure) {
110 this.name = name; // String
111 this.closure = closure; // Closure
112};
113
114function getEntryForRegisteredPrefix(name) {
115 for (var i = 0; i < NDN.CSTable.length; i++) {
116 if (NDN.CSTable[i].name.match(name) != null)
117 return NDN.CSTable[i];
118 }
119 return null;
120}
121
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800122/*
123 * Return a function that selects a host at random from hostList and returns { host: host, port: port }.
124 * If no more hosts remain, return null.
125 */
126NDN.makeShuffledGetHostAndPort = function(hostList, port) {
127 // Make a copy.
128 hostList = hostList.slice(0, hostList.length);
129 DataUtils.shuffle(hostList);
130
131 return function() {
132 if (hostList.length == 0)
133 return null;
134
135 return { host: hostList.splice(0, 1)[0], port: port };
136 };
137};
138
Jeff Thompson34419762012-10-15 22:24:12 -0700139/** Encode name as an Interest. If template is not null, use its attributes.
140 * Send the interest to host:port, read the entire response and call
141 * closure.upcall(Closure.UPCALL_CONTENT (or Closure.UPCALL_CONTENT_UNVERIFIED),
Jeff Thompson97f27432012-10-16 00:28:03 -0700142 * new UpcallInfo(this, interest, 0, contentObject)).
Jeff Thompson34419762012-10-15 22:24:12 -0700143 */
144NDN.prototype.expressInterest = function(
145 // Name
146 name,
147 // Closure
148 closure,
149 // Interest
150 template) {
Jeff Thompson5b265a72012-11-12 01:13:08 -0800151 var interest = new Interest(name);
Jeff Thompson34419762012-10-15 22:24:12 -0700152 if (template != null) {
Jeff Thompson4404ab52012-10-21 10:29:48 -0700153 interest.minSuffixComponents = template.minSuffixComponents;
154 interest.maxSuffixComponents = template.maxSuffixComponents;
155 interest.publisherPublicKeyDigest = template.publisherPublicKeyDigest;
156 interest.exclude = template.exclude;
157 interest.childSelector = template.childSelector;
158 interest.answerOriginKind = template.answerOriginKind;
159 interest.scope = template.scope;
160 interest.interestLifetime = template.interestLifetime;
Jeff Thompson34419762012-10-15 22:24:12 -0700161 }
162 else
Jeff Thompson42806a12012-12-29 18:19:39 -0800163 interest.interestLifetime = 4000; // default interest timeout value in milliseconds.
Jeff Thompson34419762012-10-15 22:24:12 -0700164
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800165 if (this.host == null || this.port == null) {
166 if (this.getHostAndPort == null)
167 console.log('ERROR: host OR port NOT SET');
Jeff Thompsona5668d52013-01-26 16:23:27 -0800168 else {
169 var thisNDN = this;
170 this.connectAndExecute
Jeff Thompsonf668acb2013-01-26 20:29:46 -0800171 (function() { thisNDN.reconnectAndExpressInterest(interest, closure); });
Jeff Thompsona5668d52013-01-26 16:23:27 -0800172 }
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800173 }
174 else
Jeff Thompsonf668acb2013-01-26 20:29:46 -0800175 this.reconnectAndExpressInterest(interest, closure);
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800176};
Jeff Thompson5b265a72012-11-12 01:13:08 -0800177
Jeff Thompson537ce142013-01-26 20:02:48 -0800178/*
Jeff Thompsonf668acb2013-01-26 20:29:46 -0800179 * If the host and port are different than the ones in this.transport, then call
180 * this.transport.connect to change the connection (or connect for the first time).
181 * Then call expressInterestHelper.
182 */
183NDN.prototype.reconnectAndExpressInterest = function(interest, closure) {
184 if (this.transport.connectedHost != this.host || this.transport.connectedPort != this.port) {
185 var thisNDN = this;
186 this.transport.connect(thisNDN, function() { thisNDN.expressInterestHelper(interest, closure); });
187 }
188 else
189 this.expressInterestHelper(interest, closure);
190};
191
192/*
193 * Do the work of reconnectAndExpressInterest once we know we are connected. Set the PITTable and call
Jeff Thompson537ce142013-01-26 20:02:48 -0800194 * this.transport.send to send the interest.
195 */
196NDN.prototype.expressInterestHelper = function(interest, closure) {
197 //TODO: check local content store first
198 if (closure != null) {
199 var pitEntry = new PITEntry(interest, closure);
200 // TODO: This needs to be a single thread-safe transaction on a global object.
201 NDN.PITTable.push(pitEntry);
202 closure.pitEntry = pitEntry;
203 }
204
205 // Set interest timer
206 var thisNDN = this;
207 if (closure != null) {
208 pitEntry.timerID = setTimeout(function() {
209 if (LOG > 3) console.log("Interest time out.");
210
211 // Remove PIT entry from NDN.PITTable.
212 // TODO: Make this a thread-safe operation on the global PITTable.
213 var index = NDN.PITTable.indexOf(pitEntry);
214 //console.log(NDN.PITTable);
215 if (index >= 0)
216 NDN.PITTable.splice(index, 1);
217 //console.log(NDN.PITTable);
218 //console.log(pitEntry.interest.name.getName());
219
220 // Raise closure callback
221 closure.upcall(Closure.UPCALL_INTEREST_TIMED_OUT, new UpcallInfo(thisNDN, interest, 0, null));
222 }, interest.interestLifetime); // interestLifetime is in milliseconds.
223 //console.log(closure.timerID);
224 }
225
226 this.transport.send(encodeToBinaryInterest(interest));
227};
228
Jeff Thompson5b265a72012-11-12 01:13:08 -0800229NDN.prototype.registerPrefix = function(name, closure, flag) {
Jeff Thompsond771b122013-01-26 19:04:41 -0800230 var thisNDN = this;
231 var onConnected = function() {
232 if (thisNDN.ccndid == null) {
233 // Fetch ccndid first, then register.
234 var interest = new Interest(NDN.ccndIdFetcher);
235 interest.interestLifetime = 4000; // milliseconds
236 if (LOG>3) console.log('Expressing interest for ccndid from ccnd.');
Jeff Thompsonf668acb2013-01-26 20:29:46 -0800237 thisNDN.reconnectAndExpressInterest
238 (interest, new NDN.FetchCcndidClosure(thisNDN, name, closure, flag));
Jeff Thompsond771b122013-01-26 19:04:41 -0800239 }
240 else
241 thisNDN.registerPrefixHelper(name, closure, flag);
242 };
Jeff Thompson75771cb2013-01-20 23:27:38 -0800243
Jeff Thompsond771b122013-01-26 19:04:41 -0800244 if (this.host == null || this.port == null) {
245 if (this.getHostAndPort == null)
246 console.log('ERROR: host OR port NOT SET');
247 else
248 this.connectAndExecute(onConnected);
249 }
250 else
251 onConnected();
252};
253
254/*
255 * This is a closure to receive the ContentObject for NDN.ccndIdFetcher and call
256 * registerPrefixHelper(name, callerClosure, flag).
257 */
258NDN.FetchCcndidClosure = function FetchCcndidClosure(ndn, name, callerClosure, flag) {
259 // Inherit from Closure.
260 Closure.call(this);
261
262 this.ndn = ndn;
263 this.name = name;
264 this.callerClosure = callerClosure;
265 this.flag = flag;
266};
267
268NDN.FetchCcndidClosure.prototype.upcall = function(kind, upcallInfo) {
269 if (kind == Closure.UPCALL_INTEREST_TIMED_OUT) {
270 console.log("Timeout while requesting the ccndid. Cannot registerPrefix for " +
271 this.name.to_uri() + " .");
272 return Closure.RESULT_OK;
273 }
274 if (!(kind == Closure.UPCALL_CONTENT ||
275 kind == Closure.UPCALL_CONTENT_UNVERIFIED))
276 // The upcall is not for us.
277 return Closure.RESULT_ERR;
278
279 var co = upcallInfo.contentObject;
280 if (!co.signedInfo || !co.signedInfo.publisher
281 || !co.signedInfo.publisher.publisherPublicKeyDigest)
282 console.log
283 ("ContentObject doesn't have a publisherPublicKeyDigest. Cannot set ccndid and registerPrefix for "
284 + this.name.to_uri() + " .");
285 else {
286 if (LOG>3) console.log('Got ccndid from ccnd.');
287 this.ndn.ccndid = co.signedInfo.publisher.publisherPublicKeyDigest;
288 if (LOG>3) console.log(this.ndn.ccndid);
289
290 this.ndn.registerPrefixHelper(this.name, this.callerClosure, this.flag);
Jeff Thompson75771cb2013-01-20 23:27:38 -0800291 }
Jeff Thompsond771b122013-01-26 19:04:41 -0800292
293 return Closure.RESULT_OK;
294};
295
Jeff Thompson537ce142013-01-26 20:02:48 -0800296/*
297 * Do the work of registerPrefix once we know we are connected with a ccndid.
298 */
Jeff Thompsond771b122013-01-26 19:04:41 -0800299NDN.prototype.registerPrefixHelper = function(name, closure, flag) {
Jeff Thompson75771cb2013-01-20 23:27:38 -0800300 var fe = new ForwardingEntry('selfreg', name, null, null, 3, 2147483647);
301 var bytes = encodeForwardingEntry(fe);
302
303 var si = new SignedInfo();
304 si.setFields();
305
306 var co = new ContentObject(new Name(), si, bytes, new Signature());
307 co.sign();
308 var coBinary = encodeToBinaryContentObject(co);
309
310 //var nodename = unescape('%00%88%E2%F4%9C%91%16%16%D6%21%8E%A0c%95%A5%A6r%11%E0%A0%82%89%A6%A9%85%AB%D6%E2%065%DB%AF');
311 var nodename = this.ccndid;
312 var interestName = new Name(['ccnx', nodename, 'selfreg', coBinary]);
313
314 var interest = new Interest(interestName);
315 interest.scope = 1;
316 if (LOG > 3) console.log('Send Interest registration packet.');
317
318 var csEntry = new CSEntry(name.getName(), closure);
319 NDN.CSTable.push(csEntry);
320
321 this.transport.send(encodeToBinaryInterest(interest));
Jeff Thompson75771cb2013-01-20 23:27:38 -0800322};
323
324/*
325 * This is called when an entire binary XML element is received, such as a ContentObject or Interest.
326 * Look up in the PITTable and call the closure callback.
327 */
328NDN.prototype.onReceivedElement = function(element) {
Jeff Thompsona46083c2013-01-20 23:55:21 -0800329 if (LOG>3) console.log('Complete element received. Length ' + element.length + '. Start decoding.');
Jeff Thompson75771cb2013-01-20 23:27:38 -0800330 var decoder = new BinaryXMLDecoder(element);
331 // Dispatch according to packet type
332 if (decoder.peekStartElement(CCNProtocolDTags.Interest)) { // Interest packet
333 if (LOG > 3) console.log('Interest packet received.');
334
335 var interest = new Interest();
336 interest.from_ccnb(decoder);
337 if (LOG > 3) console.log(interest);
338 var nameStr = escape(interest.name.getName());
339 if (LOG > 3) console.log(nameStr);
340
341 var entry = getEntryForRegisteredPrefix(nameStr);
342 if (entry != null) {
343 //console.log(entry);
344 var info = new UpcallInfo(this, interest, 0, null);
345 var ret = entry.closure.upcall(Closure.UPCALL_INTEREST, info);
346 if (ret == Closure.RESULT_INTEREST_CONSUMED && info.contentObject != null)
347 this.transport.send(encodeToBinaryContentObject(info.contentObject));
348 }
349 } else if (decoder.peekStartElement(CCNProtocolDTags.ContentObject)) { // Content packet
350 if (LOG > 3) console.log('ContentObject packet received.');
351
352 var co = new ContentObject();
353 co.from_ccnb(decoder);
354
Jeff Thompsond771b122013-01-26 19:04:41 -0800355 var pitEntry = NDN.getEntryForExpressedInterest(co.name);
356 if (pitEntry != null) {
357 //console.log(pitEntry);
358 // Remove PIT entry from NDN.PITTable
359 var index = NDN.PITTable.indexOf(pitEntry);
360 if (index >= 0)
361 NDN.PITTable.splice(index, 1);
Jeff Thompson75771cb2013-01-20 23:27:38 -0800362
Jeff Thompsond771b122013-01-26 19:04:41 -0800363 var currentClosure = pitEntry.closure;
Jeff Thompson75771cb2013-01-20 23:27:38 -0800364
Jeff Thompsond771b122013-01-26 19:04:41 -0800365 // Cancel interest timer
366 clearTimeout(pitEntry.timerID);
367 //console.log("Clear interest timer");
368 //console.log(currentClosure.timerID);
369
370 if (this.verify == false) {
371 // Pass content up without verifying the signature
372 currentClosure.upcall(Closure.UPCALL_CONTENT_UNVERIFIED, new UpcallInfo(this, null, 0, co));
373 return;
Jeff Thompson75771cb2013-01-20 23:27:38 -0800374 }
Wentao Shangd4607392013-01-24 23:08:49 -0800375
Jeff Thompsond771b122013-01-26 19:04:41 -0800376 // Key verification
377
378 // Recursive key fetching & verification closure
379 var KeyFetchClosure = function KeyFetchClosure(content, closure, key, sig, wit) {
380 this.contentObject = content; // unverified content object
381 this.closure = closure; // closure corresponding to the contentObject
382 this.keyName = key; // name of current key to be fetched
383 this.sigHex = sig; // hex signature string to be verified
384 this.witness = wit;
385
386 Closure.call(this);
387 };
388
389 var thisNDN = this;
390 KeyFetchClosure.prototype.upcall = function(kind, upcallInfo) {
391 if (kind == Closure.UPCALL_INTEREST_TIMED_OUT) {
392 console.log("In KeyFetchClosure.upcall: interest time out.");
393 console.log(this.keyName.contentName.getName());
394 } else if (kind == Closure.UPCALL_CONTENT) {
395 //console.log("In KeyFetchClosure.upcall: signature verification passed");
396
397 var rsakey = decodeSubjectPublicKeyInfo(upcallInfo.contentObject.content);
398 var verified = rsakey.verifyByteArray(this.contentObject.rawSignatureData, this.witness, this.sigHex);
399
400 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
401 //console.log("raise encapsulated closure");
402 this.closure.upcall(flag, new UpcallInfo(thisNDN, null, 0, this.contentObject));
403
404 // Store key in cache
405 var keyEntry = new KeyStoreEntry(keylocator.keyName, rsakey, new Date().getTime());
406 NDN.addKeyEntry(keyEntry);
407 //console.log(NDN.KeyStore);
408 } else if (kind == Closure.UPCALL_CONTENT_BAD) {
409 console.log("In KeyFetchClosure.upcall: signature verification failed");
Wentao Shangd4607392013-01-24 23:08:49 -0800410 }
Jeff Thompsond771b122013-01-26 19:04:41 -0800411 };
Jeff Thompson75771cb2013-01-20 23:27:38 -0800412
Jeff Thompsond771b122013-01-26 19:04:41 -0800413 if (co.signedInfo && co.signedInfo.locator && co.signature) {
414 if (LOG > 3) console.log("Key verification...");
415 var sigHex = DataUtils.toHex(co.signature.signature).toLowerCase();
Jeff Thompson75771cb2013-01-20 23:27:38 -0800416
Jeff Thompsond771b122013-01-26 19:04:41 -0800417 var wit = null;
418 if (co.signature.Witness != null) {
419 wit = new Witness();
420 wit.decode(co.signature.Witness);
421 }
Jeff Thompson75771cb2013-01-20 23:27:38 -0800422
Jeff Thompsond771b122013-01-26 19:04:41 -0800423 var keylocator = co.signedInfo.locator;
424 if (keylocator.type == KeyLocatorType.KEYNAME) {
425 if (LOG > 3) console.log("KeyLocator contains KEYNAME");
426 //var keyname = keylocator.keyName.contentName.getName();
427 //console.log(nameStr);
428 //console.log(keyname);
Jeff Thompson75771cb2013-01-20 23:27:38 -0800429
Jeff Thompsond771b122013-01-26 19:04:41 -0800430 if (keylocator.keyName.contentName.match(co.name)) {
431 if (LOG > 3) console.log("Content is key itself");
Jeff Thompson75771cb2013-01-20 23:27:38 -0800432
Jeff Thompsond771b122013-01-26 19:04:41 -0800433 var rsakey = decodeSubjectPublicKeyInfo(co.content);
434 var verified = rsakey.verifyByteArray(co.rawSignatureData, wit, sigHex);
435 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
436
437 currentClosure.upcall(flag, new UpcallInfo(this, null, 0, co));
438
439 // SWT: We don't need to store key here since the same key will be
440 // stored again in the closure.
441 //var keyEntry = new KeyStoreEntry(keylocator.keyName, rsakey, new Date().getTime());
442 //NDN.addKeyEntry(keyEntry);
443 //console.log(NDN.KeyStore);
444 } else {
445 // Check local key store
446 var keyEntry = NDN.getKeyByName(keylocator.keyName);
447 if (keyEntry) {
448 // Key found, verify now
449 if (LOG > 3) console.log("Local key cache hit");
450 var rsakey = keyEntry.rsaKey;
Jeff Thompson75771cb2013-01-20 23:27:38 -0800451 var verified = rsakey.verifyByteArray(co.rawSignatureData, wit, sigHex);
452 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
Jeff Thompson75771cb2013-01-20 23:27:38 -0800453
Jeff Thompsond771b122013-01-26 19:04:41 -0800454 // Raise callback
455 currentClosure.upcall(flag, new UpcallInfo(this, null, 0, co));
456 } else {
457 // Not found, fetch now
458 if (LOG > 3) console.log("Fetch key according to keylocator");
459 var nextClosure = new KeyFetchClosure(co, currentClosure, keylocator.keyName, sigHex, wit);
460 this.expressInterest(keylocator.keyName.contentName.getPrefix(4), nextClosure);
Jeff Thompson75771cb2013-01-20 23:27:38 -0800461 }
Jeff Thompson75771cb2013-01-20 23:27:38 -0800462 }
Jeff Thompsond771b122013-01-26 19:04:41 -0800463 } else if (keylocator.type == KeyLocatorType.KEY) {
464 if (LOG > 3) console.log("Keylocator contains KEY");
465
466 var rsakey = decodeSubjectPublicKeyInfo(co.signedInfo.locator.publicKey);
467 var verified = rsakey.verifyByteArray(co.rawSignatureData, wit, sigHex);
468
469 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
470 // Raise callback
471 currentClosure.upcall(Closure.UPCALL_CONTENT, new UpcallInfo(this, null, 0, co));
472
473 // Since KeyLocator does not contain key name for this key,
474 // we have no way to store it as a key entry in KeyStore.
475 } else {
476 var cert = keylocator.certificate;
477 console.log("KeyLocator contains CERT");
478 console.log(cert);
479
480 // TODO: verify certificate
Jeff Thompson75771cb2013-01-20 23:27:38 -0800481 }
482 }
483 }
484 } else
485 console.log('Incoming packet is not Interest or ContentObject. Discard now.');
Wentao Shangb42483a2013-01-03 15:32:32 -0800486};
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800487
488/*
489 * Assume this.getHostAndPort is not null. This is called when this.host is null or its host
Jeff Thompsona5668d52013-01-26 16:23:27 -0800490 * is not alive. Get a host and port, connect, then execute onConnected().
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800491 */
Jeff Thompsona5668d52013-01-26 16:23:27 -0800492NDN.prototype.connectAndExecute = function(onConnected) {
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800493 var hostAndPort = this.getHostAndPort();
494 if (hostAndPort == null) {
495 console.log('ERROR: No more hosts from getHostAndPort');
496 this.host = null;
497 return;
498 }
499
500 if (hostAndPort.host == this.host && hostAndPort.port == this.port) {
501 console.log('ERROR: The host returned by getHostAndPort is not alive: ' +
502 this.host + ":" + this.port);
503 return;
504 }
505
506 this.host = hostAndPort.host;
507 this.port = hostAndPort.port;
Jeff Thompsona5668d52013-01-26 16:23:27 -0800508 if (LOG>3) console.log("Connect: trying host from getHostAndPort: " + this.host);
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800509
Jeff Thompson75771cb2013-01-20 23:27:38 -0800510 // Fetch any content.
511 var interest = new Interest(new Name("/"));
Jeff Thompson42806a12012-12-29 18:19:39 -0800512 interest.interestLifetime = 4000; // milliseconds
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800513
514 var thisNDN = this;
515 var timerID = setTimeout(function() {
Jeff Thompsona5668d52013-01-26 16:23:27 -0800516 if (LOG>3) console.log("Connect: timeout waiting for host " + thisNDN.host);
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800517 // Try again.
Jeff Thompsona5668d52013-01-26 16:23:27 -0800518 thisNDN.connectAndExecute(onConnected);
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800519 }, 3000);
520
Jeff Thompsonf668acb2013-01-26 20:29:46 -0800521 this.reconnectAndExpressInterest
522 (interest, new NDN.ConnectClosure(this, onConnected, timerID));
Wentao Shangb42483a2013-01-03 15:32:32 -0800523};
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800524
Jeff Thompsona5668d52013-01-26 16:23:27 -0800525NDN.ConnectClosure = function ConnectClosure(ndn, onConnected, timerID) {
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800526 // Inherit from Closure.
527 Closure.call(this);
528
529 this.ndn = ndn;
Jeff Thompsona5668d52013-01-26 16:23:27 -0800530 this.onConnected = onConnected;
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800531 this.timerID = timerID;
532};
533
534NDN.ConnectClosure.prototype.upcall = function(kind, upcallInfo) {
535 if (!(kind == Closure.UPCALL_CONTENT ||
Jeff Thompson75771cb2013-01-20 23:27:38 -0800536 kind == Closure.UPCALL_CONTENT_UNVERIFIED))
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800537 // The upcall is not for us.
538 return Closure.RESULT_ERR;
539
Jeff Thompsona5668d52013-01-26 16:23:27 -0800540 // The host is alive, so cancel the timeout and continue with onConnected().
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800541 clearTimeout(this.timerID);
Jeff Thompsond771b122013-01-26 19:04:41 -0800542
543 // Call NDN.onopen after success
544 this.ndn.readyStatus = NDN.OPENED;
545 this.ndn.onopen();
546
Jeff Thompsona5668d52013-01-26 16:23:27 -0800547 this.onConnected();
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800548
549 return Closure.RESULT_OK;
550};
551
Jeff Thompson75771cb2013-01-20 23:27:38 -0800552/*
553 * A BinaryXmlElementReader lets you call onReceivedData multiple times which uses a
554 * BinaryXMLStructureDecoder to detect the end of a binary XML element and calls
555 * elementListener.onReceivedElement(element) with the element.
556 * This handles the case where a single call to onReceivedData may contain multiple elements.
557 */
558var BinaryXmlElementReader = function BinaryXmlElementReader(elementListener) {
559 this.elementListener = elementListener;
560 this.dataParts = [];
561 this.structureDecoder = new BinaryXMLStructureDecoder();
562};
563
564BinaryXmlElementReader.prototype.onReceivedData = function(/* Uint8Array */ rawData) {
Jeff Thompson75771cb2013-01-20 23:27:38 -0800565 // Process multiple objects in the data.
566 while(true) {
567 // Scan the input to check if a whole ccnb object has been read.
568 this.structureDecoder.seek(0);
569 if (this.structureDecoder.findElementEnd(rawData)) {
570 // Got the remainder of an object. Report to the caller.
571 this.dataParts.push(rawData.subarray(0, this.structureDecoder.offset));
Jeff Thompson0790af82013-01-26 19:54:27 -0800572 var element = DataUtils.concatArrays(this.dataParts);
573 this.dataParts = [];
574 try {
575 this.elementListener.onReceivedElement(element);
576 } catch (ex) {
577 console.log("BinaryXmlElementReader: ignoring exception from onReceivedElement: " + ex);
578 }
Jeff Thompson75771cb2013-01-20 23:27:38 -0800579
580 // Need to read a new object.
581 rawData = rawData.subarray(this.structureDecoder.offset, rawData.length);
Jeff Thompson75771cb2013-01-20 23:27:38 -0800582 this.structureDecoder = new BinaryXMLStructureDecoder();
583 if (rawData.length == 0)
584 // No more data in the packet.
585 return;
586
587 // else loop back to decode.
588 }
589 else {
590 // Save for a later call to concatArrays so that we only copy data once.
591 this.dataParts.push(rawData);
Jeff Thompsona46083c2013-01-20 23:55:21 -0800592 if (LOG>3) console.log('Incomplete packet received. Length ' + rawData.length + '. Wait for more input.');
Jeff Thompson75771cb2013-01-20 23:27:38 -0800593 return;
594 }
595 }
596}