blob: 61df84c6a094e5dff732148b404e790be2e7cb03 [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 Shang98b595c2012-12-30 10:14:26 -0800106 if (LOG > 3) console.log('ContentObject packet received.');
Jeff Thompson5b265a72012-11-12 01:13:08 -0800107
108 var co = new ContentObject();
109 co.from_ccnb(decoder);
Jeff Thompson3c263812012-12-01 17:20:28 -0800110 if (LOG > 3) console.log(co);
Wentao Shangf8b4a7d2012-12-25 12:52:07 -0800111 var nameStr = co.name.getName();
112 console.log(nameStr);
113
Jeff Thompsonbd25df22012-12-13 21:50:13 -0800114 if (self.ccndid == null && nameStr.match(NDN.ccndIdFetcher) != null) {
Jeff Thompson5b265a72012-11-12 01:13:08 -0800115 // We are in starting phase, record publisherPublicKeyDigest in self.ccndid
116 if(!co.signedInfo || !co.signedInfo.publisher
117 || !co.signedInfo.publisher.publisherPublicKeyDigest) {
Wentao Shangaf25c6b2012-12-03 00:09:30 -0800118 console.log("Cannot contact router, close NDN now.");
Wentao Shang0e291c82012-12-02 23:36:29 -0800119
120 // Close NDN if we fail to connect to a ccn router
121 ndn.readyStatus = NDN.CLOSED;
122 ndn.onclose();
Wentao Shangaf25c6b2012-12-03 00:09:30 -0800123 //console.log("NDN.onclose event fired.");
Jeff Thompson5b265a72012-11-12 01:13:08 -0800124 } else {
Wentao Shangaf25c6b2012-12-03 00:09:30 -0800125 //console.log('Connected to ccnd.');
Jeff Thompson5b265a72012-11-12 01:13:08 -0800126 self.ccndid = co.signedInfo.publisher.publisherPublicKeyDigest;
127 if (LOG>3) console.log(self.ccndid);
Wentao Shang0e291c82012-12-02 23:36:29 -0800128
129 // Call NDN.onopen after success
130 ndn.readyStatus = NDN.OPENED;
131 ndn.onopen();
Wentao Shangaf25c6b2012-12-03 00:09:30 -0800132 //console.log("NDN.onopen event fired.");
Jeff Thompson5b265a72012-11-12 01:13:08 -0800133 }
134 } else {
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800135 var pitEntry = NDN.getEntryForExpressedInterest(co.name);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800136 if (pitEntry != null) {
137 //console.log(pitEntry);
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800138 // Remove PIT entry from NDN.PITTable
139 var index = NDN.PITTable.indexOf(pitEntry);
Jeff Thompsonc881b552012-12-14 01:29:12 -0800140 if (index >= 0)
Wentao Shangfa245962012-12-25 20:26:26 -0800141 NDN.PITTable.splice(index, 1);
Wentao Shangbd63e462012-12-03 16:19:33 -0800142
Wentao Shangfa245962012-12-25 20:26:26 -0800143 var currentClosure = pitEntry.closure;
144
145 // Cancel interest timer
146 clearTimeout(currentClosure.timerID);
147 //console.log("Clear interest timer");
148 //console.log(currentClosure.timerID);
149
150 // Key verification
Wentao Shangfa245962012-12-25 20:26:26 -0800151
Wentao Shang82854bd2012-12-27 14:14:41 -0800152 // Recursive key fetching & verification closure
Wentao Shangfa245962012-12-25 20:26:26 -0800153 var KeyFetchClosure = function KeyFetchClosure(content, closure, key, signature) {
154 this.contentObject = content; // unverified content object
155 this.closure = closure; // closure corresponding to the contentObject
156 this.keyName = key; // name of current key to be fetched
157 this.signature = signature; // hex signature string to be verified
158
159 Closure.call(this);
160 };
161
162 KeyFetchClosure.prototype.upcall = function(kind, upcallInfo) {
163 if (kind == Closure.UPCALL_INTEREST_TIMED_OUT) {
164 console.log("In KeyFetchClosure.upcall: interest time out.");
165 } else if (kind == Closure.UPCALL_CONTENT) {
Wentao Shang82854bd2012-12-27 14:14:41 -0800166 console.log("In KeyFetchClosure.upcall: signature verification passed");
Wentao Shangfa245962012-12-25 20:26:26 -0800167
Wentao Shangb5d0c3e2012-12-30 11:12:03 -0800168 var rsakey = decodeSubjectPublicKeyInfo(upcallInfo.contentObject.content);
Wentao Shang82854bd2012-12-27 14:14:41 -0800169 var verified = rsakey.verifyByteArray(this.contentObject.rawSignatureData, this.signature);
Wentao Shangfa245962012-12-25 20:26:26 -0800170 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
171
Wentao Shang98b595c2012-12-30 10:14:26 -0800172 //console.log("raise encapsulated closure");
Wentao Shangfa245962012-12-25 20:26:26 -0800173 this.closure.upcall(flag, new UpcallInfo(ndn, null, 0, this.contentObject));
Wentao Shangb5d0c3e2012-12-30 11:12:03 -0800174
175 // Store key in cache
176 var keyEntry = new KeyStoreEntry(keylocator.keyName, rsakey, new Date().getTime());
177 NDN.addKeyEntry(keyEntry);
178 //console.log(NDN.KeyStore);
Wentao Shangfa245962012-12-25 20:26:26 -0800179 }
180 };
181
182 if (co.signedInfo && co.signedInfo.locator && co.signature) {
183 if (LOG > 3) console.log("Key verification...");
184 var sigHex = DataUtils.toHex(co.signature.signature).toLowerCase();
185
186 var keylocator = co.signedInfo.locator;
187 if (keylocator.type == KeyLocatorType.KEYNAME) {
188 console.log("KeyLocator contains KEYNAME");
189 var keyname = keylocator.keyName.contentName.getName();
190 console.log(keyname);
191
Wentao Shang82854bd2012-12-27 14:14:41 -0800192 if (nameStr.match(keyname)) {
193 console.log("Content is key itself");
194
Wentao Shangb5d0c3e2012-12-30 11:12:03 -0800195 var rsakey = decodeSubjectPublicKeyInfo(co.content);
Wentao Shang82854bd2012-12-27 14:14:41 -0800196 var verified = rsakey.verifyByteArray(co.rawSignatureData, sigHex);
197 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
198
199 currentClosure.upcall(flag, new UpcallInfo(ndn, null, 0, co));
200
Wentao Shangb5d0c3e2012-12-30 11:12:03 -0800201 // SWT: We don't need to store key here since the same key will be
202 // stored again in the closure.
203 //var keyEntry = new KeyStoreEntry(keylocator.keyName, rsakey, new Date().getTime());
204 //NDN.addKeyEntry(keyEntry);
205 //console.log(NDN.KeyStore);
Wentao Shangfa245962012-12-25 20:26:26 -0800206 } else {
207 console.log("Fetch key according to keylocator");
Wentao Shang82854bd2012-12-27 14:14:41 -0800208
209 // Check local key store
210 var keyEntry = NDN.getKeyByName(keylocator.keyName);
211 if (keyEntry) {
212 // Key found, verify now
213 console.log("Local key cache hit");
214 var rsakey = keyEntry.rsaKey;
Wentao Shangb5d0c3e2012-12-30 11:12:03 -0800215 var verified = rsakey.verifyByteArray(co.rawSignatureData, sigHex);
Wentao Shang82854bd2012-12-27 14:14:41 -0800216 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
217
218 // Raise callback
Wentao Shangb5d0c3e2012-12-30 11:12:03 -0800219 currentClosure.upcall(flag, new UpcallInfo(ndn, null, 0, co));
Wentao Shang82854bd2012-12-27 14:14:41 -0800220 } else {
221 // Not found, fetch now
222 var nextClosure = new KeyFetchClosure(co, currentClosure, keyname, sigHex);
223 var interest = new Interest(keylocator.keyName.contentName.getPrefix(4));
224 interest.interestLifetime = 4.0;
225 self.expressInterest(ndn, interest, nextClosure);
226 }
Wentao Shangfa245962012-12-25 20:26:26 -0800227 }
228 } else if (keylocator.type == KeyLocatorType.KEY) {
229 console.log("Keylocator contains KEY");
Wentao Shangfa245962012-12-25 20:26:26 -0800230
Wentao Shangb5d0c3e2012-12-30 11:12:03 -0800231 var rsakey = decodeSubjectPublicKeyInfo(co.signedInfo.locator.publicKey);
232 var verified = rsakey.verifyByteArray(co.rawSignatureData, sigHex);
Wentao Shangfa245962012-12-25 20:26:26 -0800233 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
234
235 // Raise callback
236 currentClosure.upcall(Closure.UPCALL_CONTENT, new UpcallInfo(ndn, null, 0, co));
Wentao Shang82854bd2012-12-27 14:14:41 -0800237
Wentao Shangb5d0c3e2012-12-30 11:12:03 -0800238 // Since KeyLocator does not contain key name for this key,
239 // we have no way to store it as a key entry in KeyStore.
Wentao Shangfa245962012-12-25 20:26:26 -0800240 } else {
241 var cert = keylocator.certificate;
242 console.log("KeyLocator contains CERT");
243 console.log(cert);
244
245 // TODO: verify certificate
246 }
247 }
Jeff Thompson5b265a72012-11-12 01:13:08 -0800248 }
249 }
250 } else {
251 console.log('Incoming packet is not Interest or ContentObject. Discard now.');
252 }
253
254 delete decoder;
255
256 // Renew StrcutureDecoder and buffer after we process a full packet
257 delete self.structureDecoder;
258 delete self.buffer;
259 self.structureDecoder = new BinaryXMLStructureDecoder();
260 self.buffer = new Uint8Array(self.maxBufferSize);
Wentao Shang2b740e62012-12-07 00:02:53 -0800261 self.bufferOffset = 0;
Jeff Thompson5b265a72012-11-12 01:13:08 -0800262 }
263 }
264
265 this.ws.onopen = function(ev) {
Jeff Thompson3c263812012-12-01 17:20:28 -0800266 if (LOG > 3) console.log(ev);
267 if (LOG > 3) console.log('ws.onopen: WebSocket connection opened.');
268 if (LOG > 3) console.log('ws.onopen: ReadyState: ' + this.readyState);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800269
270 // Fetch ccndid now
Jeff Thompsonbd25df22012-12-13 21:50:13 -0800271 var interest = new Interest(new Name(NDN.ccndIdFetcher));
Jeff Thompson42806a12012-12-29 18:19:39 -0800272 interest.interestLifetime = 4000; // milliseconds
Jeff Thompson64db7c02012-12-09 21:56:57 -0800273 var subarray = encodeToBinaryInterest(interest);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800274
Jeff Thompson64db7c02012-12-09 21:56:57 -0800275 var bytes = new Uint8Array(subarray.length);
276 bytes.set(subarray);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800277
278 self.ws.send(bytes.buffer);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800279 }
280
281 this.ws.onerror = function(ev) {
282 console.log('ws.onerror: ReadyState: ' + this.readyState);
283 console.log(ev);
284 console.log('ws.onerror: WebSocket error: ' + ev.data);
285 }
286
287 this.ws.onclose = function(ev) {
288 console.log('ws.onclose: WebSocket connection closed.');
289 self.ws = null;
Wentao Shang0e291c82012-12-02 23:36:29 -0800290
291 // Close NDN when WebSocket is closed
292 ndn.readyStatus = NDN.CLOSED;
293 ndn.onclose();
Wentao Shangaf25c6b2012-12-03 00:09:30 -0800294 //console.log("NDN.onclose event fired.");
Jeff Thompson5b265a72012-11-12 01:13:08 -0800295 }
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800296};
Jeff Thompson5b265a72012-11-12 01:13:08 -0800297
Wentao Shangc0311e52012-12-03 10:38:23 -0800298WebSocketTransport.prototype.expressInterest = function(ndn, interest, closure) {
299 if (this.ws != null) {
300 //TODO: check local content store first
301
302 var binaryInterest = encodeToBinaryInterest(interest);
303 var bytearray = new Uint8Array(binaryInterest.length);
304 bytearray.set(binaryInterest);
305
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800306 var pitEntry = new PITEntry(interest, closure);
307 NDN.PITTable.push(pitEntry);
Wentao Shangc0311e52012-12-03 10:38:23 -0800308
309 this.ws.send(bytearray.buffer);
310 if (LOG > 3) console.log('ws.send() returned.');
311
312 // Set interest timer
313 closure.timerID = setTimeout(function() {
Wentao Shangbd63e462012-12-03 16:19:33 -0800314 if (LOG > 3) console.log("Interest time out.");
Wentao Shangc0311e52012-12-03 10:38:23 -0800315
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800316 // Remove PIT entry from NDN.PITTable
317 var index = NDN.PITTable.indexOf(pitEntry);
318 //console.log(NDN.PITTable);
Jeff Thompsonc881b552012-12-14 01:29:12 -0800319 if (index >= 0)
320 NDN.PITTable.splice(index, 1);
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800321 //console.log(NDN.PITTable);
Wentao Shangc0311e52012-12-03 10:38:23 -0800322 // Raise closure callback
323 closure.upcall(Closure.UPCALL_INTEREST_TIMED_OUT, new UpcallInfo(ndn, interest, 0, null));
Jeff Thompson42806a12012-12-29 18:19:39 -0800324 }, interest.interestLifetime); // interestLifetime is in milliseconds.
Wentao Shangc0311e52012-12-03 10:38:23 -0800325 //console.log(closure.timerID);
326 }
327 else
328 console.log('WebSocket connection is not established.');
329};
330
Jeff Thompson5b265a72012-11-12 01:13:08 -0800331
332// For publishing data
333var CSTable = new Array();
334
335var CSEntry = function CSEntry(name, closure) {
336 this.name = name; // String
337 this.closure = closure; // Closure
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800338};
Jeff Thompson5b265a72012-11-12 01:13:08 -0800339
340function getEntryForRegisteredPrefix(name) {
341 for (var i = 0; i < CSTable.length; i++) {
342 if (CSTable[i].name.match(name) != null)
343 return CSTable[i];
344 }
345 return null;
346}
347
348WebSocketTransport.prototype.registerPrefix = function(ndn, name, closure, flag) {
349 if (this.ws != null) {
350 if (this.ccndid == null) {
351 console.log('ccnd node ID unkonwn. Cannot register prefix.');
Jeff Thompson3c263812012-12-01 17:20:28 -0800352 return -1;
Jeff Thompson5b265a72012-11-12 01:13:08 -0800353 }
354
Jeff Thompson48ba4ff2012-11-12 01:23:13 -0800355 var fe = new ForwardingEntry('selfreg', name, null, null, 3, 2147483647);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800356 var bytes = encodeForwardingEntry(fe);
357
358 var si = new SignedInfo();
359 si.setFields();
360
361 var co = new ContentObject(new Name(), si, bytes, new Signature());
362 co.sign();
363 var coBinary = encodeToBinaryContentObject(co);
364
Jeff Thompsonbd829262012-11-30 22:28:37 -0800365 //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');
366 var nodename = this.ccndid;
367 var interestName = new Name(['ccnx', nodename, 'selfreg', coBinary]);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800368
369 var interest = new Interest(interestName);
370 interest.scope = 1;
Jeff Thompson5b265a72012-11-12 01:13:08 -0800371 var binaryInterest = encodeToBinaryInterest(interest);
Wentao Shangc05dc532012-11-19 12:00:33 -0800372 // If we directly use binaryInterest.buffer to feed ws.send(),
373 // WebSocket will end up sending a packet with 10000 bytes of data.
374 // That is, WebSocket will flush the entire buffer in BinaryXMLEncoder
375 // regardless of the offset of the Uint8Array. So we have to create
376 // a new Uint8Array buffer with just the right size and copy the
377 // content from binaryInterest to the new buffer.
378 // ---Wentao
Jeff Thompson5b265a72012-11-12 01:13:08 -0800379 var bytearray = new Uint8Array(binaryInterest.length);
380 bytearray.set(binaryInterest);
Jeff Thompson3c263812012-12-01 17:20:28 -0800381 if (LOG > 3) console.log('Send Interest registration packet.');
Jeff Thompson5b265a72012-11-12 01:13:08 -0800382
Jeff Thompson48ba4ff2012-11-12 01:23:13 -0800383 var csEntry = new CSEntry(name.getName(), closure);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800384 CSTable.push(csEntry);
385
386 this.ws.send(bytearray.buffer);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800387
388 return 0;
389 } else {
390 console.log('WebSocket connection is not established.');
391 return -1;
392 }
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800393};
Jeff Thompson5b265a72012-11-12 01:13:08 -0800394