packet.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package firewall
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/netip"
  6. )
  7. type m map[string]interface{}
  8. const (
  9. ProtoAny = 0 // When we want to handle HOPOPT (0) we can change this, if ever
  10. ProtoTCP = 6
  11. ProtoUDP = 17
  12. ProtoICMP = 1
  13. ProtoICMPv6 = 58
  14. PortAny = 0 // Special value for matching `port: any`
  15. PortFragment = -1 // Special value for matching `port: fragment`
  16. )
  17. type Packet struct {
  18. LocalAddr netip.Addr
  19. RemoteAddr netip.Addr
  20. LocalPort uint16
  21. RemotePort uint16
  22. Protocol uint8
  23. Fragment bool
  24. }
  25. func (fp *Packet) Copy() *Packet {
  26. return &Packet{
  27. LocalAddr: fp.LocalAddr,
  28. RemoteAddr: fp.RemoteAddr,
  29. LocalPort: fp.LocalPort,
  30. RemotePort: fp.RemotePort,
  31. Protocol: fp.Protocol,
  32. Fragment: fp.Fragment,
  33. }
  34. }
  35. func (fp Packet) MarshalJSON() ([]byte, error) {
  36. var proto string
  37. switch fp.Protocol {
  38. case ProtoTCP:
  39. proto = "tcp"
  40. case ProtoICMP:
  41. proto = "icmp"
  42. case ProtoUDP:
  43. proto = "udp"
  44. default:
  45. proto = fmt.Sprintf("unknown %v", fp.Protocol)
  46. }
  47. return json.Marshal(m{
  48. "LocalAddr": fp.LocalAddr.String(),
  49. "RemoteAddr": fp.RemoteAddr.String(),
  50. "LocalPort": fp.LocalPort,
  51. "RemotePort": fp.RemotePort,
  52. "Protocol": proto,
  53. "Fragment": fp.Fragment,
  54. })
  55. }