forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy_url.go
More file actions
77 lines (68 loc) · 2.35 KB
/
Copy pathproxy_url.go
File metadata and controls
77 lines (68 loc) · 2.35 KB
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
package common
import (
"fmt"
"net"
"net/url"
"strconv"
"strings"
)
// ParseProxyURLStrict validates and normalizes a proxy URL for persistence.
func ParseProxyURLStrict(rawProxyURL string) (*url.URL, error) {
parsedURL, _, err := parseProxyURL(rawProxyURL, false)
return parsedURL, err
}
// ParseProxyURLRuntime validates and normalizes a proxy URL for runtime use.
// The boolean result reports whether a legacy path, query, or fragment was removed.
func ParseProxyURLRuntime(rawProxyURL string) (*url.URL, bool, error) {
return parseProxyURL(rawProxyURL, true)
}
func parseProxyURL(rawProxyURL string, allowLegacySuffix bool) (*url.URL, bool, error) {
trimmedProxyURL := strings.TrimSpace(rawProxyURL)
if trimmedProxyURL == "" {
return nil, false, nil
}
parsedURL, err := url.Parse(trimmedProxyURL)
if err != nil {
return nil, false, fmt.Errorf("invalid proxy URL")
}
parsedURL.Scheme = strings.ToLower(parsedURL.Scheme)
switch parsedURL.Scheme {
case "http", "https", "socks5", "socks5h":
default:
return nil, false, fmt.Errorf("proxy URL must use http, https, socks5, or socks5h")
}
if parsedURL.Hostname() == "" {
return nil, false, fmt.Errorf("proxy URL must include a host")
}
if portText := parsedURL.Port(); portText != "" {
port, err := strconv.Atoi(portText)
if err != nil || port < 1 || port > 65535 {
return nil, false, fmt.Errorf("proxy URL must include a valid port")
}
}
hasQuery := parsedURL.RawQuery != "" || parsedURL.ForceQuery
hasFragment := strings.Contains(trimmedProxyURL, "#")
escapedPath := parsedURL.EscapedPath()
hasNonRootPath := escapedPath != "" && escapedPath != "/"
legacySuffixStripped := hasQuery || hasFragment || hasNonRootPath
if !allowLegacySuffix {
switch {
case hasQuery:
return nil, false, fmt.Errorf("proxy URL must not include a query")
case hasFragment:
return nil, false, fmt.Errorf("proxy URL must not include a fragment")
case hasNonRootPath:
return nil, false, fmt.Errorf("proxy URL must not include a path")
}
}
parsedURL.Path = ""
parsedURL.RawPath = ""
parsedURL.RawQuery = ""
parsedURL.ForceQuery = false
parsedURL.Fragment = ""
parsedURL.RawFragment = ""
if (parsedURL.Scheme == "socks5" || parsedURL.Scheme == "socks5h") && parsedURL.Port() == "" {
parsedURL.Host = net.JoinHostPort(parsedURL.Hostname(), "1080")
}
return parsedURL, legacySuffixStripped, nil
}