-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
http2.py
2729 lines (2376 loc) · 102 KB
/
http2.py
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
# SPDX-License-Identifier: GPL-2.0-only
# This file is part of Scapy
# See https://scapy.net/ for more information
# Copyright (C) 2016 Florian Maury <florian.maury@ssi.gouv.fr>
"""
http2
HTTP/2 support for Scapy
see RFC7540 and RFC7541 for more information
Implements packets and fields required to encode/decode HTTP/2 Frames
and HPack encoded headers
"""
# scapy.contrib.status=loads
# scapy.contrib.description=HTTP/2 (RFC 7540, RFC 7541)
# base_classes triggers an unwanted import warning
from __future__ import absolute_import
from __future__ import print_function
import abc
import re
from io import BytesIO
import struct
import scapy.libs.six as six
from scapy.compat import raw, plain_str, hex_bytes, orb, chb, bytes_encode
# Only required if using mypy-lang for static typing
# Most symbols are used in mypy-interpreted "comments".
# Sized must be one of the superclasses of a class implementing __len__
from scapy.compat import Optional, List, Union, Callable, Any, \
Tuple, Sized, Pattern # noqa: F401
from scapy.base_classes import Packet_metaclass # noqa: F401
import scapy.fields as fields
import scapy.packet as packet
import scapy.config as config
import scapy.volatile as volatile
import scapy.error as error
###############################################################################
# HPACK Integer Fields #
###############################################################################
class HPackMagicBitField(fields.BitField):
""" HPackMagicBitField is a BitField variant that cannot be assigned another
value than the default one. This field must not be used where there is
potential for fuzzing. OTOH, this field makes sense (for instance, if the
magic bits are used by a dispatcher to select the payload class)
"""
__slots__ = ['_magic']
def __init__(self, name, default, size):
# type: (str, int, int) -> None
"""
:param str name: this field instance name.
:param int default: this field only valid value.
:param int size: this bitfield bitlength.
:return: None
:raises: AssertionError
"""
assert default >= 0
# size can be negative if encoding is little-endian (see rev property of bitfields) # noqa: E501
assert size != 0
self._magic = default
super(HPackMagicBitField, self).__init__(name, default, size)
def addfield(self, pkt, s, val):
# type: (Optional[packet.Packet], Union[str, Tuple[str, int, int]], int) -> Union[str, Tuple[str, int, int]] # noqa: E501
"""
:param packet.Packet|None pkt: the packet instance containing this field instance; probably unused. # noqa: E501
:param str|(str, int, long) s: either a str if 0 == size%8 or a tuple with the string to add this field to, the # noqa: E501
number of bits already generated and the generated value so far.
:param int val: unused; must be equal to default value
:return: str|(str, int, long): the s string extended with this field machine representation # noqa: E501
:raises: AssertionError
"""
assert val == self._magic, 'val parameter must value {}; received: {}'.format(self._magic, val) # noqa: E501
return super(HPackMagicBitField, self).addfield(pkt, s, self._magic)
def getfield(self, pkt, s):
# type: (Optional[packet.Packet], Union[str, Tuple[str, int]]) -> Tuple[Union[Tuple[str, int], str], int] # noqa: E501
"""
:param packet.Packet|None pkt: the packet instance containing this field instance; probably unused. # noqa: E501
:param str|(str, int) s: either a str if size%8==0 or a tuple with the string to parse from and the number of # noqa: E501
bits already consumed by previous bitfield-compatible fields.
:return: (str|(str, int), int): Returns the remaining string and the parsed value. May return a tuple if there # noqa: E501
are remaining bits to parse in the first byte. Returned value is equal to default value # noqa: E501
:raises: AssertionError
"""
r = super(HPackMagicBitField, self).getfield(pkt, s)
assert (
isinstance(r, tuple) and
len(r) == 2 and
isinstance(r[1], six.integer_types)
), 'Second element of BitField.getfield return value expected to be an int or a long; API change detected' # noqa: E501
assert r[1] == self._magic, 'Invalid value parsed from s; error in class guessing detected!' # noqa: E501
return r
def h2i(self, pkt, x):
# type: (Optional[packet.Packet], int) -> int
"""
:param packet.Packet|None pkt: the packet instance containing this field instance; probably unused # noqa: E501
:param int x: unused; must be equal to default value
:return: int; default value
:raises: AssertionError
"""
assert x == self._magic, \
'EINVAL: x: This field is magic. Do not attempt to modify it. Expected value: {}'.format(self._magic) # noqa: E501
return super(HPackMagicBitField, self).h2i(pkt, self._magic)
def i2h(self, pkt, x):
# type: (Optional[packet.Packet], int) -> int
"""
:param packet.Packet|None pkt: the packet instance containing this field instance; probably unused # noqa: E501
:param int x: unused; must be equal to default value
:return: int; default value
:raises: AssertionError
"""
assert x == self._magic, \
'EINVAL: x: This field is magic. Do not attempt to modify it. Expected value: {}'.format(self._magic) # noqa: E501
return super(HPackMagicBitField, self).i2h(pkt, self._magic)
def m2i(self, pkt, x):
# type: (Optional[packet.Packet], int) -> int
"""
:param packet.Packet|None pkt: the packet instance containing this field instance; probably unused # noqa: E501
:param int x: must be the machine representatino of the default value
:return: int; default value
:raises: AssertionError
"""
r = super(HPackMagicBitField, self).m2i(pkt, x)
assert r == self._magic, 'Invalid value parsed from m2i; error in class guessing detected!' # noqa: E501
return r
def i2m(self, pkt, x):
# type: (Optional[packet.Packet], int) -> int
"""
:param packet.Packet|None pkt: the packet instance containing this field instance; probably unused # noqa: E501
:param int x: unused; must be equal to default value
:return: int; default value
:raises: AssertionError
"""
assert x == self._magic, \
'EINVAL: x: This field is magic. Do not attempt to modify it. Expected value: {}'.format(self._magic) # noqa: E501
return super(HPackMagicBitField, self).i2m(pkt, self._magic)
def any2i(self, pkt, x):
# type: (Optional[packet.Packet], int) -> int
"""
:param packet.Packet|None pkt: the packet instance containing this field instance; probably unused # noqa: E501
:param int x: unused; must be equal to default value
:return: int; default value
:raises: AssertionError
"""
assert x == self._magic, \
'EINVAL: x: This field is magic. Do not attempt to modify it. Expected value: {}'.format(self._magic) # noqa: E501
return super(HPackMagicBitField, self).any2i(pkt, self._magic)
class AbstractUVarIntField(fields.Field):
"""AbstractUVarIntField represents an integer as defined in RFC7541
"""
__slots__ = ['_max_value', 'size', 'rev']
"""
:var int size: the bit length of the prefix of this AbstractUVarIntField. It # noqa: E501
represents the complement of the number of MSB that are used in the
current byte for other purposes by some other BitFields
:var int _max_value: the maximum value that can be stored in the
sole prefix. If the integer equals or exceeds this value, the max prefix
value is assigned to the size first bits and the multibyte representation
is used
:var bool rev: is a fake property, also emulated for the sake of
compatibility with Bitfields
"""
def __init__(self, name, default, size):
# type: (str, Optional[int], int) -> None
"""
:param str name: the name of this field instance
:param int|None default: positive, null or None default value for this field instance. # noqa: E501
:param int size: the number of bits to consider in the first byte. Valid range is ]0;8] # noqa: E501
:return: None
:raises: AssertionError
"""
assert default is None or (isinstance(default, six.integer_types) and default >= 0) # noqa: E501
assert 0 < size <= 8
super(AbstractUVarIntField, self).__init__(name, default)
self.size = size
self._max_value = (1 << self.size) - 1
# Configuring the fake property that is useless for this class but that is # noqa: E501
# expected from BitFields
self.rev = False
def h2i(self, pkt, x):
# type: (Optional[packet.Packet], Optional[int]) -> Optional[int]
"""
:param packet.Packet|None pkt: unused.
:param int|None x: the value to convert.
:return: int|None: the converted value.
:raises: AssertionError
"""
assert not isinstance(x, six.integer_types) or x >= 0
return x
def i2h(self, pkt, x):
# type: (Optional[packet.Packet], Optional[int]) -> Optional[int]
"""
:param packet.Packet|None pkt: unused.
:param int|None x: the value to convert.
:return:: int|None: the converted value.
"""
return x
def _detect_multi_byte(self, fb):
# type: (str) -> bool
""" _detect_multi_byte returns whether the AbstractUVarIntField is represented on # noqa: E501
multiple bytes or not.
A multibyte representation is indicated by all of the first size bits being set # noqa: E501
:param str fb: first byte, as a character.
:return: bool: True if multibyte repr detected, else False.
:raises: AssertionError
"""
assert isinstance(fb, int) or len(fb) == 1
return (orb(fb) & self._max_value) == self._max_value
def _parse_multi_byte(self, s):
# type: (str) -> int
""" _parse_multi_byte parses x as a multibyte representation to get the
int value of this AbstractUVarIntField.
:param str s: the multibyte string to parse.
:return: int: The parsed int value represented by this AbstractUVarIntField. # noqa: E501
:raises:: AssertionError
:raises:: Scapy_Exception if the input value encodes an integer larger than 1<<64 # noqa: E501
"""
assert len(s) >= 2
tmp_len = len(s)
value = 0
i = 1
byte = orb(s[i])
# For CPU sake, stops at an arbitrary large number!
max_value = 1 << 64
# As long as the MSG is set, an another byte must be read
while byte & 0x80:
value += (byte ^ 0x80) << (7 * (i - 1))
if value > max_value:
raise error.Scapy_Exception(
'out-of-bound value: the string encodes a value that is too large (>2^{{64}}): {}'.format(value) # noqa: E501
)
i += 1
assert i < tmp_len, 'EINVAL: x: out-of-bound read: the string ends before the AbstractUVarIntField!' # noqa: E501
byte = orb(s[i])
value += byte << (7 * (i - 1))
value += self._max_value
assert value >= 0
return value
def m2i(self, pkt, x):
# type: (Optional[packet.Packet], Union[str, Tuple[str, int]]) -> int
"""
A tuple is expected for the "x" param only if "size" is different than 8. If a tuple is received, some bits # noqa: E501
were consumed by another field. This field consumes the remaining bits, therefore the int of the tuple must # noqa: E501
equal "size".
:param packet.Packet|None pkt: unused.
:param str|(str, int) x: the string to convert. If bits were consumed by a previous bitfield-compatible field. # noqa: E501
:raises: AssertionError
"""
assert isinstance(x, bytes) or (isinstance(x, tuple) and x[1] >= 0)
if isinstance(x, tuple):
assert (8 - x[1]) == self.size, 'EINVAL: x: not enough bits remaining in current byte to read the prefix' # noqa: E501
val = x[0]
else:
assert isinstance(x, bytes) and self.size == 8, 'EINVAL: x: tuple expected when prefix_len is not a full byte' # noqa: E501
val = x
if self._detect_multi_byte(val[0]):
ret = self._parse_multi_byte(val)
else:
ret = orb(val[0]) & self._max_value
assert ret >= 0
return ret
def i2m(self, pkt, x):
# type: (Optional[packet.Packet], int) -> str
"""
:param packet.Packet|None pkt: unused.
:param int x: the value to convert.
:return: str: the converted value.
:raises: AssertionError
"""
assert x >= 0
if x < self._max_value:
return chb(x)
else:
# The sl list join is a performance trick, because string
# concatenation is not efficient with Python immutable strings
sl = [chb(self._max_value)]
x -= self._max_value
while x >= 0x80:
sl.append(chb(0x80 | (x & 0x7F)))
x >>= 7
sl.append(chb(x))
return b''.join(sl)
def any2i(self, pkt, x):
# type: (Optional[packet.Packet], Union[None, str, int]) -> Optional[int] # noqa: E501
"""
A "x" value as a string is parsed as a binary encoding of a UVarInt. An int is considered an internal value. # noqa: E501
None is returned as is.
:param packet.Packet|None pkt: the packet containing this field; probably unused. # noqa: E501
:param str|int|None x: the value to convert.
:return: int|None: the converted value.
:raises: AssertionError
"""
if isinstance(x, type(None)):
return x
if isinstance(x, six.integer_types):
assert x >= 0
ret = self.h2i(pkt, x)
assert isinstance(ret, six.integer_types) and ret >= 0
return ret
elif isinstance(x, bytes):
ret = self.m2i(pkt, x)
assert (isinstance(ret, six.integer_types) and ret >= 0)
return ret
assert False, 'EINVAL: x: No idea what the parameter format is'
def i2repr(self, pkt, x):
# type: (Optional[packet.Packet], Optional[int]) -> str
"""
:param packet.Packet|None pkt: probably unused.
:param x: int|None: the positive, null or none value to convert.
:return: str: the representation of the value.
"""
return repr(self.i2h(pkt, x))
def addfield(self, pkt, s, val):
# type: (Optional[packet.Packet], Union[str, Tuple[str, int, int]], int) -> str # noqa: E501
"""
An AbstractUVarIntField prefix always consumes the remaining bits
of a BitField;if no current BitField is in use (no tuple in
entry) then the prefix length is 8 bits and the whole byte is to
be consumed
:param packet.Packet|None pkt: the packet containing this field.
Probably unused.
:param str|(str, int, long) s: the string to append this field to.
A tuple indicates that some bits were already generated by another
bitfield-compatible field. This MUST be the case if "size" is not 8.
The int is the number of bits already generated in the first byte of
the str. The long is the value that was generated by the previous
bitfield-compatible fields.
:param int val: the positive or null value to be added.
:return: str: s concatenated with the machine representation of this
field.
:raises: AssertionError
"""
assert val >= 0
if isinstance(s, bytes):
assert self.size == 8, 'EINVAL: s: tuple expected when prefix_len is not a full byte' # noqa: E501
return s + self.i2m(pkt, val)
# s is a tuple
# assert s[1] >= 0
# assert s[2] >= 0
# assert (8 - s[1]) == self.size, 'EINVAL: s: not enough bits remaining in current byte to read the prefix' # noqa: E501
if val >= self._max_value:
return s[0] + chb((s[2] << self.size) + self._max_value) + self.i2m(pkt, val)[1:] # noqa: E501
# This AbstractUVarIntField is only one byte long; setting the prefix value # noqa: E501
# and appending the resulting byte to the string
return s[0] + chb((s[2] << self.size) + orb(self.i2m(pkt, val)))
@staticmethod
def _detect_bytelen_from_str(s):
# type: (str) -> int
""" _detect_bytelen_from_str returns the length of the machine
representation of an AbstractUVarIntField starting at the beginning
of s and which is assumed to expand over multiple bytes
(value > _max_prefix_value).
:param str s: the string to parse. It is assumed that it is a multibyte int. # noqa: E501
:return: The bytelength of the AbstractUVarIntField.
:raises: AssertionError
"""
assert len(s) >= 2
tmp_len = len(s)
i = 1
while orb(s[i]) & 0x80 > 0:
i += 1
assert i < tmp_len, 'EINVAL: s: out-of-bound read: unfinished AbstractUVarIntField detected' # noqa: E501
ret = i + 1
assert ret >= 0
return ret
def i2len(self, pkt, x):
# type: (Optional[packet.Packet], int) -> int
"""
:param packet.Packet|None pkt: unused.
:param int x: the positive or null value whose binary size if requested. # noqa: E501
:raises: AssertionError
"""
assert x >= 0
if x < self._max_value:
return 1
# x is expressed over multiple bytes
x -= self._max_value
i = 1
if x == 0:
i += 1
while x > 0:
x >>= 7
i += 1
ret = i
assert ret >= 0
return ret
def getfield(self, pkt, s):
# type: (Optional[packet.Packet], Union[str, Tuple[str, int]]) -> Tuple[str, int] # noqa: E501
"""
:param packet.Packet|None pkt: the packet instance containing this
field; probably unused.
:param str|(str, int) s: the input value to get this field value from.
If size is 8, s is a string, else it is a tuple containing the value
and an int indicating the number of bits already consumed in the
first byte of the str. The number of remaining bits to consume in the
first byte must be equal to "size".
:return: (str, int): the remaining bytes of s and the parsed value.
:raises: AssertionError
"""
if isinstance(s, tuple):
assert len(s) == 2
temp = s # type: Tuple[str, int]
ts, ti = temp
assert ti >= 0
assert 8 - ti == self.size, 'EINVAL: s: not enough bits remaining in current byte to read the prefix' # noqa: E501
val = ts
else:
assert isinstance(s, bytes) and self.size == 8, 'EINVAL: s: tuple expected when prefix_len is not a full byte' # noqa: E501
val = s
if self._detect_multi_byte(val[0]):
tmp_len = self._detect_bytelen_from_str(val)
else:
tmp_len = 1
ret = val[tmp_len:], self.m2i(pkt, s)
assert ret[1] >= 0
return ret
def randval(self):
# type: () -> volatile.VolatileValue
"""
:return: volatile.VolatileValue: a volatile value for this field "long"-compatible internal value. # noqa: E501
"""
return volatile.RandLong()
class UVarIntField(AbstractUVarIntField):
def __init__(self, name, default, size):
# type: (str, int, int) -> None
"""
:param str name: the name of this field instance.
:param default: the default value for this field instance. default must be positive or null. # noqa: E501
:raises: AssertionError
"""
assert default >= 0
assert 0 < size <= 8
super(UVarIntField, self).__init__(name, default, size)
self.size = size
self._max_value = (1 << self.size) - 1
# Configuring the fake property that is useless for this class but that is # noqa: E501
# expected from BitFields
self.rev = False
def h2i(self, pkt, x):
# type: (Optional[packet.Packet], int) -> int
""" h2i is overloaded to restrict the acceptable x values (not None)
:param packet.Packet|None pkt: the packet instance containing this field instance; probably unused. # noqa: E501
:param int x: the value to convert.
:return: int: the converted value.
:raises: AssertionError
"""
ret = super(UVarIntField, self).h2i(pkt, x)
assert not isinstance(ret, type(None)) and ret >= 0
return ret
def i2h(self, pkt, x):
# type: (Optional[packet.Packet], int) -> int
""" i2h is overloaded to restrict the acceptable x values (not None)
:param packet.Packet|None pkt: the packet instance containing this field instance; probably unused. # noqa: E501
:param int x: the value to convert.
:return: int: the converted value.
:raises: AssertionError
"""
ret = super(UVarIntField, self).i2h(pkt, x)
assert not isinstance(ret, type(None)) and ret >= 0
return ret
def any2i(self, pkt, x):
# type: (Optional[packet.Packet], Union[str, int]) -> int
""" any2i is overloaded to restrict the acceptable x values (not None)
:param packet.Packet|None pkt: the packet instance containing this field instance; probably unused. # noqa: E501
:param str|int x: the value to convert.
:return: int: the converted value.
:raises: AssertionError
"""
ret = super(UVarIntField, self).any2i(pkt, x)
assert not isinstance(ret, type(None)) and ret >= 0
return ret
def i2repr(self, pkt, x):
# type: (Optional[packet.Packet], int) -> str
""" i2repr is overloaded to restrict the acceptable x values (not None)
:param packet.Packet|None pkt: the packet instance containing this field instance; probably unused. # noqa: E501
:param int x: the value to convert.
:return: str: the converted value.
"""
return super(UVarIntField, self).i2repr(pkt, x)
class FieldUVarLenField(AbstractUVarIntField):
__slots__ = ['_length_of', '_adjust']
def __init__(self, name, default, size, length_of, adjust=lambda x: x):
# type: (str, Optional[int], int, str, Callable[[int], int]) -> None
""" Initializes a FieldUVarLenField
:param str name: The name of this field instance.
:param int|None default: the default value of this field instance.
:param int size: the number of bits that are occupied by this field in the first byte of a binary string. # noqa: E501
size must be in the range ]0;8].
:param str length_of: The name of the field this field value is measuring/representing. # noqa: E501
:param callable adjust: A function that modifies the value computed from the "length_of" field. # noqa: E501
adjust can be used for instance to add a constant to the length_of field # noqa: E501
length. For instance, let's say that i2len of the length_of field
returns 2. If adjust is lambda x: x+1 In that case, this field will
value 3 at build time.
:return: None
:raises: AssertionError
"""
assert default is None or default >= 0
assert 0 < size <= 8
super(FieldUVarLenField, self).__init__(name, default, size)
self._length_of = length_of
self._adjust = adjust
def addfield(self, pkt, s, val):
# type: (Optional[packet.Packet], Union[str, Tuple[str, int, int]], Optional[int]) -> str # noqa: E501
"""
:param packet.Packet|None pkt: the packet instance containing this field instance. This parameter must not be # noqa: E501
None if the val parameter is.
:param str|(str, int, long) s: the string to append this field to. A tuple indicates that some bits were already # noqa: E501
generated by another bitfield-compatible field. This MUST be the case if "size" is not 8. The int is the # noqa: E501
number of bits already generated in the first byte of the str. The long is the value that was generated by the # noqa: E501
previous bitfield-compatible fields.
:param int|None val: the positive or null value to be added. If None, the value is computed from pkt. # noqa: E501
:return: str: s concatenated with the machine representation of this field. # noqa: E501
:raises: AssertionError
"""
if val is None:
assert isinstance(pkt, packet.Packet), \
'EINVAL: pkt: Packet expected when val is None; received {}'.format(type(pkt)) # noqa: E501
val = self._compute_value(pkt)
return super(FieldUVarLenField, self).addfield(pkt, s, val)
def i2m(self, pkt, x):
# type: (Optional[packet.Packet], Optional[int]) -> str
"""
:param packet.Packet|None pkt: the packet instance containing this field instance. This parameter must not be # noqa: E501
None if the x parameter is.
:param int|None x: the positive or null value to be added. If None, the value is computed from pkt. # noqa: E501
:return: str
:raises: AssertionError
"""
if x is None:
assert isinstance(pkt, packet.Packet), \
'EINVAL: pkt: Packet expected when x is None; received {}'.format(type(pkt)) # noqa: E501
x = self._compute_value(pkt)
return super(FieldUVarLenField, self).i2m(pkt, x)
def _compute_value(self, pkt):
# type: (packet.Packet) -> int
""" Computes the value of this field based on the provided packet and
the length_of field and the adjust callback
:param packet.Packet pkt: the packet from which is computed this field value. # noqa: E501
:return: int: the computed value for this field.
:raises: KeyError: the packet nor its payload do not contain an attribute
with the length_of name.
:raises: AssertionError
:raises: KeyError if _length_of is not one of pkt fields
"""
fld, fval = pkt.getfield_and_val(self._length_of)
val = fld.i2len(pkt, fval)
ret = self._adjust(val)
assert ret >= 0
return ret
###############################################################################
# HPACK String Fields #
###############################################################################
@six.add_metaclass(abc.ABCMeta)
class HPackStringsInterface(Sized): # type: ignore
@abc.abstractmethod
def __str__(self):
pass
def __bytes__(self):
r = self.__str__()
return bytes_encode(r)
@abc.abstractmethod
def origin(self):
pass
@abc.abstractmethod
def __len__(self):
pass
class HPackLiteralString(HPackStringsInterface):
""" HPackLiteralString is a string. This class is used as a marker and
implements an interface in common with HPackZString
"""
__slots__ = ['_s']
def __init__(self, s):
# type: (str) -> None
self._s = s
def __str__(self):
# type: () -> str
return self._s
def origin(self):
# type: () -> str
return plain_str(self._s)
def __len__(self):
# type: () -> int
return len(self._s)
class EOS(object):
""" Simple "marker" to designate the End Of String symbol in the huffman table
"""
class HuffmanNode(object):
""" HuffmanNode is an entry of the binary tree used for encoding/decoding
HPack compressed HTTP/2 headers
"""
__slots__ = ['left', 'right']
"""@var l: the left branch of this node
@var r: the right branch of this Node
These variables can value None (leaf node), another HuffmanNode, or a
symbol. Symbols are either a character or the End Of String symbol (class
EOS)
"""
def __init__(self, left, right):
# type: (Union[None, HuffmanNode, EOS, str], Union[None, HuffmanNode, EOS, str]) -> None # noqa: E501
self.left = left
self.right = right
def __getitem__(self, b):
# type: (int) -> Union[None, HuffmanNode, EOS, str]
return self.right if b else self.left
def __setitem__(self, b, val):
# type: (int, Union[None, HuffmanNode, EOS, str]) -> None
if b:
self.right = val
else:
self.left = val
def __str__(self):
# type: () -> str
return self.__repr__()
def __repr__(self):
# type: () -> str
return '({}, {})'.format(self.left, self.right)
class InvalidEncodingException(Exception):
""" InvalidEncodingException is raised when a supposedly huffman-encoded
string is decoded and a decoding error arises
"""
class HPackZString(HPackStringsInterface):
__slots__ = ['_s', '_encoded']
# From RFC 7541
# Tuple is (code,code bitlength)
# The bitlength is required to know how long the left padding
# (implicit 0's) there are
static_huffman_code = [
(0x1ff8, 13),
(0x7fffd8, 23),
(0xfffffe2, 28),
(0xfffffe3, 28),
(0xfffffe4, 28),
(0xfffffe5, 28),
(0xfffffe6, 28),
(0xfffffe7, 28),
(0xfffffe8, 28),
(0xffffea, 24),
(0x3ffffffc, 30),
(0xfffffe9, 28),
(0xfffffea, 28),
(0x3ffffffd, 30),
(0xfffffeb, 28),
(0xfffffec, 28),
(0xfffffed, 28),
(0xfffffee, 28),
(0xfffffef, 28),
(0xffffff0, 28),
(0xffffff1, 28),
(0xffffff2, 28),
(0x3ffffffe, 30),
(0xffffff3, 28),
(0xffffff4, 28),
(0xffffff5, 28),
(0xffffff6, 28),
(0xffffff7, 28),
(0xffffff8, 28),
(0xffffff9, 28),
(0xffffffa, 28),
(0xffffffb, 28),
(0x14, 6),
(0x3f8, 10),
(0x3f9, 10),
(0xffa, 12),
(0x1ff9, 13),
(0x15, 6),
(0xf8, 8),
(0x7fa, 11),
(0x3fa, 10),
(0x3fb, 10),
(0xf9, 8),
(0x7fb, 11),
(0xfa, 8),
(0x16, 6),
(0x17, 6),
(0x18, 6),
(0x0, 5),
(0x1, 5),
(0x2, 5),
(0x19, 6),
(0x1a, 6),
(0x1b, 6),
(0x1c, 6),
(0x1d, 6),
(0x1e, 6),
(0x1f, 6),
(0x5c, 7),
(0xfb, 8),
(0x7ffc, 15),
(0x20, 6),
(0xffb, 12),
(0x3fc, 10),
(0x1ffa, 13),
(0x21, 6),
(0x5d, 7),
(0x5e, 7),
(0x5f, 7),
(0x60, 7),
(0x61, 7),
(0x62, 7),
(0x63, 7),
(0x64, 7),
(0x65, 7),
(0x66, 7),
(0x67, 7),
(0x68, 7),
(0x69, 7),
(0x6a, 7),
(0x6b, 7),
(0x6c, 7),
(0x6d, 7),
(0x6e, 7),
(0x6f, 7),
(0x70, 7),
(0x71, 7),
(0x72, 7),
(0xfc, 8),
(0x73, 7),
(0xfd, 8),
(0x1ffb, 13),
(0x7fff0, 19),
(0x1ffc, 13),
(0x3ffc, 14),
(0x22, 6),
(0x7ffd, 15),
(0x3, 5),
(0x23, 6),
(0x4, 5),
(0x24, 6),
(0x5, 5),
(0x25, 6),
(0x26, 6),
(0x27, 6),
(0x6, 5),
(0x74, 7),
(0x75, 7),
(0x28, 6),
(0x29, 6),
(0x2a, 6),
(0x7, 5),
(0x2b, 6),
(0x76, 7),
(0x2c, 6),
(0x8, 5),
(0x9, 5),
(0x2d, 6),
(0x77, 7),
(0x78, 7),
(0x79, 7),
(0x7a, 7),
(0x7b, 7),
(0x7ffe, 15),
(0x7fc, 11),
(0x3ffd, 14),
(0x1ffd, 13),
(0xffffffc, 28),
(0xfffe6, 20),
(0x3fffd2, 22),
(0xfffe7, 20),
(0xfffe8, 20),
(0x3fffd3, 22),
(0x3fffd4, 22),
(0x3fffd5, 22),
(0x7fffd9, 23),
(0x3fffd6, 22),
(0x7fffda, 23),
(0x7fffdb, 23),
(0x7fffdc, 23),
(0x7fffdd, 23),
(0x7fffde, 23),
(0xffffeb, 24),
(0x7fffdf, 23),
(0xffffec, 24),
(0xffffed, 24),
(0x3fffd7, 22),
(0x7fffe0, 23),
(0xffffee, 24),
(0x7fffe1, 23),
(0x7fffe2, 23),
(0x7fffe3, 23),
(0x7fffe4, 23),
(0x1fffdc, 21),
(0x3fffd8, 22),
(0x7fffe5, 23),
(0x3fffd9, 22),
(0x7fffe6, 23),
(0x7fffe7, 23),
(0xffffef, 24),
(0x3fffda, 22),
(0x1fffdd, 21),
(0xfffe9, 20),
(0x3fffdb, 22),
(0x3fffdc, 22),
(0x7fffe8, 23),
(0x7fffe9, 23),
(0x1fffde, 21),
(0x7fffea, 23),
(0x3fffdd, 22),
(0x3fffde, 22),
(0xfffff0, 24),
(0x1fffdf, 21),
(0x3fffdf, 22),
(0x7fffeb, 23),
(0x7fffec, 23),
(0x1fffe0, 21),
(0x1fffe1, 21),
(0x3fffe0, 22),
(0x1fffe2, 21),
(0x7fffed, 23),
(0x3fffe1, 22),
(0x7fffee, 23),
(0x7fffef, 23),
(0xfffea, 20),
(0x3fffe2, 22),
(0x3fffe3, 22),
(0x3fffe4, 22),
(0x7ffff0, 23),
(0x3fffe5, 22),
(0x3fffe6, 22),
(0x7ffff1, 23),
(0x3ffffe0, 26),
(0x3ffffe1, 26),
(0xfffeb, 20),
(0x7fff1, 19),
(0x3fffe7, 22),
(0x7ffff2, 23),
(0x3fffe8, 22),
(0x1ffffec, 25),
(0x3ffffe2, 26),
(0x3ffffe3, 26),
(0x3ffffe4, 26),
(0x7ffffde, 27),
(0x7ffffdf, 27),
(0x3ffffe5, 26),
(0xfffff1, 24),
(0x1ffffed, 25),
(0x7fff2, 19),
(0x1fffe3, 21),
(0x3ffffe6, 26),
(0x7ffffe0, 27),
(0x7ffffe1, 27),
(0x3ffffe7, 26),
(0x7ffffe2, 27),
(0xfffff2, 24),
(0x1fffe4, 21),
(0x1fffe5, 21),
(0x3ffffe8, 26),
(0x3ffffe9, 26),
(0xffffffd, 28),
(0x7ffffe3, 27),
(0x7ffffe4, 27),
(0x7ffffe5, 27),
(0xfffec, 20),
(0xfffff3, 24),
(0xfffed, 20),
(0x1fffe6, 21),
(0x3fffe9, 22),
(0x1fffe7, 21),
(0x1fffe8, 21),
(0x7ffff3, 23),
(0x3fffea, 22),
(0x3fffeb, 22),
(0x1ffffee, 25),
(0x1ffffef, 25),
(0xfffff4, 24),
(0xfffff5, 24),
(0x3ffffea, 26),
(0x7ffff4, 23),
(0x3ffffeb, 26),
(0x7ffffe6, 27),
(0x3ffffec, 26),
(0x3ffffed, 26),
(0x7ffffe7, 27),
(0x7ffffe8, 27),
(0x7ffffe9, 27),
(0x7ffffea, 27),
(0x7ffffeb, 27),
(0xffffffe, 28),
(0x7ffffec, 27),
(0x7ffffed, 27),
(0x7ffffee, 27),
(0x7ffffef, 27),
(0x7fffff0, 27),
(0x3ffffee, 26),
(0x3fffffff, 30)
]
static_huffman_tree = None # type: HuffmanNode
@classmethod
def _huffman_encode_char(cls, c):
# type: (Union[str, EOS]) -> Tuple[int, int]
""" huffman_encode_char assumes that the static_huffman_tree was
previously initialized