proxy_protocol_initializer.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. package cproxy
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. "strings"
  7. )
  8. type proxyProtocolInitializer struct{}
  9. func newProxyProtocolInitializer() *proxyProtocolInitializer {
  10. return &proxyProtocolInitializer{}
  11. }
  12. func (this *proxyProtocolInitializer) Initialize(client, server Socket) bool {
  13. header := formatHeader(client.RemoteAddr(), server.RemoteAddr())
  14. _, err := io.WriteString(server, header)
  15. return err == nil
  16. }
  17. func formatHeader(client, server net.Addr) string {
  18. clientAddress, clientPort := parseAddress(client.String())
  19. serverAddress, serverPort := parseAddress(server.String())
  20. if strings.Contains(clientAddress, ":") {
  21. return fmt.Sprintf(proxyProtocolIPv6Preamble, clientAddress, serverAddress, clientPort, serverPort)
  22. }
  23. return fmt.Sprintf(proxyProtocolIPv4Preamble, clientAddress, serverAddress, clientPort, serverPort)
  24. }
  25. func parseAddress(address string) (string, string) {
  26. address, port, _ := net.SplitHostPort(address)
  27. return address, port
  28. }
  29. const proxyProtocolIPv4Preamble = "PROXY TCP4 %s %s %s %s\r\n"
  30. const proxyProtocolIPv6Preamble = "PROXY TCP6 %s %s %s %s\r\n"