2020-06-04 22:42:44 +00: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-06-04 22:42:44 +00:00
|
|
|
// UDPHeader represents an UDP packet header.
|
2020-11-09 23:34:03 +00:00
|
|
|
type UDP4Header struct {
|
|
|
|
IP4Header
|
2020-06-04 22:42:44 +00:00
|
|
|
SrcPort uint16
|
|
|
|
DstPort uint16
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
2020-11-11 05:12:46 +00:00
|
|
|
// udpHeaderLength is the size of the UDP packet header, not
|
|
|
|
// including the outer IP header.
|
2020-06-04 22:42:44 +00:00
|
|
|
udpHeaderLength = 8
|
|
|
|
)
|
|
|
|
|
2020-11-09 23:34:03 +00:00
|
|
|
func (UDP4Header) Len() int {
|
2020-11-11 05:12:46 +00:00
|
|
|
return ip4HeaderLength + udpHeaderLength
|
2020-06-04 22:42:44 +00:00
|
|
|
}
|
|
|
|
|
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 22:42:44 +00: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 22:42:44 +00:00
|
|
|
|
|
|
|
// UDP checksum with IP pseudo header.
|
2020-11-11 05:12:46 +00:00
|
|
|
h.IP4Header.MarshalPseudo(buf)
|
2020-11-11 03:09:47 +00:00
|
|
|
binary.BigEndian.PutUint16(buf[26:28], ipChecksum(buf[8:]))
|
2020-06-04 22:42:44 +00:00
|
|
|
|
2020-11-09 23:34:03 +00:00
|
|
|
h.IP4Header.Marshal(buf)
|
2020-06-04 22:42:44 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-11-09 23:34:03 +00:00
|
|
|
func (h *UDP4Header) ToResponse() {
|
2020-06-04 22:42:44 +00:00
|
|
|
h.SrcPort, h.DstPort = h.DstPort, h.SrcPort
|
2020-11-09 23:34:03 +00:00
|
|
|
h.IP4Header.ToResponse()
|
2020-06-04 22:42:44 +00:00
|
|
|
}
|