cowboy_compress_h.erl 6.3 KB

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