forked from Carthage/Carthage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Proxy.swift
53 lines (40 loc) · 1.57 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
import Foundation
struct Proxy {
let connectionProxyDictionary: [AnyHashable: Any]?
init(environment: [String: String]) {
let http = Proxy.makeHTTPDictionary(environment)
let https = Proxy.makeHTTPSDictionary(environment)
let combined = http.merging(https) { _, 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
}
}
extension Proxy {
static let `default`: Proxy = Proxy(environment: ProcessInfo.processInfo.environment)
}