您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

282 行
11 KiB

  1. %%% File : ibrowse_test_server.erl
  2. %%% Author : Chandrashekhar Mullaparthi <chandrashekhar.mullaparthi@t-mobile.co.uk>
  3. %%% Benjamin Lee <yardspoon@gmail.com>
  4. %%% Brian Richards <bmrichards16@gmail.com>
  5. %%% Description : A server to simulate various test scenarios
  6. %%% Created : 17 Oct 2010 by Chandrashekhar Mullaparthi <chandrashekhar.mullaparthi@t-mobile.co.uk>
  7. -module(ibrowse_test_server).
  8. -export([
  9. start_server/2,
  10. stop_server/1,
  11. get_conn_pipeline_depth/0
  12. ]).
  13. -record(request, {method, uri, version, headers = [], body = []}).
  14. -define(dec2hex(X), erlang:integer_to_list(X, 16)).
  15. -define(ACCEPT_TIMEOUT_MS, 1000).
  16. -define(CONN_PIPELINE_DEPTH, conn_pipeline_depth).
  17. start_server(Port, Sock_type) ->
  18. Fun = fun() ->
  19. Name = server_proc_name(Port),
  20. register(Name, self()),
  21. ets:new(?CONN_PIPELINE_DEPTH, [named_table, public, set]),
  22. case do_listen(Sock_type, Port, [{active, false},
  23. {reuseaddr, true},
  24. {nodelay, true},
  25. {packet, http}]) of
  26. {ok, Sock} ->
  27. do_trace("Server listening on port: ~p~n", [Port]),
  28. accept_loop(Sock, Sock_type);
  29. Err ->
  30. erlang:error(
  31. lists:flatten(
  32. io_lib:format(
  33. "Failed to start server on port ~p. ~p~n",
  34. [Port, Err]))),
  35. exit({listen_error, Err})
  36. end,
  37. unregister(Name)
  38. end,
  39. spawn_link(Fun).
  40. stop_server(Port) ->
  41. server_proc_name(Port) ! stop,
  42. timer:sleep(2000), % wait for server to receive msg and unregister
  43. ok.
  44. get_conn_pipeline_depth() ->
  45. ets:tab2list(?CONN_PIPELINE_DEPTH).
  46. server_proc_name(Port) ->
  47. list_to_atom("ibrowse_test_server_"++integer_to_list(Port)).
  48. do_listen(tcp, Port, Opts) ->
  49. gen_tcp:listen(Port, Opts);
  50. do_listen(ssl, Port, Opts) ->
  51. application:start(crypto),
  52. application:start(ssl),
  53. ssl:listen(Port, Opts).
  54. do_accept(tcp, Listen_sock) ->
  55. gen_tcp:accept(Listen_sock, ?ACCEPT_TIMEOUT_MS);
  56. do_accept(ssl, Listen_sock) ->
  57. ssl:ssl_accept(Listen_sock, ?ACCEPT_TIMEOUT_MS).
  58. accept_loop(Sock, Sock_type) ->
  59. case do_accept(Sock_type, Sock) of
  60. {ok, Conn} ->
  61. Pid = spawn_link(fun() -> connection(Conn, Sock_type) end),
  62. set_controlling_process(Conn, Sock_type, Pid),
  63. Pid ! {setopts, [{active, true}]},
  64. accept_loop(Sock, Sock_type);
  65. {error, timeout} ->
  66. receive
  67. stop ->
  68. ok
  69. after 10 ->
  70. accept_loop(Sock, Sock_type)
  71. end;
  72. Err ->
  73. Err
  74. end.
  75. connection(Conn, Sock_type) ->
  76. ets:insert(?CONN_PIPELINE_DEPTH, {self(), 0}),
  77. try
  78. server_loop(Conn, Sock_type, #request{})
  79. after
  80. ets:delete(?CONN_PIPELINE_DEPTH, self())
  81. end.
  82. set_controlling_process(Sock, tcp, Pid) ->
  83. gen_tcp:controlling_process(Sock, Pid);
  84. set_controlling_process(Sock, ssl, Pid) ->
  85. ssl:controlling_process(Sock, Pid).
  86. setopts(Sock, tcp, Opts) ->
  87. inet:setopts(Sock, Opts);
  88. setopts(Sock, ssl, Opts) ->
  89. ssl:setopts(Sock, Opts).
  90. server_loop(Sock, Sock_type, #request{headers = Headers} = Req) ->
  91. receive
  92. {http, Sock, {http_request, HttpMethod, HttpUri, HttpVersion}} ->
  93. ets:update_counter(?CONN_PIPELINE_DEPTH, self(), 1),
  94. server_loop(Sock, Sock_type, Req#request{method = HttpMethod,
  95. uri = HttpUri,
  96. version = HttpVersion});
  97. {http, Sock, {http_header, _, _, _, _} = H} ->
  98. server_loop(Sock, Sock_type, Req#request{headers = [H | Headers]});
  99. {http, Sock, http_eoh} ->
  100. case process_request(Sock, Sock_type, Req) of
  101. not_done ->
  102. ok;
  103. _ ->
  104. ets:update_counter(?CONN_PIPELINE_DEPTH, self(), -1)
  105. end,
  106. server_loop(Sock, Sock_type, #request{});
  107. {http, Sock, {http_error, Err}} ->
  108. do_trace("Error parsing HTTP request:~n"
  109. "Req so far : ~p~n"
  110. "Err : ", [Req, Err]),
  111. exit({http_error, Err});
  112. {setopts, Opts} ->
  113. setopts(Sock, Sock_type, Opts),
  114. server_loop(Sock, Sock_type, Req);
  115. {tcp_closed, Sock} ->
  116. do_trace("Client closed connection~n", []),
  117. ok;
  118. Other ->
  119. do_trace("Recvd unknown msg: ~p~n", [Other]),
  120. exit({unknown_msg, Other})
  121. after 5000 ->
  122. do_trace("Timing out client connection~n", []),
  123. ok
  124. end.
  125. do_trace(Fmt, Args) ->
  126. do_trace(get(my_trace_flag), Fmt, Args).
  127. do_trace(true, Fmt, Args) ->
  128. io:format("~s -- " ++ Fmt, [ibrowse_lib:printable_date() | Args]);
  129. do_trace(_, _, _) ->
  130. ok.
  131. process_request(Sock, Sock_type,
  132. #request{method='GET',
  133. headers = Headers,
  134. uri = {abs_path, "/ibrowse_stream_once_chunk_pipeline_test"}} = Req) ->
  135. Req_id = case lists:keysearch("X-Ibrowse-Request-Id", 3, Headers) of
  136. false ->
  137. "";
  138. {value, {http_header, _, _, _, Req_id_1}} ->
  139. Req_id_1
  140. end,
  141. Req_id_header = ["x-ibrowse-request-id: ", Req_id, "\r\n"],
  142. do_trace("Recvd req: ~p~n", [Req]),
  143. Body = string:join([integer_to_list(X) || X <- lists:seq(1,100)], "-"),
  144. Chunked_body = chunk_request_body(Body, 50),
  145. Resp_1 = [<<"HTTP/1.1 200 OK\r\n">>,
  146. Req_id_header,
  147. <<"Transfer-Encoding: chunked\r\n\r\n">>],
  148. Resp_2 = Chunked_body,
  149. do_send(Sock, Sock_type, Resp_1),
  150. timer:sleep(100),
  151. do_send(Sock, Sock_type, Resp_2);
  152. process_request(Sock, Sock_type,
  153. #request{method='GET',
  154. headers = _Headers,
  155. uri = {abs_path, "/ibrowse_inac_timeout_test"}} = Req) ->
  156. do_trace("Recvd req: ~p. Sleeping for 30 secs...~n", [Req]),
  157. timer:sleep(30000),
  158. do_trace("...Sending response now.~n", []),
  159. Resp = <<"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n">>,
  160. do_send(Sock, Sock_type, Resp);
  161. process_request(Sock, Sock_type,
  162. #request{method='HEAD',
  163. headers = _Headers,
  164. uri = {abs_path, "/ibrowse_head_transfer_enc"}}) ->
  165. Resp = <<"HTTP/1.1 400 Bad Request\r\nServer: Apache-Coyote/1.1\r\nContent-Length:5\r\nDate: Wed, 04 Apr 2012 16:53:49 GMT\r\n\r\nabcde">>,
  166. do_send(Sock, Sock_type, Resp);
  167. process_request(Sock, Sock_type,
  168. #request{method='GET',
  169. headers = Headers,
  170. uri = {abs_path, "/ibrowse_echo_header"}}) ->
  171. Tag = "x-binary",
  172. Headers_1 = [{to_lower(X), to_lower(Y)} || {http_header, _, X, _, Y} <- Headers],
  173. X_binary_header_val = case lists:keysearch(Tag, 1, Headers_1) of
  174. false ->
  175. "not_found";
  176. {value, {_, V}} ->
  177. V
  178. end,
  179. Resp = [<<"HTTP/1.1 200 OK\r\n">>,
  180. <<"Server: ibrowse_test\r\n">>,
  181. Tag, ": ", X_binary_header_val, "\r\n",
  182. <<"Content-Length: 0\r\n\r\n">>],
  183. do_send(Sock, Sock_type, Resp);
  184. process_request(Sock, Sock_type,
  185. #request{method='HEAD',
  186. headers = _Headers,
  187. uri = {abs_path, "/ibrowse_head_test"}}) ->
  188. Resp = <<"HTTP/1.1 200 OK\r\nServer: Apache-Coyote/1.1\r\nTransfer-Encoding: chunked\r\nDate: Wed, 04 Apr 2012 16:53:49 GMT\r\nConnection: close\r\n\r\n">>,
  189. do_send(Sock, Sock_type, Resp);
  190. process_request(Sock, Sock_type,
  191. #request{method='POST',
  192. headers = _Headers,
  193. uri = {abs_path, "/ibrowse_303_no_body_test"}}) ->
  194. Resp = <<"HTTP/1.1 303 See Other\r\nLocation: http://example.org\r\n">>,
  195. do_send(Sock, Sock_type, Resp);
  196. process_request(Sock, Sock_type,
  197. #request{method='POST',
  198. headers = _Headers,
  199. uri = {abs_path, "/ibrowse_303_with_body_test"}}) ->
  200. Resp = <<"HTTP/1.1 303 See Other\r\nLocation: http://example.org\r\nContent-Length: 5\r\n\r\nabcde">>,
  201. do_send(Sock, Sock_type, Resp);
  202. process_request(_Sock, _Sock_type, #request{uri = {abs_path, "/never_respond"} } ) ->
  203. not_done;
  204. process_request(Sock, Sock_type, Req) ->
  205. do_trace("Recvd req: ~p~n", [Req]),
  206. Resp = <<"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n">>,
  207. do_send(Sock, Sock_type, Resp).
  208. do_send(Sock, tcp, Resp) ->
  209. gen_tcp:send(Sock, Resp);
  210. do_send(Sock, ssl, Resp) ->
  211. ssl:send(Sock, Resp).
  212. %%------------------------------------------------------------------------------
  213. %% Utility functions
  214. %%------------------------------------------------------------------------------
  215. chunk_request_body(Body, _ChunkSize) when is_tuple(Body) orelse
  216. is_function(Body) ->
  217. Body;
  218. chunk_request_body(Body, ChunkSize) ->
  219. chunk_request_body(Body, ChunkSize, []).
  220. chunk_request_body(Body, _ChunkSize, Acc) when Body == <<>>; Body == [] ->
  221. LastChunk = "0\r\n",
  222. lists:reverse(["\r\n", LastChunk | Acc]);
  223. chunk_request_body(Body, ChunkSize, Acc) when is_binary(Body),
  224. size(Body) >= ChunkSize ->
  225. <<ChunkBody:ChunkSize/binary, Rest/binary>> = Body,
  226. Chunk = [?dec2hex(ChunkSize),"\r\n",
  227. ChunkBody, "\r\n"],
  228. chunk_request_body(Rest, ChunkSize, [Chunk | Acc]);
  229. chunk_request_body(Body, _ChunkSize, Acc) when is_binary(Body) ->
  230. BodySize = size(Body),
  231. Chunk = [?dec2hex(BodySize),"\r\n",
  232. Body, "\r\n"],
  233. LastChunk = "0\r\n",
  234. lists:reverse(["\r\n", LastChunk, Chunk | Acc]);
  235. chunk_request_body(Body, ChunkSize, Acc) when length(Body) >= ChunkSize ->
  236. {ChunkBody, Rest} = split_list_at(Body, ChunkSize),
  237. Chunk = [?dec2hex(ChunkSize),"\r\n",
  238. ChunkBody, "\r\n"],
  239. chunk_request_body(Rest, ChunkSize, [Chunk | Acc]);
  240. chunk_request_body(Body, _ChunkSize, Acc) when is_list(Body) ->
  241. BodySize = length(Body),
  242. Chunk = [?dec2hex(BodySize),"\r\n",
  243. Body, "\r\n"],
  244. LastChunk = "0\r\n",
  245. lists:reverse(["\r\n", LastChunk, Chunk | Acc]).
  246. split_list_at(List, N) ->
  247. split_list_at(List, N, []).
  248. split_list_at([], _, Acc) ->
  249. {lists:reverse(Acc), []};
  250. split_list_at(List2, 0, List1) ->
  251. {lists:reverse(List1), List2};
  252. split_list_at([H | List2], N, List1) ->
  253. split_list_at(List2, N-1, [H | List1]).
  254. to_lower(X) when is_atom(X) ->
  255. list_to_atom(to_lower(atom_to_list(X)));
  256. to_lower(X) when is_list(X) ->
  257. string:to_lower(X).