2021-06-18 12:39:13 -04:00
|
|
|
package burst
|
2021-01-29 19:31:11 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-06-18 12:39:13 -04:00
|
|
|
"github.com/v2fly/v2ray-core/v4/transport/internet/tagged"
|
2021-01-29 19:31:11 -05:00
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/v2fly/v2ray-core/v4/common/net"
|
|
|
|
)
|
|
|
|
|
|
|
|
type pingClient struct {
|
|
|
|
destination string
|
|
|
|
httpClient *http.Client
|
|
|
|
}
|
|
|
|
|
2021-06-18 12:39:13 -04:00
|
|
|
func newPingClient(ctx context.Context, destination string, timeout time.Duration, handler string) *pingClient {
|
2021-01-29 19:31:11 -05:00
|
|
|
return &pingClient{
|
|
|
|
destination: destination,
|
2021-06-18 12:39:13 -04:00
|
|
|
httpClient: newHTTPClient(ctx, handler, timeout),
|
2021-01-29 19:31:11 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func newDirectPingClient(destination string, timeout time.Duration) *pingClient {
|
|
|
|
return &pingClient{
|
|
|
|
destination: destination,
|
|
|
|
httpClient: &http.Client{Timeout: timeout},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-18 12:39:13 -04:00
|
|
|
func newHTTPClient(ctxv context.Context, handler string, timeout time.Duration) *http.Client {
|
2021-01-29 19:31:11 -05:00
|
|
|
tr := &http.Transport{
|
|
|
|
DisableKeepAlives: true,
|
|
|
|
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
|
|
dest, err := net.ParseDestination(network + ":" + addr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-06-18 12:39:13 -04:00
|
|
|
return tagged.Dialer(ctxv, dest, handler)
|
2021-01-29 19:31:11 -05:00
|
|
|
},
|
|
|
|
}
|
|
|
|
return &http.Client{
|
|
|
|
Transport: tr,
|
|
|
|
Timeout: timeout,
|
|
|
|
// don't follow redirect
|
|
|
|
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
|
|
|
return http.ErrUseLastResponse
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// MeasureDelay returns the delay time of the request to dest
|
|
|
|
func (s *pingClient) MeasureDelay() (time.Duration, error) {
|
|
|
|
if s.httpClient == nil {
|
|
|
|
panic("pingClient no initialized")
|
|
|
|
}
|
|
|
|
req, err := http.NewRequest(http.MethodHead, s.destination, nil)
|
|
|
|
if err != nil {
|
|
|
|
return rttFailed, err
|
|
|
|
}
|
|
|
|
start := time.Now()
|
|
|
|
resp, err := s.httpClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return rttFailed, err
|
|
|
|
}
|
|
|
|
// don't wait for body
|
|
|
|
resp.Body.Close()
|
|
|
|
return time.Since(start), nil
|
|
|
|
}
|