forked from MatsuriDayo/NekoBoxForAndroid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
241 lines (210 loc) · 5.36 KB
/
http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package libcore
import (
"bytes"
"context"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"strconv"
"sync"
"github.com/sagernet/sing/common/metadata"
"github.com/sagernet/sing/protocol/socks"
"github.com/sagernet/sing/protocol/socks/socks5"
)
type HTTPClient interface {
RestrictedTLS()
ModernTLS()
PinnedTLS12()
PinnedSHA256(sumHex string)
TrySocks5(port int32)
KeepAlive()
NewRequest() HTTPRequest
Close()
}
type HTTPRequest interface {
SetURL(link string) error
SetMethod(method string)
SetHeader(key string, value string)
SetContent(content []byte)
SetContentString(content string)
SetUserAgent(userAgent string)
Execute() (HTTPResponse, error)
}
type HTTPResponse interface {
GetHeader(string) string
GetContent() ([]byte, error)
GetContentString() (string, error)
WriteTo(path string) error
}
var (
_ HTTPClient = (*httpClient)(nil)
_ HTTPRequest = (*httpRequest)(nil)
_ HTTPResponse = (*httpResponse)(nil)
)
type httpClient struct {
tls tls.Config
client http.Client
transport http.Transport
}
func NewHttpClient() HTTPClient {
client := new(httpClient)
client.client.Transport = &client.transport
client.transport.TLSClientConfig = &client.tls
client.transport.DisableKeepAlives = true
return client
}
func (c *httpClient) ModernTLS() {
c.tls.MinVersion = tls.VersionTLS12
// c.tls.CipherSuites = nekoutils.Map(tls.CipherSuites(), func(it *tls.CipherSuite) uint16 { return it.ID })
}
func (c *httpClient) RestrictedTLS() {
c.tls.MinVersion = tls.VersionTLS13
// c.tls.CipherSuites = nekoutils.Map(nekoutils.Filter(tls.CipherSuites(), func(it *tls.CipherSuite) bool {
// return nekoutils.Contains(it.SupportedVersions, uint16(tls.VersionTLS13))
// }), func(it *tls.CipherSuite) uint16 {
// return it.ID
// })
}
func (c *httpClient) PinnedTLS12() {
c.tls.MinVersion = tls.VersionTLS12
c.tls.MaxVersion = tls.VersionTLS12
}
func (c *httpClient) PinnedSHA256(sumHex string) {
c.tls.VerifyPeerCertificate = func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
for _, rawCert := range rawCerts {
certSum := sha256.Sum256(rawCert)
if sumHex == hex.EncodeToString(certSum[:]) {
return nil
}
}
return errors.New("pinned sha256 sum mismatch")
}
}
func (c *httpClient) TrySocks5(port int32) {
dialer := new(net.Dialer)
c.transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
for {
socksConn, err := dialer.DialContext(ctx, "tcp", "127.0.0.1:"+strconv.Itoa(int(port)))
if err != nil {
break
}
_, err = socks.ClientHandshake5(socksConn, socks5.CommandConnect, metadata.ParseSocksaddr(addr), "", "")
if err != nil {
break
}
return socksConn, err
}
return dialer.DialContext(ctx, network, addr)
}
}
func (c *httpClient) KeepAlive() {
c.transport.ForceAttemptHTTP2 = true
c.transport.DisableKeepAlives = false
}
func (c *httpClient) NewRequest() HTTPRequest {
req := &httpRequest{httpClient: c}
req.request = http.Request{
Method: "GET",
Header: http.Header{},
}
return req
}
func (c *httpClient) Close() {
c.transport.CloseIdleConnections()
}
type httpRequest struct {
*httpClient
request http.Request
}
func (r *httpRequest) SetURL(link string) (err error) {
r.request.URL, err = url.Parse(link)
if err != nil {
return
}
if r.request.URL.User != nil {
user := r.request.URL.User.Username()
password, _ := r.request.URL.User.Password()
r.request.SetBasicAuth(user, password)
}
return
}
func (r *httpRequest) SetMethod(method string) {
r.request.Method = method
}
func (r *httpRequest) SetHeader(key string, value string) {
r.request.Header.Set(key, value)
}
func (r *httpRequest) SetUserAgent(userAgent string) {
r.request.Header.Set("User-Agent", userAgent)
}
func (r *httpRequest) SetContent(content []byte) {
buffer := bytes.Buffer{}
buffer.Write(content)
r.request.Body = io.NopCloser(bytes.NewReader(buffer.Bytes()))
r.request.ContentLength = int64(len(content))
}
func (r *httpRequest) SetContentString(content string) {
r.SetContent([]byte(content))
}
func (r *httpRequest) Execute() (HTTPResponse, error) {
response, err := r.client.Do(&r.request)
if err != nil {
return nil, err
}
httpResp := &httpResponse{Response: response}
if response.StatusCode != http.StatusOK {
return nil, errors.New(httpResp.errorString())
}
return httpResp, nil
}
type httpResponse struct {
*http.Response
getContentOnce sync.Once
content []byte
contentError error
}
func (h *httpResponse) errorString() string {
content, err := h.GetContentString()
if err != nil {
return fmt.Sprint("HTTP ", h.Status)
}
if len(content) > 100 {
content = content[:100] + " ..."
}
return fmt.Sprint("HTTP ", h.Status, ": ", content)
}
func (h *httpResponse) GetHeader(key string) string {
return h.Header.Get(key)
}
func (h *httpResponse) GetContent() ([]byte, error) {
h.getContentOnce.Do(func() {
defer h.Body.Close()
h.content, h.contentError = io.ReadAll(h.Body)
})
return h.content, h.contentError
}
func (h *httpResponse) GetContentString() (string, error) {
content, err := h.GetContent()
if err != nil {
return "", err
}
return string(content), nil
}
func (h *httpResponse) WriteTo(path string) error {
defer h.Body.Close()
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(file, h.Body)
return err
}