summaryrefslogtreecommitdiff
path: root/external/construct/protocols/layer4/tcp.py
blob: 44f1bd713f74ad604178342ace5dc9a7d3f6a81c (plain) (blame)
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
"""
Transmission Control Protocol (TCP/IP protocol stack)
"""
from construct import *
from binascii import unhexlify
import six


tcp_header = Struct("tcp_header",
    UBInt16("source"),
    UBInt16("destination"),
    UBInt32("seq"),
    UBInt32("ack"),
    EmbeddedBitStruct(
        ExprAdapter(Nibble("header_length"), 
            encoder = lambda obj, ctx: obj / 4,
            decoder = lambda obj, ctx: obj * 4,
        ),
        Padding(3),
        Struct("flags",
            Flag("ns"),
            Flag("cwr"),
            Flag("ece"),
            Flag("urg"),
            Flag("ack"),
            Flag("psh"),
            Flag("rst"),
            Flag("syn"),
            Flag("fin"),
        ),
    ),
    UBInt16("window"),
    UBInt16("checksum"),
    UBInt16("urgent"),
    Field("options", lambda ctx: ctx.header_length - 20),
)

if __name__ == "__main__":
    cap = unhexlify(six.b("0db5005062303fb21836e9e650184470c9bc0000"))
    
    obj = tcp_header.parse(cap)
    print (obj)
    built = tcp_header.build(obj)
    print (built)
    assert cap == built