// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package socks

import (
	
	
	
	
	
	
)

var (
	noDeadline   = time.Time{}
	aLongTimeAgo = time.Unix(1, 0)
)

func ( *Dialer) ( context.Context,  net.Conn,  string) ( net.Addr,  error) {
	, ,  := splitHostPort()
	if  != nil {
		return nil, 
	}
	if ,  := .Deadline();  && !.IsZero() {
		.SetDeadline()
		defer .SetDeadline(noDeadline)
	}
	if  != context.Background() {
		 := make(chan error, 1)
		 := make(chan struct{})
		defer func() {
			close()
			if  == nil {
				 = <-
			}
		}()
		go func() {
			select {
			case <-.Done():
				.SetDeadline(aLongTimeAgo)
				 <- .Err()
			case <-:
				 <- nil
			}
		}()
	}

	var  net.Addr
	if .version() == Version4 {
		,  = .connect4(, , , )
	} else {
		,  = .connect5(, , , )
	}
	return , 
}

// maxSocks4aDomainLen is the maximum domain name length accepted for SOCKS4a.
// Matches the practical FQDN limit used by SOCKS5 in this package.
const maxSocks4aDomainLen = 255

// connect4 implements the SOCKS4 and SOCKS4a CONNECT handshake.
func ( *Dialer) ( context.Context,  net.Conn,  string,  int) (net.Addr, error) {
	if  := validateSocks4CString(.UserID, "user ID");  != nil {
		return nil, 
	}

	var (
		     net.IP
		 string
	)
	if  := net.ParseIP();  != nil {
		 := .To4()
		if  == nil {
			return nil, errors.New("SOCKS4 does not support IPv6 addresses")
		}
		 = 
	} else if .Socks4A {
		// SOCKS4a: use invalid IP 0.0.0.x (x != 0) and append domain after userid.
		if  == "" {
			return nil, errors.New("SOCKS4a domain name is empty")
		}
		if len() > maxSocks4aDomainLen {
			return nil, errors.New("SOCKS4a domain name too long")
		}
		if  := validateSocks4CString(, "domain name");  != nil {
			return nil, 
		}
		 = net.IPv4(0, 0, 0, 1).To4()
		 = 
	} else {
		,  := net.DefaultResolver.LookupIP(, "ip4", )
		if  != nil {
			return nil, 
		}
		if len() == 0 {
			return nil, errors.New("no IPv4 address found for host")
		}
		 = [0].To4()
		if  == nil {
			return nil, errors.New("no IPv4 address found for host")
		}
	}

	// VN | CD | DSTPORT | DSTIP | USERID | NULL [| DOMAIN | NULL]
	 := make([]byte, 0, 9+len(.UserID)+len()+1)
	 = append(, Version4, byte(.cmd))
	 = append(, byte(>>8), byte())
	 = append(, ...)
	 = append(, .UserID...)
	 = append(, 0)
	if  != "" {
		 = append(, ...)
		 = append(, 0)
	}
	if ,  := .Write();  != nil {
		return nil, 
	}

	// Reply is always 8 bytes: VN | CD | DSTPORT | DSTIP
	var  [8]byte
	if ,  := io.ReadFull(, [:]);  != nil {
		return nil, 
	}
	// Spec says VN should be 0; some servers incorrectly echo 4.
	if [0] != 0 && [0] != Version4 {
		return nil, errors.New("unexpected protocol version " + strconv.Itoa(int([0])))
	}
	if  := Reply([1]);  != Status4Granted {
		return nil, errors.New(.String())
	}

	 := &Addr{
		IP:   net.IPv4([4], [5], [6], [7]),
		Port: int([2])<<8 | int([3]),
	}
	return , nil
}

// validateSocks4CString rejects strings that would truncate a SOCKS4 C-string field.
func validateSocks4CString(,  string) error {
	for  := 0;  < len(); ++ {
		if [] == 0 {
			return errors.New("invalid SOCKS4 " +  + ": contains NUL")
		}
	}
	return nil
}

// connect5 implements the SOCKS5 CONNECT handshake.
func ( *Dialer) ( context.Context,  net.Conn,  string,  int) (net.Addr, error) {
	 := make([]byte, 0, 6+len()) // the size here is just an estimate
	 = append(, Version5)
	if len(.AuthMethods) == 0 || .Authenticate == nil {
		 = append(, 1, byte(AuthMethodNotRequired))
	} else {
		 := .AuthMethods
		if len() > 255 {
			return nil, errors.New("too many authentication methods")
		}
		 = append(, byte(len()))
		for ,  := range  {
			 = append(, byte())
		}
	}
	if ,  := .Write();  != nil {
		return nil, 
	}

	if ,  := io.ReadFull(, [:2]);  != nil {
		return nil, 
	}
	if [0] != Version5 {
		return nil, errors.New("unexpected protocol version " + strconv.Itoa(int([0])))
	}
	 := AuthMethod([1])
	if  == AuthMethodNoAcceptableMethods {
		return nil, errors.New("no acceptable authentication methods")
	}
	if .Authenticate != nil {
		if  := .Authenticate(, , );  != nil {
			return nil, 
		}
	}

	 = [:0]
	 = append(, Version5, byte(.cmd), 0)
	if  := net.ParseIP();  != nil {
		if  := .To4();  != nil {
			 = append(, AddrTypeIPv4)
			 = append(, ...)
		} else if  := .To16();  != nil {
			 = append(, AddrTypeIPv6)
			 = append(, ...)
		} else {
			return nil, errors.New("unknown address type")
		}
	} else {
		if len() > 255 {
			return nil, errors.New("FQDN too long")
		}
		 = append(, AddrTypeFQDN)
		 = append(, byte(len()))
		 = append(, ...)
	}
	 = append(, byte(>>8), byte())
	if ,  := .Write();  != nil {
		return nil, 
	}

	if ,  := io.ReadFull(, [:4]);  != nil {
		return nil, 
	}
	if [0] != Version5 {
		return nil, errors.New("unexpected protocol version " + strconv.Itoa(int([0])))
	}
	if  := Reply([1]);  != StatusSucceeded {
		return nil, errors.New("unknown error " + .String())
	}
	if [2] != 0 {
		return nil, errors.New("non-zero reserved field")
	}
	 := 2
	var  Addr
	switch [3] {
	case AddrTypeIPv4:
		 += net.IPv4len
		.IP = make(net.IP, net.IPv4len)
	case AddrTypeIPv6:
		 += net.IPv6len
		.IP = make(net.IP, net.IPv6len)
	case AddrTypeFQDN:
		if ,  := io.ReadFull(, [:1]);  != nil {
			return nil, 
		}
		 += int([0])
	default:
		return nil, errors.New("unknown address type " + strconv.Itoa(int([3])))
	}
	if cap() <  {
		 = make([]byte, )
	} else {
		 = [:]
	}
	if ,  := io.ReadFull(, );  != nil {
		return nil, 
	}
	if .IP != nil {
		copy(.IP, )
	} else {
		.Name = string([:len()-2])
	}
	.Port = int([len()-2])<<8 | int([len()-1])
	return &, nil
}

func splitHostPort( string) (string, int, error) {
	, ,  := net.SplitHostPort()
	if  != nil {
		return "", 0, 
	}
	,  := strconv.Atoi()
	if  != nil {
		return "", 0, 
	}
	if 1 >  ||  > 0xffff {
		return "", 0, errors.New("port number out of range " + )
	}
	return , , nil
}