You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.7 KiB

  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package icmp
  5. import (
  6. "encoding/binary"
  7. "net"
  8. "runtime"
  9. "golang.org/x/net/internal/socket"
  10. "golang.org/x/net/ipv4"
  11. )
  12. // freebsdVersion is set in sys_freebsd.go.
  13. // See http://www.freebsd.org/doc/en/books/porters-handbook/freebsd-versions.html.
  14. var freebsdVersion uint32
  15. // ParseIPv4Header parses b as an IPv4 header of ICMP error message
  16. // invoking packet, which is contained in ICMP error message.
  17. func ParseIPv4Header(b []byte) (*ipv4.Header, error) {
  18. if len(b) < ipv4.HeaderLen {
  19. return nil, errHeaderTooShort
  20. }
  21. hdrlen := int(b[0]&0x0f) << 2
  22. if hdrlen > len(b) {
  23. return nil, errBufferTooShort
  24. }
  25. h := &ipv4.Header{
  26. Version: int(b[0] >> 4),
  27. Len: hdrlen,
  28. TOS: int(b[1]),
  29. ID: int(binary.BigEndian.Uint16(b[4:6])),
  30. FragOff: int(binary.BigEndian.Uint16(b[6:8])),
  31. TTL: int(b[8]),
  32. Protocol: int(b[9]),
  33. Checksum: int(binary.BigEndian.Uint16(b[10:12])),
  34. Src: net.IPv4(b[12], b[13], b[14], b[15]),
  35. Dst: net.IPv4(b[16], b[17], b[18], b[19]),
  36. }
  37. switch runtime.GOOS {
  38. case "darwin":
  39. h.TotalLen = int(socket.NativeEndian.Uint16(b[2:4]))
  40. case "freebsd":
  41. if freebsdVersion >= 1000000 {
  42. h.TotalLen = int(binary.BigEndian.Uint16(b[2:4]))
  43. } else {
  44. h.TotalLen = int(socket.NativeEndian.Uint16(b[2:4]))
  45. }
  46. default:
  47. h.TotalLen = int(binary.BigEndian.Uint16(b[2:4]))
  48. }
  49. h.Flags = ipv4.HeaderFlags(h.FragOff&0xe000) >> 13
  50. h.FragOff = h.FragOff & 0x1fff
  51. if hdrlen-ipv4.HeaderLen > 0 {
  52. h.Options = make([]byte, hdrlen-ipv4.HeaderLen)
  53. copy(h.Options, b[ipv4.HeaderLen:])
  54. }
  55. return h, nil
  56. }