| 1 |
%% Copyright (c) jdamanalo <[email protected]> |
| 2 |
%% Copyright (c) Loïc Hoguin <[email protected]> |
| 3 |
%% |
| 4 |
%% Permission to use, copy, modify, and/or distribute this software for any |
| 5 |
%% purpose with or without fee is hereby granted, provided that the above |
| 6 |
%% copyright notice and this permission notice appear in all copies. |
| 7 |
%% |
| 8 |
%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |
| 9 |
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
| 10 |
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |
| 11 |
%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
| 12 |
%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
| 13 |
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |
| 14 |
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| 15 |
|
| 16 |
-module(cowboy_decompress_h). |
| 17 |
-behavior(cowboy_stream). |
| 18 |
|
| 19 |
-export([init/3]). |
| 20 |
-export([data/4]). |
| 21 |
-export([info/3]). |
| 22 |
-export([terminate/3]). |
| 23 |
-export([early_error/5]). |
| 24 |
|
| 25 |
-record(state, { |
| 26 |
next :: any(), |
| 27 |
enabled = true :: boolean(), |
| 28 |
ratio_limit :: non_neg_integer() | undefined, |
| 29 |
compress = undefined :: undefined | gzip, |
| 30 |
inflate = undefined :: undefined | zlib:zstream(), |
| 31 |
is_reading = false :: boolean(), |
| 32 |
|
| 33 |
%% We use a list of binaries to avoid doing unnecessary |
| 34 |
%% memory allocations when inflating. We convert to binary |
| 35 |
%% when we propagate the data. The data must be reversed |
| 36 |
%% before converting to binary or inflating: this is done |
| 37 |
%% via the buffer_to_binary/buffer_to_iovec functions. |
| 38 |
read_body_buffer = [] :: [binary()], |
| 39 |
read_body_is_fin = nofin :: nofin | {fin, non_neg_integer()} |
| 40 |
}). |
| 41 |
|
| 42 |
-spec init(cowboy_stream:streamid(), cowboy_req:req(), cowboy:opts()) |
| 43 |
-> {cowboy_stream:commands(), #state{}}. |
| 44 |
init(StreamID, Req0, Opts) -> |
| 45 |
Enabled = maps:get(decompress_enabled, Opts, true), |
| 46 |
RatioLimit = maps:get(decompress_ratio_limit, Opts, 20), |
| 47 |
{Req, State} = check_and_update_req(Req0), |
| 48 |
Inflate = case State#state.compress of |
| 49 |
undefined -> |
| 50 |
undefined; |
| 51 |
gzip -> |
| 52 |
Z = zlib:open(), |
| 53 |
zlib:inflateInit(Z, 31), |
| 54 |
Z |
| 55 |
end, |
| 56 |
{Commands, Next} = cowboy_stream:init(StreamID, Req, Opts), |
| 57 |
fold(Commands, State#state{next=Next, enabled=Enabled, |
| 58 |
ratio_limit=RatioLimit, inflate=Inflate}). |
| 59 |
|
| 60 |
-spec data(cowboy_stream:streamid(), cowboy_stream:fin(), cowboy_req:resp_body(), State) |
| 61 |
-> {cowboy_stream:commands(), State} when State::#state{}. |
| 62 |
data(StreamID, IsFin, Data, State=#state{next=Next0, inflate=undefined}) -> |
| 63 |
{Commands, Next} = cowboy_stream:data(StreamID, IsFin, Data, Next0), |
| 64 |
fold(Commands, State#state{next=Next, read_body_is_fin=IsFin}); |
| 65 |
data(StreamID, IsFin, Data, State=#state{next=Next0, enabled=false, read_body_buffer=Buffer}) -> |
| 66 |
{Commands, Next} = cowboy_stream:data(StreamID, IsFin, |
| 67 |
buffer_to_binary([Data|Buffer]), Next0), |
| 68 |
fold(Commands, State#state{next=Next, read_body_is_fin=IsFin}); |
| 69 |
data(StreamID, IsFin, Data0, State0=#state{next=Next0, ratio_limit=RatioLimit, |
| 70 |
inflate=Z, is_reading=true, read_body_buffer=Buffer}) -> |
| 71 |
Data = buffer_to_iovec([Data0|Buffer]), |
| 72 |
Limit = iolist_size(Data) * RatioLimit, |
| 73 |
case cow_deflate:inflate(Z, Data, Limit) of |
| 74 |
{error, ErrorType} -> |
| 75 |
zlib:close(Z), |
| 76 |
Status = case ErrorType of |
| 77 |
data_error -> 400; |
| 78 |
size_error -> 413 |
| 79 |
end, |
| 80 |
Commands = [ |
| 81 |
{error_response, Status, #{<<"content-length">> => <<"0">>}, <<>>}, |
| 82 |
stop |
| 83 |
], |
| 84 |
fold(Commands, State0#state{inflate=undefined, read_body_buffer=[]}); |
| 85 |
{ok, Inflated} -> |
| 86 |
State = case IsFin of |
| 87 |
nofin -> |
| 88 |
State0; |
| 89 |
fin -> |
| 90 |
zlib:close(Z), |
| 91 |
State0#state{inflate=undefined} |
| 92 |
end, |
| 93 |
{Commands, Next} = cowboy_stream:data(StreamID, IsFin, Inflated, Next0), |
| 94 |
fold(Commands, State#state{next=Next, read_body_buffer=[], |
| 95 |
read_body_is_fin=IsFin}) |
| 96 |
end; |
| 97 |
data(_, IsFin, Data, State=#state{read_body_buffer=Buffer}) -> |
| 98 |
{[], State#state{read_body_buffer=[Data|Buffer], read_body_is_fin=IsFin}}. |
| 99 |
|
| 100 |
-spec info(cowboy_stream:streamid(), any(), State) |
| 101 |
-> {cowboy_stream:commands(), State} when State::#state{}. |
| 102 |
info(StreamID, Info, State=#state{next=Next0, inflate=undefined}) -> |
| 103 |
{Commands, Next} = cowboy_stream:info(StreamID, Info, Next0), |
| 104 |
fold(Commands, State#state{next=Next}); |
| 105 |
info(StreamID, Info={CommandTag, _, _, _, _}, State=#state{next=Next0, read_body_is_fin=IsFin}) |
| 106 |
when CommandTag =:= read_body; CommandTag =:= read_body_timeout -> |
| 107 |
{Commands0, Next1} = cowboy_stream:info(StreamID, Info, Next0), |
| 108 |
{Commands, Next} = data(StreamID, IsFin, <<>>, State#state{next=Next1, is_reading=true}), |
| 109 |
fold(Commands ++ Commands0, Next); |
| 110 |
info(StreamID, Info={set_options, Opts}, State0=#state{next=Next0, |
| 111 |
enabled=Enabled0, ratio_limit=RatioLimit0, is_reading=IsReading}) -> |
| 112 |
Enabled = maps:get(decompress_enabled, Opts, Enabled0), |
| 113 |
RatioLimit = maps:get(decompress_ratio_limit, Opts, RatioLimit0), |
| 114 |
{Commands, Next} = cowboy_stream:info(StreamID, Info, Next0), |
| 115 |
%% We can't change the enabled setting after we start reading, |
| 116 |
%% otherwise the data becomes garbage. Changing the setting |
| 117 |
%% is not treated as an error, it is just ignored. |
| 118 |
State = case IsReading of |
| 119 |
true -> State0; |
| 120 |
false -> State0#state{enabled=Enabled} |
| 121 |
end, |
| 122 |
fold(Commands, State#state{next=Next, ratio_limit=RatioLimit}); |
| 123 |
info(StreamID, Info, State=#state{next=Next0}) -> |
| 124 |
{Commands, Next} = cowboy_stream:info(StreamID, Info, Next0), |
| 125 |
fold(Commands, State#state{next=Next}). |
| 126 |
|
| 127 |
-spec terminate(cowboy_stream:streamid(), cowboy_stream:reason(), #state{}) -> any(). |
| 128 |
terminate(StreamID, Reason, #state{next=Next, inflate=Z}) -> |
| 129 |
case Z of |
| 130 |
undefined -> ok; |
| 131 |
_ -> zlib:close(Z) |
| 132 |
end, |
| 133 |
cowboy_stream:terminate(StreamID, Reason, Next). |
| 134 |
|
| 135 |
-spec early_error(cowboy_stream:streamid(), cowboy_stream:reason(), |
| 136 |
cowboy_stream:partial_req(), Resp, cowboy:opts()) -> Resp |
| 137 |
when Resp::cowboy_stream:resp_command(). |
| 138 |
early_error(StreamID, Reason, PartialReq, Resp, Opts) -> |
| 139 |
cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts). |
| 140 |
|
| 141 |
%% Internal. |
| 142 |
|
| 143 |
%% Check whether the request needs content decoding, and if it does |
| 144 |
%% whether it fits our criteria for decoding. We also update the |
| 145 |
%% Req to indicate whether content was decoded. |
| 146 |
%% |
| 147 |
%% We always set the content_decoded value in the Req because it |
| 148 |
%% indicates whether content decoding was attempted. |
| 149 |
%% |
| 150 |
%% A malformed content-encoding header results in no decoding. |
| 151 |
check_and_update_req(Req=#{headers := Headers}) -> |
| 152 |
ContentDecoded = maps:get(content_decoded, Req, []), |
| 153 |
try cowboy_req:parse_header(<<"content-encoding">>, Req) of |
| 154 |
%% We only automatically decompress when gzip is the only |
| 155 |
%% encoding used. Since it's the only encoding used, we |
| 156 |
%% can remove the header entirely before passing the Req |
| 157 |
%% forward. |
| 158 |
[<<"gzip">>] -> |
| 159 |
{Req#{ |
| 160 |
headers => maps:remove(<<"content-encoding">>, Headers), |
| 161 |
content_decoded => [<<"gzip">>|ContentDecoded] |
| 162 |
}, #state{compress=gzip}}; |
| 163 |
_ -> |
| 164 |
{Req#{content_decoded => ContentDecoded}, |
| 165 |
#state{compress=undefined}} |
| 166 |
catch _:_ -> |
| 167 |
{Req#{content_decoded => ContentDecoded}, |
| 168 |
#state{compress=undefined}} |
| 169 |
end. |
| 170 |
|
| 171 |
buffer_to_iovec(Buffer) -> |
| 172 |
lists:reverse(Buffer). |
| 173 |
|
| 174 |
buffer_to_binary(Buffer) -> |
| 175 |
iolist_to_binary(lists:reverse(Buffer)). |
| 176 |
|
| 177 |
fold(Commands, State) -> |
| 178 |
fold(Commands, State, []). |
| 179 |
|
| 180 |
fold([], State, Acc) -> |
| 181 |
{lists:reverse(Acc), State}; |
| 182 |
fold([{response, Status, Headers0, Body}|Tail], State=#state{enabled=true}, Acc) -> |
| 183 |
Headers = add_accept_encoding(Headers0), |
| 184 |
fold(Tail, State, [{response, Status, Headers, Body}|Acc]); |
| 185 |
fold([{headers, Status, Headers0} | Tail], State=#state{enabled=true}, Acc) -> |
| 186 |
Headers = add_accept_encoding(Headers0), |
| 187 |
fold(Tail, State, [{headers, Status, Headers}|Acc]); |
| 188 |
fold([Command|Tail], State, Acc) -> |
| 189 |
fold(Tail, State, [Command|Acc]). |
| 190 |
|
| 191 |
add_accept_encoding(Headers=#{<<"accept-encoding">> := AcceptEncoding}) -> |
| 192 |
try cow_http_hd:parse_accept_encoding(iolist_to_binary(AcceptEncoding)) of |
| 193 |
List -> |
| 194 |
case lists:keyfind(<<"gzip">>, 1, List) of |
| 195 |
%% gzip is excluded but this handler is enabled; we replace. |
| 196 |
{_, 0} -> |
| 197 |
Replaced = lists:keyreplace(<<"gzip">>, 1, List, {<<"gzip">>, 1000}), |
| 198 |
Codings = build_accept_encoding(Replaced), |
| 199 |
Headers#{<<"accept-encoding">> => Codings}; |
| 200 |
{_, _} -> |
| 201 |
Headers; |
| 202 |
false -> |
| 203 |
case lists:keyfind(<<"*">>, 1, List) of |
| 204 |
%% Others are excluded along with gzip; we add. |
| 205 |
{_, 0} -> |
| 206 |
WithGzip = [{<<"gzip">>, 1000} | List], |
| 207 |
Codings = build_accept_encoding(WithGzip), |
| 208 |
Headers#{<<"accept-encoding">> => Codings}; |
| 209 |
{_, _} -> |
| 210 |
Headers; |
| 211 |
false -> |
| 212 |
Headers#{<<"accept-encoding">> => [AcceptEncoding, <<", gzip">>]} |
| 213 |
end |
| 214 |
end |
| 215 |
catch _:_ -> |
| 216 |
%% The accept-encoding header is invalid. Probably empty. We replace it with ours. |
| 217 |
Headers#{<<"accept-encoding">> => <<"gzip">>} |
| 218 |
end; |
| 219 |
add_accept_encoding(Headers) -> |
| 220 |
Headers#{<<"accept-encoding">> => <<"gzip">>}. |
| 221 |
|
| 222 |
%% @todo From cowlib, maybe expose? |
| 223 |
qvalue_to_iodata(0) -> <<"0">>; |
| 224 |
qvalue_to_iodata(Q) when Q < 10 -> [<<"0.00">>, integer_to_binary(Q)]; |
| 225 |
qvalue_to_iodata(Q) when Q < 100 -> [<<"0.0">>, integer_to_binary(Q)]; |
| 226 |
qvalue_to_iodata(Q) when Q < 1000 -> [<<"0.">>, integer_to_binary(Q)]; |
| 227 |
qvalue_to_iodata(1000) -> <<"1">>. |
| 228 |
|
| 229 |
%% @todo Should be added to Cowlib. |
| 230 |
build_accept_encoding([{ContentCoding, Q}|Tail]) -> |
| 231 |
Weight = iolist_to_binary(qvalue_to_iodata(Q)), |
| 232 |
Acc = <<ContentCoding/binary, ";q=", Weight/binary>>, |
| 233 |
do_build_accept_encoding(Tail, Acc). |
| 234 |
|
| 235 |
do_build_accept_encoding([{ContentCoding, Q}|Tail], Acc0) -> |
| 236 |
Weight = iolist_to_binary(qvalue_to_iodata(Q)), |
| 237 |
Acc = <<Acc0/binary, ", ", ContentCoding/binary, ";q=", Weight/binary>>, |
| 238 |
do_build_accept_encoding(Tail, Acc); |
| 239 |
do_build_accept_encoding([], Acc) -> |
| 240 |
Acc. |