From 694acd39643019ca570ce52dee22ea6da3adc43e Mon Sep 17 00:00:00 2001 From: Sergio Almeida Date: Tue, 27 Oct 2026 17:04:51 +0000 Subject: [PATCH 1/3] Make lhttpc compatible with OTP 29. Update elvis config and deps. Add specs to functions. --- .github/workflows/ci.yml | 11 ++- CHANGELOG.md | 18 +++++ elvis.config | 31 ++++---- rebar.config | 4 +- rebar.lock | 6 +- src/lhttpc.erl | 27 ++++--- src/lhttpc_client.erl | 133 ++++++++++++++++++++++++---------- src/lhttpc_lib.erl | 12 ++- src/lhttpc_manager.erl | 82 ++++++++++++++------- src/lhttpc_sup.erl | 3 +- test/lhttpc_manager_tests.erl | 22 ++++-- test/lhttpc_test_SUITE.erl | 104 +++++++++++++------------- 12 files changed, 287 insertions(+), 166 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7042740..bcd73ee 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,25 +13,24 @@ jobs: runs-on: ${{matrix.os}} strategy: matrix: - otp_vsn: [22, 23, 24] + otp_vsn: [26, 27, 28, 29] os: [ubuntu-latest] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - uses: erlef/setup-beam@v1 id: setup-beam with: otp-version: ${{matrix.otp_vsn}} - rebar3-version: '3.18' + rebar3-version: '3' - name: restore _build - uses: actions/cache@v2 + uses: actions/cache@v4 with: path: _build key: _build-cache-for-os-${{runner.os}}-otp-${{steps.setup-beam.outputs.otp-version}}-rebar3-${{steps.setup-beam.outputs.rebar3-version}}-hash-${{hashFiles('rebar.lock')}} - name: restore rebar3's cache - uses: actions/cache@v2 + uses: actions/cache@v4 with: path: ~/.cache/rebar3 key: rebar3-cache-for-os-${{runner.os}}-otp-${{steps.setup-beam.outputs.otp-version}}-rebar3-${{steps.setup-beam.outputs.rebar3-version}}-hash-${{hashFiles('rebar.lock')}} - run: make version - run: make ex_doc-dry - if: ${{matrix.otp_vsn >= 24}} diff --git a/CHANGELOG.md b/CHANGELOG.md index b59c53e..aa3b530 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,24 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added +- type specs to all functions [Sérgio Almeida] + +### Changed +- [dep.] `tls_certificate_check` from 1.21.0 to 1.35.0 [Sérgio Almeida] +- CI to run on OTP 26 to 29 [Sérgio Almeida] +- unexpected request failures to be reported + as `{error, Reason}` instead of `{error, {Reason, Stacktrace}}` [Sérgio Almeida] + +### Fixed +- TLS connections rejected with `{verify_ssl_cert, false}` on OTP 26 and later [Sérgio Almeida] +- `elvis.config` to the `elvis_core` 6.x format [Sérgio Almeida] + +### Removed +- compatibility with OTP 22 to 25 [Sérgio Almeida] + ## [4.3.2] - 2024-03-11 ### Changed diff --git a/elvis.config b/elvis.config index 766e629..bdc26c8 100644 --- a/elvis.config +++ b/elvis.config @@ -1,24 +1,19 @@ -[{elvis, [ - {config, [ - #{ dirs => ["src/**"], - filter => "*.erl", +[{config, [ + #{ files => ["src/**/*.erl"], ruleset => erl_files, rules => [{elvis_style, dont_repeat_yourself, disable}, - {elvis_style, no_if_expression, disable}] }, - #{ dirs => ["test/**"], - filter => "*.erl", - ruleset => erl_files, - rules => [{elvis_style, dont_repeat_yourself, disable}, - {elvis_style, invalid_dynamic_call, disable}, + {elvis_style, no_if_expression, disable}, + {elvis_style, no_receive_without_timeout, disable}, + {elvis_style, max_function_arity, disable}] }, + #{ files => ["test/**/*.erl"], + ruleset => erl_files_test, + rules => [{elvis_style, no_invalid_dynamic_calls, disable}, {elvis_style, function_naming_convention, disable}, {elvis_style, no_if_expression, disable}, - {elvis_style, atom_naming_convention, disable}] }, - #{ dirs => ["."], - filter => "rebar.config", - ruleset => rebar_config }, - #{ dirs => ["."], - filter => "elvis.config", - ruleset => elvis_config } + {elvis_style, atom_naming_convention, disable}, + {elvis_style, no_receive_without_timeout, disable}] }, + #{ files => ["rebar.config"], + ruleset => rebar_config } ]}, {verbose, true} -]}]. +]. diff --git a/rebar.config b/rebar.config index 3396cf8..4f2906d 100644 --- a/rebar.config +++ b/rebar.config @@ -1,6 +1,6 @@ %% == Erlang Compiler == -{minimum_otp_vsn, "22"}. +{minimum_otp_vsn, "26"}. {erl_opts, [ debug_info, @@ -13,7 +13,7 @@ %% == Dependencies and plugins == {deps, [ - {tls_certificate_check, "1.21.0"} + {tls_certificate_check, "1.35.0"} ]}. {project_plugins, [ diff --git a/rebar.lock b/rebar.lock index 4f80761..5f56f7f 100644 --- a/rebar.lock +++ b/rebar.lock @@ -1,13 +1,13 @@ {"1.2.0", [{<<"ssl_verify_fun">>,{pkg,<<"ssl_verify_fun">>,<<"1.1.7">>},1}, {<<"tls_certificate_check">>, - {pkg,<<"tls_certificate_check">>,<<"1.21.0">>}, + {pkg,<<"tls_certificate_check">>,<<"1.35.0">>}, 0}]}. [ {pkg_hash,[ {<<"ssl_verify_fun">>, <<"354C321CF377240C7B8716899E182CE4890C5938111A1296ADD3EC74CF1715DF">>}, - {<<"tls_certificate_check">>, <<"042AB2C0C860652BC5CF69C94E3A31F96676D14682E22EC7813BD173CEFF1788">>}]}, + {<<"tls_certificate_check">>, <<"6237B9CB9632B1F52F00EF852CD04D4AF70319C308D4F65BE1E45DA637578867">>}]}, {pkg_hash_ext,[ {<<"ssl_verify_fun">>, <<"FE4C190E8F37401D30167C8C405EDA19469F34577987C76DDE613E838BBC67F8">>}, - {<<"tls_certificate_check">>, <<"6CEE6CFFC35A390840D48D463541D50746A7B0E421ACAADB833CFC7961E490E7">>}]} + {<<"tls_certificate_check">>, <<"36FD91D635761DAFFA12E75B0C784B24510A69AD53348B8276A553D2D665B579">>}]} ]. diff --git a/src/lhttpc.erl b/src/lhttpc.erl index 456c2e7..dc5716b 100644 --- a/src/lhttpc.erl +++ b/src/lhttpc.erl @@ -26,7 +26,7 @@ %%% ---------------------------------------------------------------------------- %%------------------------------------------------------------------------------ -%%% @author Oscar Hellström +%%% @author Oscar Hellstr�m %%% @doc Main interface to the lightweight http client. %%% See {@link request/4}, {@link request/5} and {@link request/6} functions. %%% @end @@ -80,7 +80,7 @@ -type bodypart() :: iodata() | 'http_eob'. -export_type([bodypart/0]). --type socket() :: _. +-type socket() :: inet:socket() | ssl:sslsocket(). -export_type([socket/0]). -type port_num() :: 1..65535. @@ -194,7 +194,7 @@ stop() -> %% @doc Add a new named httpc_manager pool to the supervisor tree %% @end %%------------------------------------------------------------------------------ --spec add_pool(atom()) -> {ok, pid()} | {error, already_exists|term()}. +-spec add_pool(atom()) -> {ok, pid()} | {error, already_exists | term()}. add_pool(Name) when is_atom(Name) -> {ok, ConnTimeout} = application:get_env(lhttpc, connection_timeout), {ok, PoolSize} = application:get_env(lhttpc, pool_size), @@ -206,7 +206,7 @@ add_pool(Name) when is_atom(Name) -> %% @doc Add a new httpc_manager to the supervisor tree %% @end %%------------------------------------------------------------------------------ --spec add_pool(atom(), pos_integer()) -> {ok, pid()} | {error, already_exists|term()}. +-spec add_pool(atom(), pos_integer()) -> {ok, pid()} | {error, already_exists | term()}. add_pool(Name, ConnTimeout) when is_atom(Name), is_integer(ConnTimeout), ConnTimeout > 0 -> @@ -218,7 +218,7 @@ add_pool(Name, ConnTimeout) when is_atom(Name), %% @end %%------------------------------------------------------------------------------ -spec add_pool(atom(), non_neg_integer(), poolsize()) -> - {ok, pid()} | {error, already_exists|term()}. + {ok, pid()} | {error, already_exists | term()}. add_pool(Name, ConnTimeout, PoolSize) -> ChildSpec = {Name, {lhttpc_manager, start_link, [[{name, Name}, @@ -608,15 +608,19 @@ kill_client(Pid) -> %% @private %%------------------------------------------------------------------------------ -spec verify_options(options()) -> ok. -verify_options([{send_retry, N} | Options]) when is_integer(N), N >= 0 -> +verify_options([{send_retry, N} | Options]) + when is_integer(N) andalso + N >= 0 -> verify_options(Options); verify_options([{connect_timeout, infinity} | Options]) -> verify_options(Options); verify_options([{connect_timeout, MS} | Options]) - when is_integer(MS), MS >= 0 -> + when is_integer(MS) andalso + MS >= 0 -> verify_options(Options); verify_options([{partial_upload, WindowSize} | Options]) - when is_integer(WindowSize), WindowSize >= 0 -> + when is_integer(WindowSize) andalso + WindowSize >= 0 -> verify_options(Options); verify_options([{partial_upload, infinity} | Options]) -> verify_options(Options); @@ -631,7 +635,8 @@ verify_options([{proxy, List} | Options]) when is_list(List) -> verify_options([{proxy_ssl_options, List} | Options]) when is_list(List) -> verify_options(Options); verify_options([{pool, PidOrName} | Options]) - when is_pid(PidOrName); is_atom(PidOrName) -> + when is_pid(PidOrName) orelse + is_atom(PidOrName) -> verify_options(Options); verify_options([{pool_ensure, Bool} | Options]) when is_boolean(Bool) -> @@ -641,7 +646,7 @@ verify_options([{pool_connection_timeout, Size} | Options]) verify_options(Options); verify_options([{pool_max_size, Size} | Options]) when is_integer(Size) orelse - Size =:= infinity-> + Size =:= infinity -> verify_options(Options); verify_options([{use_pool, UsePool} | Options]) when is_boolean(UsePool) -> @@ -658,7 +663,7 @@ verify_options([]) -> %% @private %%------------------------------------------------------------------------------ -spec verify_partial_download([partial_download_option()]) -> ok. -verify_partial_download([{window_size, infinity} | Options])-> +verify_partial_download([{window_size, infinity} | Options]) -> verify_partial_download(Options); verify_partial_download([{window_size, Size} | Options]) when is_integer(Size), Size >= 0 -> diff --git a/src/lhttpc_client.erl b/src/lhttpc_client.erl index be89ae4..d6eeb02 100644 --- a/src/lhttpc_client.erl +++ b/src/lhttpc_client.erl @@ -28,7 +28,7 @@ %%------------------------------------------------------------------------------ %%% @private -%%% @author Oscar Hellström +%%% @author Oscar Hellstr�m %%% @doc This module implements the HTTP request handling. This should normally %%% not be called directly since it should be spawned by the lhttpc module. %%% @end @@ -74,7 +74,7 @@ host :: string(), port :: integer(), path :: string(), - is_ssl:: boolean(), + is_ssl :: boolean(), user :: string(), password :: string() }). @@ -102,12 +102,12 @@ new_url(Host, Port, Path, IsSSL, User, Password) -> user = User, password = Password }. --spec url(LhttpcURL :: lhttpc_url(), host) -> string(); - (LhttpcURL :: lhttpc_url(), port) -> integer(); - (LhttpcURL :: lhttpc_url(), path) -> string(); - (LhttpcURL :: lhttpc_url(), is_ssl) -> boolean(); - (LhttpcURL :: lhttpc_url(), user) -> string(); - (LhttpcURL :: lhttpc_url(), password) -> string(). +-spec url(LhttpcUrl :: lhttpc_url(), host) -> string(); + (LhttpcUrl :: lhttpc_url(), port) -> integer(); + (LhttpcUrl :: lhttpc_url(), path) -> string(); + (LhttpcUrl :: lhttpc_url(), is_ssl) -> boolean(); + (LhttpcUrl :: lhttpc_url(), user) -> string(); + (LhttpcUrl :: lhttpc_url(), password) -> string(). url(#lhttpc_url{ host = Host }, host) -> Host; url(#lhttpc_url{ port = Port }, port) -> Port; url(#lhttpc_url{ path = Path }, path) -> Path; @@ -129,12 +129,10 @@ request(From, Host, Port, Ssl, Path, Method, Hdrs, Body, Options) -> Result = try execute(From, Host, Port, Ssl, Path, Method, Hdrs, Body, Options) catch - throw:Reason -> - {response, self(), {error, Reason}}; error:closed -> {response, self(), {error, connection_closed}}; - error:Reason:Stack -> - {response, self(), {error, {Reason, Stack}}} + error:Reason:_ -> + {response, self(), {error, Reason}} end, case Result of {response, _, {ok, {no_return, _}}} -> ok; @@ -155,6 +153,9 @@ request(From, Host, Port, Ssl, Path, Method, Hdrs, Body, Options) -> %% socket used is new, it also makes the pool gen_server its controlling process. %% @end %%------------------------------------------------------------------------------ +-spec execute(pid(), string(), lhttpc:port_num(), boolean(), string(), + lhttpc:method(), lhttpc:headers(), iolist(), lhttpc:options()) -> + {'response', pid(), {'ok', any()}} | no_return(). execute(From, Host, Port, Ssl, Path, Method, Hdrs0, Body, Options) -> UploadWindowSize = proplists:get_value(partial_upload, Options), PartialUpload = proplists:is_defined(partial_upload, Options), @@ -167,7 +168,7 @@ execute(From, Host, Port, Ssl, Path, Method, Hdrs0, Body, Options) -> ProxyUrl when is_list(ProxyUrl), not Ssl -> % The point of HTTP CONNECT proxying is to use TLS tunneled in % a plain HTTP/1.1 connection to the proxy (RFC2817). - throw(origin_server_not_https); + error(origin_server_not_https); ProxyUrl when is_list(ProxyUrl) -> lhttpc_lib:parse_url(ProxyUrl) end, @@ -186,10 +187,18 @@ execute(From, Host, Port, Ssl, Path, Method, Hdrs0, Body, Options) -> BaseConnectOptions = proplists:get_value(connect_options, Options, []), ConnectOptions = - case Ssl andalso proplists:get_value(verify_ssl_cert, Options, ?DEFAULT_VERIFY_SSL_CERT) of - true -> + case {Ssl, proplists:get_value(verify_ssl_cert, Options, ?DEFAULT_VERIFY_SSL_CERT)} of + {true, true} -> tls_certificate_check:options(Host); - false -> + {true, false} -> + % Since OTP 26 ssl defaults to {verify, verify_peer}, which is + % rejected without CA certificates, so opting out of certificate + % verification has to be explicit. + case proplists:is_defined(verify, BaseConnectOptions) of + true -> BaseConnectOptions; + false -> [{verify, verify_none} | BaseConnectOptions] + end; + {false, _} -> BaseConnectOptions end, @@ -231,7 +240,12 @@ execute(From, Host, Port, Ssl, Path, Method, Hdrs0, Body, Options) -> % * Due to an error in this module (returning dead sockets for % instance) case UsePool of - false -> catch lhttpc_sock:close(NewSocket, Ssl); + false -> + try lhttpc_sock:close(NewSocket, Ssl) of + _ -> ok + catch + _:_ -> ok + end; true -> ok = lhttpc_manager:client_done(Pool, Host, Port, Ssl, NewSocket) end, @@ -245,9 +259,10 @@ execute(From, Host, Port, Ssl, Path, Method, Hdrs0, Body, Options) -> %% handles the proxy connection. %% @end %%------------------------------------------------------------------------------ +-spec send_request(client_state()) -> {any(), lhttpc:socket() | 'undefined'} | no_return(). send_request(#client_state{attempts = 0}) -> % Don't try again if the number of allowed attempts is 0. - throw(connection_closed); + error(closed); %we need a socket. send_request(#client_state{socket = undefined} = State) -> {Host, Port, Ssl} = request_first_destination(State), @@ -267,16 +282,16 @@ send_request(#client_state{socket = undefined} = State) -> send_request(State#client_state{socket = Socket}); {error, etimedout} -> % TCP stack decided to give up - throw(connect_timeout); + error(connect_timeout); {error, timeout} -> - throw(connect_timeout); + error(connect_timeout); {error, 'record overflow'} -> - throw(ssl_error); + error(ssl_error); {error, Reason} -> erlang:error(Reason) catch exit:{{{badmatch, {error, {asn1, _}}}, _}, _} -> - throw(ssl_decode_error); + error(ssl_decode_error); Type:Error:Stack -> error_logger:error_msg("Socket connection error: ~p ~p, ~p", [Type, Error, Stack]) @@ -316,7 +331,7 @@ send_request(#client_state{proxy = #lhttpc_url{}, proxy_setup = false} = State) read_proxy_connect_response(State, nil, nil); {error, closed} -> lhttpc_sock:close(Socket, Ssl), - throw(proxy_connection_closed); + error(proxy_connection_closed); {error, Reason} -> lhttpc_sock:close(Socket, Ssl), erlang:error(Reason) @@ -348,6 +363,8 @@ send_request(State) -> %%------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec request_first_destination(client_state()) -> + {lhttpc:host(), lhttpc:port_num(), boolean()}. request_first_destination(#client_state{proxy = #lhttpc_url{} = Proxy}) -> {url(Proxy, host), url(Proxy, port), url(Proxy, is_ssl)}; request_first_destination(#client_state{host = Host, port = Port, ssl = Ssl}) -> @@ -356,6 +373,8 @@ request_first_destination(#client_state{host = Host, port = Port, ssl = Ssl}) -> %%------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec read_proxy_connect_response(client_state(), integer() | 'nil', any()) -> + {any(), lhttpc:socket() | 'undefined'} | no_return(). read_proxy_connect_response(State, StatusCode, StatusText) -> Socket = State#client_state.socket, ProxyIsSsl = url((State#client_state.proxy), is_ssl), @@ -386,10 +405,10 @@ read_proxy_connect_response(State, StatusCode, StatusText) -> end, send_request(State2); {ok, http_eoh} -> - throw({proxy_connection_refused, StatusCode, StatusText}); + error({proxy_connection_refused, StatusCode, StatusText}); {error, closed} -> lhttpc_sock:close(Socket, ProxyIsSsl), - throw(proxy_connection_closed); + error(proxy_connection_closed); {error, Reason} -> erlang:error({proxy_connection_failed, Reason}) end. @@ -401,6 +420,8 @@ read_proxy_connect_response(State, StatusCode, StatusText) -> %% messages using functions in lhttpc module %% @end %%------------------------------------------------------------------------------ +-spec partial_upload(client_state()) -> + {any(), lhttpc:socket() | 'undefined'} | no_return(). partial_upload(State) -> Response = {ok, {self(), State#client_state.upload_window}}, State#client_state.requester ! {response, self(), Response}, @@ -409,7 +430,9 @@ partial_upload(State) -> %%------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ -partial_upload_loop(State = #client_state{requester = Pid}) -> +-spec partial_upload_loop(client_state()) -> + {any(), lhttpc:socket() | 'undefined'} | no_return(). +partial_upload_loop(#client_state{requester = Pid} = State) -> receive {trailers, Pid, Trailers} -> send_trailers(State, Trailers), @@ -426,14 +449,16 @@ partial_upload_loop(State = #client_state{requester = Pid}) -> %%------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ -send_body_part(State = #client_state{socket = Socket, ssl = Ssl}, BodyPart) -> +-spec send_body_part(client_state(), lhttpc:bodypart()) -> ok | no_return(). +send_body_part(#client_state{socket = Socket, ssl = Ssl} = State, BodyPart) -> Data = encode_body_part(State, BodyPart), check_send_result(State, lhttpc_sock:send(Socket, Data, Ssl)). %%------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ -send_trailers(State = #client_state{chunked_upload = true}, Trailers) -> +-spec send_trailers(client_state(), lhttpc:headers()) -> ok | no_return(). +send_trailers(#client_state{chunked_upload = true} = State, Trailers) -> Socket = State#client_state.socket, Ssl = State#client_state.ssl, Data = [<<"0\r\n">>, lhttpc_lib:format_hdrs(Trailers)], @@ -444,6 +469,7 @@ send_trailers(#client_state{chunked_upload = false}, _Trailers) -> %%------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec encode_body_part(client_state(), lhttpc:bodypart()) -> iodata(). encode_body_part(#client_state{chunked_upload = true}, http_eob) -> <<"0\r\n\r\n">>; % We don't send trailers after http_eob encode_body_part(#client_state{chunked_upload = false}, http_eob) -> @@ -457,16 +483,17 @@ encode_body_part(#client_state{chunked_upload = false}, Data) -> %%------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec check_send_result(client_state(), ok | {error, atom()}) -> ok | no_return(). check_send_result(_State, ok) -> ok; check_send_result(#client_state{socket = Sock, ssl = Ssl}, {error, Reason}) -> lhttpc_sock:close(Sock, Ssl), - throw(Reason). + error(Reason). %%------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ --spec read_response(client_state()) -> {any(), lhttpc:socket()} | no_return(). +-spec read_response(client_state()) -> {any(), lhttpc:socket() | 'undefined'} | no_return(). read_response(#client_state{socket = Socket, ssl = Ssl} = State) -> lhttpc_sock:setopts(Socket, [{packet, http}], Ssl), read_response(State, nil, {nil, nil}, []). @@ -477,7 +504,7 @@ read_response(#client_state{socket = Socket, ssl = Ssl} = State) -> %% @end %%------------------------------------------------------------------------------ -spec read_response(client_state(), {integer(), integer()} | 'nil', lhttpc:http_status(), - any()) -> {any(), lhttpc:socket()} | no_return(). + any()) -> {any(), lhttpc:socket() | 'undefined'} | no_return(). read_response(State, Vsn, {StatusCode, _} = Status, Hdrs) -> Socket = State#client_state.socket, Ssl = State#client_state.ssl, @@ -612,6 +639,9 @@ body_type(Hdrs) -> %%% @doc Called when {partial_download, PartialDownloadOptions} option is used. %%% @end %%------------------------------------------------------------------------------ +-spec read_partial_body(client_state(), {integer(), integer()} | 'nil', lhttpc:headers(), + 'chunked' | 'infinite' | {fixed_length, integer()}) -> + {'no_return', lhttpc:headers()} | no_return(). read_partial_body(State, _Vsn, Hdrs, chunked) -> Window = State#client_state.download_window, read_partial_chunked_body(State, Hdrs, Window, 0, [], 0); @@ -627,6 +657,9 @@ read_partial_body(State, _Vsn, Hdrs, {fixed_length, ContentLength}) -> %%% @doc Called when {partial_download, PartialDownloadOptions} option is NOT used. %%% @end %%------------------------------------------------------------------------------ +-spec read_body({integer(), integer()} | 'nil', lhttpc:headers(), boolean(), lhttpc:socket(), + 'chunked' | 'infinite' | {fixed_length, integer()}) -> + {binary(), lhttpc:headers()} | no_return(). read_body(_Vsn, Hdrs, Ssl, Socket, chunked) -> read_chunked_body(Socket, Ssl, Hdrs, []); read_body(Vsn, Hdrs, Ssl, Socket, infinite) -> @@ -638,9 +671,11 @@ read_body(_Vsn, Hdrs, Ssl, Socket, {fixed_length, ContentLength}) -> %%------------------------------------------------------------------------------ %%% @private %%------------------------------------------------------------------------------ -read_partial_finite_body(State = #client_state{}, Hdrs, 0, _Window) -> +-spec read_partial_finite_body(client_state(), lhttpc:headers(), integer(), + lhttpc:window_size()) -> {'no_return', lhttpc:headers()} | no_return(). +read_partial_finite_body(#client_state{} = State, Hdrs, 0, _Window) -> reply_end_of_body(State, [], Hdrs); -read_partial_finite_body(State = #client_state{requester = To}, Hdrs, +read_partial_finite_body(#client_state{requester = To} = State, Hdrs, ContentLength, 0) -> receive {ack, To} -> @@ -648,7 +683,7 @@ read_partial_finite_body(State = #client_state{requester = To}, Hdrs, {'DOWN', _, process, To, _} -> exit(normal) end; -read_partial_finite_body(State, Hdrs, ContentLength, Window) when Window >= 0-> +read_partial_finite_body(State, Hdrs, ContentLength, Window) when Window >= 0 -> case read_body_part(State, ContentLength) of {ok, Bin} -> State#client_state.requester ! {body_part, self(), Bin}, @@ -671,6 +706,7 @@ read_partial_finite_body(State, Hdrs, ContentLength, Window) when Window >= 0-> %%------------------------------------------------------------------------------ %%% @private %%------------------------------------------------------------------------------ +-spec read_body_part(client_state(), integer()) -> {ok, any()} | {error, atom()}. read_body_part(#client_state{part_size = infinity} = State, _ContentLength) -> lhttpc_sock:recv(State#client_state.socket, State#client_state.ssl); read_body_part(#client_state{part_size = PartSize} = State, ContentLength) @@ -688,6 +724,8 @@ read_body_part(#client_state{part_size = PartSize} = State, ContentLength) %%------------------------------------------------------------------------------ %%% @private %%------------------------------------------------------------------------------ +-spec read_length(lhttpc:headers(), boolean(), lhttpc:socket(), integer()) -> + {binary(), lhttpc:headers()} | no_return(). read_length(Hdrs, Ssl, Socket, Length) -> case lhttpc_sock:recv(Socket, Length, Ssl) of {ok, Data} -> @@ -699,6 +737,9 @@ read_length(Hdrs, Ssl, Socket, Length) -> %%------------------------------------------------------------------------------ %%% @private %%------------------------------------------------------------------------------ +-spec read_partial_chunked_body(client_state(), lhttpc:headers(), lhttpc:window_size(), + non_neg_integer(), [binary()], non_neg_integer()) -> + {'no_return', lhttpc:headers()} | no_return(). read_partial_chunked_body(State, Hdrs, Window, BufferSize, Buffer, 0) -> Socket = State#client_state.socket, Ssl = State#client_state.ssl, @@ -742,6 +783,7 @@ read_partial_chunked_body(State, Hdrs, Window, BufferSize, Buffer, RemSize) -> %%------------------------------------------------------------------------------ %%% @private %%------------------------------------------------------------------------------ +-spec read_chunk_size(lhttpc:socket(), boolean()) -> integer() | no_return(). read_chunk_size(Socket, Ssl) -> lhttpc_sock:setopts(Socket, [{packet, line}], Ssl), case lhttpc_sock:recv(Socket, Ssl) of @@ -754,9 +796,11 @@ read_chunk_size(Socket, Ssl) -> %%------------------------------------------------------------------------------ %%% @private %%------------------------------------------------------------------------------ +-spec reply_chunked_part(client_state(), [binary()], lhttpc:window_size()) -> + lhttpc:window_size() | no_return(). reply_chunked_part(_State, [], Window) -> Window; -reply_chunked_part(State = #client_state{requester = Pid}, Buff, 0) -> +reply_chunked_part(#client_state{requester = Pid} = State, Buff, 0) -> receive {ack, Pid} -> reply_chunked_part(State, Buff, 1); @@ -775,6 +819,8 @@ reply_chunked_part(#client_state{requester = Pid}, Buffer, Window) -> %%------------------------------------------------------------------------------ %%% @private %%------------------------------------------------------------------------------ +-spec read_chunked_body(lhttpc:socket(), boolean(), lhttpc:headers(), [binary()]) -> + {binary(), lhttpc:headers()} | no_return(). read_chunked_body(Socket, Ssl, Hdrs, Chunks) -> case read_chunk_size(Socket, Ssl) of 0 -> @@ -789,12 +835,14 @@ read_chunked_body(Socket, Ssl, Hdrs, Chunks) -> %%------------------------------------------------------------------------------ %%% @private %%------------------------------------------------------------------------------ +-spec chunk_size(nonempty_binary()) -> integer() | no_return(). chunk_size(Bin) -> erlang:list_to_integer(lists:reverse(chunk_size(Bin, [])), 16). %%------------------------------------------------------------------------------ %%% @private %%------------------------------------------------------------------------------ +-spec chunk_size(nonempty_binary(), [byte()]) -> [byte()]. chunk_size(<<$;, _/binary>>, Chars) -> Chars; chunk_size(<<"\r\n", _/binary>>, Chars) -> @@ -808,6 +856,8 @@ chunk_size(<>, Chars) -> %%------------------------------------------------------------------------------ %%% @private %%------------------------------------------------------------------------------ +-spec read_partial_chunk(lhttpc:socket(), boolean(), integer(), integer()) -> + {binary(), integer()} | no_return(). read_partial_chunk(Socket, Ssl, ChunkSize, ChunkSize) -> {read_chunk(Socket, Ssl, ChunkSize), 0}; read_partial_chunk(Socket, Ssl, Size, ChunkSize) -> @@ -822,6 +872,7 @@ read_partial_chunk(Socket, Ssl, Size, ChunkSize) -> %%------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec read_chunk(lhttpc:socket(), boolean(), non_neg_integer()) -> binary() | no_return(). read_chunk(Socket, Ssl, Size) -> lhttpc_sock:setopts(Socket, [{packet, raw}], Ssl), case lhttpc_sock:recv(Socket, Size + 2, Ssl) of @@ -861,14 +912,16 @@ reply_end_of_body(#client_state{requester = Requester}, Trailers, Hdrs) -> %%------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ -read_partial_infinite_body(State = #client_state{requester = To}, Hdrs, 0) -> +-spec read_partial_infinite_body(client_state(), lhttpc:headers(), lhttpc:window_size()) -> + {'no_return', lhttpc:headers()} | no_return(). +read_partial_infinite_body(#client_state{requester = To} = State, Hdrs, 0) -> receive {ack, To} -> read_partial_infinite_body(State, Hdrs, 1); {'DOWN', _, process, To, _} -> exit(normal) end; -read_partial_infinite_body(State = #client_state{requester = To}, Hdrs, Window) +read_partial_infinite_body(#client_state{requester = To} = State, Hdrs, Window) when Window >= 0 -> case read_infinite_body_part(State) of http_eob -> reply_end_of_body(State, [], Hdrs); @@ -901,6 +954,8 @@ read_infinite_body_part(#client_state{socket = Socket, ssl = Ssl}) -> %%------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec check_infinite_response({integer(), integer()} | 'nil', lhttpc:headers()) -> + ok | no_return(). check_infinite_response({1, Minor}, Hdrs) when Minor >= 1 -> HdrValue = lhttpc_lib:header_value("connection", Hdrs, "keep-alive"), case string:to_lower(HdrValue) of @@ -941,7 +996,9 @@ read_until_closed(Socket, Acc, Hdrs, Ssl) -> %%------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ -maybe_close_socket(Socket, Ssl, {1, Minor}, ReqHdrs, RespHdrs) when Minor >= 1-> +-spec maybe_close_socket(lhttpc:socket(), boolean(), {integer(), integer()}, + lhttpc:headers(), lhttpc:headers()) -> lhttpc:socket() | 'undefined'. +maybe_close_socket(Socket, Ssl, {1, Minor}, ReqHdrs, RespHdrs) when Minor >= 1 -> ClientConnection = ?CONNECTION_HDR(ReqHdrs, "keep-alive"), ServerConnection = ?CONNECTION_HDR(RespHdrs, "keep-alive"), if diff --git a/src/lhttpc_lib.erl b/src/lhttpc_lib.erl index 1f7103c..a0e1c43 100644 --- a/src/lhttpc_lib.erl +++ b/src/lhttpc_lib.erl @@ -28,7 +28,7 @@ %%------------------------------------------------------------------------------ %%% @private -%%% @author Oscar Hellström +%%% @author Oscar Hellstr�m %%% @doc %%% This module implements various library functions used in lhttpc. %%------------------------------------------------------------------------------ @@ -85,6 +85,7 @@ header_value(Hdr, Headers, Default) -> %% @doc %% @end %%------------------------------------------------------------------------------ +-spec canonical_headers(lhttpc:headers()) -> [{string(), iodata()}]. canonical_headers(Headers) -> [canonical_header(Header) || Header <- Headers]. @@ -92,9 +93,11 @@ canonical_headers(Headers) -> %% @doc %% @end %%------------------------------------------------------------------------------ +-spec canonical_header({lhttpc:header(), iodata()}) -> {string(), iodata()}. canonical_header({Name, Value}) -> {canonical_header_name(Name), Value}. +-spec canonical_header_name(atom() | binary() | [byte()]) -> [byte()]. canonical_header_name(Name) when is_list(Name) -> string:to_lower(Name); canonical_header_name(Name) when is_atom(Name) -> @@ -118,7 +121,7 @@ maybe_atom_to_list(List) -> %% @doc %% @end %%------------------------------------------------------------------------------ --spec parse_url(string()) -> lhttpc_client:lhttpc_url(). +-spec parse_url(nonempty_string()) -> lhttpc_client:lhttpc_url(). parse_url(URL) -> % XXX This should be possible to do with the re module? {Scheme, CredsHostPortPath} = split_scheme(URL), @@ -189,6 +192,7 @@ format_hdrs(Headers) -> %% @doc %% @end %%------------------------------------------------------------------------------ +-spec split_scheme(string()) -> {'http' | 'https', string()}. split_scheme("http://" ++ HostPortPath) -> {http, HostPortPath}; split_scheme("https://" ++ HostPortPath) -> @@ -199,6 +203,7 @@ split_scheme("https://" ++ HostPortPath) -> %% @doc %% @end %%------------------------------------------------------------------------------ +-spec split_credentials(string()) -> {string(), string(), nonempty_string()}. split_credentials(CredsHostPortPath) -> case string:tokens(CredsHostPortPath, "@") of [HostPortPath] -> @@ -218,6 +223,7 @@ split_credentials(CredsHostPortPath) -> end end. +-spec parse_query_string(string()) -> string(). -ifdef(OTP_RELEASE). -if(?OTP_RELEASE >= 23). parse_query_string(User0) -> @@ -271,6 +277,7 @@ split_host([], Host) -> %% @doc %% @end %%------------------------------------------------------------------------------ +-spec split_port('http' | 'https', string(), string()) -> {lhttpc:port_num(), string()}. split_port(http, [$/ | _] = Path, []) -> {80, Path}; split_port(https, [$/ | _] = Path, []) -> @@ -291,6 +298,7 @@ split_port(Scheme, [P | T], Port) -> %% @doc %% @end %%------------------------------------------------------------------------------ +-spec format_hdrs(lhttpc:headers(), iolist()) -> iolist(). format_hdrs([{Hdr, Value} | T], Acc) -> NewAcc = [Hdr, ": ", Value, "\r\n" | Acc], diff --git a/src/lhttpc_manager.erl b/src/lhttpc_manager.erl index a76f374..6bb6559 100644 --- a/src/lhttpc_manager.erl +++ b/src/lhttpc_manager.erl @@ -26,7 +26,7 @@ %%% ---------------------------------------------------------------------------- %%------------------------------------------------------------------------------ -%%% @author Oscar Hellström +%%% @author Oscar Hellstr�m %%% @author Filipe David Manana %%% @doc Connection manager for the HTTP client. %%% This gen_server is responsible for keeping track of persistent @@ -74,14 +74,18 @@ -behaviour(gen_server). -record(state, { - destinations = dict:new(), - sockets = dict:new(), - clients = dict:new(), % Pid => {Dest, MonRef} - queues = dict:new(), % Dest => queue of Froms + destinations = dict:new() :: destinations(), + sockets = dict:new() :: sockets(), + clients = dict:new() :: clients(), % Pid => {Dest, MonRef} + queues = dict:new() :: queues(), % Dest => queue of Froms max_pool_size = 50 :: non_neg_integer(), timeout = 300000 :: non_neg_integer() }). -type state() :: #state{}. +-type destinations() :: dict:dict(lhttpc:destination(), [lhttpc:socket()]). +-type sockets() :: dict:dict(lhttpc:socket(), {lhttpc:destination(), reference()}). +-type clients() :: dict:dict(pid(), {lhttpc:destination(), reference()}). +-type queues() :: dict:dict(lhttpc:destination(), queue:queue(gen_server:from())). %%============================================================================== %% Exported functions @@ -192,7 +196,7 @@ start_link(Options0) -> %%------------------------------------------------------------------------------ -spec ensure_call(lhttpc:pool_id(), pid(), lhttpc:host(), lhttpc:port_num(), boolean(), lhttpc:options()) -> - lhttpc:socket() | 'no_socket'. + lhttpc:socket() | 'undefined'. ensure_call(Pool, Pid, Host, Port, Ssl, Options) -> SocketRequest = {socket, Pid, Host, Port, Ssl}, try gen_server:call(Pool, SocketRequest, infinity) of @@ -246,13 +250,16 @@ client_done(Pool, Host, Port, Ssl, Socket) -> case lhttpc_sock:controlling_process(Socket, Pool, Ssl) of {ok, PoolPid} -> DoneMsg = {done, Host, Port, Ssl, Socket}, - DeliveryStatus = (catch gen_server:call(PoolPid, DoneMsg, infinity)), - case DeliveryStatus of - {'EXIT', {noproc, _}} -> catch lhttpc_sock:close(Socket, Ssl); - {'EXIT', {killed, _}} -> catch lhttpc_sock:close(Socket, Ssl); - ok -> ok - end, - ok; + try + ok = gen_server:call(PoolPid, DoneMsg, infinity) + catch + exit:{noproc, _} -> + _ = safe_close(Socket, Ssl), + ok; + exit:{killed, _} -> + _ = safe_close(Socket, Ssl), + ok + end; _ -> ok end. @@ -312,23 +319,22 @@ handle_call({connection_count, Destination}, _, State) -> {reply, Count, State}; handle_call({done, Host, Port, Ssl, Socket}, {Pid, _} = From, State) -> gen_server:reply(From, ok), - FinalState = case catch - begin + FinalState = + try Dest = {Host, Port, Ssl}, {Dest, MonRef} = dict:fetch(Pid, State#state.clients), true = erlang:demonitor(MonRef, [flush]), Clients2 = dict:erase(Pid, State#state.clients), deliver_socket(Socket, Dest, State#state{clients = Clients2}) - end - of - #state{}=NewState -> - NewState; - UnexpectedExc -> - CloseStatus = (catch lhttpc_sock:close(Socket, Ssl)), - error_logger:info_msg("lhttpc_manager, unrecognized socket (close_status ~p) is done " - "(error ~p)", [CloseStatus, UnexpectedExc]), - State - end, + catch + Class:Reason:Stacktrace -> + CloseStatus = safe_close(Socket, Ssl), + error_logger:info_msg("lhttpc_manager, unrecognized socket (close_status ~p) " + "is done (error ~p:~p, stacktrace ~p)", + [CloseStatus, Class, Reason, Stacktrace]), + State + end, + {noreply, FinalState}; handle_call(_, _, State) -> {reply, {error, unknown_request}, State}. @@ -397,6 +403,8 @@ code_change(_, State, _) -> %------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec find_socket(lhttpc:destination(), pid(), state()) -> + {{'ok', lhttpc:socket()} | 'no_socket', state()}. find_socket({_, _, Ssl} = Dest, Pid, State) -> Dests = State#state.destinations, case dict:find(Dest, Dests) of @@ -424,6 +432,7 @@ find_socket({_, _, Ssl} = Dest, Pid, State) -> %------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec remove_socket(lhttpc:socket(), state()) -> state(). remove_socket(Socket, State) -> Dests = State#state.destinations, case dict:find(Socket, State#state.sockets) of @@ -442,6 +451,7 @@ remove_socket(Socket, State) -> %------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec store_socket(lhttpc:destination(), lhttpc:socket(), state()) -> state(). store_socket({_, _, Ssl} = Dest, Socket, State) -> Timeout = State#state.timeout, Timer = erlang:send_after(Timeout, self(), {timeout, Socket}), @@ -460,6 +470,7 @@ store_socket({_, _, Ssl} = Dest, Socket, State) -> %------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec update_dest(lhttpc:destination(), [lhttpc:socket()], destinations()) -> destinations(). update_dest(Destination, [], Destinations) -> dict:erase(Destination, Destinations); update_dest(Destination, Sockets, Destinations) -> @@ -468,6 +479,7 @@ update_dest(Destination, Sockets, Destinations) -> %------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec close_sockets(sockets()) -> ok. close_sockets(Sockets) -> lists:foreach(fun({Socket, {{_, _, Ssl}, Timer}}) -> lhttpc_sock:close(Socket, Ssl), @@ -477,6 +489,7 @@ close_sockets(Sockets) -> %------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec cancel_timer(reference(), lhttpc:socket()) -> ok. cancel_timer(Timer, Socket) -> case erlang:cancel_timer(Timer) of false -> @@ -491,6 +504,7 @@ cancel_timer(Timer, Socket) -> %------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec add_to_queue(lhttpc:destination(), gen_server:from(), queues()) -> queues(). add_to_queue({_Host, _Port, _Ssl} = Dest, From, Queues) -> case dict:find(Dest, Queues) of error -> @@ -502,6 +516,8 @@ add_to_queue({_Host, _Port, _Ssl} = Dest, From, Queues) -> %------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec queue_out(lhttpc:destination(), queues()) -> + 'empty' | {'ok', gen_server:from(), queues()}. queue_out({_Host, _Port, _Ssl} = Dest, Queues) -> case dict:find(Dest, Queues) of error -> @@ -520,6 +536,7 @@ queue_out({_Host, _Port, _Ssl} = Dest, Queues) -> %------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec deliver_socket(lhttpc:socket(), lhttpc:destination(), state()) -> state(). deliver_socket(Socket, {_, _, Ssl} = Dest, State) -> case queue_out(Dest, State#state.queues) of empty -> @@ -534,7 +551,7 @@ deliver_socket(Socket, {_, _, Ssl} = Dest, State) -> lhttpc_sock:setopts(Socket, [{active, once}], Ssl), deliver_socket(Socket, Dest, State#state{queues = Queues2}); _ -> % Something wrong with the socket; just remove it - catch lhttpc_sock:close(Socket, Ssl), + _ = safe_close(Socket, Ssl), State end end. @@ -542,6 +559,7 @@ deliver_socket(Socket, {_, _, Ssl} = Dest, State) -> %------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec monitor_client(lhttpc:destination(), gen_server:from(), state()) -> state(). monitor_client(Dest, {Pid, _} = _From, State) -> MonRef = erlang:monitor(process, Pid), Clients2 = dict:store(Pid, {Dest, MonRef}, State#state.clients), @@ -550,6 +568,7 @@ monitor_client(Dest, {Pid, _} = _From, State) -> %------------------------------------------------------------------------------ %% @private %%------------------------------------------------------------------------------ +-spec maybe_apply_defaults([atom()], [{atom(), term()}]) -> [{atom(), term()}]. maybe_apply_defaults([], Options) -> Options; maybe_apply_defaults([OptName | Rest], Options) -> @@ -560,3 +579,14 @@ maybe_apply_defaults([OptName | Rest], Options) -> {ok, Default} = application:get_env(lhttpc, OptName), maybe_apply_defaults(Rest, [{OptName, Default} | Options]) end. + +%------------------------------------------------------------------------------ +%% @private +%%------------------------------------------------------------------------------ +-spec safe_close(lhttpc:socket(), boolean()) -> ok | {error, term()}. +safe_close(Socket, Ssl) -> + try + lhttpc_sock:close(Socket, Ssl) + catch + Class:Reason -> {error, {Class, Reason}} + end. diff --git a/src/lhttpc_sup.erl b/src/lhttpc_sup.erl index aa22f67..22b6176 100644 --- a/src/lhttpc_sup.erl +++ b/src/lhttpc_sup.erl @@ -27,7 +27,7 @@ %%% ---------------------------------------------------------------------------- %%------------------------------------------------------------------------------ -%%% @author Oscar Hellström +%%% @author Oscar Hellstr�m %%% @doc Top supervisor for the lhttpc application. %%% This is normally started by the application behaviour implemented in %%% {@link lhttpc}. @@ -60,6 +60,7 @@ start_link() -> %%------------------------------------------------------------------------------ %% @hidden %%------------------------------------------------------------------------------ +-spec init(any()) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec()]}}. init(_) -> LHTTPCManager = {lhttpc_manager, {lhttpc_manager, start_link, [[{name, lhttpc_manager}]]}, diff --git a/test/lhttpc_manager_tests.erl b/test/lhttpc_manager_tests.erl index 30be36a..b20ded0 100644 --- a/test/lhttpc_manager_tests.erl +++ b/test/lhttpc_manager_tests.erl @@ -25,7 +25,7 @@ %%% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %%% ---------------------------------------------------------------------------- -%%% @author Oscar Hellström +%%% @author Oscar Hellstr�m %%% @author Filipe David Manana -module(lhttpc_manager_tests). @@ -71,7 +71,7 @@ empty_manager() -> ?assertEqual(ok, stop_client(Client)), ?assertEqual(0, lhttpc_manager:connection_count(lhttpc_manager)), - catch gen_tcp:close(LS), + safe_close(LS), unlink(whereis(lhttpc_manager)), ok. @@ -103,7 +103,7 @@ one_socket() -> ?assertEqual(ok, stop_client(Client1)), ?assertEqual(ok, stop_client(Client2)), - catch gen_tcp:close(LS), + safe_close(LS), unlink(whereis(lhttpc_manager)), ok. @@ -141,7 +141,7 @@ connection_timeout() -> ?assertEqual(ok, ping_client(Client)), ?assertEqual(1, lhttpc_manager:connection_count(lhttpc_manager)), - catch gen_tcp:close(LS), + safe_close(LS), ?assertEqual(ok, stop_client(Client)), unlink(whereis(lhttpc_manager)), ok. @@ -266,7 +266,7 @@ many_sockets() -> lhttpc_manager ! {tcp_closed, Socket3}, ?assertEqual(0, lhttpc_manager:connection_count(lhttpc_manager)), - catch gen_tcp:close(LS), + safe_close(LS), ?assertEqual(ok, stop_client(Client1)), ?assertEqual(ok, stop_client(Client2)), ?assertEqual(ok, stop_client(Client3)), @@ -314,7 +314,7 @@ closed_race_cond() -> ?assertEqual(0, lhttpc_manager:connection_count(lhttpc_manager)), ?assertEqual(ok, stop_client(Client)), - catch gen_tcp:close(LS), + safe_close(LS), unlink(whereis(lhttpc_manager)), ok. @@ -327,7 +327,7 @@ spawn_client() -> client_loop(Parent, Socket) -> receive stop -> - catch gen_tcp:close(Socket), + safe_close(Socket), Parent ! stopped; {get_socket, Ref} -> Parent ! {socket, Ref, Socket}, @@ -419,3 +419,11 @@ stop_client(Client) -> get_port() -> {ok, P} = application:get_env(lhttpc, test_port), P. + +-spec safe_close(gen_tcp:socket()) -> ok | {error, term()}. +safe_close(Socket) -> + try + gen_tcp:close(Socket) + catch + Class:Reason -> {error, {Class, Reason}} + end. diff --git a/test/lhttpc_test_SUITE.erl b/test/lhttpc_test_SUITE.erl index ae824ea..6e3bbd7 100644 --- a/test/lhttpc_test_SUITE.erl +++ b/test/lhttpc_test_SUITE.erl @@ -25,12 +25,11 @@ %%% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %%% ---------------------------------------------------------------------------- -%%% @author Oscar Hellström +%%% @author Oscar Hellstr�m -module(lhttpc_test_SUITE). -compile(export_all). -export([test_no/2]). --import(webserver, [start/3, start/4]). -include_lib("eunit/include/eunit.hrl"). @@ -209,7 +208,7 @@ simple_get_ipv6(_Config) -> -endif. empty_get(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun empty_body/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun empty_body/5]), URL = url(Port, "/empty"), {ok, Response} = lhttpc:request(URL, "GET", [], 1000), ?assertEqual({200, "OK"}, status(Response)), @@ -218,7 +217,7 @@ empty_get(_Config) -> basic_auth(_Config) -> User = "foo", Passwd = "bar", - Port = start(?PROJECT_ROOT, gen_tcp, [basic_auth_responder(User, Passwd)]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [basic_auth_responder(User, Passwd)]), URL = url(Port, "/empty", User, Passwd), {ok, Response} = lhttpc:request(URL, "GET", [], 1000), ?assertEqual({200, "OK"}, status(Response)), @@ -227,7 +226,7 @@ basic_auth(_Config) -> missing_basic_auth(_Config) -> User = "foo", Passwd = "bar", - Port = start(?PROJECT_ROOT, gen_tcp, [basic_auth_responder(User, Passwd)]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [basic_auth_responder(User, Passwd)]), URL = url(Port, "/empty"), {ok, Response} = lhttpc:request(URL, "GET", [], 1000), ?assertEqual({401, "Unauthorized"}, status(Response)), @@ -236,14 +235,14 @@ missing_basic_auth(_Config) -> wrong_basic_auth(_Config) -> User = "foo", Passwd = "bar", - Port = start(?PROJECT_ROOT, gen_tcp, [basic_auth_responder(User, Passwd)]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [basic_auth_responder(User, Passwd)]), URL = url(Port, "/empty", User, "wrong_password"), {ok, Response} = lhttpc:request(URL, "GET", [], 1000), ?assertEqual({401, "Unauthorized"}, status(Response)), ?assertEqual(<<"wrong_auth">>, body(Response)). get_with_mandatory_hdrs(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5]), URL = url(Port, "/host"), Body = <>, Hdrs = [ @@ -255,7 +254,7 @@ get_with_mandatory_hdrs(_Config) -> ?assertEqual(<>, body(Response)). get_with_mandatory_hdrs_by_atoms(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5]), URL = url(Port, "/host"), Body = <>, Hdrs = [ @@ -267,7 +266,7 @@ get_with_mandatory_hdrs_by_atoms(_Config) -> ?assertEqual(<>, body(Response)). get_with_mandatory_hdrs_by_binaries(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5]), URL = url(Port, "/host"), Body = <>, Hdrs = [ @@ -279,7 +278,7 @@ get_with_mandatory_hdrs_by_binaries(_Config) -> ?assertEqual(<>, body(Response)). get_with_connect_options(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun empty_body/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun empty_body/5]), URL = url(Port, "/empty"), Options = [{connect_options, [{ip, {127, 0, 0, 1}}, {port, 0}]}], {ok, Response} = lhttpc:request(URL, "GET", [], [], 1000, Options), @@ -287,14 +286,14 @@ get_with_connect_options(_Config) -> ?assertEqual(<<>>, body(Response)). no_content_length(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun no_content_length/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun no_content_length/5]), URL = url(Port, "/no_cl"), {ok, Response} = lhttpc:request(URL, "GET", [], 1000), ?assertEqual({200, "OK"}, status(Response)), ?assertEqual(<>, body(Response)). no_content_length_1_0(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun no_content_length_1_0/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun no_content_length_1_0/5]), URL = url(Port, "/no_cl"), {ok, Response} = lhttpc:request(URL, "GET", [], 1000), ?assertEqual({200, "OK"}, status(Response)), @@ -308,7 +307,7 @@ trailing_space_header(_Config) -> %% which can cause crash in lhttpc_client:body_type when Content-Length %% is converted from list to integer trailing_space_header(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun trailing_space_header/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun trailing_space_header/5]), URL = url(Port, "/no_cl"), {ok, Response} = lhttpc:request(URL, "GET", [], 1000), Headers = headers(Response), @@ -317,56 +316,56 @@ trailing_space_header(_Config) -> -endif. get_not_modified(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun not_modified_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun not_modified_response/5]), URL = url(Port, "/not_modified"), {ok, Response} = lhttpc:request(URL, "GET", [], [], 1000), ?assertEqual({304, "Not Modified"}, status(Response)), ?assertEqual(<<>>, body(Response)). simple_head(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun head_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun head_response/5]), URL = url(Port, "/HEAD"), {ok, Response} = lhttpc:request(URL, "HEAD", [], 1000), ?assertEqual({200, "OK"}, status(Response)), ?assertEqual(<<>>, body(Response)). simple_head_atom(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun head_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun head_response/5]), URL = url(Port, "/head"), {ok, Response} = lhttpc:request(URL, head, [], 1000), ?assertEqual({200, "OK"}, status(Response)), ?assertEqual(<<>>, body(Response)). delete_no_content(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun no_content_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun no_content_response/5]), URL = url(Port, "/delete_no_content"), {ok, Response} = lhttpc:request(URL, delete, [], 1000), ?assertEqual({204, "OK"}, status(Response)), ?assertEqual(<<>>, body(Response)). delete_content(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5]), URL = url(Port, "/delete_content"), {ok, Response} = lhttpc:request(URL, "DELETE", [], 1000), ?assertEqual({200, "OK"}, status(Response)), ?assertEqual(<>, body(Response)). options_no_content(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun head_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun head_response/5]), URL = url(Port, "/options_no_content"), {ok, Response} = lhttpc:request(URL, "OPTIONS", [], 1000), ?assertEqual({200, "OK"}, status(Response)), ?assertEqual(<<>>, body(Response)). options_content(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5]), URL = url(Port, "/options_content"), {ok, Response} = lhttpc:request(URL, "OPTIONS", [], 1000), ?assertEqual({200, "OK"}, status(Response)), ?assertEqual(<>, body(Response)). server_connection_close(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun respond_and_close/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun respond_and_close/5]), URL = url(Port, "/close"), Body = pid_to_list(self()), {ok, Response} = lhttpc:request(URL, "PUT", [], Body, 1000), @@ -375,7 +374,7 @@ server_connection_close(_Config) -> receive closed -> ok end. client_connection_close(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun respond_and_wait/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun respond_and_wait/5]), URL = url(Port, "/close"), Body = pid_to_list(self()), Hdrs = [{"Connection", "close"}], @@ -384,7 +383,7 @@ client_connection_close(_Config) -> receive closed -> ok end. pre_1_1_server_connection(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun pre_1_1_server/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun pre_1_1_server/5]), URL = url(Port, "/close"), Body = pid_to_list(self()), {ok, _} = lhttpc:request(URL, put, [], Body, 1000), @@ -394,7 +393,7 @@ pre_1_1_server_connection(_Config) -> receive closed -> ok end. pre_1_1_server_keep_alive(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [ + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [ fun pre_1_1_server_keep_alive/5, fun pre_1_1_server/5 ]), @@ -416,7 +415,7 @@ simple_put(_Config) -> simple("PUT"). post(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun copy_body/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun copy_body/5]), URL = url(Port, "/post"), {X, Y, Z} = erlang:timestamp(), Body = [ @@ -432,7 +431,7 @@ post(_Config) -> ?assertEqual(iolist_to_binary(Body), body(Response)). post_100_continue(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun copy_body_100_continue/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun copy_body_100_continue/5]), URL = url(Port, "/post"), {X, Y, Z} = erlang:timestamp(), Body = [ @@ -448,7 +447,7 @@ post_100_continue(_Config) -> ?assertEqual(iolist_to_binary(Body), body(Response)). persistent_connection(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [ + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [ fun simple_response/5, fun simple_response/5, fun copy_body/5 @@ -466,12 +465,12 @@ persistent_connection(_Config) -> ?assertEqual(<<>>, body(ThirdResponse)). request_timeout(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun very_slow_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun very_slow_response/5]), URL = url(Port, "/slow"), ?assertEqual({error, timeout}, lhttpc:request(URL, get, [], 50)). connection_timeout(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5, fun simple_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5, fun simple_response/5]), URL = url(Port, "/close_conn"), lhttpc_manager:update_connection_timeout(lhttpc_manager, 50), % very short keep alive {ok, Response} = lhttpc:request(URL, get, [], 100), @@ -483,7 +482,7 @@ connection_timeout(_Config) -> lhttpc_manager:update_connection_timeout(lhttpc_manager, 300000). % set back suspended_manager(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5, fun simple_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5, fun simple_response/5]), URL = url(Port, "/persistent"), {ok, FirstResponse} = lhttpc:request(URL, get, [], 50), ?assertEqual({200, "OK"}, status(FirstResponse)), @@ -499,7 +498,9 @@ suspended_manager(_Config) -> ?assertEqual(<>, body(SecondResponse)). chunked_encoding(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun chunked_response/5, fun chunked_response_t/5]), + Port = webserver:start(?PROJECT_ROOT, + gen_tcp, + [fun chunked_response/5, fun chunked_response_t/5]), URL = url(Port, "/chunked"), {ok, FirstResponse} = lhttpc:request(URL, get, [], 50), ?assertEqual({200, "OK"}, status(FirstResponse)), @@ -517,7 +518,7 @@ chunked_encoding(_Config) -> headers(SecondResponse))). partial_upload_identity(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5, fun simple_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5, fun simple_response/5]), URL = url(Port, "/partial_upload"), Body = [<<"This">>, <<" is ">>, <<"chunky">>, <<" stuff!">>], Hdrs = [{"Content-Length", integer_to_list(iolist_size(Body))}], @@ -539,7 +540,7 @@ partial_upload_identity(_Config) -> lhttpc_lib:header_value("x-test-orig-body", headers(Response2))). partial_upload_identity_iolist(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5, fun simple_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5, fun simple_response/5]), URL = url(Port, "/partial_upload"), Body = ["This", [<<" ">>, $i, $s, [" "]], <<"chunky">>, [<<" stuff!">>]], Hdrs = [{"Content-Length", integer_to_list(iolist_size(Body))}], @@ -565,7 +566,7 @@ partial_upload_chunked(_Config) -> {skip, "Broken test case"}. -else. partial_upload_chunked(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun chunked_upload/5, fun chunked_upload/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun chunked_upload/5, fun chunked_upload/5]), URL = url(Port, "/partial_upload_chunked"), Body = ["This", [<<" ">>, $i, $s, [" "]], <<"chunky">>, [<<" stuff!">>]], Options = [{partial_upload, 1}], @@ -601,7 +602,7 @@ partial_upload_chunked_no_trailer(_Config) -> {skip, "Broken test case"}. -else. partial_upload_chunked_no_trailer(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun chunked_upload/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun chunked_upload/5]), URL = url(Port, "/partial_upload_chunked_no_trailer"), Body = [<<"This">>, <<" is ">>, <<"chunky">>, <<" stuff!">>], Options = [{partial_upload, 1}], @@ -622,7 +623,7 @@ partial_download_illegal_option(_Config) -> [{partial_download, [{foo, bar}]}])). partial_download_identity(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun large_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun large_response/5]), URL = url(Port, "/partial_download_identity"), PartialDownload = [ {window_size, 1} @@ -635,7 +636,7 @@ partial_download_identity(_Config) -> ?assertEqual(<>, Body). partial_download_infinity_window(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun large_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun large_response/5]), URL = url(Port, "/partial_download_identity"), PartialDownload = [ {window_size, infinity} @@ -647,7 +648,7 @@ partial_download_infinity_window(_Config) -> ?assertEqual(<>, Body). partial_download_no_content_length(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun no_content_length/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun no_content_length/5]), URL = url(Port, "/no_cl"), PartialDownload = [ {window_size, 1} @@ -659,7 +660,7 @@ partial_download_no_content_length(_Config) -> ?assertEqual(<>, Body). partial_download_no_content(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun no_content_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun no_content_response/5]), URL = url(Port, "/partial_download_identity"), PartialDownload = [ {window_size, 1} @@ -671,7 +672,7 @@ partial_download_no_content(_Config) -> ?assertEqual(undefined, Body). limited_partial_download_identity(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun large_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun large_response/5]), URL = url(Port, "/partial_download_identity"), PartialDownload = [ {window_size, 1}, @@ -685,7 +686,7 @@ limited_partial_download_identity(_Config) -> ?assertEqual(<>, Body). partial_download_chunked(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun large_chunked_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun large_chunked_response/5]), URL = url(Port, "/partial_download_identity"), PartialDownload = [ {window_size, 1}, @@ -699,7 +700,7 @@ partial_download_chunked(_Config) -> ?assertEqual(<>, Body). partial_download_chunked_infinite_part(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun large_chunked_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun large_chunked_response/5]), URL = url(Port, "/partial_download_identity"), PartialDownload = [ {window_size, 1}, @@ -713,7 +714,7 @@ partial_download_chunked_infinite_part(_Config) -> ?assertEqual(<>, Body). partial_download_smallish_chunks(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun large_chunked_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun large_chunked_response/5]), URL = url(Port, "/partial_download_identity"), PartialDownload = [ {window_size, 1}, @@ -727,7 +728,7 @@ partial_download_smallish_chunks(_Config) -> ?assertEqual(<>, Body). partial_download_slow_chunks(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun slow_chunked_response/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun slow_chunked_response/5]), URL = url(Port, "/slow"), PartialDownload = [ {window_size, 1}, @@ -740,13 +741,12 @@ partial_download_slow_chunks(_Config) -> ?assertEqual(<>, Body). close_connection(_Config) -> - Port = start(?PROJECT_ROOT, gen_tcp, [fun close_connection/5]), + Port = webserver:start(?PROJECT_ROOT, gen_tcp, [fun close_connection/5]), URL = url(Port, "/close"), - ?assertEqual({error, connection_closed}, lhttpc:request(URL, "GET", [], - 1000)). + ?assertEqual({error, connection_closed}, lhttpc:request(URL, "GET", [], 1000)). ssl_get(_Config) -> - Port = start(?PROJECT_ROOT, ssl, [fun simple_response/5]), + Port = webserver:start(?PROJECT_ROOT, ssl, [fun simple_response/5]), URL = ssl_url(Port, "/simple"), {ok, Response} = lhttpc:request(URL, "GET", [], <<>>, 1000, [{verify_ssl_cert, false}]), ?assertEqual({200, "OK"}, status(Response)), @@ -757,7 +757,7 @@ ssl_get_ipv6(_Config) -> {skip, "IPv6 support not considered"}. -else. ssl_get_ipv6(_Config) -> - case start(?PROJECT_ROOT, ssl, [fun simple_response/5], inet6) of + case webserver:start(?PROJECT_ROOT, ssl, [fun simple_response/5], inet6) of {error, family_not_supported} -> % Localhost has no IPv6 support - not a big issue. {skip, "Impossible to test IPv6 support"}; @@ -770,7 +770,7 @@ ssl_get_ipv6(_Config) -> -endif. ssl_post(_Config) -> - Port = start(?PROJECT_ROOT, ssl, [fun copy_body/5]), + Port = webserver:start(?PROJECT_ROOT, ssl, [fun copy_body/5]), URL = ssl_url(Port, "/simple"), Body = "SSL Test ?assertEqual(BinaryBody, body(Response)). ssl_chunked(_Config) -> - Port = start(?PROJECT_ROOT, ssl, [fun chunked_response/5, fun chunked_response_t/5]), + Port = webserver:start(?PROJECT_ROOT, ssl, [fun chunked_response/5, fun chunked_response_t/5]), URL = ssl_url(Port, "/ssl_chunked"), FirstResult = lhttpc:request(URL, get, [], <<>>, 100, [{verify_ssl_cert, false}]), ?assertMatch({ok, _}, FirstResult), @@ -833,7 +833,7 @@ simple(Method) -> simple(Method, inet). simple(Method, Family) -> - case start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5], Family) of + case webserver:start(?PROJECT_ROOT, gen_tcp, [fun simple_response/5], Family) of {error, family_not_supported} when Family =:= inet6 -> % Localhost has no IPv6 support - not a big issue. {skip, "Impossible to test IPv6 support"}; From 8dd06b2f286b82f2c43d5b055557cb0556510453 Mon Sep 17 00:00:00 2001 From: Sergio Almeida Date: Wed, 28 Oct 2026 09:39:42 +0000 Subject: [PATCH 2/3] Fix PR comments --- CHANGELOG.md | 6 +++--- elvis.config | 5 +++-- src/lhttpc.app.src | 4 ++-- src/lhttpc.erl | 4 ++-- src/lhttpc_client.erl | 30 ++++++++++++++++-------------- src/lhttpc_lib.erl | 14 ++------------ src/lhttpc_manager.erl | 4 ++-- src/lhttpc_sock.erl | 4 ++-- src/lhttpc_sup.erl | 4 ++-- test/lhttpc_lib_tests.erl | 5 +++-- test/lhttpc_manager_tests.erl | 4 ++-- test/lhttpc_test_SUITE.erl | 4 ++-- test/util/socket_server.erl | 4 ++-- test/util/webserver.erl | 4 ++-- 14 files changed, 45 insertions(+), 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aa3b530..1d79e5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [Unreleased] ### Added - type specs to all functions [Sérgio Almeida] @@ -13,8 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - [dep.] `tls_certificate_check` from 1.21.0 to 1.35.0 [Sérgio Almeida] - CI to run on OTP 26 to 29 [Sérgio Almeida] -- unexpected request failures to be reported - as `{error, Reason}` instead of `{error, {Reason, Stacktrace}}` [Sérgio Almeida] +- `elvis.config` to disable `no_receive_without_timeout` and `no_throw` rules [Sérgio Almeida] +- exported type `lhttpc:socket()` from `_` to `inet:socket() | ssl:sslsocket()` [Sérgio Almeida] ### Fixed - TLS connections rejected with `{verify_ssl_cert, false}` on OTP 26 and later [Sérgio Almeida] diff --git a/elvis.config b/elvis.config index bdc26c8..b218a68 100644 --- a/elvis.config +++ b/elvis.config @@ -3,8 +3,9 @@ ruleset => erl_files, rules => [{elvis_style, dont_repeat_yourself, disable}, {elvis_style, no_if_expression, disable}, - {elvis_style, no_receive_without_timeout, disable}, - {elvis_style, max_function_arity, disable}] }, + {elvis_style, max_function_arity, disable}, + {elvis_style, no_throw, disable}, + {elvis_style, no_receive_without_timeout, disable}] }, #{ files => ["test/**/*.erl"], ruleset => erl_files_test, rules => [{elvis_style, no_invalid_dynamic_calls, disable}, diff --git a/src/lhttpc.app.src b/src/lhttpc.app.src index bbd504a..61de32d 100644 --- a/src/lhttpc.app.src +++ b/src/lhttpc.app.src @@ -1,4 +1,4 @@ -%%% -*- coding: latin-1 -*- +%%% -*- coding: utf-8 -*- %%% ---------------------------------------------------------------------------- %%% Copyright (c) 2009, Erlang Training and Consulting Ltd. %%% All rights reserved. @@ -25,7 +25,7 @@ %%% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %%% ---------------------------------------------------------------------------- -%%% @author Oscar Hellström +%%% @author Oscar Hellström %%% @doc This is the specification for the lhttpc application. %%% @end {application, lhttpc, [ diff --git a/src/lhttpc.erl b/src/lhttpc.erl index dc5716b..30d2249 100644 --- a/src/lhttpc.erl +++ b/src/lhttpc.erl @@ -1,4 +1,4 @@ -%%% -*- coding: latin-1 -*- +%%% -*- coding: utf-8 -*- %%% ---------------------------------------------------------------------------- %%% Copyright (c) 2009, Erlang Training and Consulting Ltd. %%% All rights reserved. @@ -26,7 +26,7 @@ %%% ---------------------------------------------------------------------------- %%------------------------------------------------------------------------------ -%%% @author Oscar Hellstr�m +%%% @author Oscar Hellström %%% @doc Main interface to the lightweight http client. %%% See {@link request/4}, {@link request/5} and {@link request/6} functions. %%% @end diff --git a/src/lhttpc_client.erl b/src/lhttpc_client.erl index d6eeb02..01b67c4 100644 --- a/src/lhttpc_client.erl +++ b/src/lhttpc_client.erl @@ -1,5 +1,5 @@ %% @hidden -%%% -*- coding: latin-1 -*- +%%% -*- coding: utf-8 -*- %%% ---------------------------------------------------------------------------- %%% Copyright (c) 2009, Erlang Training and Consulting Ltd. %%% All rights reserved. @@ -28,7 +28,7 @@ %%------------------------------------------------------------------------------ %%% @private -%%% @author Oscar Hellstr�m +%%% @author Oscar Hellström %%% @doc This module implements the HTTP request handling. This should normally %%% not be called directly since it should be spawned by the lhttpc module. %%% @end @@ -129,10 +129,12 @@ request(From, Host, Port, Ssl, Path, Method, Hdrs, Body, Options) -> Result = try execute(From, Host, Port, Ssl, Path, Method, Hdrs, Body, Options) catch + throw:Reason -> + {response, self(), {error, Reason}}; error:closed -> {response, self(), {error, connection_closed}}; - error:Reason:_ -> - {response, self(), {error, Reason}} + error:Reason:Stack -> + {response, self(), {error, {Reason, Stack}}} end, case Result of {response, _, {ok, {no_return, _}}} -> ok; @@ -168,7 +170,7 @@ execute(From, Host, Port, Ssl, Path, Method, Hdrs0, Body, Options) -> ProxyUrl when is_list(ProxyUrl), not Ssl -> % The point of HTTP CONNECT proxying is to use TLS tunneled in % a plain HTTP/1.1 connection to the proxy (RFC2817). - error(origin_server_not_https); + throw(origin_server_not_https); ProxyUrl when is_list(ProxyUrl) -> lhttpc_lib:parse_url(ProxyUrl) end, @@ -262,7 +264,7 @@ execute(From, Host, Port, Ssl, Path, Method, Hdrs0, Body, Options) -> -spec send_request(client_state()) -> {any(), lhttpc:socket() | 'undefined'} | no_return(). send_request(#client_state{attempts = 0}) -> % Don't try again if the number of allowed attempts is 0. - error(closed); + throw(connection_closed); %we need a socket. send_request(#client_state{socket = undefined} = State) -> {Host, Port, Ssl} = request_first_destination(State), @@ -282,16 +284,16 @@ send_request(#client_state{socket = undefined} = State) -> send_request(State#client_state{socket = Socket}); {error, etimedout} -> % TCP stack decided to give up - error(connect_timeout); + throw(connect_timeout); {error, timeout} -> - error(connect_timeout); + throw(connect_timeout); {error, 'record overflow'} -> - error(ssl_error); + throw(ssl_error); {error, Reason} -> erlang:error(Reason) catch exit:{{{badmatch, {error, {asn1, _}}}, _}, _} -> - error(ssl_decode_error); + throw(ssl_decode_error); Type:Error:Stack -> error_logger:error_msg("Socket connection error: ~p ~p, ~p", [Type, Error, Stack]) @@ -331,7 +333,7 @@ send_request(#client_state{proxy = #lhttpc_url{}, proxy_setup = false} = State) read_proxy_connect_response(State, nil, nil); {error, closed} -> lhttpc_sock:close(Socket, Ssl), - error(proxy_connection_closed); + throw(proxy_connection_closed); {error, Reason} -> lhttpc_sock:close(Socket, Ssl), erlang:error(Reason) @@ -405,10 +407,10 @@ read_proxy_connect_response(State, StatusCode, StatusText) -> end, send_request(State2); {ok, http_eoh} -> - error({proxy_connection_refused, StatusCode, StatusText}); + throw({proxy_connection_refused, StatusCode, StatusText}); {error, closed} -> lhttpc_sock:close(Socket, ProxyIsSsl), - error(proxy_connection_closed); + throw(proxy_connection_closed); {error, Reason} -> erlang:error({proxy_connection_failed, Reason}) end. @@ -488,7 +490,7 @@ check_send_result(_State, ok) -> ok; check_send_result(#client_state{socket = Sock, ssl = Ssl}, {error, Reason}) -> lhttpc_sock:close(Sock, Ssl), - error(Reason). + throw(Reason). %%------------------------------------------------------------------------------ %% @private diff --git a/src/lhttpc_lib.erl b/src/lhttpc_lib.erl index a0e1c43..51e94bd 100644 --- a/src/lhttpc_lib.erl +++ b/src/lhttpc_lib.erl @@ -1,5 +1,5 @@ %% @hidden -%%% -*- coding: latin-1 -*- +%%% -*- coding: utf-8 -*- %%% ---------------------------------------------------------------------------- %%% Copyright (c) 2009, Erlang Training and Consulting Ltd. %%% All rights reserved. @@ -28,7 +28,7 @@ %%------------------------------------------------------------------------------ %%% @private -%%% @author Oscar Hellstr�m +%%% @author Oscar Hellström %%% @doc %%% This module implements various library functions used in lhttpc. %%------------------------------------------------------------------------------ @@ -224,19 +224,9 @@ split_credentials(CredsHostPortPath) -> end. -spec parse_query_string(string()) -> string(). --ifdef(OTP_RELEASE). --if(?OTP_RELEASE >= 23). parse_query_string(User0) -> [{User, true}] = uri_string:dissect_query(User0), User. --else. -parse_query_string(User) -> - http_uri:decode(User). --endif. --else. -parse_query_string(User) -> - http_uri:decode(User). --endif. %%------------------------------------------------------------------------------ %% @private diff --git a/src/lhttpc_manager.erl b/src/lhttpc_manager.erl index 6bb6559..c7f5ef0 100644 --- a/src/lhttpc_manager.erl +++ b/src/lhttpc_manager.erl @@ -1,4 +1,4 @@ -%%% -*- coding: latin-1 -*- +%%% -*- coding: utf-8 -*- %%% ---------------------------------------------------------------------------- %%% Copyright (c) 2009, Erlang Training and Consulting Ltd. %%% All rights reserved. @@ -26,7 +26,7 @@ %%% ---------------------------------------------------------------------------- %%------------------------------------------------------------------------------ -%%% @author Oscar Hellstr�m +%%% @author Oscar Hellström %%% @author Filipe David Manana %%% @doc Connection manager for the HTTP client. %%% This gen_server is responsible for keeping track of persistent diff --git a/src/lhttpc_sock.erl b/src/lhttpc_sock.erl index a0adbbf..165377e 100644 --- a/src/lhttpc_sock.erl +++ b/src/lhttpc_sock.erl @@ -1,5 +1,5 @@ %% @hidden -%%% -*- coding: latin-1 -*- +%%% -*- coding: utf-8 -*- %%% ---------------------------------------------------------------------------- %%% Copyright (c) 2009, Erlang Training and Consulting Ltd. %%% All rights reserved. @@ -28,7 +28,7 @@ %%------------------------------------------------------------------------------ %%% @private -%%% @author Oscar Hellström +%%% @author Oscar Hellström %%% @doc %%% This module implements wrappers for socket operations. %%% Makes it possible to have the same interface to ssl and tcp sockets. diff --git a/src/lhttpc_sup.erl b/src/lhttpc_sup.erl index 22b6176..240a8f3 100644 --- a/src/lhttpc_sup.erl +++ b/src/lhttpc_sup.erl @@ -1,5 +1,5 @@ %% @hidden -%%% -*- coding: latin-1 -*- +%%% -*- coding: utf-8 -*- %%% ---------------------------------------------------------------------------- %%% Copyright (c) 2009, Erlang Training and Consulting Ltd. %%% All rights reserved. @@ -27,7 +27,7 @@ %%% ---------------------------------------------------------------------------- %%------------------------------------------------------------------------------ -%%% @author Oscar Hellstr�m +%%% @author Oscar Hellström %%% @doc Top supervisor for the lhttpc application. %%% This is normally started by the application behaviour implemented in %%% {@link lhttpc}. diff --git a/test/lhttpc_lib_tests.erl b/test/lhttpc_lib_tests.erl index 43b27c2..e71f1b9 100644 --- a/test/lhttpc_lib_tests.erl +++ b/test/lhttpc_lib_tests.erl @@ -1,4 +1,4 @@ -%%% -*- coding: latin-1 -*- +%%% -*- coding: utf-8 -*- %%% ---------------------------------------------------------------------------- %%% Copyright (c) 2009, Erlang Training and Consulting Ltd. %%% All rights reserved. @@ -25,7 +25,8 @@ %%% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %%% ---------------------------------------------------------------------------- -%%% @author Oscar Hellström +%%% @author Oscar Hellström + -module(lhttpc_lib_tests). -include_lib("eunit/include/eunit.hrl"). diff --git a/test/lhttpc_manager_tests.erl b/test/lhttpc_manager_tests.erl index b20ded0..a5a745b 100644 --- a/test/lhttpc_manager_tests.erl +++ b/test/lhttpc_manager_tests.erl @@ -1,4 +1,4 @@ -%%% -*- coding: latin-1 -*- +%%% -*- coding: utf-8 -*- %%% ---------------------------------------------------------------------------- %%% Copyright (c) 2009, Erlang Training and Consulting Ltd. %%% All rights reserved. @@ -25,7 +25,7 @@ %%% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %%% ---------------------------------------------------------------------------- -%%% @author Oscar Hellstr�m +%%% @author Oscar Hellström %%% @author Filipe David Manana -module(lhttpc_manager_tests). diff --git a/test/lhttpc_test_SUITE.erl b/test/lhttpc_test_SUITE.erl index 6e3bbd7..fdf5122 100644 --- a/test/lhttpc_test_SUITE.erl +++ b/test/lhttpc_test_SUITE.erl @@ -1,4 +1,4 @@ -%%% -*- coding: latin-1 -*- +%%% -*- coding: utf-8 -*- %%% ---------------------------------------------------------------------------- %%% Copyright (c) 2009, Erlang Training and Consulting Ltd. %%% All rights reserved. @@ -25,7 +25,7 @@ %%% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %%% ---------------------------------------------------------------------------- -%%% @author Oscar Hellstr�m +%%% @author Oscar Hellström -module(lhttpc_test_SUITE). -compile(export_all). diff --git a/test/util/socket_server.erl b/test/util/socket_server.erl index e29f957..54d764e 100644 --- a/test/util/socket_server.erl +++ b/test/util/socket_server.erl @@ -1,4 +1,4 @@ -%%% -*- coding: latin-1 -*- +%%% -*- coding: utf-8 -*- %%% ---------------------------------------------------------------------------- %%% Copyright (c) 2009, Erlang Training and Consulting Ltd. %%% All rights reserved. @@ -25,7 +25,7 @@ %%% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %%% ---------------------------------------------------------------------------- -%%% @author Oscar Hellström +%%% @author Oscar Hellström -module(socket_server). -export([connect/1, listen/0, accept/1]). diff --git a/test/util/webserver.erl b/test/util/webserver.erl index 61abd47..eaf809a 100644 --- a/test/util/webserver.erl +++ b/test/util/webserver.erl @@ -1,4 +1,4 @@ -%%% -*- coding: latin-1 -*- +%%% -*- coding: utf-8 -*- %%% ---------------------------------------------------------------------------- %%% Copyright (c) 2009, Erlang Training and Consulting Ltd. %%% All rights reserved. @@ -25,7 +25,7 @@ %%% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. %%% ---------------------------------------------------------------------------- -%%% @author Oscar Hellström +%%% @author Oscar Hellström %%% @author Magnus Henoch %%% @doc Simple web server for testing purposes %%% @end From 17ff82ddef603756ae831ab97a1465ece2cad295 Mon Sep 17 00:00:00 2001 From: Sergio Almeida Date: Wed, 28 Oct 2026 09:42:12 +0000 Subject: [PATCH 3/3] Move min OTP to 27 --- .github/workflows/ci.yml | 2 +- CHANGELOG.md | 4 ++-- rebar.config | 10 +++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bcd73ee..af0f218 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ jobs: runs-on: ${{matrix.os}} strategy: matrix: - otp_vsn: [26, 27, 28, 29] + otp_vsn: [27, 28, 29] os: [ubuntu-latest] steps: - uses: actions/checkout@v4 diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d79e5a..3925e21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - [dep.] `tls_certificate_check` from 1.21.0 to 1.35.0 [Sérgio Almeida] -- CI to run on OTP 26 to 29 [Sérgio Almeida] +- CI to run on OTP 27 to 29 [Sérgio Almeida] - `elvis.config` to disable `no_receive_without_timeout` and `no_throw` rules [Sérgio Almeida] - exported type `lhttpc:socket()` from `_` to `inet:socket() | ssl:sslsocket()` [Sérgio Almeida] @@ -21,7 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `elvis.config` to the `elvis_core` 6.x format [Sérgio Almeida] ### Removed -- compatibility with OTP 22 to 25 [Sérgio Almeida] +- compatibility with OTP 22 to 26 [Sérgio Almeida] ## [4.3.2] - 2024-03-11 diff --git a/rebar.config b/rebar.config index 4f2906d..2224021 100644 --- a/rebar.config +++ b/rebar.config @@ -1,6 +1,6 @@ %% == Erlang Compiler == -{minimum_otp_vsn, "26"}. +{minimum_otp_vsn, "27"}. {erl_opts, [ debug_info, @@ -17,10 +17,10 @@ ]}. {project_plugins, [ - rebar3_ex_doc, - rebar3_hank, - rebar3_hex, - rebar3_lint + {rebar3_ex_doc, "0.3.0"}, + {rebar3_hank, "2.0.0"}, + {rebar3_hex, "7.3.0"}, + {rebar3_lint, "6.0.0"} ]}. %% == Dialyzer ==