2020-06-04 23:42:44 +01:00
|
|
|
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package packet
|
|
|
|
|
2020-11-11 03:09:47 +00:00
|
|
|
import "encoding/binary"
|
|
|
|
|
2020-11-11 06:26:00 +00:00
|
|
|
// udpHeaderLength is the size of the UDP packet header, not including
|
|
|
|
// the outer IP header.
|
|
|
|
const udpHeaderLength = 8
|
|
|
|
|
|
|
|
// UDP4Header is an IPv4+UDP header.
|
2020-11-09 23:34:03 +00:00
|
|
|
type UDP4Header struct {
|
|
|
|
IP4Header
|
2020-06-04 23:42:44 +01:00
|
|
|
SrcPort uint16
|
|
|
|
DstPort uint16
|
|
|
|
}
|
|
|
|
|
2020-11-11 06:26:00 +00:00
|
|
|
// Len implements Header.
|
|
|
|
func (h UDP4Header) Len() int {
|
|
|
|
return h.IP4Header.Len() + udpHeaderLength
|
2020-06-04 23:42:44 +01:00
|
|
|
}
|
|
|
|
|
2020-11-11 06:26:00 +00:00
|
|
|
// Marshal implements Header.
|
2020-11-09 23:34:03 +00:00
|
|
|
func (h UDP4Header) Marshal(buf []byte) error {
|
2020-11-11 05:12:46 +00:00
|
|
|
if len(buf) < h.Len() {
|
2020-06-04 23:42:44 +01:00
|
|
|
return errSmallBuffer
|
|
|
|
}
|
|
|
|
if len(buf) > maxPacketLength {
|
|
|
|
return errLargePacket
|
|
|
|
}
|
|
|
|
// The caller does not need to set this.
|
|
|
|
h.IPProto = UDP
|
|
|
|
|
2020-11-09 23:34:03 +00:00
|
|
|
length := len(buf) - h.IP4Header.Len()
|
2020-11-11 03:09:47 +00:00
|
|
|
binary.BigEndian.PutUint16(buf[20:22], h.SrcPort)
|
|
|
|
binary.BigEndian.PutUint16(buf[22:24], h.DstPort)
|
|
|
|
binary.BigEndian.PutUint16(buf[24:26], uint16(length))
|
|
|
|
binary.BigEndian.PutUint16(buf[26:28], 0) // blank checksum
|
2020-06-04 23:42:44 +01:00
|
|
|
|
|
|
|
// UDP checksum with IP pseudo header.
|
2020-11-11 06:26:00 +00:00
|
|
|
h.IP4Header.marshalPseudo(buf)
|
|
|
|
binary.BigEndian.PutUint16(buf[26:28], ip4Checksum(buf[ip4PseudoHeaderOffset:]))
|
2020-06-04 23:42:44 +01:00
|
|
|
|
2020-11-09 23:34:03 +00:00
|
|
|
h.IP4Header.Marshal(buf)
|
2020-06-04 23:42:44 +01:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-11-11 06:26:00 +00:00
|
|
|
// ToResponse implements Header.
|
2020-11-09 23:34:03 +00:00
|
|
|
func (h *UDP4Header) ToResponse() {
|
2020-06-04 23:42:44 +01:00
|
|
|
h.SrcPort, h.DstPort = h.DstPort, h.SrcPort
|
2020-11-09 23:34:03 +00:00
|
|
|
h.IP4Header.ToResponse()
|
2020-06-04 23:42:44 +01:00
|
|
|
}
|