forked from Carthage/Carthage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Proxy.swift
84 lines (63 loc) · 2.56 KB
/
Proxy.swift
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
import Foundation
struct Proxy {
let connectionProxyDictionary: [AnyHashable: Any]?
init(environment: [String: String]) {
let http = Proxy.makeHTTPDictionary(environment)
let https = Proxy.makeHTTPSDictionary(environment)
let noProxy = Proxy.makeNoProxyDictionary(environment)
let combined = http.merging(https) { _, property in property }.merging(noProxy) { _, property in property }
// the proxy dictionary on URLSessionConfiguration must be nil so that it can default to the system proxy.
connectionProxyDictionary = combined.isEmpty ? nil : combined
}
private static func makeHTTPDictionary(_ environment: [String: String]) -> [AnyHashable: Any] {
let vars = ["http_proxy", "HTTP_PROXY"]
guard let proxyURL = URL(string: vars.compactMap { environment[$0] }.first ?? "") else {
return [:]
}
var dictionary: [AnyHashable: Any] = [:]
dictionary[kCFNetworkProxiesHTTPEnable] = true
dictionary[kCFNetworkProxiesHTTPProxy] = proxyURL.host
if let port = proxyURL.port {
dictionary[kCFNetworkProxiesHTTPPort] = port
}
return dictionary
}
private static func makeHTTPSDictionary(_ environment: [String: String]) -> [AnyHashable: Any] {
let vars = ["https_proxy", "HTTPS_PROXY"]
guard let proxyURL = URL(string: vars.compactMap { environment[$0] }.first ?? "") else {
return [:]
}
var dictionary: [AnyHashable: Any] = [:]
dictionary[kCFNetworkProxiesHTTPSEnable] = true
dictionary[kCFNetworkProxiesHTTPSProxy] = proxyURL.host
if let port = proxyURL.port {
dictionary[kCFNetworkProxiesHTTPSPort] = port
}
return dictionary
}
private static func makeNoProxyDictionary(_ environment: [String: String]) -> [AnyHashable: Any] {
#if os(OSX)
let vars = ["no_proxy", "NO_PROXY"]
guard
let noProxyList: [String] = (vars.compactMap { environment[$0] }.first)?.split(separator: ",").compactMap({ String($0) }),
!noProxyList.isEmpty
else { return [:] }
let dictionary: [AnyHashable: Any] = [
kCFNetworkProxiesExceptionsList: noProxyList
]
return dictionary
#else
return [:]
#endif
}
}
extension Proxy {
static let `default`: Proxy = Proxy(environment: ProcessInfo.processInfo.environment)
}
extension URLSession {
public static var proxiedSession: URLSession {
let configuration = URLSessionConfiguration.default
configuration.connectionProxyDictionary = Proxy.default.connectionProxyDictionary
return URLSession(configuration: configuration)
}
}