cowboy_compress_h.erl 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. %% Copyright (c) 2017, Loïc Hoguin <essen@ninenines.eu>
  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. -module(cowboy_compress_h).
  15. -behavior(cowboy_stream).
  16. -export([init/3]).
  17. -export([data/4]).
  18. -export([info/3]).
  19. -export([terminate/3]).
  20. -export([early_error/5]).
  21. -record(state, {
  22. next :: any(),
  23. threshold :: non_neg_integer() | undefined,
  24. compress = undefined :: undefined | gzip,
  25. deflate = undefined :: undefined | zlib:zstream()
  26. }).
  27. -spec init(cowboy_stream:streamid(), cowboy_req:req(), cowboy:opts())
  28. -> {cowboy_stream:commands(), #state{}}.
  29. init(StreamID, Req, Opts) ->
  30. State0 = check_req(Req),
  31. CompressThreshold = maps:get(compress_threshold, Opts, 300),
  32. {Commands0, Next} = cowboy_stream:init(StreamID, Req, Opts),
  33. fold(Commands0, State0#state{next=Next, threshold=CompressThreshold}).
  34. -spec data(cowboy_stream:streamid(), cowboy_stream:fin(), cowboy_req:resp_body(), State)
  35. -> {cowboy_stream:commands(), State} when State::#state{}.
  36. data(StreamID, IsFin, Data, State0=#state{next=Next0}) ->
  37. {Commands0, Next} = cowboy_stream:data(StreamID, IsFin, Data, Next0),
  38. fold(Commands0, State0#state{next=Next}).
  39. -spec info(cowboy_stream:streamid(), any(), State)
  40. -> {cowboy_stream:commands(), State} when State::#state{}.
  41. info(StreamID, Info, State0=#state{next=Next0}) ->
  42. {Commands0, Next} = cowboy_stream:info(StreamID, Info, Next0),
  43. fold(Commands0, State0#state{next=Next}).
  44. -spec terminate(cowboy_stream:streamid(), cowboy_stream:reason(), #state{}) -> any().
  45. terminate(StreamID, Reason, #state{next=Next, deflate=Z}) ->
  46. %% Clean the zlib:stream() in case something went wrong.
  47. %% In the normal scenario the stream is already closed.
  48. case Z of
  49. undefined -> ok;
  50. _ -> zlib:close(Z)
  51. end,
  52. cowboy_stream:terminate(StreamID, Reason, Next).
  53. -spec early_error(cowboy_stream:streamid(), cowboy_stream:reason(),
  54. cowboy_stream:partial_req(), Resp, cowboy:opts()) -> Resp
  55. when Resp::cowboy_stream:resp_command().
  56. early_error(StreamID, Reason, PartialReq, Resp, Opts) ->
  57. cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts).
  58. %% Internal.
  59. %% Check if the client supports decoding of gzip responses.
  60. check_req(Req) ->
  61. %% @todo Probably shouldn't unconditionally crash on failure.
  62. case cowboy_req:parse_header(<<"accept-encoding">>, Req) of
  63. %% Client doesn't support any compression algorithm.
  64. undefined ->
  65. #state{compress=undefined};
  66. Encodings ->
  67. %% We only support gzip so look for it specifically.
  68. %% @todo A recipient SHOULD consider "x-gzip" to be
  69. %% equivalent to "gzip". (RFC7230 4.2.3)
  70. case [E || E={<<"gzip">>, Q} <- Encodings, Q =/= 0] of
  71. [] ->
  72. #state{compress=undefined};
  73. _ ->
  74. #state{compress=gzip}
  75. end
  76. end.
  77. %% Do not compress responses that contain the content-encoding header.
  78. check_resp_headers(#{<<"content-encoding">> := _}, State) ->
  79. State#state{compress=undefined};
  80. check_resp_headers(_, State) ->
  81. State.
  82. fold(Commands, State=#state{compress=undefined}) ->
  83. {Commands, State};
  84. fold(Commands, State) ->
  85. fold(Commands, State, []).
  86. fold([], State, Acc) ->
  87. {lists:reverse(Acc), State};
  88. %% We do not compress sendfile bodies.
  89. fold([Response={response, _, _, {sendfile, _, _, _}}|Tail], State, Acc) ->
  90. fold(Tail, State, [Response|Acc]);
  91. %% We compress full responses directly, unless they are lower than
  92. %% the configured threshold or we find we are not able to by looking at the headers.
  93. fold([Response0={response, _, Headers, Body}|Tail],
  94. State0=#state{threshold=CompressThreshold}, Acc) ->
  95. case check_resp_headers(Headers, State0) of
  96. State=#state{compress=undefined} ->
  97. fold(Tail, State, [Response0|Acc]);
  98. State1 ->
  99. BodyLength = iolist_size(Body),
  100. if
  101. BodyLength =< CompressThreshold ->
  102. fold(Tail, State1, [Response0|Acc]);
  103. true ->
  104. {Response, State} = gzip_response(Response0, State1),
  105. fold(Tail, State, [Response|Acc])
  106. end
  107. end;
  108. %% Check headers and initiate compression...
  109. fold([Response0={headers, _, Headers}|Tail], State0, Acc) ->
  110. case check_resp_headers(Headers, State0) of
  111. State=#state{compress=undefined} ->
  112. fold(Tail, State, [Response0|Acc]);
  113. State1 ->
  114. {Response, State} = gzip_headers(Response0, State1),
  115. fold(Tail, State, [Response|Acc])
  116. end;
  117. %% then compress each data commands individually.
  118. fold([Data0={data, _, _}|Tail], State0=#state{compress=gzip}, Acc) ->
  119. {Data, State} = gzip_data(Data0, State0),
  120. fold(Tail, State, [Data|Acc]);
  121. %% When trailers are sent we need to end the compression.
  122. %% This results in an extra data command being sent.
  123. fold([Trailers={trailers, _}|Tail], State0=#state{compress=gzip}, Acc) ->
  124. {{data, fin, Data}, State} = gzip_data({data, fin, <<>>}, State0),
  125. fold(Tail, State, [Trailers, {data, nofin, Data}|Acc]);
  126. %% Otherwise, we have an unrelated command or compression is disabled.
  127. fold([Command|Tail], State, Acc) ->
  128. fold(Tail, State, [Command|Acc]).
  129. gzip_response({response, Status, Headers, Body}, State) ->
  130. %% We can't call zlib:gzip/1 because it does an
  131. %% iolist_to_binary(GzBody) at the end to return
  132. %% a binary(). Therefore the code here is largely
  133. %% a duplicate of the code of that function.
  134. Z = zlib:open(),
  135. GzBody = try
  136. %% 31 = 16+?MAX_WBITS from zlib.erl
  137. %% @todo It might be good to allow them to be configured?
  138. zlib:deflateInit(Z, default, deflated, 31, 8, default),
  139. Gz = zlib:deflate(Z, Body, finish),
  140. zlib:deflateEnd(Z),
  141. Gz
  142. after
  143. zlib:close(Z)
  144. end,
  145. {{response, Status, Headers#{
  146. <<"content-length">> => integer_to_binary(iolist_size(GzBody)),
  147. <<"content-encoding">> => <<"gzip">>
  148. }, GzBody}, State}.
  149. gzip_headers({headers, Status, Headers0}, State) ->
  150. Z = zlib:open(),
  151. %% We use the same arguments as when compressing the body fully.
  152. %% @todo It might be good to allow them to be configured?
  153. zlib:deflateInit(Z, default, deflated, 31, 8, default),
  154. Headers = maps:remove(<<"content-length">>, Headers0),
  155. {{headers, Status, Headers#{
  156. <<"content-encoding">> => <<"gzip">>
  157. }}, State#state{deflate=Z}}.
  158. gzip_data({data, nofin, Data0}, State=#state{deflate=Z}) ->
  159. Data = zlib:deflate(Z, Data0),
  160. {{data, nofin, Data}, State};
  161. gzip_data({data, fin, Data0}, State=#state{deflate=Z}) ->
  162. Data = zlib:deflate(Z, Data0, finish),
  163. zlib:deflateEnd(Z),
  164. zlib:close(Z),
  165. {{data, fin, Data}, State#state{deflate=undefined}}.