-
Notifications
You must be signed in to change notification settings - Fork 189
/
Copy pathhttp.ex
280 lines (221 loc) · 6.53 KB
/
http.ex
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
defmodule Hex.HTTP do
@moduledoc false
@request_timeout 15_000
@request_redirects 3
@request_retries 2
def request(method, url, headers, body, opts \\ []) do
headers = build_headers(headers)
timeout =
opts[:timeout] ||
Hex.State.fetch!(:http_timeout, fn val -> if is_integer(val), do: val * 1000 end) ||
@request_timeout
http_opts = build_http_opts(url, timeout)
opts = [body_format: :binary]
request = build_request(url, headers, body)
profile = Hex.State.fetch!(:httpc_profile)
retry(method, request, @request_retries, fn request ->
redirect(request, @request_redirects, fn request ->
timeout(request, timeout, fn request ->
:httpc.request(method, request, http_opts, opts, profile)
|> handle_response()
end)
end)
end)
end
defp build_headers(headers) do
default_headers = %{'user-agent' => user_agent()}
headers = Enum.into(headers, %{})
Map.merge(default_headers, headers)
end
defp build_http_opts(url, timeout) do
[
relaxed: true,
timeout: timeout,
ssl: Hex.HTTP.SSL.ssl_opts(url),
autoredirect: false
] ++ proxy_config(url)
end
defp build_request(url, headers, body) do
url = Hex.string_to_charlist(url)
headers = Map.to_list(headers)
case body do
{content_type, body} ->
{url, headers, content_type, body}
nil ->
{url, headers}
end
end
defp retry(:get, request, times, fun) do
result =
case fun.(request) do
{:http_error, _, _} = error ->
{:retry, error}
{:error, :socket_closed_remotely} = error ->
{:retry, error}
other ->
{:noretry, other}
end
case result do
{:retry, _} when times > 0 ->
retry(:get, request, times - 1, fun)
{_other, result} ->
result
end
end
defp retry(_method, request, _times, fun), do: fun.(request)
defp redirect(request, times, fun) do
case fun.(request) do
{:ok, response} ->
case handle_redirect(response) do
{:ok, location} when times > 0 ->
request
|> update_request(location)
|> redirect(times - 0, fun)
{:ok, _location} ->
Mix.raise("Too many redirects")
:error ->
{:ok, response}
end
{:error, reason} ->
{:error, reason}
end
end
defp handle_redirect({code, _body, headers})
when code in [301, 302, 303, 307, 308] do
headers = Enum.into(headers, %{})
if location = headers['location'] do
{:ok, location}
else
:error
end
end
defp handle_redirect(_) do
:error
end
defp update_request({_url, headers, content_type, body}, new_url) do
{new_url, headers, content_type, body}
end
defp update_request({_url, headers}, new_url) do
{new_url, headers}
end
defp timeout(request, timeout, fun) do
Task.async(fn ->
fun.(request)
end)
|> task_await(:timeout, timeout)
end
defp task_await(%Task{ref: ref, pid: pid} = task, reason, timeout) do
receive do
{^ref, result} ->
Process.demonitor(ref, [:flush])
result
{:DOWN, ^ref, _, _, _reason} ->
{:error, :timeout}
after
timeout ->
Process.unlink(pid)
Process.exit(pid, reason)
task_await(task, :kill, timeout)
end
end
defp handle_response({:ok, {{_version, code, _reason}, headers, body}}) do
headers = Enum.into(headers, %{})
handle_hex_message(headers['x-hex-message'])
{:ok, {code, unzip(body, headers), headers}}
end
defp handle_response({:error, term}) do
{:error, term}
end
defp unzip(body, headers) do
content_encoding = List.to_string(headers['content-encoding'] || '')
if String.contains?(content_encoding, "gzip") do
:zlib.gunzip(body)
else
body
end
end
def proxy_config(url) do
{http_proxy, https_proxy} = proxy_setup()
proxy_auth(URI.parse(url), http_proxy, https_proxy)
end
defp proxy_setup do
http_proxy = (proxy = Hex.State.fetch!(:http_proxy)) && proxy(:http, proxy)
https_proxy = (proxy = Hex.State.fetch!(:https_proxy)) && proxy(:https, proxy)
{http_proxy, https_proxy}
end
defp proxy(scheme, proxy) do
uri = URI.parse(proxy)
if uri.host && uri.port do
host = Hex.string_to_charlist(uri.host)
:httpc.set_options([{proxy_scheme(scheme), {{host, uri.port}, []}}], :hex)
end
uri
end
defp proxy_scheme(scheme) do
case scheme do
:http -> :proxy
:https -> :https_proxy
end
end
defp proxy_auth(%URI{scheme: "http"}, http_proxy, _https_proxy) do
proxy_auth(http_proxy)
end
defp proxy_auth(%URI{scheme: "https"}, _http_proxy, https_proxy) do
proxy_auth(https_proxy)
end
defp proxy_auth(nil) do
[]
end
defp proxy_auth(%URI{userinfo: nil}) do
[]
end
defp proxy_auth(%URI{userinfo: auth}) do
destructure [user, pass], String.split(auth, ":", parts: 2)
user = Hex.string_to_charlist(user)
pass = Hex.string_to_charlist(pass || "")
[proxy_auth: {user, pass}]
end
defp user_agent do
'Hex/#{Hex.version()} (Elixir/#{System.version()}) (OTP/#{Hex.Utils.otp_version()})'
end
def handle_hex_message(nil) do
:ok
end
def handle_hex_message(header) do
{message, level} = :binary.list_to_bin(header) |> parse_hex_message
case level do
"warn" -> Hex.Shell.info("API warning: " <> message)
"fatal" -> Hex.Shell.error("API error: " <> message)
_ -> :ok
end
end
@space [?\s, ?\t]
defp parse_hex_message(message) do
{message, rest} = skip_ws(message) |> quoted
level = skip_ws(rest) |> opt_level
{message, level}
end
defp skip_ws(<<char, rest::binary>>) when char in @space, do: skip_ws(rest)
defp skip_ws(rest), do: rest
defp skip_trail_ws(<<char, rest::binary>>, str, ws) when char in @space do
skip_trail_ws(rest, str, <<ws::binary, char>>)
end
defp skip_trail_ws(<<char, rest::binary>>, str, ws) do
skip_trail_ws(rest, <<str::binary, ws::binary, char>>, "")
end
defp skip_trail_ws("", str, _ws) do
str
end
defp quoted("\"" <> rest), do: do_quoted(rest, "")
defp do_quoted("\"" <> rest, acc), do: {acc, rest}
defp do_quoted(<<char, rest::binary>>, acc), do: do_quoted(rest, <<acc::binary, char>>)
defp opt_level(";" <> rest), do: do_level(rest)
defp opt_level(_), do: nil
defp do_level(rest) do
"level" <> rest = skip_ws(rest)
"=" <> rest = skip_ws(rest)
rest
|> skip_ws()
|> skip_trail_ws("", "")
end
end