blob: 6b65b37f188d618a24f60c4fba2aeb6bde734ce9 [file] [log] [blame]
Wentao Shangc0311e52012-12-03 10:38:23 -08001/**
Jeff Thompson5b265a72012-11-12 01:13:08 -08002 * @author: Wentao Shang
3 * See COPYING for copyright and distribution information.
Jeff Thompson5b265a72012-11-12 01:13:08 -08004 */
5
6var WebSocketTransport = function WebSocketTransport() {
7 this.ws = null;
8 this.ccndid = null;
9 this.maxBufferSize = 10000; // Currently support 10000 bytes data input, consistent with BinaryXMLEncoder
10 this.buffer = new Uint8Array(this.maxBufferSize);
Wentao Shang2b740e62012-12-07 00:02:53 -080011 this.bufferOffset = 0;
Jeff Thompson5b265a72012-11-12 01:13:08 -080012 this.structureDecoder = new BinaryXMLStructureDecoder();
Jeff Thompsonc881b552012-12-14 01:29:12 -080013 this.defaultGetHostAndPort = NDN.makeShuffledGetHostAndPort
14 (["A.ws.ndn.ucla.edu", "B.ws.ndn.ucla.edu", "C.ws.ndn.ucla.edu", "D.ws.ndn.ucla.edu",
15 "E.ws.ndn.ucla.edu"],
16 9696);
Jeff Thompson5b265a72012-11-12 01:13:08 -080017};
18
Jeff Thompson5b265a72012-11-12 01:13:08 -080019WebSocketTransport.prototype.connectWebSocket = function(ndn) {
20 if (this.ws != null)
21 delete this.ws;
22
23 this.ws = new WebSocket('ws://' + ndn.host + ':' + ndn.port);
Jeff Thompson3c263812012-12-01 17:20:28 -080024 if (LOG > 0) console.log('ws connection created.');
Jeff Thompson5b265a72012-11-12 01:13:08 -080025
26 this.ws.binaryType = "arraybuffer";
27
28 var self = this;
29 this.ws.onmessage = function(ev) {
30 var result = ev.data;
31 //console.log('RecvHandle called.');
32
33 if(result == null || result == undefined || result == "" ) {
34 console.log('INVALID ANSWER');
35 } else if (result instanceof ArrayBuffer) {
36 var bytearray = new Uint8Array(result);
37
Jeff Thompson13c2e7b2012-12-01 17:33:30 -080038 if (LOG>3) console.log('BINARY RESPONSE IS ' + DataUtils.toHex(bytearray));
Jeff Thompson5b265a72012-11-12 01:13:08 -080039
40 try {
Wentao Shang2b740e62012-12-07 00:02:53 -080041 if (bytearray.length + self.bufferOffset >= self.buffer.byteLength) {
42 if (LOG>3) {
43 console.log("NDN.ws.onmessage: buffer overflow. Accumulate received length: " + self.bufferOffset
44 + ". Current packet length: " + bytearray.length + ".");
45 }
46
Jeff Thompson5b265a72012-11-12 01:13:08 -080047 // Purge and quit.
48 delete self.structureDecoder;
49 delete self.buffer;
50 self.structureDecoder = new BinaryXMLStructureDecoder();
51 self.buffer = new Uint8Array(self.maxBufferSize);
Wentao Shang2b740e62012-12-07 00:02:53 -080052 self.bufferOffset = 0;
Jeff Thompson5b265a72012-11-12 01:13:08 -080053 return;
54 }
55
56 /*for (var i = 0; i < bytearray.length; i++) {
57 self.buffer.push(bytearray[i]);
58 }*/
Wentao Shang2b740e62012-12-07 00:02:53 -080059 self.buffer.set(bytearray, self.bufferOffset);
60 self.bufferOffset += bytearray.length;
Jeff Thompson5b265a72012-11-12 01:13:08 -080061
Wentao Shang2b740e62012-12-07 00:02:53 -080062 if (!self.structureDecoder.findElementEnd(self.buffer.subarray(0, self.bufferOffset))) {
Jeff Thompson5b265a72012-11-12 01:13:08 -080063 // Need more data to decode
Wentao Shang2b740e62012-12-07 00:02:53 -080064 if (LOG>3) console.log('Incomplete packet received. Length ' + bytearray.length + '. Wait for more input.');
Jeff Thompson5b265a72012-11-12 01:13:08 -080065 return;
66 }
Wentao Shang2b740e62012-12-07 00:02:53 -080067 if (LOG>3) console.log('Complete packet received. Length ' + bytearray.length + '. Start decoding.');
Jeff Thompson5b265a72012-11-12 01:13:08 -080068 } catch (ex) {
69 console.log("NDN.ws.onmessage exception: " + ex);
70 return;
71 }
72
73 var decoder = new BinaryXMLDecoder(self.buffer);
74 // Dispatch according to packet type
75 if (decoder.peekStartElement(CCNProtocolDTags.Interest)) { // Interest packet
Jeff Thompson3c263812012-12-01 17:20:28 -080076 if (LOG > 3) console.log('Interest packet received.');
Jeff Thompson5b265a72012-11-12 01:13:08 -080077
78 var interest = new Interest();
79 interest.from_ccnb(decoder);
80 if (LOG>3) console.log(interest);
81 var nameStr = escape(interest.name.getName());
Jeff Thompson3c263812012-12-01 17:20:28 -080082 if (LOG > 3) console.log(nameStr);
Jeff Thompson5b265a72012-11-12 01:13:08 -080083
84 var entry = getEntryForRegisteredPrefix(nameStr);
85 if (entry != null) {
86 //console.log(entry);
Wentao Shangab9018d2012-12-18 11:35:45 -080087 var info = new UpcallInfo(ndn, interest, 0, null);
88 var ret = entry.closure.upcall(Closure.UPCALL_INTEREST, info);
89 if (ret == Closure.RESULT_INTEREST_CONSUMED && info.contentObject != null) {
90 var coBinary = encodeToBinaryContentObject(info.contentObject);
91 // If we directly use coBinary.buffer to feed ws.send(), WebSocket
92 // will end up sending a packet with 10000 bytes of data. That
93 // is, WebSocket will flush the entire buffer in BinaryXMLEncoder
94 // regardless of the offset of the Uint8Array. So we have to
95 // create a new Uint8Array buffer with just the right size and
96 // copy the content from coBinary to the new buffer.
97 // ---Wentao
98 var bytearray = new Uint8Array(coBinary.length);
99 bytearray.set(coBinary);
100
101 self.ws.send(bytearray.buffer);
102 }
Jeff Thompson5b265a72012-11-12 01:13:08 -0800103 }
104
105 } else if (decoder.peekStartElement(CCNProtocolDTags.ContentObject)) { // Content packet
Wentao Shangfa245962012-12-25 20:26:26 -0800106 //if (LOG > 3)
107 console.log('ContentObject packet received.');
Jeff Thompson5b265a72012-11-12 01:13:08 -0800108
109 var co = new ContentObject();
110 co.from_ccnb(decoder);
Jeff Thompson3c263812012-12-01 17:20:28 -0800111 if (LOG > 3) console.log(co);
Wentao Shangf8b4a7d2012-12-25 12:52:07 -0800112 var nameStr = co.name.getName();
113 console.log(nameStr);
114
Jeff Thompsonbd25df22012-12-13 21:50:13 -0800115 if (self.ccndid == null && nameStr.match(NDN.ccndIdFetcher) != null) {
Jeff Thompson5b265a72012-11-12 01:13:08 -0800116 // We are in starting phase, record publisherPublicKeyDigest in self.ccndid
117 if(!co.signedInfo || !co.signedInfo.publisher
118 || !co.signedInfo.publisher.publisherPublicKeyDigest) {
Wentao Shangaf25c6b2012-12-03 00:09:30 -0800119 console.log("Cannot contact router, close NDN now.");
Wentao Shang0e291c82012-12-02 23:36:29 -0800120
121 // Close NDN if we fail to connect to a ccn router
122 ndn.readyStatus = NDN.CLOSED;
123 ndn.onclose();
Wentao Shangaf25c6b2012-12-03 00:09:30 -0800124 //console.log("NDN.onclose event fired.");
Jeff Thompson5b265a72012-11-12 01:13:08 -0800125 } else {
Wentao Shangaf25c6b2012-12-03 00:09:30 -0800126 //console.log('Connected to ccnd.');
Jeff Thompson5b265a72012-11-12 01:13:08 -0800127 self.ccndid = co.signedInfo.publisher.publisherPublicKeyDigest;
128 if (LOG>3) console.log(self.ccndid);
Wentao Shang0e291c82012-12-02 23:36:29 -0800129
130 // Call NDN.onopen after success
131 ndn.readyStatus = NDN.OPENED;
132 ndn.onopen();
Wentao Shangaf25c6b2012-12-03 00:09:30 -0800133 //console.log("NDN.onopen event fired.");
Jeff Thompson5b265a72012-11-12 01:13:08 -0800134 }
135 } else {
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800136 var pitEntry = NDN.getEntryForExpressedInterest(co.name);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800137 if (pitEntry != null) {
138 //console.log(pitEntry);
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800139 // Remove PIT entry from NDN.PITTable
140 var index = NDN.PITTable.indexOf(pitEntry);
Jeff Thompsonc881b552012-12-14 01:29:12 -0800141 if (index >= 0)
Wentao Shangfa245962012-12-25 20:26:26 -0800142 NDN.PITTable.splice(index, 1);
Wentao Shangbd63e462012-12-03 16:19:33 -0800143
Wentao Shangfa245962012-12-25 20:26:26 -0800144 var currentClosure = pitEntry.closure;
145
146 // Cancel interest timer
147 clearTimeout(currentClosure.timerID);
148 //console.log("Clear interest timer");
149 //console.log(currentClosure.timerID);
150
151 // Key verification
152 var verified = false;
153
Wentao Shang82854bd2012-12-27 14:14:41 -0800154 // Recursive key fetching & verification closure
Wentao Shangfa245962012-12-25 20:26:26 -0800155 var KeyFetchClosure = function KeyFetchClosure(content, closure, key, signature) {
156 this.contentObject = content; // unverified content object
157 this.closure = closure; // closure corresponding to the contentObject
158 this.keyName = key; // name of current key to be fetched
159 this.signature = signature; // hex signature string to be verified
160
161 Closure.call(this);
162 };
163
164 KeyFetchClosure.prototype.upcall = function(kind, upcallInfo) {
165 if (kind == Closure.UPCALL_INTEREST_TIMED_OUT) {
166 console.log("In KeyFetchClosure.upcall: interest time out.");
167 } else if (kind == Closure.UPCALL_CONTENT) {
Wentao Shang82854bd2012-12-27 14:14:41 -0800168 console.log("In KeyFetchClosure.upcall: signature verification passed");
Wentao Shangfa245962012-12-25 20:26:26 -0800169 var keyHex = DataUtils.toHex(upcallInfo.contentObject.content).toLowerCase();
170 console.log("Key: " + keyHex);
171
172 var kp = keyHex.slice(56, 314);
173 var exp = keyHex.slice(318, 324);
174
175 var rsakey = new RSAKey();
176 rsakey.setPublic(kp, exp);
Wentao Shang82854bd2012-12-27 14:14:41 -0800177 var verified = rsakey.verifyByteArray(this.contentObject.rawSignatureData, this.signature);
Wentao Shangfa245962012-12-25 20:26:26 -0800178 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
179
180 console.log("raise encapsulated closure");
181 this.closure.upcall(flag, new UpcallInfo(ndn, null, 0, this.contentObject));
182 }
183 };
184
185 if (co.signedInfo && co.signedInfo.locator && co.signature) {
186 if (LOG > 3) console.log("Key verification...");
187 var sigHex = DataUtils.toHex(co.signature.signature).toLowerCase();
188
189 var keylocator = co.signedInfo.locator;
190 if (keylocator.type == KeyLocatorType.KEYNAME) {
191 console.log("KeyLocator contains KEYNAME");
192 var keyname = keylocator.keyName.contentName.getName();
193 console.log(keyname);
194
Wentao Shang82854bd2012-12-27 14:14:41 -0800195 if (nameStr.match(keyname)) {
196 console.log("Content is key itself");
197
198 var keyHex = DataUtils.toHex(co.content).toLowerCase();
199 console.log("Key content: " + keyHex);
200
201 var kp = keyHex.slice(56, 314);
202 var exp = keyHex.slice(318, 324);
203
204 var rsakey = new RSAKey();
205 rsakey.setPublic(kp, exp);
206 var verified = rsakey.verifyByteArray(co.rawSignatureData, sigHex);
207 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
208
209 currentClosure.upcall(flag, new UpcallInfo(ndn, null, 0, co));
210
211 // Store key in cache
212 var keyEntry = new KeyStoreEntry(keylocator.keyName, keyHex, rsakey);
213 NDN.KeyStore.push(keyEntry);
Wentao Shangfa245962012-12-25 20:26:26 -0800214 } else {
215 console.log("Fetch key according to keylocator");
Wentao Shang82854bd2012-12-27 14:14:41 -0800216
217 // Check local key store
218 var keyEntry = NDN.getKeyByName(keylocator.keyName);
219 if (keyEntry) {
220 // Key found, verify now
221 console.log("Local key cache hit");
222 var rsakey = keyEntry.rsaKey;
223 verified = rsakey.verifyByteArray(co.rawSignatureData, sigHex);
224
225 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
226
227 // Raise callback
228 currentClosure.upcall(Closure.UPCALL_CONTENT, new UpcallInfo(ndn, null, 0, co));
229 } else {
230 // Not found, fetch now
231 var nextClosure = new KeyFetchClosure(co, currentClosure, keyname, sigHex);
232 var interest = new Interest(keylocator.keyName.contentName.getPrefix(4));
233 interest.interestLifetime = 4.0;
234 self.expressInterest(ndn, interest, nextClosure);
235 }
Wentao Shangfa245962012-12-25 20:26:26 -0800236 }
237 } else if (keylocator.type == KeyLocatorType.KEY) {
238 console.log("Keylocator contains KEY");
Wentao Shang82854bd2012-12-27 14:14:41 -0800239 var publickeyHex = DataUtils.toHex(keylocator.publicKey).toLowerCase();
Wentao Shangfa245962012-12-25 20:26:26 -0800240 console.log(publickeyHex);
241
242 var kp = publickeyHex.slice(56, 314);
243 var exp = publickeyHex.slice(318, 324);
244
245 var rsakey = new RSAKey();
246 rsakey.setPublic(kp, exp);
247 verified = rsakey.verifyByteArray(co.rawSignatureData, sigHex);
248
249 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
250
251 // Raise callback
252 currentClosure.upcall(Closure.UPCALL_CONTENT, new UpcallInfo(ndn, null, 0, co));
Wentao Shang82854bd2012-12-27 14:14:41 -0800253
254 // Store key in cache
255 var keyEntry = new KeyStoreEntry(keylocator.keyName, publickeyHex, rsakey);
256 NDN.KeyStore.push(keyEntry);
Wentao Shangfa245962012-12-25 20:26:26 -0800257 } else {
258 var cert = keylocator.certificate;
259 console.log("KeyLocator contains CERT");
260 console.log(cert);
261
262 // TODO: verify certificate
263 }
264 }
Jeff Thompson5b265a72012-11-12 01:13:08 -0800265 }
266 }
267 } else {
268 console.log('Incoming packet is not Interest or ContentObject. Discard now.');
269 }
270
271 delete decoder;
272
273 // Renew StrcutureDecoder and buffer after we process a full packet
274 delete self.structureDecoder;
275 delete self.buffer;
276 self.structureDecoder = new BinaryXMLStructureDecoder();
277 self.buffer = new Uint8Array(self.maxBufferSize);
Wentao Shang2b740e62012-12-07 00:02:53 -0800278 self.bufferOffset = 0;
Jeff Thompson5b265a72012-11-12 01:13:08 -0800279 }
280 }
281
282 this.ws.onopen = function(ev) {
Jeff Thompson3c263812012-12-01 17:20:28 -0800283 if (LOG > 3) console.log(ev);
284 if (LOG > 3) console.log('ws.onopen: WebSocket connection opened.');
285 if (LOG > 3) console.log('ws.onopen: ReadyState: ' + this.readyState);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800286
287 // Fetch ccndid now
Jeff Thompsonbd25df22012-12-13 21:50:13 -0800288 var interest = new Interest(new Name(NDN.ccndIdFetcher));
Jeff Thompson84db2632012-12-09 22:31:39 -0800289 interest.interestLifetime = 4.0; // seconds
Jeff Thompson64db7c02012-12-09 21:56:57 -0800290 var subarray = encodeToBinaryInterest(interest);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800291
Jeff Thompson64db7c02012-12-09 21:56:57 -0800292 var bytes = new Uint8Array(subarray.length);
293 bytes.set(subarray);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800294
295 self.ws.send(bytes.buffer);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800296 }
297
298 this.ws.onerror = function(ev) {
299 console.log('ws.onerror: ReadyState: ' + this.readyState);
300 console.log(ev);
301 console.log('ws.onerror: WebSocket error: ' + ev.data);
302 }
303
304 this.ws.onclose = function(ev) {
305 console.log('ws.onclose: WebSocket connection closed.');
306 self.ws = null;
Wentao Shang0e291c82012-12-02 23:36:29 -0800307
308 // Close NDN when WebSocket is closed
309 ndn.readyStatus = NDN.CLOSED;
310 ndn.onclose();
Wentao Shangaf25c6b2012-12-03 00:09:30 -0800311 //console.log("NDN.onclose event fired.");
Jeff Thompson5b265a72012-11-12 01:13:08 -0800312 }
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800313};
Jeff Thompson5b265a72012-11-12 01:13:08 -0800314
Wentao Shangc0311e52012-12-03 10:38:23 -0800315WebSocketTransport.prototype.expressInterest = function(ndn, interest, closure) {
316 if (this.ws != null) {
317 //TODO: check local content store first
318
319 var binaryInterest = encodeToBinaryInterest(interest);
320 var bytearray = new Uint8Array(binaryInterest.length);
321 bytearray.set(binaryInterest);
322
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800323 var pitEntry = new PITEntry(interest, closure);
324 NDN.PITTable.push(pitEntry);
Wentao Shangc0311e52012-12-03 10:38:23 -0800325
326 this.ws.send(bytearray.buffer);
327 if (LOG > 3) console.log('ws.send() returned.');
328
329 // Set interest timer
330 closure.timerID = setTimeout(function() {
Wentao Shangbd63e462012-12-03 16:19:33 -0800331 if (LOG > 3) console.log("Interest time out.");
Wentao Shangc0311e52012-12-03 10:38:23 -0800332
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800333 // Remove PIT entry from NDN.PITTable
334 var index = NDN.PITTable.indexOf(pitEntry);
335 //console.log(NDN.PITTable);
Jeff Thompsonc881b552012-12-14 01:29:12 -0800336 if (index >= 0)
337 NDN.PITTable.splice(index, 1);
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800338 //console.log(NDN.PITTable);
Wentao Shangc0311e52012-12-03 10:38:23 -0800339 // Raise closure callback
340 closure.upcall(Closure.UPCALL_INTEREST_TIMED_OUT, new UpcallInfo(ndn, interest, 0, null));
Jeff Thompson84db2632012-12-09 22:31:39 -0800341 }, interest.interestLifetime * 1000); // convert interestLifetime from seconds to ms.
Wentao Shangc0311e52012-12-03 10:38:23 -0800342 //console.log(closure.timerID);
343 }
344 else
345 console.log('WebSocket connection is not established.');
346};
347
Jeff Thompson5b265a72012-11-12 01:13:08 -0800348
349// For publishing data
350var CSTable = new Array();
351
352var CSEntry = function CSEntry(name, closure) {
353 this.name = name; // String
354 this.closure = closure; // Closure
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800355};
Jeff Thompson5b265a72012-11-12 01:13:08 -0800356
357function getEntryForRegisteredPrefix(name) {
358 for (var i = 0; i < CSTable.length; i++) {
359 if (CSTable[i].name.match(name) != null)
360 return CSTable[i];
361 }
362 return null;
363}
364
365WebSocketTransport.prototype.registerPrefix = function(ndn, name, closure, flag) {
366 if (this.ws != null) {
367 if (this.ccndid == null) {
368 console.log('ccnd node ID unkonwn. Cannot register prefix.');
Jeff Thompson3c263812012-12-01 17:20:28 -0800369 return -1;
Jeff Thompson5b265a72012-11-12 01:13:08 -0800370 }
371
Jeff Thompson48ba4ff2012-11-12 01:23:13 -0800372 var fe = new ForwardingEntry('selfreg', name, null, null, 3, 2147483647);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800373 var bytes = encodeForwardingEntry(fe);
374
375 var si = new SignedInfo();
376 si.setFields();
377
378 var co = new ContentObject(new Name(), si, bytes, new Signature());
379 co.sign();
380 var coBinary = encodeToBinaryContentObject(co);
381
Jeff Thompsonbd829262012-11-30 22:28:37 -0800382 //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');
383 var nodename = this.ccndid;
384 var interestName = new Name(['ccnx', nodename, 'selfreg', coBinary]);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800385
386 var interest = new Interest(interestName);
387 interest.scope = 1;
Jeff Thompson5b265a72012-11-12 01:13:08 -0800388 var binaryInterest = encodeToBinaryInterest(interest);
Wentao Shangc05dc532012-11-19 12:00:33 -0800389 // If we directly use binaryInterest.buffer to feed ws.send(),
390 // WebSocket will end up sending a packet with 10000 bytes of data.
391 // That is, WebSocket will flush the entire buffer in BinaryXMLEncoder
392 // regardless of the offset of the Uint8Array. So we have to create
393 // a new Uint8Array buffer with just the right size and copy the
394 // content from binaryInterest to the new buffer.
395 // ---Wentao
Jeff Thompson5b265a72012-11-12 01:13:08 -0800396 var bytearray = new Uint8Array(binaryInterest.length);
397 bytearray.set(binaryInterest);
Jeff Thompson3c263812012-12-01 17:20:28 -0800398 if (LOG > 3) console.log('Send Interest registration packet.');
Jeff Thompson5b265a72012-11-12 01:13:08 -0800399
Jeff Thompson48ba4ff2012-11-12 01:23:13 -0800400 var csEntry = new CSEntry(name.getName(), closure);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800401 CSTable.push(csEntry);
402
403 this.ws.send(bytearray.buffer);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800404
405 return 0;
406 } else {
407 console.log('WebSocket connection is not established.');
408 return -1;
409 }
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800410};
Jeff Thompson5b265a72012-11-12 01:13:08 -0800411