blob: f3ee4d9d6459a3a07f9c59fdc8bdba76860d4656 [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
154 // Recursive key fetching closure
155 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) {
168 console.log("In KeyFetchClosure.upcall");
169 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);
177 verified = rsakey.verifyByteArray(this.contentObject.rawSignatureData, sigHex);
178 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
195 if (nameStr.match("/ccnx.org/Users/")) {
196 console.log("Key found");
197 currentClosure.upcall(Closure.UPCALL_CONTENT, new UpcallInfo(ndn, null, 0, co));
198 } else {
199 console.log("Fetch key according to keylocator");
200 var nextClosure = new KeyFetchClosure(co, currentClosure, keyname, sigHex);
201 var interest = new Interest(keylocator.keyName.contentName.getPrefix(4));
202 interest.interestLifetime = 4.0;
203 self.expressInterest(ndn, interest, nextClosure);
204 }
205 } else if (keylocator.type == KeyLocatorType.KEY) {
206 console.log("Keylocator contains KEY");
207 var publickeyHex = DataUtils.toHex(co.signedInfo.locator.publicKey).toLowerCase();
208 console.log(publickeyHex);
209
210 var kp = publickeyHex.slice(56, 314);
211 var exp = publickeyHex.slice(318, 324);
212
213 var rsakey = new RSAKey();
214 rsakey.setPublic(kp, exp);
215 verified = rsakey.verifyByteArray(co.rawSignatureData, sigHex);
216
217 var flag = (verified == true) ? Closure.UPCALL_CONTENT : Closure.UPCALL_CONTENT_BAD;
218
219 // Raise callback
220 currentClosure.upcall(Closure.UPCALL_CONTENT, new UpcallInfo(ndn, null, 0, co));
221 } else {
222 var cert = keylocator.certificate;
223 console.log("KeyLocator contains CERT");
224 console.log(cert);
225
226 // TODO: verify certificate
227 }
228 }
Jeff Thompson5b265a72012-11-12 01:13:08 -0800229 }
230 }
231 } else {
232 console.log('Incoming packet is not Interest or ContentObject. Discard now.');
233 }
234
235 delete decoder;
236
237 // Renew StrcutureDecoder and buffer after we process a full packet
238 delete self.structureDecoder;
239 delete self.buffer;
240 self.structureDecoder = new BinaryXMLStructureDecoder();
241 self.buffer = new Uint8Array(self.maxBufferSize);
Wentao Shang2b740e62012-12-07 00:02:53 -0800242 self.bufferOffset = 0;
Jeff Thompson5b265a72012-11-12 01:13:08 -0800243 }
244 }
245
246 this.ws.onopen = function(ev) {
Jeff Thompson3c263812012-12-01 17:20:28 -0800247 if (LOG > 3) console.log(ev);
248 if (LOG > 3) console.log('ws.onopen: WebSocket connection opened.');
249 if (LOG > 3) console.log('ws.onopen: ReadyState: ' + this.readyState);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800250
251 // Fetch ccndid now
Jeff Thompsonbd25df22012-12-13 21:50:13 -0800252 var interest = new Interest(new Name(NDN.ccndIdFetcher));
Jeff Thompson84db2632012-12-09 22:31:39 -0800253 interest.interestLifetime = 4.0; // seconds
Jeff Thompson64db7c02012-12-09 21:56:57 -0800254 var subarray = encodeToBinaryInterest(interest);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800255
Jeff Thompson64db7c02012-12-09 21:56:57 -0800256 var bytes = new Uint8Array(subarray.length);
257 bytes.set(subarray);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800258
259 self.ws.send(bytes.buffer);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800260 }
261
262 this.ws.onerror = function(ev) {
263 console.log('ws.onerror: ReadyState: ' + this.readyState);
264 console.log(ev);
265 console.log('ws.onerror: WebSocket error: ' + ev.data);
266 }
267
268 this.ws.onclose = function(ev) {
269 console.log('ws.onclose: WebSocket connection closed.');
270 self.ws = null;
Wentao Shang0e291c82012-12-02 23:36:29 -0800271
272 // Close NDN when WebSocket is closed
273 ndn.readyStatus = NDN.CLOSED;
274 ndn.onclose();
Wentao Shangaf25c6b2012-12-03 00:09:30 -0800275 //console.log("NDN.onclose event fired.");
Jeff Thompson5b265a72012-11-12 01:13:08 -0800276 }
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800277};
Jeff Thompson5b265a72012-11-12 01:13:08 -0800278
Wentao Shangc0311e52012-12-03 10:38:23 -0800279WebSocketTransport.prototype.expressInterest = function(ndn, interest, closure) {
280 if (this.ws != null) {
281 //TODO: check local content store first
282
283 var binaryInterest = encodeToBinaryInterest(interest);
284 var bytearray = new Uint8Array(binaryInterest.length);
285 bytearray.set(binaryInterest);
286
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800287 var pitEntry = new PITEntry(interest, closure);
288 NDN.PITTable.push(pitEntry);
Wentao Shangc0311e52012-12-03 10:38:23 -0800289
290 this.ws.send(bytearray.buffer);
291 if (LOG > 3) console.log('ws.send() returned.');
292
293 // Set interest timer
294 closure.timerID = setTimeout(function() {
Wentao Shangbd63e462012-12-03 16:19:33 -0800295 if (LOG > 3) console.log("Interest time out.");
Wentao Shangc0311e52012-12-03 10:38:23 -0800296
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800297 // Remove PIT entry from NDN.PITTable
298 var index = NDN.PITTable.indexOf(pitEntry);
299 //console.log(NDN.PITTable);
Jeff Thompsonc881b552012-12-14 01:29:12 -0800300 if (index >= 0)
301 NDN.PITTable.splice(index, 1);
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800302 //console.log(NDN.PITTable);
Wentao Shangc0311e52012-12-03 10:38:23 -0800303 // Raise closure callback
304 closure.upcall(Closure.UPCALL_INTEREST_TIMED_OUT, new UpcallInfo(ndn, interest, 0, null));
Jeff Thompson84db2632012-12-09 22:31:39 -0800305 }, interest.interestLifetime * 1000); // convert interestLifetime from seconds to ms.
Wentao Shangc0311e52012-12-03 10:38:23 -0800306 //console.log(closure.timerID);
307 }
308 else
309 console.log('WebSocket connection is not established.');
310};
311
Jeff Thompson5b265a72012-11-12 01:13:08 -0800312
313// For publishing data
314var CSTable = new Array();
315
316var CSEntry = function CSEntry(name, closure) {
317 this.name = name; // String
318 this.closure = closure; // Closure
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800319};
Jeff Thompson5b265a72012-11-12 01:13:08 -0800320
321function getEntryForRegisteredPrefix(name) {
322 for (var i = 0; i < CSTable.length; i++) {
323 if (CSTable[i].name.match(name) != null)
324 return CSTable[i];
325 }
326 return null;
327}
328
329WebSocketTransport.prototype.registerPrefix = function(ndn, name, closure, flag) {
330 if (this.ws != null) {
331 if (this.ccndid == null) {
332 console.log('ccnd node ID unkonwn. Cannot register prefix.');
Jeff Thompson3c263812012-12-01 17:20:28 -0800333 return -1;
Jeff Thompson5b265a72012-11-12 01:13:08 -0800334 }
335
Jeff Thompson48ba4ff2012-11-12 01:23:13 -0800336 var fe = new ForwardingEntry('selfreg', name, null, null, 3, 2147483647);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800337 var bytes = encodeForwardingEntry(fe);
338
339 var si = new SignedInfo();
340 si.setFields();
341
342 var co = new ContentObject(new Name(), si, bytes, new Signature());
343 co.sign();
344 var coBinary = encodeToBinaryContentObject(co);
345
Jeff Thompsonbd829262012-11-30 22:28:37 -0800346 //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');
347 var nodename = this.ccndid;
348 var interestName = new Name(['ccnx', nodename, 'selfreg', coBinary]);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800349
350 var interest = new Interest(interestName);
351 interest.scope = 1;
Jeff Thompson5b265a72012-11-12 01:13:08 -0800352 var binaryInterest = encodeToBinaryInterest(interest);
Wentao Shangc05dc532012-11-19 12:00:33 -0800353 // If we directly use binaryInterest.buffer to feed ws.send(),
354 // WebSocket will end up sending a packet with 10000 bytes of data.
355 // That is, WebSocket will flush the entire buffer in BinaryXMLEncoder
356 // regardless of the offset of the Uint8Array. So we have to create
357 // a new Uint8Array buffer with just the right size and copy the
358 // content from binaryInterest to the new buffer.
359 // ---Wentao
Jeff Thompson5b265a72012-11-12 01:13:08 -0800360 var bytearray = new Uint8Array(binaryInterest.length);
361 bytearray.set(binaryInterest);
Jeff Thompson3c263812012-12-01 17:20:28 -0800362 if (LOG > 3) console.log('Send Interest registration packet.');
Jeff Thompson5b265a72012-11-12 01:13:08 -0800363
Jeff Thompson48ba4ff2012-11-12 01:23:13 -0800364 var csEntry = new CSEntry(name.getName(), closure);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800365 CSTable.push(csEntry);
366
367 this.ws.send(bytearray.buffer);
Jeff Thompson5b265a72012-11-12 01:13:08 -0800368
369 return 0;
370 } else {
371 console.log('WebSocket connection is not established.');
372 return -1;
373 }
Jeff Thompsonbe85be62012-12-13 22:32:01 -0800374};
Jeff Thompson5b265a72012-11-12 01:13:08 -0800375