| 1 | package socks5 |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "log" |
| 6 | "net" |
| 7 | ) |
| 8 | |
| 9 | // UDP remote conn which u want to connect with your dialer. |
| 10 | // Error or OK both replied. |
| 11 | // Addr can be used to associate TCP connection with the coming UDP connection. |
| 12 | func (r *Request) UDP(c net.Conn, serverAddr net.Addr) (net.Addr, error) { |
| 13 | var clientAddr net.Addr |
| 14 | var err error |
| 15 | if bytes.Compare(r.DstPort, []byte{0x00, 0x00}) == 0 { |
| 16 | // If the requested Host/Port is all zeros, the relay should simply use the Host/Port that sent the request. |
| 17 | // https://stackoverflow.com/questions/62283351/how-to-use-socks-5-proxy-with-tidudpclient-properly |
| 18 | clientAddr, err = net.ResolveUDPAddr("udp", c.RemoteAddr().String()) |
| 19 | } else { |
| 20 | clientAddr, err = net.ResolveUDPAddr("udp", r.Address()) |
| 21 | } |
| 22 | if err != nil { |
| 23 | var p *Reply |
| 24 | if r.Atyp == ATYPIPv4 || r.Atyp == ATYPDomain { |
| 25 | p = NewReply(RepHostUnreachable, ATYPIPv4, []byte{0x00, 0x00, 0x00, 0x00}, []byte{0x00, 0x00}) |
| 26 | } else { |
| 27 | p = NewReply(RepHostUnreachable, ATYPIPv6, []byte(net.IPv6zero), []byte{0x00, 0x00}) |
| 28 | } |
| 29 | if _, err := p.WriteTo(c); err != nil { |
| 30 | return nil, err |
| 31 | } |
| 32 | return nil, err |
| 33 | } |
| 34 | if Debug { |
| 35 | log.Println("Client wants to start UDP talk use", clientAddr.String()) |
| 36 | } |
| 37 | a, addr, port, err := ParseAddress(serverAddr.String()) |
| 38 | if err != nil { |
| 39 | var p *Reply |
| 40 | if r.Atyp == ATYPIPv4 || r.Atyp == ATYPDomain { |
| 41 | p = NewReply(RepHostUnreachable, ATYPIPv4, []byte{0x00, 0x00, 0x00, 0x00}, []byte{0x00, 0x00}) |
| 42 | } else { |
| 43 | p = NewReply(RepHostUnreachable, ATYPIPv6, []byte(net.IPv6zero), []byte{0x00, 0x00}) |
| 44 | } |
| 45 | if _, err := p.WriteTo(c); err != nil { |
| 46 | return nil, err |
| 47 | } |
| 48 | return nil, err |
| 49 | } |
| 50 | if a == ATYPDomain { |
| 51 | addr = addr[1:] |
| 52 | } |
| 53 | p := NewReply(RepSuccess, a, addr, port) |
| 54 | if _, err := p.WriteTo(c); err != nil { |
| 55 | return nil, err |
| 56 | } |
| 57 | |
| 58 | return clientAddr, nil |
| 59 | } |