Skip to content

Commit 031b9ca

Browse files
committed
Compute TCP checksum
Construct the pseudoheader and ones complement that with the serialized packet (and a zero'd out checksum field).
1 parent d92c0b5 commit 031b9ca

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

lib/Packet.ml

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,21 @@ module Tcp = struct
202202
let bits = Cstruct.shift bits sizeof_tcp in
203203
Cstruct.blit pkt.payload 0 bits 0 (Cstruct.len pkt.payload)
204204

205+
206+
let checksum (bits : Cstruct.t) (src : nwAddr) (dst : nwAddr) (pkt : t) =
207+
(* XXX(seliopou): pseudo_header's allocated on every call. Would it be safe
208+
* to allocate once and reuse? *)
209+
let pseudo_header = Cstruct.create 12 in
210+
Cstruct.BE.set_uint32 pseudo_header 0 src;
211+
Cstruct.BE.set_uint32 pseudo_header 4 dst;
212+
Cstruct.set_uint8 pseudo_header 8 0;
213+
Cstruct.set_uint8 pseudo_header 9 0x6;
214+
Cstruct.BE.set_uint16 pseudo_header 10 (len pkt);
215+
set_tcp_chksum bits 0;
216+
let chksum = Checksum.ones_complement_list
217+
[pseudo_header; Cstruct.sub bits 0 (len pkt)] in
218+
set_tcp_chksum bits chksum
219+
205220
end
206221

207222
module Udp = struct
@@ -883,7 +898,8 @@ module Ip = struct
883898
let bits = Cstruct.shift bits header_len in
884899
match pkt.tp with
885900
| Tcp tcp ->
886-
Tcp.marshal bits tcp
901+
Tcp.marshal bits tcp;
902+
Tcp.checksum bits pkt.src pkt.dst tcp
887903
| Udp udp ->
888904
Udp.marshal bits udp
889905
| Icmp icmp ->

0 commit comments

Comments
 (0)