udpproxy_direct.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package vnet
  2. import (
  3. "fmt"
  4. "net"
  5. )
  6. // Deliver directly send packet to vnet or real-server.
  7. // For example, we can use this API to simulate the REPLAY ATTACK.
  8. func (v *UDPProxy) Deliver(sourceAddr, destAddr net.Addr, b []byte) (nn int, err error) {
  9. v.workers.Range(func(key, value interface{}) bool {
  10. if nn, err = value.(*aUDPProxyWorker).Deliver(sourceAddr, destAddr, b); err != nil {
  11. return false // Fail, abort.
  12. } else if nn == len(b) {
  13. return false // Done.
  14. }
  15. return true // Deliver by next worker.
  16. })
  17. return
  18. }
  19. func (v *aUDPProxyWorker) Deliver(sourceAddr, destAddr net.Addr, b []byte) (nn int, err error) {
  20. addr, ok := sourceAddr.(*net.UDPAddr)
  21. if !ok {
  22. return 0, fmt.Errorf("invalid addr %v", sourceAddr) // nolint:goerr113
  23. }
  24. // nolint:godox // TODO: Support deliver packet from real server to vnet.
  25. // If packet is from vnet, proxy to real server.
  26. var realSocket *net.UDPConn
  27. if value, ok := v.endpoints.Load(addr.String()); !ok {
  28. return 0, nil
  29. } else { // nolint:golint
  30. realSocket = value.(*net.UDPConn)
  31. }
  32. // Send to real server.
  33. if _, err := realSocket.Write(b); err != nil {
  34. return 0, err
  35. }
  36. return len(b), nil
  37. }