/
Tlv0_2WireFormat.java
1740 lines (1534 loc) · 67.8 KB
/
Tlv0_2WireFormat.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (C) 2016-2019 Regents of the University of California.
* @author: Jeff Thompson <jefft0@remap.ucla.edu>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* A copy of the GNU Lesser General Public License is in the file COPYING.
*/
package net.named_data.jndn.encoding;
import java.nio.ByteBuffer;
import java.util.Random;
import net.named_data.jndn.ComponentType;
import net.named_data.jndn.ContentType;
import net.named_data.jndn.ControlParameters;
import net.named_data.jndn.ControlResponse;
import net.named_data.jndn.Data;
import net.named_data.jndn.DelegationSet;
import net.named_data.jndn.DigestSha256Signature;
import net.named_data.jndn.Exclude;
import net.named_data.jndn.RegistrationOptions;
import net.named_data.jndn.GenericSignature;
import net.named_data.jndn.HmacWithSha256Signature;
import net.named_data.jndn.Interest;
import net.named_data.jndn.KeyLocator;
import net.named_data.jndn.KeyLocatorType;
import net.named_data.jndn.MetaInfo;
import net.named_data.jndn.Name;
import net.named_data.jndn.Sha256WithEcdsaSignature;
import net.named_data.jndn.Sha256WithRsaSignature;
import net.named_data.jndn.Signature;
import net.named_data.jndn.encoding.tlv.Tlv;
import net.named_data.jndn.encoding.tlv.TlvDecoder;
import net.named_data.jndn.encoding.tlv.TlvEncoder;
import net.named_data.jndn.encrypt.EncryptedContent;
import net.named_data.jndn.encrypt.algo.EncryptAlgorithmType;
import net.named_data.jndn.lp.IncomingFaceId;
import net.named_data.jndn.lp.LpPacket;
import net.named_data.jndn.NetworkNack;
import net.named_data.jndn.encrypt.Schedule;
import net.named_data.jndn.lp.CongestionMark;
import net.named_data.jndn.security.ValidityPeriod;
import net.named_data.jndn.util.Blob;
/**
* A Tlv0_2WireFormat implements the WireFormat interface for encoding and
* decoding with the NDN-TLV wire format, version 0.2.
*/
public class Tlv0_2WireFormat extends WireFormat {
/**
* Encode name in NDN-TLV and return the encoding.
* @param name The Name object to encode.
* @return A Blob containing the encoding.
*/
public Blob
encodeName(Name name)
{
TlvEncoder encoder = new TlvEncoder(256);
encodeName(name, new int[1], new int[1], encoder);
return new Blob(encoder.getOutput(), false);
}
/**
* Decode input as a name in NDN-TLV and set the fields of the Name object.
* @param name The Name object whose fields are updated.
* @param input The input buffer to decode. This reads from position() to limit(), but does not change the position.
* @param copy If true, copy from the input when making new Blob values. If
* false, then Blob values share memory with the input, which must remain
* unchanged while the Blob values are used.
* @throws EncodingException For invalid encoding.
*/
public void
decodeName(Name name, ByteBuffer input, boolean copy) throws EncodingException
{
TlvDecoder decoder = new TlvDecoder(input);
decodeName(name, new int[1], new int[1], decoder, copy);
}
/**
* Encode interest using NDN-TLV and return the encoding.
* @param interest The Interest object to encode.
* @param signedPortionBeginOffset Return the offset in the encoding of the
* beginning of the signed portion. The signed portion starts from the first
* name component and ends just before the final name component (which is
* assumed to be a signature for a signed interest).
* @param signedPortionEndOffset Return the offset in the encoding of the end
* of the signed portion. The signed portion starts from the first
* name component and ends just before the final name component (which is
* assumed to be a signature for a signed interest).
* @return A Blob containing the encoding.
*/
public Blob
encodeInterest
(Interest interest, int[] signedPortionBeginOffset, int[] signedPortionEndOffset)
{
if (!interest.getDidSetCanBePrefix_() && !didCanBePrefixWarning_) {
System.out.println
("WARNING: The default CanBePrefix will change. See Interest.setDefaultCanBePrefix() for details.");
didCanBePrefixWarning_ = true;
}
if (interest.hasApplicationParameters())
// The application has specified a format v0.3 field. As we transition to
// format v0.3, encode as format v0.3 even though the application default
// is Tlv0_2WireFormat.
return encodeInterestV03
(interest, signedPortionBeginOffset, signedPortionEndOffset);
TlvEncoder encoder = new TlvEncoder(256);
int saveLength = encoder.getLength();
// Encode backwards.
if (interest.getForwardingHint().size() > 0) {
if (interest.getSelectedDelegationIndex() >= 0)
throw new Error
("An Interest may not have a selected delegation when encoding a forwarding hint");
if (interest.hasLink())
throw new Error
("An Interest may not have a link object when encoding a forwarding hint");
int forwardingHintSaveLength = encoder.getLength();
encodeDelegationSet(interest.getForwardingHint(), encoder);
encoder.writeTypeAndLength
(Tlv.ForwardingHint, encoder.getLength() - forwardingHintSaveLength);
}
encoder.writeOptionalNonNegativeIntegerTlv(
Tlv.SelectedDelegation, interest.getSelectedDelegationIndex());
try {
Blob linkWireEncoding = interest.getLinkWireEncoding(this);
if (!linkWireEncoding.isNull())
// Encode the entire link as is.
encoder.writeBuffer(linkWireEncoding.buf());
} catch (EncodingException ex) {
throw new Error(ex.getMessage());
}
encoder.writeOptionalNonNegativeIntegerTlvFromDouble
(Tlv.InterestLifetime, interest.getInterestLifetimeMilliseconds());
// Encode the Nonce as 4 bytes.
if (interest.getNonce().size() == 0)
{
// This is the most common case. Generate a nonce.
ByteBuffer nonce = ByteBuffer.allocate(4);
random_.nextBytes(nonce.array());
encoder.writeBlobTlv(Tlv.Nonce, nonce);
}
else if (interest.getNonce().size() < 4) {
ByteBuffer nonce = ByteBuffer.allocate(4);
// Copy existing nonce bytes.
nonce.put(interest.getNonce().buf());
// Generate random bytes for remaining bytes in the nonce.
for (int i = 0; i < 4 - interest.getNonce().size(); ++i)
nonce.put((byte)random_.nextInt());
nonce.flip();
encoder.writeBlobTlv(Tlv.Nonce, nonce);
}
else if (interest.getNonce().size() == 4)
// Use the nonce as-is.
encoder.writeBlobTlv(Tlv.Nonce, interest.getNonce().buf());
else
{
// Truncate.
ByteBuffer nonce = interest.getNonce().buf();
// buf() returns a new ByteBuffer, so we can change its limit.
nonce.limit(nonce.position() + 4);
encoder.writeBlobTlv(Tlv.Nonce, nonce);
}
encodeSelectors(interest, encoder);
int[] tempSignedPortionBeginOffset = new int[1];
int[] tempSignedPortionEndOffset = new int[1];
encodeName
(interest.getName(), tempSignedPortionBeginOffset,
tempSignedPortionEndOffset, encoder);
int signedPortionBeginOffsetFromBack =
encoder.getLength() - tempSignedPortionBeginOffset[0];
int signedPortionEndOffsetFromBack =
encoder.getLength() - tempSignedPortionEndOffset[0];
encoder.writeTypeAndLength(Tlv.Interest, encoder.getLength() - saveLength);
signedPortionBeginOffset[0] =
encoder.getLength() - signedPortionBeginOffsetFromBack;
signedPortionEndOffset[0] =
encoder.getLength() - signedPortionEndOffsetFromBack;
return new Blob(encoder.getOutput(), false);
}
/**
* Decode input as an interest in NDN-TLV and set the fields of the interest
* object.
* @param interest The Interest object whose fields are updated.
* @param input The input buffer to decode. This reads from position() to
* limit(), but does not change the position.
* @param signedPortionBeginOffset Return the offset in the encoding of the
* beginning of the signed portion. The signed portion starts from the first
* name component and ends just before the final name component (which is
* assumed to be a signature for a signed interest).
* @param signedPortionEndOffset Return the offset in the encoding of the end
* of the signed portion. The signed portion starts from the first
* name component and ends just before the final name component (which is
* assumed to be a signature for a signed interest).
* @param copy If true, copy from the input when making new Blob values. If
* false, then Blob values share memory with the input, which must remain
* unchanged while the Blob values are used.
* @throws EncodingException For invalid encoding.
*/
public void
decodeInterest
(Interest interest, ByteBuffer input, int[] signedPortionBeginOffset,
int[] signedPortionEndOffset, boolean copy) throws EncodingException
{
try {
decodeInterestV02
(interest, input, signedPortionBeginOffset, signedPortionEndOffset,
copy);
} catch (Exception exceptionV02) {
try {
// Failed to decode as format v0.2. Try to decode as v0.3.
decodeInterestV03
(interest, input, signedPortionBeginOffset, signedPortionEndOffset,
copy);
} catch (Exception ex) {
// Ignore the exception decoding as format v0.3 and throw the exception
// from trying to decode as format as format v0.2.
throw exceptionV02;
}
}
}
/**
* Do the work of decodeInterest to decode strictly as format v0.2.
*/
private void
decodeInterestV02
(Interest interest, ByteBuffer input, int[] signedPortionBeginOffset,
int[] signedPortionEndOffset, boolean copy) throws EncodingException
{
TlvDecoder decoder = new TlvDecoder(input);
int endOffset = decoder.readNestedTlvsStart(Tlv.Interest);
decodeName
(interest.getName(), signedPortionBeginOffset,signedPortionEndOffset,
decoder, copy);
if (decoder.peekType(Tlv.Selectors, endOffset))
decodeSelectors(interest, decoder, copy);
else {
// Set selectors to none.
interest.setMinSuffixComponents(-1);
interest.setMaxSuffixComponents(-1);
interest.getKeyLocator().clear();
interest.getExclude().clear();
interest.setChildSelector(-1);
interest.setMustBeFresh(false);
}
// Require a Nonce, but don't force it to be 4 bytes.
ByteBuffer nonce = decoder.readBlobTlv(Tlv.Nonce);
interest.setInterestLifetimeMilliseconds
(decoder.readOptionalNonNegativeIntegerTlv(Tlv.InterestLifetime, endOffset));
if (decoder.peekType(Tlv.ForwardingHint, endOffset)) {
int forwardingHintEndOffset = decoder.readNestedTlvsStart
(Tlv.ForwardingHint);
decodeDelegationSet
(interest.getForwardingHint(), forwardingHintEndOffset, decoder, copy);
decoder.finishNestedTlvs(forwardingHintEndOffset);
}
if (decoder.peekType(Tlv.Data, endOffset)) {
// Get the bytes of the Link TLV.
int linkBeginOffset = decoder.getOffset();
int linkEndOffset = decoder.readNestedTlvsStart(Tlv.Data);
decoder.seek(linkEndOffset);
interest.setLinkWireEncoding
(new Blob(decoder.getSlice(linkBeginOffset, linkEndOffset), copy), this);
}
else
interest.unsetLink();
interest.setSelectedDelegationIndex
((int)decoder.readOptionalNonNegativeIntegerTlv
(Tlv.SelectedDelegation, endOffset));
if (interest.getSelectedDelegationIndex() >= 0 && !interest.hasLink())
throw new EncodingException
("Interest has a selected delegation, but no link object");
// Format v0.2 doesn't have application parameters.
interest.setApplicationParameters(new Blob());
// Set the nonce last because setting other interest fields clears it.
interest.setNonce(new Blob(nonce, copy));
decoder.finishNestedTlvs(endOffset);
}
/**
* Encode data in NDN-TLV and return the encoding.
* @param data The Data object to encode.
* @param signedPortionBeginOffset Return the offset in the encoding of the
* beginning of the signed portion by setting signedPortionBeginOffset[0].
* If you are not encoding in order to sign, you can call encodeData(data) to
* ignore this returned value.
* @param signedPortionEndOffset Return the offset in the encoding of the end
* of the signed portion by setting signedPortionEndOffset[0].
* If you are not encoding in order to sign, you can call encodeData(data) to
* ignore this returned value.
* @return A Blob containing the encoding.
*/
public Blob
encodeData
(Data data, int[] signedPortionBeginOffset, int[] signedPortionEndOffset)
{
TlvEncoder encoder = new TlvEncoder(1500);
int saveLength = encoder.getLength();
// Encode backwards.
encoder.writeBlobTlv
(Tlv.SignatureValue, (data.getSignature()).getSignature().buf());
int signedPortionEndOffsetFromBack = encoder.getLength();
encodeSignatureInfo(data.getSignature(), encoder);
encoder.writeBlobTlv(Tlv.Content, data.getContent().buf());
encodeMetaInfo(data.getMetaInfo(), encoder);
encodeName(data.getName(), new int[1], new int[1], encoder);
int signedPortionBeginOffsetFromBack = encoder.getLength();
encoder.writeTypeAndLength(Tlv.Data, encoder.getLength() - saveLength);
signedPortionBeginOffset[0] =
encoder.getLength() - signedPortionBeginOffsetFromBack;
signedPortionEndOffset[0] =
encoder.getLength() - signedPortionEndOffsetFromBack;
return new Blob(encoder.getOutput(), false);
}
/**
* Decode input as a data packet in NDN-TLV and set the fields in the data
* object.
* @param data The Data object whose fields are updated.
* @param input The input buffer to decode. This reads from position() to
* limit(), but does not change the position.
* @param signedPortionBeginOffset Return the offset in the input buffer of
* the beginning of the signed portion by setting signedPortionBeginOffset[0].
* If you are not decoding in order to verify, you can call
* decodeData(data, input) to ignore this returned value.
* @param signedPortionEndOffset Return the offset in the input buffer of the
* end of the signed portion by setting signedPortionEndOffset[0]. If you are
* not decoding in order to verify, you can call decodeData(data, input) to
* ignore this returned value.
* @param copy If true, copy from the input when making new Blob values. If
* false, then Blob values share memory with the input, which must remain
* unchanged while the Blob values are used.
* @throws EncodingException For invalid encoding.
*/
public void
decodeData
(Data data, ByteBuffer input, int[] signedPortionBeginOffset,
int[] signedPortionEndOffset, boolean copy) throws EncodingException
{
TlvDecoder decoder = new TlvDecoder(input);
int endOffset = decoder.readNestedTlvsStart(Tlv.Data);
signedPortionBeginOffset[0] = decoder.getOffset();
decodeName(data.getName(), new int[1], new int[1], decoder, copy);
decodeMetaInfo(data.getMetaInfo(), decoder, copy);
data.setContent(new Blob(decoder.readBlobTlv(Tlv.Content), copy));
decodeSignatureInfo(data, decoder, copy);
signedPortionEndOffset[0] = decoder.getOffset();
data.getSignature().setSignature
(new Blob(decoder.readBlobTlv(Tlv.SignatureValue), copy));
decoder.finishNestedTlvs(endOffset);
}
/**
* Encode controlParameters in NDN-TLV and return the encoding.
* @param controlParameters The ControlParameters object to encode.
* @return A Blob containing the encoding.
*/
public Blob
encodeControlParameters(ControlParameters controlParameters)
{
TlvEncoder encoder = new TlvEncoder(256);
encodeControlParameters(controlParameters, encoder);
return new Blob(encoder.getOutput(), false);
}
/**
* Decode input as a control parameters in NDN-TLV and set the fields of the
* controlParameters object.
* @param controlParameters The ControlParameters object whose fields are
* updated.
* @param input The input buffer to decode. This reads from position() to
* limit(), but does not change the position.
* @param copy If true, copy from the input when making new Blob values. If
* false, then Blob values share memory with the input, which must remain
* unchanged while the Blob values are used.
* @throws EncodingException For invalid encoding
*/
public void
decodeControlParameters
(ControlParameters controlParameters, ByteBuffer input, boolean copy)
throws EncodingException
{
TlvDecoder decoder = new TlvDecoder(input);
decodeControlParameters(controlParameters, decoder, copy);
}
/**
* Encode controlResponse in NDN-TLV and return the encoding.
* @param controlResponse The ControlResponse object to encode.
* @return A Blob containing the encoding.
*/
public Blob
encodeControlResponse(ControlResponse controlResponse)
{
TlvEncoder encoder = new TlvEncoder(256);
int saveLength = encoder.getLength();
// Encode backwards.
// Encode the body.
if (controlResponse.getBodyAsControlParameters() != null)
encodeControlParameters
(controlResponse.getBodyAsControlParameters(), encoder);
encoder.writeBlobTlv(Tlv.NfdCommand_StatusText,
new Blob(controlResponse.getStatusText()).buf());
encoder.writeNonNegativeIntegerTlv
(Tlv.NfdCommand_StatusCode, controlResponse.getStatusCode());
encoder.writeTypeAndLength
(Tlv.NfdCommand_ControlResponse, encoder.getLength() - saveLength);
return new Blob(encoder.getOutput(), false);
}
/**
* Decode input as a control parameters in NDN-TLV and set the fields of the
* controlResponse object.
* @param controlResponse The ControlResponse object whose fields are
* updated.
* @param input The input buffer to decode. This reads from position() to
* limit(), but does not change the position.
* @param copy If true, copy from the input when making new Blob values. If
* false, then Blob values share memory with the input, which must remain
* unchanged while the Blob values are used.
* @throws EncodingException For invalid encoding
*/
public void
decodeControlResponse
(ControlResponse controlResponse, ByteBuffer input, boolean copy)
throws EncodingException
{
TlvDecoder decoder = new TlvDecoder(input);
int endOffset = decoder.readNestedTlvsStart(Tlv.NfdCommand_ControlResponse);
controlResponse.setStatusCode
((int)decoder.readNonNegativeIntegerTlv(Tlv.NfdCommand_StatusCode));
// Set copy false since we just immediately get a string.
Blob statusText = new Blob
(decoder.readBlobTlv(Tlv.NfdCommand_StatusText), false);
controlResponse.setStatusText(statusText.toString());
// Decode the body.
if (decoder.peekType(Tlv.ControlParameters_ControlParameters, endOffset)) {
controlResponse.setBodyAsControlParameters(new ControlParameters());
// Decode into the existing ControlParameters to avoid copying.
decodeControlParameters
(controlResponse.getBodyAsControlParameters(), decoder, copy);
}
else
controlResponse.setBodyAsControlParameters(null);
// The NFD management protocol is at the application-layer, so skip
// unrecognized type codes.
decoder.finishNestedTlvs(endOffset, true);
}
/**
* Encode signature as a SignatureInfo in NDN-TLV and return the encoding.
* @param signature An object of a subclass of Signature to encode.
* @return A Blob containing the encoding.
*/
public Blob
encodeSignatureInfo(Signature signature)
{
TlvEncoder encoder = new TlvEncoder(256);
encodeSignatureInfo(signature, encoder);
return new Blob(encoder.getOutput(), false);
}
private static class SimpleSignatureHolder implements SignatureHolder {
public Data setSignature(Signature signature)
{
signature_ = signature;
return null;
}
public Signature getSignature()
{
return signature_;
}
private Signature signature_;
}
/**
* Decode signatureInfo as an NDN-TLV signature info and signatureValue as the
* related NDN-TLV SignatureValue, and return a new object which is a subclass
* of Signature.
* @param signatureInfo The signature info input buffer to decode. This reads
* from position() to limit(), but does not change the position.
* @param signatureValue The signature value input buffer to decode. This reads
* from position() to limit(), but does not change the position.
* @param copy If true, copy from the input when making new Blob values. If
* false, then Blob values share memory with the input, which must remain
* unchanged while the Blob values are used.
* @return A new object which is a subclass of Signature.
* @throws EncodingException For invalid encoding.
*/
public Signature
decodeSignatureInfoAndValue
(ByteBuffer signatureInfo, ByteBuffer signatureValue, boolean copy)
throws EncodingException
{
// Use a SignatureHolder to imitate a Data object for _decodeSignatureInfo.
SimpleSignatureHolder signatureHolder = new SimpleSignatureHolder();
TlvDecoder decoder = new TlvDecoder(signatureInfo);
decodeSignatureInfo(signatureHolder, decoder, copy);
decoder = new TlvDecoder(signatureValue);
signatureHolder.getSignature().setSignature
(new Blob(decoder.readBlobTlv(Tlv.SignatureValue), copy));
return signatureHolder.getSignature();
}
/**
* Encode the signatureValue in the Signature object as a SignatureValue (the
* signature bits) in NDN-TLV and return the encoding.
* @param signature An object of a subclass of Signature with the signature
* value to encode.
* @return A Blob containing the encoding.
*/
public Blob
encodeSignatureValue(Signature signature)
{
TlvEncoder encoder = new TlvEncoder(256);
encoder.writeBlobTlv(Tlv.SignatureValue, signature.getSignature().buf());
return new Blob(encoder.getOutput(), false);
}
/**
* Decode input as an NDN-TLV LpPacket and set the fields of the lpPacket object.
* @param lpPacket The LpPacket object whose fields are updated.
* @param input The input buffer to decode. This reads from position() to
* limit(), but does not change the position.
* @param copy If true, copy from the input when making new Blob values. If
* false, then Blob values share memory with the input, which must remain
* unchanged while the Blob values are used.
* @throws EncodingException For invalid encoding.
*/
public void
decodeLpPacket
(LpPacket lpPacket, ByteBuffer input, boolean copy) throws EncodingException
{
lpPacket.clear();
TlvDecoder decoder = new TlvDecoder(input);
int endOffset = decoder.readNestedTlvsStart(Tlv.LpPacket_LpPacket);
while (decoder.getOffset() < endOffset) {
// Imitate TlvDecoder.readTypeAndLength.
int fieldType = decoder.readVarNumber();
int fieldLength = decoder.readVarNumber();
int fieldEndOffset = decoder.getOffset() + fieldLength;
if (fieldEndOffset > input.limit())
throw new EncodingException("TLV length exceeds the buffer length");
if (fieldType == Tlv.LpPacket_Fragment) {
// Set the fragment to the bytes of the TLV value.
lpPacket.setFragmentWireEncoding
(new Blob(decoder.getSlice(decoder.getOffset(), fieldEndOffset), copy));
decoder.seek(fieldEndOffset);
// The fragment is supposed to be the last field.
break;
}
else if (fieldType == Tlv.LpPacket_Nack) {
NetworkNack networkNack = new NetworkNack();
int code = (int)decoder.readOptionalNonNegativeIntegerTlv
(Tlv.LpPacket_NackReason, fieldEndOffset);
// The enum numeric values are the same as this wire format, so use as is.
if (code < 0 || code == NetworkNack.Reason.NONE.getNumericType())
// This includes an omitted NackReason.
networkNack.setReason(NetworkNack.Reason.NONE);
else if (code == NetworkNack.Reason.CONGESTION.getNumericType())
networkNack.setReason(NetworkNack.Reason.CONGESTION);
else if (code == NetworkNack.Reason.DUPLICATE.getNumericType())
networkNack.setReason(NetworkNack.Reason.DUPLICATE);
else if (code == NetworkNack.Reason.NO_ROUTE.getNumericType())
networkNack.setReason(NetworkNack.Reason.NO_ROUTE);
else {
// Unrecognized reason.
networkNack.setReason(NetworkNack.Reason.OTHER_CODE);
networkNack.setOtherReasonCode(code);
}
lpPacket.addHeaderField(networkNack);
}
else if (fieldType == Tlv.LpPacket_IncomingFaceId) {
IncomingFaceId incomingFaceId = new IncomingFaceId();
incomingFaceId.setFaceId(decoder.readNonNegativeInteger(fieldLength));
lpPacket.addHeaderField(incomingFaceId);
}
else if (fieldType == Tlv.LpPacket_CongestionMark) {
CongestionMark congestionMark = new CongestionMark();
congestionMark.setCongestionMark(decoder.readNonNegativeInteger
(fieldLength));
lpPacket.addHeaderField(congestionMark);
}
else {
// Unrecognized field type. The conditions for ignoring are here:
// http://redmine.named-data.net/projects/nfd/wiki/NDNLPv2
boolean canIgnore =
(fieldType >= Tlv.LpPacket_IGNORE_MIN &&
fieldType <= Tlv.LpPacket_IGNORE_MAX &&
(fieldType & 0x03) == 0);
if (!canIgnore)
throw new EncodingException("Did not get the expected TLV type");
// Ignore.
decoder.seek(fieldEndOffset);
}
decoder.finishNestedTlvs(fieldEndOffset);
}
decoder.finishNestedTlvs(endOffset);
}
/**
* Encode delegationSet as a sequence of NDN-TLV Delegation, and return the
* encoding. Note that the sequence of Delegation does not have an outer TLV
* type and length because it is intended to use the type and length of a Data
* packet's Content.
* @param delegationSet The DelegationSet object to encode.
* @return A Blob containing the encoding.
*/
public Blob
encodeDelegationSet(DelegationSet delegationSet)
{
TlvEncoder encoder = new TlvEncoder(256);
encodeDelegationSet(delegationSet, encoder);
return new Blob(encoder.getOutput(), false);
}
/**
* Decode input as a sequence of NDN-TLV Delegation and set the fields of the
* delegationSet object. Note that the sequence of Delegation does not have an
* outer TLV type and length because it is intended to use the type and length
* of a Data packet's Content. This ignores any elements after the sequence
* of Delegation and before input.limit().
* @param delegationSet The DelegationSet object whose fields are updated.
* @param input The input buffer to decode. This reads from position() to
* limit(), but does not change the position.
* @param copy If true, copy from the input when making new Blob values. If
* false, then Blob values share memory with the input, which must remain
* unchanged while the Blob values are used.
* @throws EncodingException For invalid encoding.
*/
public void
decodeDelegationSet
(DelegationSet delegationSet, ByteBuffer input, boolean copy)
throws EncodingException
{
TlvDecoder decoder = new TlvDecoder(input);
decodeDelegationSet(delegationSet, input.limit(), decoder, copy);
}
/**
* Encode the EncryptedContent v1 in NDN-TLV and return the encoding.
* @param encryptedContent The EncryptedContent object to encode.
* @return A Blob containing the encoding.
*/
public Blob
encodeEncryptedContent(EncryptedContent encryptedContent)
{
TlvEncoder encoder = new TlvEncoder(256);
int saveLength = encoder.getLength();
// Encode backwards.
encoder.writeBlobTlv
(Tlv.Encrypt_EncryptedPayload, encryptedContent.getPayload().buf());
encoder.writeOptionalBlobTlv
(Tlv.Encrypt_InitialVector, encryptedContent.getInitialVector().buf());
// Assume the algorithmType value is the same as the TLV type.
encoder.writeNonNegativeIntegerTlv
(Tlv.Encrypt_EncryptionAlgorithm,
encryptedContent.getAlgorithmType().getNumericType());
Tlv0_2WireFormat.encodeKeyLocator
(Tlv.KeyLocator, encryptedContent.getKeyLocator(), encoder);
encoder.writeTypeAndLength
(Tlv.Encrypt_EncryptedContent, encoder.getLength() - saveLength);
return new Blob(encoder.getOutput(), false);
}
/**
* Decode input as a EncryptedContent v1 in NDN-TLV and set the fields of the
* encryptedContent object.
* @param encryptedContent The EncryptedContent object whose fields are
* updated.
* @param input The input buffer to decode. This reads from position() to
* limit(), but does not change the position.
* @param copy If true, copy from the input when making new Blob values. If
* false, then Blob values share memory with the input, which must remain
* unchanged while the Blob values are used.
* @throws EncodingException For invalid encoding
*/
public void
decodeEncryptedContent
(EncryptedContent encryptedContent, ByteBuffer input, boolean copy)
throws EncodingException
{
TlvDecoder decoder = new TlvDecoder(input);
int endOffset = decoder.readNestedTlvsStart
(Tlv.Encrypt_EncryptedContent);
encryptedContent.clear();
Tlv0_2WireFormat.decodeKeyLocator
(Tlv.KeyLocator, encryptedContent.getKeyLocator(), decoder, copy);
int algorithmType = (int)decoder.readNonNegativeIntegerTlv
(Tlv.Encrypt_EncryptionAlgorithm);
if (algorithmType == EncryptAlgorithmType.AesEcb.getNumericType())
encryptedContent.setAlgorithmType(EncryptAlgorithmType.AesEcb);
else if (algorithmType == EncryptAlgorithmType.AesCbc.getNumericType())
encryptedContent.setAlgorithmType(EncryptAlgorithmType.AesCbc);
else if (algorithmType == EncryptAlgorithmType.RsaPkcs.getNumericType())
encryptedContent.setAlgorithmType(EncryptAlgorithmType.RsaPkcs);
else if (algorithmType == EncryptAlgorithmType.RsaOaep.getNumericType())
encryptedContent.setAlgorithmType(EncryptAlgorithmType.RsaOaep);
else
throw new EncodingException
("Unrecognized EncryptionAlgorithm code " + algorithmType);
encryptedContent.setInitialVector
(new Blob(decoder.readOptionalBlobTlv
(Tlv.Encrypt_InitialVector, endOffset), copy));
encryptedContent.setPayload
(new Blob(decoder.readBlobTlv(Tlv.Encrypt_EncryptedPayload), copy));
decoder.finishNestedTlvs(endOffset);
}
/**
* Encode the EncryptedContent v2 (used in Name-based Access Control v2) in
* NDN-TLV and return the encoding.
* See https://github.com/named-data/name-based-access-control/blob/new/docs/spec.rst .
* @param encryptedContent The EncryptedContent object to encode.
* @return A Blob containing the encoding.
*/
public Blob
encodeEncryptedContentV2(EncryptedContent encryptedContent)
{
TlvEncoder encoder = new TlvEncoder(256);
int saveLength = encoder.getLength();
// Encode backwards.
if (encryptedContent.getKeyLocator().getType() == KeyLocatorType.KEYNAME)
Tlv0_2WireFormat.encodeName
(encryptedContent.getKeyLocator().getKeyName(), new int[1], new int[1],
encoder);
encoder.writeOptionalBlobTlv
(Tlv.Encrypt_EncryptedPayloadKey, encryptedContent.getPayloadKey().buf());
encoder.writeOptionalBlobTlv
(Tlv.Encrypt_InitialVector, encryptedContent.getInitialVector().buf());
encoder.writeBlobTlv
(Tlv.Encrypt_EncryptedPayload, encryptedContent.getPayload().buf());
encoder.writeTypeAndLength
(Tlv.Encrypt_EncryptedContent, encoder.getLength() - saveLength);
return new Blob(encoder.getOutput(), false);
}
/**
* Decode input as an EncryptedContent v2 (used in Name-based Access Control
* v2) in NDN-TLV and set the fields of the encryptedContent object.
* See https://github.com/named-data/name-based-access-control/blob/new/docs/spec.rst .
* @param encryptedContent The EncryptedContent object whose fields are
* updated.
* @param input The input buffer to decode. This reads from position() to
* limit(), but does not change the position.
* @param copy If true, copy from the input when making new Blob values. If
* false, then Blob values share memory with the input, which must remain
* unchanged while the Blob values are used.
* @throws EncodingException For invalid encoding.
*/
public void
decodeEncryptedContentV2
(EncryptedContent encryptedContent, ByteBuffer input, boolean copy)
throws EncodingException
{
TlvDecoder decoder = new TlvDecoder(input);
int endOffset = decoder.readNestedTlvsStart
(Tlv.Encrypt_EncryptedContent);
encryptedContent.clear();
encryptedContent.setPayload
(new Blob(decoder.readBlobTlv(Tlv.Encrypt_EncryptedPayload), copy));
encryptedContent.setInitialVector
(new Blob(decoder.readOptionalBlobTlv
(Tlv.Encrypt_InitialVector, endOffset), copy));
encryptedContent.setPayloadKey
(new Blob(decoder.readOptionalBlobTlv
(Tlv.Encrypt_EncryptedPayloadKey, endOffset), copy));
if (decoder.peekType(Tlv.Name, endOffset)) {
decodeName
(encryptedContent.getKeyLocator().getKeyName(), new int[1], new int[1],
decoder, copy);
encryptedContent.getKeyLocator().setType(KeyLocatorType.KEYNAME);
}
decoder.finishNestedTlvs(endOffset);
}
/**
* Get a singleton instance of a Tlv0_2WireFormat. To always use the
* preferred version NDN-TLV, you should use TlvWireFormat.get().
* @return The singleton instance.
*/
public static Tlv0_2WireFormat
get()
{
return instance_;
}
/**
* Encode the name component to the encoder as NDN-TLV. This handles different
* component types such as ImplicitSha256DigestComponent.
* @param component The name component to encode.
* @param encoder The TlvEncoder to receive the encoding.
*/
private static void
encodeNameComponent(Name.Component component, TlvEncoder encoder)
{
int type;
if (component.getType() == ComponentType.OTHER_CODE)
type = component.getOtherTypeCode();
else
// The enum values are the same as the TLV type codes.
type = component.getType().getNumericType();
encoder.writeBlobTlv(type, component.getValue().buf());
}
/**
* Decode the name component as NDN-TLV and return the component. This handles
* different component types such as ImplicitSha256DigestComponent.
* @param decoder The decoder with the input to decode.
* @param copy If true, copy from the input when making new Blob values. If
* false, then Blob values share memory with the input, which must remain
* unchanged while the Blob values are used.
* @return A new Name.Component.
* @throws EncodingException
*/
private static Name.Component
decodeNameComponent(TlvDecoder decoder, boolean copy) throws EncodingException
{
int savePosition = decoder.getOffset();
int type = decoder.readVarNumber();
// Restore the position.
decoder.seek(savePosition);
Blob value = new Blob(decoder.readBlobTlv(type), copy);
if (type == Tlv.ImplicitSha256DigestComponent)
return Name.Component.fromImplicitSha256Digest(value);
else if (type == Tlv.ParametersSha256DigestComponent)
return Name.Component.fromParametersSha256Digest(value);
else if (type == Tlv.NameComponent)
return new Name.Component(value);
else
// Unrecognized type code.
return new Name.Component(value, ComponentType.OTHER_CODE, type);
}
/**
* Encode the name as NDN-TLV to the encoder.
* @param name The name to encode.
* @param signedPortionBeginOffset Return the offset in the encoding of the
* beginning of the signed portion. The signed portion starts from the first
* name component and ends just before the final name component (which is
* assumed to be a signature for a signed interest).
* @param signedPortionEndOffset Return the offset in the encoding of the end
* of the signed portion. The signed portion starts from the first
* name component and ends just before the final name component (which is
* assumed to be a signature for a signed interest).
* @param encoder The TlvEncoder to receive the encoding.
*/
private static void
encodeName
(Name name, int[] signedPortionBeginOffset, int[] signedPortionEndOffset,
TlvEncoder encoder)
{
int saveLength = encoder.getLength();
// Encode the components backwards.
int signedPortionEndOffsetFromBack = 0;
for (int i = name.size() - 1; i >= 0; --i) {
encodeNameComponent(name.get(i), encoder);
if (i == name.size() - 1)
signedPortionEndOffsetFromBack = encoder.getLength();
}
int signedPortionBeginOffsetFromBack = encoder.getLength();
encoder.writeTypeAndLength(Tlv.Name, encoder.getLength() - saveLength);
signedPortionBeginOffset[0] =
encoder.getLength() - signedPortionBeginOffsetFromBack;
if (name.size() == 0)
// There is no "final component", so set signedPortionEndOffset
// arbitrarily.
signedPortionEndOffset[0] = signedPortionBeginOffset[0];
else
signedPortionEndOffset[0] =
encoder.getLength() - signedPortionEndOffsetFromBack;
}
/**
* Decode the name as NDN-TLV and set the fields in name.
* @param name The name object whose fields are set.
* @param signedPortionBeginOffset Return the offset in the encoding of the
* beginning of the signed portion. The signed portion starts from the first
* name component and ends just before the final name component (which is
* assumed to be a signature for a signed interest).
* If you are not decoding in order to verify, you can ignore this returned value.
* @param signedPortionEndOffset Return the offset in the encoding of the end
* of the signed portion. The signed portion starts from the first
* name component and ends just before the final name component (which is
* assumed to be a signature for a signed interest).
* If you are not decoding in order to verify, you can ignore this returned value.
* @param decoder The decoder with the input to decode.
* @param copy If true, copy from the input when making new Blob values. If
* false, then Blob values share memory with the input, which must remain
* unchanged while the Blob values are used.
* @throws EncodingException
*/
private static void
decodeName
(Name name, int[] signedPortionBeginOffset, int[] signedPortionEndOffset,
TlvDecoder decoder, boolean copy) throws EncodingException
{
name.clear();
int endOffset = decoder.readNestedTlvsStart(Tlv.Name);
signedPortionBeginOffset[0] = decoder.getOffset();
// In case there are no components, set signedPortionEndOffset arbitrarily.
signedPortionEndOffset[0] = signedPortionBeginOffset[0];
while (decoder.getOffset() < endOffset) {
signedPortionEndOffset[0] = decoder.getOffset();
name.append(decodeNameComponent(decoder, copy));
}
decoder.finishNestedTlvs(endOffset);
}
/**
* Encode the interest selectors. If no selectors are written, do not output
* a Selectors TLV.
*/
private static void
encodeSelectors(Interest interest, TlvEncoder encoder)