-
Notifications
You must be signed in to change notification settings - Fork 574
/
utils.ex
332 lines (239 loc) · 8.51 KB
/
utils.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
defmodule Plug.Conn.Utils do
@moduledoc """
Utilities for working with connection data
"""
@type params :: %{optional(binary) => binary}
@upper ?A..?Z
@lower ?a..?z
@alpha ?0..?9
@other [?., ?-, ?+]
@space [?\s, ?\t]
@specials ~c|()<>@,;:\\"/[]?={}|
@doc ~S"""
Parses media types (with wildcards).
Type and subtype are case insensitive while the
sensitiveness of params depends on their keys and
therefore are not handled by this parser.
Returns:
* `{:ok, type, subtype, map_of_params}` if everything goes fine
* `:error` if the media type isn't valid
## Examples
iex> media_type "text/plain"
{:ok, "text", "plain", %{}}
iex> media_type "APPLICATION/vnd.ms-data+XML"
{:ok, "application", "vnd.ms-data+xml", %{}}
iex> media_type "text/*; q=1.0"
{:ok, "text", "*", %{"q" => "1.0"}}
iex> media_type "*/*; q=1.0"
{:ok, "*", "*", %{"q" => "1.0"}}
iex> media_type "x y"
:error
iex> media_type "*/html"
:error
iex> media_type "/"
:error
iex> media_type "x/y z"
:error
"""
@spec media_type(binary) :: {:ok, type :: binary, subtype :: binary, params} | :error
def media_type(binary) when is_binary(binary) do
case strip_spaces(binary) do
"*/*" <> t -> mt_params(t, "*", "*")
t -> mt_first(t, "")
end
end
defp mt_first(<<?/, t::binary>>, acc) when acc != "", do: mt_wildcard(t, acc)
defp mt_first(<<h, t::binary>>, acc) when h in @upper,
do: mt_first(t, <<acc::binary, downcase_char(h)>>)
defp mt_first(<<h, t::binary>>, acc) when h in @lower or h in @alpha or h == ?-,
do: mt_first(t, <<acc::binary, h>>)
defp mt_first(_, _acc), do: :error
defp mt_wildcard(<<?*, t::binary>>, first), do: mt_params(t, first, "*")
defp mt_wildcard(t, first), do: mt_second(t, "", first)
defp mt_second(<<h, t::binary>>, acc, first) when h in @upper,
do: mt_second(t, <<acc::binary, downcase_char(h)>>, first)
defp mt_second(<<h, t::binary>>, acc, first) when h in @lower or h in @alpha or h in @other,
do: mt_second(t, <<acc::binary, h>>, first)
defp mt_second(t, acc, first), do: mt_params(t, first, acc)
defp mt_params(t, first, second) do
case strip_spaces(t) do
"" -> {:ok, first, second, %{}}
";" <> t -> {:ok, first, second, params(t)}
_ -> :error
end
end
@doc ~S"""
Parses content type (without wildcards).
It is similar to `media_type/1` except wildcards are
not accepted in the type nor in the subtype.
## Examples
iex> content_type "x-sample/json; charset=utf-8"
{:ok, "x-sample", "json", %{"charset" => "utf-8"}}
iex> content_type "x-sample/json ; charset=utf-8 ; foo=bar"
{:ok, "x-sample", "json", %{"charset" => "utf-8", "foo" => "bar"}}
iex> content_type "\r\n text/plain;\r\n charset=utf-8\r\n"
{:ok, "text", "plain", %{"charset" => "utf-8"}}
iex> content_type "text/plain"
{:ok, "text", "plain", %{}}
iex> content_type "x/*"
:error
iex> content_type "*/*"
:error
"""
@spec content_type(binary) :: {:ok, type :: binary, subtype :: binary, params} | :error
def content_type(binary) do
case media_type(binary) do
{:ok, _, "*", _} -> :error
{:ok, _, _, _} = ok -> ok
:error -> :error
end
end
@doc ~S"""
Parses headers parameters.
Keys are case insensitive and downcased,
invalid key-value pairs are discarded.
## Examples
iex> params("foo=bar")
%{"foo" => "bar"}
iex> params(" foo=bar ")
%{"foo" => "bar"}
iex> params("FOO=bar")
%{"foo" => "bar"}
iex> params("Foo=bar; baz=BOING")
%{"foo" => "bar", "baz" => "BOING"}
iex> params("foo=BAR ; wat")
%{"foo" => "BAR"}
iex> params("foo=\"bar\"; baz=\"boing\"")
%{"foo" => "bar", "baz" => "boing"}
iex> params("foo=\"bar;\"; baz=\"boing\"")
%{"foo" => "bar;", "baz" => "boing"}
iex> params("=")
%{}
iex> params(";")
%{}
"""
@spec params(binary) :: params
def params(t) do
t
|> split_semicolon("", [], false)
|> Enum.reduce(%{}, ¶ms/2)
end
defp params(param, acc) do
case params_key(strip_spaces(param), "") do
{k, v} -> Map.put(acc, k, v)
false -> acc
end
end
defp params_key(<<?=, t::binary>>, acc) when acc != "", do: params_value(t, acc)
defp params_key(<<h, _::binary>>, _acc)
when h in @specials or h in @space or h < 32 or h === 127,
do: false
defp params_key(<<h, t::binary>>, acc), do: params_key(t, <<acc::binary, downcase_char(h)>>)
defp params_key(<<>>, _acc), do: false
defp params_value(token, key) do
case token(token) do
false -> false
value -> {key, value}
end
end
@doc ~S"""
Parses a value as defined in [RFC-1341](http://www.w3.org/Protocols/rfc1341/4_Content-Type.html).
For convenience, trims whitespace at the end of the token.
Returns `false` if the token is invalid.
## Examples
iex> token("foo")
"foo"
iex> token("foo-bar")
"foo-bar"
iex> token("<foo>")
false
iex> token(~s["<foo>"])
"<foo>"
iex> token(~S["<f\oo>\"<b\ar>"])
"<foo>\"<bar>"
iex> token(~s["])
false
iex> token("foo ")
"foo"
iex> token("foo bar")
false
iex> token("")
false
iex> token(" ")
""
"""
@spec token(binary) :: binary | false
def token(""), do: false
def token(<<?", quoted::binary>>), do: quoted_token(quoted, "")
def token(token), do: unquoted_token(token, "")
defp quoted_token(<<>>, _acc), do: false
defp quoted_token(<<?", t::binary>>, acc), do: strip_spaces(t) == "" and acc
defp quoted_token(<<?\\, h, t::binary>>, acc), do: quoted_token(t, <<acc::binary, h>>)
defp quoted_token(<<h, t::binary>>, acc), do: quoted_token(t, <<acc::binary, h>>)
defp unquoted_token(<<>>, acc), do: acc
defp unquoted_token("\r\n" <> t, acc), do: strip_spaces(t) == "" and acc
defp unquoted_token(<<h, t::binary>>, acc) when h in @space, do: strip_spaces(t) == "" and acc
defp unquoted_token(<<h, _::binary>>, _acc) when h in @specials or h < 32 or h === 127,
do: false
defp unquoted_token(<<h, t::binary>>, acc), do: unquoted_token(t, <<acc::binary, h>>)
@doc """
Parses a comma-separated list of header values.
## Examples
iex> list("foo, bar")
["foo", "bar"]
iex> list("foobar")
["foobar"]
iex> list("")
[]
iex> list("empties, , are,, filtered")
["empties", "are", "filtered"]
iex> list("whitespace , , ,, is ,definitely,optional")
["whitespace", "is", "definitely", "optional"]
"""
@spec list(binary) :: [binary]
def list(binary) do
for elem <- :binary.split(binary, ",", [:global]),
stripped = strip_spaces(elem),
stripped != "",
do: stripped
end
@doc """
Validates the given binary is valid UTF-8.
"""
@spec validate_utf8!(binary, module, binary) :: :ok | no_return
def validate_utf8!(binary, exception, context)
def validate_utf8!(<<binary::binary>>, exception, context) do
do_validate_utf8!(binary, exception, context)
end
defp do_validate_utf8!(<<_::utf8, rest::bits>>, exception, context) do
do_validate_utf8!(rest, exception, context)
end
defp do_validate_utf8!(<<byte, _::bits>>, exception, context) do
raise exception, "invalid UTF-8 on #{context}, got byte #{byte}"
end
defp do_validate_utf8!(<<>>, _exception, _context) do
:ok
end
## Helpers
defp strip_spaces("\r\n" <> t), do: strip_spaces(t)
defp strip_spaces(<<h, t::binary>>) when h in [?\s, ?\t], do: strip_spaces(t)
defp strip_spaces(t), do: trim_trailing(t)
defp trim_trailing(binary), do: trim_trailing(binary, byte_size(binary))
defp trim_trailing(binary, pos) do
if pos > 0 and :binary.at(binary, pos - 1) in [?\s, ?\t] do
trim_trailing(binary, pos - 1)
else
binary_part(binary, 0, pos)
end
end
defp downcase_char(char) when char in @upper, do: char + 32
defp downcase_char(char), do: char
defp split_semicolon(<<>>, <<>>, acc, _), do: acc
defp split_semicolon(<<>>, buffer, acc, _), do: [buffer | acc]
defp split_semicolon(<<?", rest::binary>>, buffer, acc, quoted?),
do: split_semicolon(rest, <<buffer::binary, ?">>, acc, not quoted?)
defp split_semicolon(<<?;, rest::binary>>, buffer, acc, false),
do: split_semicolon(rest, <<>>, [buffer | acc], false)
defp split_semicolon(<<char, rest::binary>>, buffer, acc, quoted?),
do: split_semicolon(rest, <<buffer::binary, char>>, acc, quoted?)
end