56c557179a366c3ed0efa85855099320e822d0e5
[tpg/acess2.git] / Tools / NetTest_Runner / tcp.c
1 /*
2  */
3 #include "common.h"
4 #include "tcp.h"
5 #include "ip.h"
6 #include "test.h"       // TEST_ASSERT
7 #include <string.h>
8
9 typedef struct {
10         uint16_t        SPort;
11         uint16_t        DPort;
12         uint32_t        Seq;
13         uint32_t        Ack;
14         uint8_t         DataOfs;
15         uint8_t         Flags;
16         uint16_t        Window;
17         uint16_t        Checksum;
18         uint16_t        UrgPtr;
19 } __attribute__((packed)) tTCPHeader;
20
21 // === CODE ===
22 void TCP_Send(int IF, int AF, const void *IP, short sport, short dport,
23         uint32_t seq, uint32_t ack, uint8_t flags, uint16_t window,
24         size_t data_len, const void *data
25         )
26 {
27         tTCPHeader      hdr;
28         hdr.SPort = htons(sport);
29         hdr.DPort = htons(dport);
30         hdr.Seq = htonl(seq);
31         hdr.Ack = htonl(ack);
32         hdr.DataOfs = sizeof(hdr)/4;
33         hdr.Flags = flags;
34         hdr.Window = htons(window);
35         hdr.Checksum = htons(0);
36         hdr.UrgPtr = htons(0);
37
38         uint16_t        checksum = IP_CHECKSUM_START;
39         checksum = IP_Checksum(checksum, sizeof(hdr), &hdr);
40         checksum = IP_Checksum(checksum, data_len, data);
41         hdr.Checksum = htons( checksum );
42
43         size_t  buflens[] = {sizeof(hdr), data_len};
44         const void *bufs[] = {&hdr, data};
45         IP_Send(IF, AF, BLOB(HOST_IP), IP, IPPROTO_TCP, 2, buflens, bufs);
46 }
47
48 bool TCP_Pkt_Check(size_t len, const void *data, size_t *out_ofs, int AF, const void *IP, short sport, short dport,
49         uint8_t flags)
50 {
51         size_t  ofs;
52         if( !IP_Pkt_Check(len, data, &ofs, AF, IP, BLOB(HOST_IP), IPPROTO_TCP) )
53                 return false;
54         
55         tTCPHeader      hdr;
56         TEST_ASSERT_REL(len - ofs, >=, sizeof(hdr));    
57         memcpy(&hdr, (char*)data + ofs, sizeof(hdr));
58         
59         TEST_ASSERT_REL( ntohs(hdr.SPort), ==, sport );
60         TEST_ASSERT_REL( ntohs(hdr.DPort), ==, dport );
61         // TODO: Checks on Seq/Ack
62         TEST_ASSERT_REL( hdr.Flags, ==, flags);
63
64         uint16_t        real_cksum = htons(hdr.Checksum);
65         hdr.Checksum = 0;
66         uint16_t        calc_cksum = IP_CHECKSUM_START;
67         calc_cksum = IP_Checksum(calc_cksum, sizeof(hdr), &hdr);
68         calc_cksum = IP_Checksum(calc_cksum, len - ofs - sizeof(hdr), (char*)data+ofs+sizeof(hdr));
69         TEST_ASSERT_REL( real_cksum, ==, calc_cksum );
70         
71         *out_ofs = ofs + sizeof(hdr);
72         return true;
73 }
74

UCC git Repository :: git.ucc.asn.au