| 1 |
%% Copyright (c) Loïc Hoguin <[email protected]> |
| 2 |
%% |
| 3 |
%% Permission to use, copy, modify, and/or distribute this software for any |
| 4 |
%% purpose with or without fee is hereby granted, provided that the above |
| 5 |
%% copyright notice and this permission notice appear in all copies. |
| 6 |
%% |
| 7 |
%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |
| 8 |
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
| 9 |
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |
| 10 |
%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
| 11 |
%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
| 12 |
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |
| 13 |
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| 14 |
|
| 15 |
-module(cowboy_compress_h). |
| 16 |
-behavior(cowboy_stream). |
| 17 |
|
| 18 |
-export([init/3]). |
| 19 |
-export([data/4]). |
| 20 |
-export([info/3]). |
| 21 |
-export([terminate/3]). |
| 22 |
-export([early_error/5]). |
| 23 |
|
| 24 |
-record(state, { |
| 25 |
next :: any(), |
| 26 |
threshold :: non_neg_integer() | undefined, |
| 27 |
compress = undefined :: undefined | gzip, |
| 28 |
deflate = undefined :: undefined | zlib:zstream(), |
| 29 |
deflate_flush = sync :: none | sync |
| 30 |
}). |
| 31 |
|
| 32 |
-spec init(cowboy_stream:streamid(), cowboy_req:req(), cowboy:opts()) |
| 33 |
-> {cowboy_stream:commands(), #state{}}. |
| 34 |
init(StreamID, Req, Opts) -> |
| 35 |
State0 = check_req(Req), |
| 36 |
CompressThreshold = maps:get(compress_threshold, Opts, 300), |
| 37 |
DeflateFlush = buffering_to_zflush(maps:get(compress_buffering, Opts, false)), |
| 38 |
{Commands0, Next} = cowboy_stream:init(StreamID, Req, Opts), |
| 39 |
fold(Commands0, State0#state{next=Next, |
| 40 |
threshold=CompressThreshold, |
| 41 |
deflate_flush=DeflateFlush}). |
| 42 |
|
| 43 |
-spec data(cowboy_stream:streamid(), cowboy_stream:fin(), cowboy_req:resp_body(), State) |
| 44 |
-> {cowboy_stream:commands(), State} when State::#state{}. |
| 45 |
data(StreamID, IsFin, Data, State0=#state{next=Next0}) -> |
| 46 |
{Commands0, Next} = cowboy_stream:data(StreamID, IsFin, Data, Next0), |
| 47 |
fold(Commands0, State0#state{next=Next}). |
| 48 |
|
| 49 |
-spec info(cowboy_stream:streamid(), any(), State) |
| 50 |
-> {cowboy_stream:commands(), State} when State::#state{}. |
| 51 |
info(StreamID, Info, State0=#state{next=Next0}) -> |
| 52 |
{Commands0, Next} = cowboy_stream:info(StreamID, Info, Next0), |
| 53 |
fold(Commands0, State0#state{next=Next}). |
| 54 |
|
| 55 |
-spec terminate(cowboy_stream:streamid(), cowboy_stream:reason(), #state{}) -> any(). |
| 56 |
terminate(StreamID, Reason, #state{next=Next, deflate=Z}) -> |
| 57 |
%% Clean the zlib:stream() in case something went wrong. |
| 58 |
%% In the normal scenario the stream is already closed. |
| 59 |
case Z of |
| 60 |
undefined -> ok; |
| 61 |
_ -> zlib:close(Z) |
| 62 |
end, |
| 63 |
cowboy_stream:terminate(StreamID, Reason, Next). |
| 64 |
|
| 65 |
-spec early_error(cowboy_stream:streamid(), cowboy_stream:reason(), |
| 66 |
cowboy_stream:partial_req(), Resp, cowboy:opts()) -> Resp |
| 67 |
when Resp::cowboy_stream:resp_command(). |
| 68 |
early_error(StreamID, Reason, PartialReq, Resp, Opts) -> |
| 69 |
cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts). |
| 70 |
|
| 71 |
%% Internal. |
| 72 |
|
| 73 |
%% Check if the client supports decoding of gzip responses. |
| 74 |
%% |
| 75 |
%% A malformed accept-encoding header is ignored (no compression). |
| 76 |
check_req(Req) -> |
| 77 |
try cowboy_req:parse_header(<<"accept-encoding">>, Req) of |
| 78 |
%% Client doesn't support any compression algorithm. |
| 79 |
undefined -> |
| 80 |
#state{compress=undefined}; |
| 81 |
Encodings -> |
| 82 |
%% We only support gzip so look for it specifically. |
| 83 |
%% @todo A recipient SHOULD consider "x-gzip" to be |
| 84 |
%% equivalent to "gzip". (RFC7230 4.2.3) |
| 85 |
case [E || E={<<"gzip">>, Q} <- Encodings, Q =/= 0] of |
| 86 |
[] -> |
| 87 |
#state{compress=undefined}; |
| 88 |
_ -> |
| 89 |
#state{compress=gzip} |
| 90 |
end |
| 91 |
catch |
| 92 |
_:_ -> |
| 93 |
#state{compress=undefined} |
| 94 |
end. |
| 95 |
|
| 96 |
%% Do not compress responses that contain the content-encoding header. |
| 97 |
check_resp_headers(#{<<"content-encoding">> := _}, State) -> |
| 98 |
State#state{compress=undefined}; |
| 99 |
%% Do not compress responses that contain the etag header. |
| 100 |
check_resp_headers(#{<<"etag">> := _}, State) -> |
| 101 |
State#state{compress=undefined}; |
| 102 |
check_resp_headers(_, State) -> |
| 103 |
State. |
| 104 |
|
| 105 |
fold(Commands, State=#state{compress=undefined}) -> |
| 106 |
fold_vary_only(Commands, State, []); |
| 107 |
fold(Commands, State) -> |
| 108 |
fold(Commands, State, []). |
| 109 |
|
| 110 |
fold([], State, Acc) -> |
| 111 |
{lists:reverse(Acc), State}; |
| 112 |
%% We do not compress full sendfile bodies. |
| 113 |
fold([Response={response, _, _, {sendfile, _, _, _}}|Tail], State, Acc) -> |
| 114 |
fold(Tail, State, [vary_response(Response)|Acc]); |
| 115 |
%% We compress full responses directly, unless they are lower than |
| 116 |
%% the configured threshold or we find we are not able to by looking at the headers. |
| 117 |
fold([Response0={response, _, Headers, Body}|Tail], |
| 118 |
State0=#state{threshold=CompressThreshold}, Acc) -> |
| 119 |
case check_resp_headers(Headers, State0) of |
| 120 |
State=#state{compress=undefined} -> |
| 121 |
fold(Tail, State, [vary_response(Response0)|Acc]); |
| 122 |
State1 -> |
| 123 |
BodyLength = iolist_size(Body), |
| 124 |
if |
| 125 |
BodyLength =< CompressThreshold -> |
| 126 |
fold(Tail, State1, [vary_response(Response0)|Acc]); |
| 127 |
true -> |
| 128 |
{Response, State} = gzip_response(Response0, State1), |
| 129 |
fold(Tail, State, [vary_response(Response)|Acc]) |
| 130 |
end |
| 131 |
end; |
| 132 |
%% Check headers and initiate compression... |
| 133 |
fold([Response0={headers, _, Headers}|Tail], State0, Acc) -> |
| 134 |
case check_resp_headers(Headers, State0) of |
| 135 |
State=#state{compress=undefined} -> |
| 136 |
fold(Tail, State, [vary_headers(Response0)|Acc]); |
| 137 |
State1 -> |
| 138 |
{Response, State} = gzip_headers(Response0, State1), |
| 139 |
fold(Tail, State, [vary_headers(Response)|Acc]) |
| 140 |
end; |
| 141 |
%% then compress each data commands individually. |
| 142 |
fold([Data0={data, _, _}|Tail], State0=#state{compress=gzip}, Acc) -> |
| 143 |
{Data, State} = gzip_data(Data0, State0), |
| 144 |
fold(Tail, State, [Data|Acc]); |
| 145 |
%% When trailers are sent we need to end the compression. |
| 146 |
%% This results in an extra data command being sent. |
| 147 |
fold([Trailers={trailers, _}|Tail], State0=#state{compress=gzip}, Acc) -> |
| 148 |
{{data, fin, Data}, State} = gzip_data({data, fin, <<>>}, State0), |
| 149 |
fold(Tail, State, [Trailers, {data, nofin, Data}|Acc]); |
| 150 |
%% All the options from this handler can be updated for the current stream. |
| 151 |
%% The set_options command must be propagated as-is regardless. |
| 152 |
fold([SetOptions={set_options, Opts}|Tail], State=#state{ |
| 153 |
threshold=CompressThreshold0, deflate_flush=DeflateFlush0}, Acc) -> |
| 154 |
CompressThreshold = maps:get(compress_threshold, Opts, CompressThreshold0), |
| 155 |
DeflateFlush = case Opts of |
| 156 |
#{compress_buffering := CompressBuffering} -> |
| 157 |
buffering_to_zflush(CompressBuffering); |
| 158 |
_ -> |
| 159 |
DeflateFlush0 |
| 160 |
end, |
| 161 |
fold(Tail, State#state{threshold=CompressThreshold, deflate_flush=DeflateFlush}, |
| 162 |
[SetOptions|Acc]); |
| 163 |
%% Otherwise, we have an unrelated command or compression is disabled. |
| 164 |
fold([Command|Tail], State, Acc) -> |
| 165 |
fold(Tail, State, [Command|Acc]). |
| 166 |
|
| 167 |
fold_vary_only([], State, Acc) -> |
| 168 |
{lists:reverse(Acc), State}; |
| 169 |
fold_vary_only([Response={response, _, _, _}|Tail], State, Acc) -> |
| 170 |
fold_vary_only(Tail, State, [vary_response(Response)|Acc]); |
| 171 |
fold_vary_only([Response={headers, _, _}|Tail], State, Acc) -> |
| 172 |
fold_vary_only(Tail, State, [vary_headers(Response)|Acc]); |
| 173 |
fold_vary_only([Command|Tail], State, Acc) -> |
| 174 |
fold_vary_only(Tail, State, [Command|Acc]). |
| 175 |
|
| 176 |
buffering_to_zflush(true) -> none; |
| 177 |
buffering_to_zflush(false) -> sync. |
| 178 |
|
| 179 |
gzip_response({response, Status, Headers, Body}, State) -> |
| 180 |
%% We can't call zlib:gzip/1 because it does an |
| 181 |
%% iolist_to_binary(GzBody) at the end to return |
| 182 |
%% a binary(). Therefore the code here is largely |
| 183 |
%% a duplicate of the code of that function. |
| 184 |
Z = zlib:open(), |
| 185 |
GzBody = try |
| 186 |
%% 31 = 16+?MAX_WBITS from zlib.erl |
| 187 |
%% @todo It might be good to allow them to be configured? |
| 188 |
zlib:deflateInit(Z, default, deflated, 31, 8, default), |
| 189 |
Gz = zlib:deflate(Z, Body, finish), |
| 190 |
zlib:deflateEnd(Z), |
| 191 |
Gz |
| 192 |
after |
| 193 |
zlib:close(Z) |
| 194 |
end, |
| 195 |
{{response, Status, Headers#{ |
| 196 |
<<"content-length">> => integer_to_binary(iolist_size(GzBody)), |
| 197 |
<<"content-encoding">> => <<"gzip">> |
| 198 |
}, GzBody}, State}. |
| 199 |
|
| 200 |
gzip_headers({headers, Status, Headers0}, State) -> |
| 201 |
Z = zlib:open(), |
| 202 |
%% We use the same arguments as when compressing the body fully. |
| 203 |
%% @todo It might be good to allow them to be configured? |
| 204 |
zlib:deflateInit(Z, default, deflated, 31, 8, default), |
| 205 |
Headers = maps:remove(<<"content-length">>, Headers0), |
| 206 |
{{headers, Status, Headers#{ |
| 207 |
<<"content-encoding">> => <<"gzip">> |
| 208 |
}}, State#state{deflate=Z}}. |
| 209 |
|
| 210 |
vary_response({response, Status, Headers, Body}) -> |
| 211 |
{response, Status, vary(Headers), Body}. |
| 212 |
|
| 213 |
vary_headers({headers, Status, Headers}) -> |
| 214 |
{headers, Status, vary(Headers)}. |
| 215 |
|
| 216 |
%% We must add content-encoding to vary if it's not already there. |
| 217 |
vary(Headers=#{<<"vary">> := Vary}) -> |
| 218 |
try cow_http_hd:parse_vary(iolist_to_binary(Vary)) of |
| 219 |
'*' -> Headers; |
| 220 |
List -> |
| 221 |
case lists:member(<<"accept-encoding">>, List) of |
| 222 |
true -> Headers; |
| 223 |
false -> Headers#{<<"vary">> => [Vary, <<", accept-encoding">>]} |
| 224 |
end |
| 225 |
catch _:_ -> |
| 226 |
%% The vary header is invalid. Probably empty. We replace it with ours. |
| 227 |
Headers#{<<"vary">> => <<"accept-encoding">>} |
| 228 |
end; |
| 229 |
vary(Headers) -> |
| 230 |
Headers#{<<"vary">> => <<"accept-encoding">>}. |
| 231 |
|
| 232 |
%% It is not possible to combine zlib and the sendfile |
| 233 |
%% syscall as far as I can tell, because the zlib format |
| 234 |
%% includes a checksum at the end of the stream. We have |
| 235 |
%% to read the file in memory, making this not suitable for |
| 236 |
%% large files. |
| 237 |
gzip_data({data, nofin, Sendfile={sendfile, _, _, _}}, |
| 238 |
State=#state{deflate=Z, deflate_flush=Flush}) -> |
| 239 |
{ok, Data0} = read_file(Sendfile), |
| 240 |
Data = zlib:deflate(Z, Data0, Flush), |
| 241 |
{{data, nofin, Data}, State}; |
| 242 |
gzip_data({data, fin, Sendfile={sendfile, _, _, _}}, State=#state{deflate=Z}) -> |
| 243 |
{ok, Data0} = read_file(Sendfile), |
| 244 |
Data = zlib:deflate(Z, Data0, finish), |
| 245 |
zlib:deflateEnd(Z), |
| 246 |
zlib:close(Z), |
| 247 |
{{data, fin, Data}, State#state{deflate=undefined}}; |
| 248 |
gzip_data({data, nofin, Data0}, State=#state{deflate=Z, deflate_flush=Flush}) -> |
| 249 |
Data = zlib:deflate(Z, Data0, Flush), |
| 250 |
{{data, nofin, Data}, State}; |
| 251 |
gzip_data({data, fin, Data0}, State=#state{deflate=Z}) -> |
| 252 |
Data = zlib:deflate(Z, Data0, finish), |
| 253 |
zlib:deflateEnd(Z), |
| 254 |
zlib:close(Z), |
| 255 |
{{data, fin, Data}, State#state{deflate=undefined}}. |
| 256 |
|
| 257 |
read_file({sendfile, Offset, Bytes, Path}) -> |
| 258 |
{ok, IoDevice} = file:open(Path, [read, raw, binary]), |
| 259 |
try |
| 260 |
_ = case Offset of |
| 261 |
0 -> ok; |
| 262 |
_ -> file:position(IoDevice, {bof, Offset}) |
| 263 |
end, |
| 264 |
file:read(IoDevice, Bytes) |
| 265 |
after |
| 266 |
file:close(IoDevice) |
| 267 |
end. |