blob: 30d5d3fa31789875b8d2a197e6594e025d50b7ff [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,
14 * host: 'localhost', // If null, use getHostAndPort when connecting.
15 * 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);
28 this.host = (settings.host !== undefined ? settings.host : 'localhost');
29 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
171 (function() { thisNDN.transport.expressInterest(thisNDN, interest, closure); });
172 }
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800173 }
174 else
175 this.transport.expressInterest(this, interest, closure);
176};
Jeff Thompson5b265a72012-11-12 01:13:08 -0800177
178NDN.prototype.registerPrefix = function(name, closure, flag) {
Jeff Thompson75771cb2013-01-20 23:27:38 -0800179 if (this.readyStatus != NDN.OPENED) {
180 console.log('Connection is not established.');
181 return -1;
182 }
183
184 if (this.ccndid == null) {
185 console.log('ccnd node ID unkonwn. Cannot register prefix.');
186 return -1;
187 }
188
189 var fe = new ForwardingEntry('selfreg', name, null, null, 3, 2147483647);
190 var bytes = encodeForwardingEntry(fe);
191
192 var si = new SignedInfo();
193 si.setFields();
194
195 var co = new ContentObject(new Name(), si, bytes, new Signature());
196 co.sign();
197 var coBinary = encodeToBinaryContentObject(co);
198
199 //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');
200 var nodename = this.ccndid;
201 var interestName = new Name(['ccnx', nodename, 'selfreg', coBinary]);
202
203 var interest = new Interest(interestName);
204 interest.scope = 1;
205 if (LOG > 3) console.log('Send Interest registration packet.');
206
207 var csEntry = new CSEntry(name.getName(), closure);
208 NDN.CSTable.push(csEntry);
209
210 this.transport.send(encodeToBinaryInterest(interest));
211
212 return 0;
213};
214
215/*
216 * This is called when an entire binary XML element is received, such as a ContentObject or Interest.
217 * Look up in the PITTable and call the closure callback.
218 */
219NDN.prototype.onReceivedElement = function(element) {
Jeff Thompsona46083c2013-01-20 23:55:21 -0800220 if (LOG>3) console.log('Complete element received. Length ' + element.length + '. Start decoding.');
Jeff Thompson75771cb2013-01-20 23:27:38 -0800221 var decoder = new BinaryXMLDecoder(element);
222 // Dispatch according to packet type
223 if (decoder.peekStartElement(CCNProtocolDTags.Interest)) { // Interest packet
224 if (LOG > 3) console.log('Interest packet received.');
225
226 var interest = new Interest();
227 interest.from_ccnb(decoder);
228 if (LOG > 3) console.log(interest);
229 var nameStr = escape(interest.name.getName());
230 if (LOG > 3) console.log(nameStr);
231
232 var entry = getEntryForRegisteredPrefix(nameStr);
233 if (entry != null) {
234 //console.log(entry);
235 var info = new UpcallInfo(this, interest, 0, null);
236 var ret = entry.closure.upcall(Closure.UPCALL_INTEREST, info);
237 if (ret == Closure.RESULT_INTEREST_CONSUMED && info.contentObject != null)
238 this.transport.send(encodeToBinaryContentObject(info.contentObject));
239 }
240 } else if (decoder.peekStartElement(CCNProtocolDTags.ContentObject)) { // Content packet
241 if (LOG > 3) console.log('ContentObject packet received.');
242
243 var co = new ContentObject();
244 co.from_ccnb(decoder);
245
246 if (this.ccndid == null && NDN.ccndIdFetcher.match(co.name)) {
247 // We are in starting phase, record publisherPublicKeyDigest in ccndid
248 if(!co.signedInfo || !co.signedInfo.publisher
249 || !co.signedInfo.publisher.publisherPublicKeyDigest) {
250 console.log("Cannot contact router, close NDN now.");
251
252 // Close NDN if we fail to connect to a ccn router
253 this.readyStatus = NDN.CLOSED;
254 this.onclose();
255 //console.log("NDN.onclose event fired.");
256 } else {
Wentao Shang261b4be2013-01-26 09:22:37 -0800257 if (LOG>3) console.log('Connected to ccnd.');
Jeff Thompson75771cb2013-01-20 23:27:38 -0800258 this.ccndid = co.signedInfo.publisher.publisherPublicKeyDigest;
259 if (LOG>3) console.log(ndn.ccndid);
260
261 // Call NDN.onopen after success
262 this.readyStatus = NDN.OPENED;
263 this.onopen();
264 //console.log("NDN.onopen event fired.");
265 }
266 } else {
267 var pitEntry = NDN.getEntryForExpressedInterest(co.name);
268 if (pitEntry != null) {
269 //console.log(pitEntry);
270 // Remove PIT entry from NDN.PITTable
271 var index = NDN.PITTable.indexOf(pitEntry);
272 if (index >= 0)
273 NDN.PITTable.splice(index, 1);
274
275 var currentClosure = pitEntry.closure;
276
277 // Cancel interest timer
278 clearTimeout(pitEntry.timerID);
279 //console.log("Clear interest timer");
280 //console.log(currentClosure.timerID);
Wentao Shangd4607392013-01-24 23:08:49 -0800281
282 if (this.verify == false) {
283 // Pass content up without verifying the signature
284 currentClosure.upcall(Closure.UPCALL_CONTENT_UNVERIFIED, new UpcallInfo(this, null, 0, co));
285 return;
286 }
287
Jeff Thompson75771cb2013-01-20 23:27:38 -0800288 // Key verification
289
290 // Recursive key fetching & verification closure
291 var KeyFetchClosure = function KeyFetchClosure(content, closure, key, sig, wit) {
292 this.contentObject = content; // unverified content object
293 this.closure = closure; // closure corresponding to the contentObject
294 this.keyName = key; // name of current key to be fetched
295 this.sigHex = sig; // hex signature string to be verified
296 this.witness = wit;
297
298 Closure.call(this);
299 };
300
301 var thisNdn = this;
302 KeyFetchClosure.prototype.upcall = function(kind, upcallInfo) {
303 if (kind == Closure.UPCALL_INTEREST_TIMED_OUT) {
304 console.log("In KeyFetchClosure.upcall: interest time out.");
305 console.log(this.keyName.contentName.getName());
306 } else if (kind == Closure.UPCALL_CONTENT) {
307 //console.log("In KeyFetchClosure.upcall: signature verification passed");
308
309 var rsakey = decodeSubjectPublicKeyInfo(upcallInfo.contentObject.content);
310 var verified = rsakey.verifyByteArray(this.contentObject.rawSignatureData, this.witness, this.sigHex);
311
312 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
313 //console.log("raise encapsulated closure");
314 this.closure.upcall(flag, new UpcallInfo(thisNdn, null, 0, this.contentObject));
315
316 // Store key in cache
317 var keyEntry = new KeyStoreEntry(keylocator.keyName, rsakey, new Date().getTime());
318 NDN.addKeyEntry(keyEntry);
319 //console.log(NDN.KeyStore);
320 } else if (kind == Closure.UPCALL_CONTENT_BAD) {
321 console.log("In KeyFetchClosure.upcall: signature verification failed");
322 }
323 };
324
325 if (co.signedInfo && co.signedInfo.locator && co.signature) {
326 if (LOG > 3) console.log("Key verification...");
327 var sigHex = DataUtils.toHex(co.signature.signature).toLowerCase();
328
329 var wit = null;
330 if (co.signature.Witness != null) {
331 wit = new Witness();
332 wit.decode(co.signature.Witness);
333 }
334
335 var keylocator = co.signedInfo.locator;
336 if (keylocator.type == KeyLocatorType.KEYNAME) {
337 if (LOG > 3) console.log("KeyLocator contains KEYNAME");
338 //var keyname = keylocator.keyName.contentName.getName();
339 //console.log(nameStr);
340 //console.log(keyname);
341
342 if (keylocator.keyName.contentName.match(co.name)) {
343 if (LOG > 3) console.log("Content is key itself");
344
345 var rsakey = decodeSubjectPublicKeyInfo(co.content);
346 var verified = rsakey.verifyByteArray(co.rawSignatureData, wit, sigHex);
347 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
348
349 currentClosure.upcall(flag, new UpcallInfo(this, null, 0, co));
350
351 // SWT: We don't need to store key here since the same key will be
352 // stored again in the closure.
353 //var keyEntry = new KeyStoreEntry(keylocator.keyName, rsakey, new Date().getTime());
354 //NDN.addKeyEntry(keyEntry);
355 //console.log(NDN.KeyStore);
356 } else {
357 // Check local key store
358 var keyEntry = NDN.getKeyByName(keylocator.keyName);
359 if (keyEntry) {
360 // Key found, verify now
361 if (LOG > 3) console.log("Local key cache hit");
362 var rsakey = keyEntry.rsaKey;
363 var verified = rsakey.verifyByteArray(co.rawSignatureData, wit, sigHex);
364 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
365
366 // Raise callback
367 currentClosure.upcall(flag, new UpcallInfo(this, null, 0, co));
368 } else {
369 // Not found, fetch now
370 if (LOG > 3) console.log("Fetch key according to keylocator");
371 var nextClosure = new KeyFetchClosure(co, currentClosure, keylocator.keyName, sigHex, wit);
372 this.expressInterest(keylocator.keyName.contentName.getPrefix(4), nextClosure);
373 }
374 }
375 } else if (keylocator.type == KeyLocatorType.KEY) {
376 if (LOG > 3) console.log("Keylocator contains KEY");
377
378 var rsakey = decodeSubjectPublicKeyInfo(co.signedInfo.locator.publicKey);
379 var verified = rsakey.verifyByteArray(co.rawSignatureData, wit, sigHex);
380
381 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
382 // Raise callback
383 currentClosure.upcall(Closure.UPCALL_CONTENT, new UpcallInfo(this, null, 0, co));
384
385 // Since KeyLocator does not contain key name for this key,
386 // we have no way to store it as a key entry in KeyStore.
387 } else {
388 var cert = keylocator.certificate;
389 console.log("KeyLocator contains CERT");
390 console.log(cert);
391
392 // TODO: verify certificate
393 }
394 }
395 }
396 }
397 } else
398 console.log('Incoming packet is not Interest or ContentObject. Discard now.');
Wentao Shangb42483a2013-01-03 15:32:32 -0800399};
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800400
401/*
402 * Assume this.getHostAndPort is not null. This is called when this.host is null or its host
Jeff Thompsona5668d52013-01-26 16:23:27 -0800403 * is not alive. Get a host and port, connect, then execute onConnected().
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800404 */
Jeff Thompsona5668d52013-01-26 16:23:27 -0800405NDN.prototype.connectAndExecute = function(onConnected) {
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800406 var hostAndPort = this.getHostAndPort();
407 if (hostAndPort == null) {
408 console.log('ERROR: No more hosts from getHostAndPort');
409 this.host = null;
410 return;
411 }
412
413 if (hostAndPort.host == this.host && hostAndPort.port == this.port) {
414 console.log('ERROR: The host returned by getHostAndPort is not alive: ' +
415 this.host + ":" + this.port);
416 return;
417 }
418
419 this.host = hostAndPort.host;
420 this.port = hostAndPort.port;
Jeff Thompsona5668d52013-01-26 16:23:27 -0800421 if (LOG>3) console.log("Connect: trying host from getHostAndPort: " + this.host);
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800422
Jeff Thompson75771cb2013-01-20 23:27:38 -0800423 // Fetch any content.
424 var interest = new Interest(new Name("/"));
Jeff Thompson42806a12012-12-29 18:19:39 -0800425 interest.interestLifetime = 4000; // milliseconds
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800426
427 var thisNDN = this;
428 var timerID = setTimeout(function() {
Jeff Thompsona5668d52013-01-26 16:23:27 -0800429 if (LOG>3) console.log("Connect: timeout waiting for host " + thisNDN.host);
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800430 // Try again.
Jeff Thompsona5668d52013-01-26 16:23:27 -0800431 thisNDN.connectAndExecute(onConnected);
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800432 }, 3000);
433
434 this.transport.expressInterest
Jeff Thompsona5668d52013-01-26 16:23:27 -0800435 (this, interest, new NDN.ConnectClosure(this, onConnected, timerID));
Wentao Shangb42483a2013-01-03 15:32:32 -0800436};
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800437
Jeff Thompsona5668d52013-01-26 16:23:27 -0800438NDN.ConnectClosure = function ConnectClosure(ndn, onConnected, timerID) {
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800439 // Inherit from Closure.
440 Closure.call(this);
441
442 this.ndn = ndn;
Jeff Thompsona5668d52013-01-26 16:23:27 -0800443 this.onConnected = onConnected;
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800444 this.timerID = timerID;
445};
446
447NDN.ConnectClosure.prototype.upcall = function(kind, upcallInfo) {
448 if (!(kind == Closure.UPCALL_CONTENT ||
Jeff Thompson75771cb2013-01-20 23:27:38 -0800449 kind == Closure.UPCALL_CONTENT_UNVERIFIED))
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800450 // The upcall is not for us.
451 return Closure.RESULT_ERR;
452
Jeff Thompsona5668d52013-01-26 16:23:27 -0800453 // The host is alive, so cancel the timeout and continue with onConnected().
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800454 clearTimeout(this.timerID);
Jeff Thompsona5668d52013-01-26 16:23:27 -0800455 this.onConnected();
Jeff Thompsond3a80dc2012-12-16 17:52:43 -0800456
457 return Closure.RESULT_OK;
458};
459
Jeff Thompson75771cb2013-01-20 23:27:38 -0800460/*
461 * A BinaryXmlElementReader lets you call onReceivedData multiple times which uses a
462 * BinaryXMLStructureDecoder to detect the end of a binary XML element and calls
463 * elementListener.onReceivedElement(element) with the element.
464 * This handles the case where a single call to onReceivedData may contain multiple elements.
465 */
466var BinaryXmlElementReader = function BinaryXmlElementReader(elementListener) {
467 this.elementListener = elementListener;
468 this.dataParts = [];
469 this.structureDecoder = new BinaryXMLStructureDecoder();
470};
471
472BinaryXmlElementReader.prototype.onReceivedData = function(/* Uint8Array */ rawData) {
Jeff Thompson75771cb2013-01-20 23:27:38 -0800473 // Process multiple objects in the data.
474 while(true) {
475 // Scan the input to check if a whole ccnb object has been read.
476 this.structureDecoder.seek(0);
477 if (this.structureDecoder.findElementEnd(rawData)) {
478 // Got the remainder of an object. Report to the caller.
479 this.dataParts.push(rawData.subarray(0, this.structureDecoder.offset));
Jeff Thompson75771cb2013-01-20 23:27:38 -0800480 this.elementListener.onReceivedElement(DataUtils.concatArrays(this.dataParts));
481
482 // Need to read a new object.
483 rawData = rawData.subarray(this.structureDecoder.offset, rawData.length);
484 this.dataParts = [];
485 this.structureDecoder = new BinaryXMLStructureDecoder();
486 if (rawData.length == 0)
487 // No more data in the packet.
488 return;
489
490 // else loop back to decode.
491 }
492 else {
493 // Save for a later call to concatArrays so that we only copy data once.
494 this.dataParts.push(rawData);
Jeff Thompsona46083c2013-01-20 23:55:21 -0800495 if (LOG>3) console.log('Incomplete packet received. Length ' + rawData.length + '. Wait for more input.');
Jeff Thompson75771cb2013-01-20 23:27:38 -0800496 return;
497 }
498 }
499}