-
-
Notifications
You must be signed in to change notification settings - Fork 443
Expand file tree
/
Copy pathhackney.erl
More file actions
1594 lines (1458 loc) · 59.4 KB
/
hackney.erl
File metadata and controls
1594 lines (1458 loc) · 59.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%%% -*- erlang -*-
%%%
%%% This file is part of hackney released under the Apache 2 license.
%%% See the NOTICE for more information.
%%%
%%% Simplified hackney API using process-per-connection architecture.
%%% Connection handles are now hackney_conn process PIDs.
-module(hackney).
-export([connect/1, connect/2, connect/3, connect/4,
close/1,
peername/1,
peercert/1,
sockname/1,
request/1, request/2, request/3, request/4, request/5,
send_request/2,
cookies/1,
send_body/2, finish_send_body/1, start_response/1,
setopts/2]).
%% WebSocket API
-export([ws_connect/1, ws_connect/2,
ws_send/2,
ws_recv/1, ws_recv/2,
ws_setopts/2,
ws_close/1, ws_close/2]).
-export([redirect_location/1, location/1]).
-export([get_version/0]).
-export([default_ua/0]).
%% Async streaming
-export([stream_next/1,
stop_async/1,
pause_stream/1,
resume_stream/1]).
-export([parse_proxy_url/1]).
-ifdef(TEST).
-export([get_proxy_env/1, do_get_proxy_env/1]).
-export([get_proxy_config/3]).
-export([check_no_proxy/2]).
-export([start_conn_with_socket/5]).
-endif.
-define(METHOD_TPL(Method),
-export([Method/1, Method/2, Method/3, Method/4])).
-include("hackney_methods.hrl").
-include("hackney.hrl").
-include("hackney_lib.hrl").
-include_lib("hackney_internal.hrl").
-type url() :: #hackney_url{} | binary().
-type conn() :: pid().
-type request_ret() ::
{ok, integer(), list(), binary()} | %% response with body
{ok, integer(), list()} | %% HEAD request
{ok, reference()} | %% async mode
{error, term()}.
-export_type([url/0, conn/0, request_ret/0]).
%%====================================================================
%% Connection API
%%====================================================================
connect(URL) ->
connect(URL, []).
connect(#hackney_url{}=URL, Options) ->
#hackney_url{transport=Transport,
host=Host,
port=Port} = URL,
connect(Transport, Host, Port, Options);
connect(URL, Options) when is_binary(URL) orelse is_list(URL) ->
connect(hackney_url:parse_url(URL), Options).
%% @doc Connect to a host and return a connection handle (hackney_conn PID).
-spec connect(module(), string(), inet:port_number()) -> {ok, conn()} | {error, term()}.
connect(Transport, Host, Port) ->
connect(Transport, Host, Port, []).
-spec connect(module(), string(), inet:port_number(), list()) -> {ok, conn()} | {error, term()}.
connect(Transport, Host, Port, Options) ->
%% Check if using a pool
UsePool = use_pool(Options),
case UsePool of
false ->
%% Direct connection - start a hackney_conn process
connect_direct(Transport, Host, Port, Options);
_PoolName ->
%% Pool mode with per-host load regulation
connect_pool(Transport, Host, Port, Options)
end.
%% @private Direct connection without pool
connect_direct(Transport, Host, Port, Options) ->
%% Build connect_options including protocols for ALPN
BaseConnectOpts = proplists:get_value(connect_options, Options, []),
Protocols = proplists:get_value(protocols, Options, undefined),
ConnectOpts = case Protocols of
undefined -> BaseConnectOpts;
_ -> [{protocols, Protocols} | BaseConnectOpts]
end,
ConnOpts = #{
host => Host,
port => Port,
transport => Transport,
connect_timeout => proplists:get_value(connect_timeout, Options, 8000),
recv_timeout => proplists:get_value(recv_timeout, Options, 5000),
connect_options => ConnectOpts,
ssl_options => proplists:get_value(ssl_options, Options, [])
},
case hackney_conn_sup:start_conn(ConnOpts) of
{ok, ConnPid} ->
case hackney_conn:connect(ConnPid) of
ok ->
hackney_manager:start_request(Host),
{ok, ConnPid};
{error, Reason} ->
catch hackney_conn:stop(ConnPid),
{error, Reason}
end;
{error, Reason} ->
{error, Reason}
end.
%% @private Pool connection with load regulation
%% Flow:
%% 1. For SSL: Check if existing HTTP/3 or HTTP/2 connection can be reused (multiplexing)
%% 2. If HTTP/3 allowed and available (via Alt-Svc), try HTTP/3 first
%% 3. Acquire slot from load_regulation (blocks if at per-host limit)
%% 4. Get TCP connection from pool (always TCP, pool doesn't store SSL)
%% 5. Upgrade to SSL if needed (in-place upgrade)
%% 6. If HTTP/2 negotiated, register for multiplexing
%% Note: load_regulation slot is released when connection is checked in or dies
connect_pool(Transport, Host, Port, Options) ->
PoolHandler = hackney_app:get_app_env(pool_handler, hackney_pool),
%% Check which protocols are allowed (default from application env)
Protocols = proplists:get_value(protocols, Options, hackney_util:default_protocols()),
H3Allowed = lists:member(http3, Protocols),
H2Allowed = lists:member(http2, Protocols),
%% For SSL connections, try multiplexed protocols (HTTP/3 first, then HTTP/2)
case Transport of
hackney_ssl ->
%% Check HTTP/3 first if allowed
case H3Allowed andalso try_h3_connection(Host, Port, Transport, Options, PoolHandler) of
{ok, H3Pid} ->
hackney_manager:start_request(Host),
{ok, H3Pid};
_ when H2Allowed ->
%% Try HTTP/2 multiplexing
case PoolHandler:checkout_h2(Host, Port, Transport, Options) of
{ok, H2Pid} ->
%% Verify connection is actually in connected state
%% (OTP 28 on FreeBSD may have timing issues with SSL connections)
case hackney_conn:get_state(H2Pid) of
{ok, connected} ->
hackney_manager:start_request(Host),
{ok, H2Pid};
_ ->
%% Connection not ready, unregister and create new
PoolHandler:unregister_h2(H2Pid, Options),
connect_pool_new(Transport, Host, Port, Options, PoolHandler)
end;
none ->
connect_pool_new(Transport, Host, Port, Options, PoolHandler)
end;
_ ->
%% No multiplexed protocols allowed or available
connect_pool_new(Transport, Host, Port, Options, PoolHandler)
end;
_ ->
%% Non-SSL, use normal pool
connect_pool_new(Transport, Host, Port, Options, PoolHandler)
end.
%% @private Try to get or establish an HTTP/3 connection
try_h3_connection(Host, Port, Transport, Options, PoolHandler) ->
%% Check if HTTP/3 is blocked for this host (negative cache)
case hackney_altsvc:is_h3_blocked(Host, Port) of
true ->
false;
false ->
%% Check if we have an existing HTTP/3 connection
case PoolHandler:checkout_h3(Host, Port, Transport, Options) of
{ok, H3Pid} ->
%% Verify connection is actually in connected state
case hackney_conn:get_state(H3Pid) of
{ok, connected} ->
{ok, H3Pid};
_ ->
%% Connection not ready, unregister and try new connection
PoolHandler:unregister_h3(H3Pid, Options),
try_new_h3_connection(Host, Port, Transport, Options, PoolHandler)
end;
none ->
%% Check Alt-Svc cache for known HTTP/3 endpoint
case hackney_altsvc:lookup(Host, Port) of
{ok, h3, H3Port} ->
%% Alt-Svc says HTTP/3 is available, try connecting
try_new_h3_connection(Host, H3Port, Transport, Options, PoolHandler);
none ->
%% No Alt-Svc cached, only try H3 if explicitly requested
case lists:member(http3, proplists:get_value(protocols, Options, [])) of
true ->
%% User explicitly wants HTTP/3, try it
try_new_h3_connection(Host, Port, Transport, Options, PoolHandler);
false ->
false
end
end
end
end.
%% @private Establish a new HTTP/3 connection
try_new_h3_connection(Host, Port, Transport, Options, PoolHandler) ->
%% Start HTTP/3 connection via hackney_conn
ConnectTimeout = proplists:get_value(connect_timeout, Options, 8000),
ConnOpts = #{
host => Host,
port => Port,
transport => Transport,
connect_timeout => ConnectTimeout,
recv_timeout => proplists:get_value(recv_timeout, Options, 5000),
connect_options => [{protocols, [http3]}],
ssl_options => proplists:get_value(ssl_options, Options, [])
},
case hackney_conn_sup:start_conn(ConnOpts) of
{ok, ConnPid} ->
case hackney_conn:connect(ConnPid, ConnectTimeout) of
ok ->
%% Verify it's HTTP/3
case catch hackney_conn:get_protocol(ConnPid) of
http3 ->
%% Register for multiplexing
PoolHandler:register_h3(Host, Port, Transport, ConnPid, Options),
{ok, ConnPid};
_ ->
%% Not HTTP/3 or connection terminated, close and fail
catch hackney_conn:stop(ConnPid),
hackney_altsvc:mark_h3_blocked(Host, Port),
false
end;
{error, _Reason} ->
catch hackney_conn:stop(ConnPid),
hackney_altsvc:mark_h3_blocked(Host, Port),
false
end;
{error, _Reason} ->
hackney_altsvc:mark_h3_blocked(Host, Port),
false
end.
connect_pool_new(Transport, Host, Port, Options, PoolHandler) ->
MaxPerHost = proplists:get_value(max_per_host, Options, 50),
CheckoutTimeout = proplists:get_value(checkout_timeout, Options,
proplists:get_value(connect_timeout, Options, 8000)),
%% 1. Acquire per-host slot (blocks with backoff until available)
case hackney_load_regulation:acquire(Host, Port, MaxPerHost, CheckoutTimeout) of
ok ->
%% Slot acquired - now get connection from pool
%% Always checkout as TCP - pool only stores TCP connections
case PoolHandler:checkout(Host, Port, hackney_tcp, Options) of
{ok, _PoolRef, ConnPid} ->
%% Got TCP connection - upgrade to SSL if needed
case maybe_upgrade_ssl(Transport, ConnPid, Host, Options) of
ok ->
%% Check if HTTP/2 was negotiated, register for multiplexing
maybe_register_h2(ConnPid, Host, Port, Transport, Options, PoolHandler),
hackney_manager:start_request(Host),
{ok, ConnPid};
{error, Reason} ->
%% Upgrade failed - release slot and close connection
hackney_load_regulation:release(Host, Port),
catch hackney_conn:stop(ConnPid),
{error, Reason}
end;
{error, Reason} ->
%% Checkout failed - release slot
hackney_load_regulation:release(Host, Port),
{error, Reason}
end;
{error, timeout} ->
{error, checkout_timeout}
end.
%% @private Register HTTP/2 connection for multiplexing if applicable
%% Uses catch to handle race condition where connection terminates before call
maybe_register_h2(ConnPid, Host, Port, Transport, Options, PoolHandler) ->
case catch hackney_conn:get_protocol(ConnPid) of
http2 ->
%% HTTP/2 negotiated - register for connection sharing
PoolHandler:register_h2(Host, Port, Transport, ConnPid, Options);
http1 ->
ok;
http3 ->
ok;
{'EXIT', _} ->
%% Connection terminated before we could check - ignore
ok
end.
%% @private Upgrade TCP connection to SSL if needed
maybe_upgrade_ssl(hackney_ssl, ConnPid, Host, Options) ->
SslOpts = proplists:get_value(ssl_options, Options, []),
%% Add protocols option for ALPN negotiation if specified
Protocols = proplists:get_value(protocols, Options, undefined),
SslOpts2 = case Protocols of
undefined -> SslOpts;
_ -> [{protocols, Protocols} | SslOpts]
end,
%% Check if connection is already SSL (e.g., reused SSL connection)
case catch hackney_conn:is_upgraded_ssl(ConnPid) of
true ->
%% Already SSL, no upgrade needed
ok;
_ ->
%% Upgrade TCP to SSL with ALPN
hackney_conn:upgrade_to_ssl(ConnPid, [{server_name_indication, Host} | SslOpts2])
end;
maybe_upgrade_ssl(_, _ConnPid, _Host, _Options) ->
%% Not SSL, no upgrade needed
ok.
%% @doc Close a connection.
-spec close(conn()) -> ok.
close(ConnPid) when is_pid(ConnPid) ->
hackney_conn:stop(ConnPid).
%% @doc Start a connection with a pre-established socket.
%% Used for proxy connections where the tunnel is established first.
%% Socket can be a raw socket or a {Transport, Socket} tuple from proxy modules.
-spec start_conn_with_socket(string(), inet:port_number(), module(),
inet:socket() | {module(), inet:socket()}, list()) ->
{ok, conn()} | {error, term()}.
start_conn_with_socket(Host, Port, _Transport, {SocketTransport, Socket}, Options) ->
%% Handle {Transport, Socket} tuple from proxy modules
%% Use the socket's transport for operations
ActualTransport = normalize_transport(SocketTransport),
start_conn_with_socket_internal(Host, Port, ActualTransport, Socket, Options);
start_conn_with_socket(Host, Port, Transport, Socket, Options) ->
%% Raw socket
ActualTransport = normalize_transport(Transport),
start_conn_with_socket_internal(Host, Port, ActualTransport, Socket, Options).
start_conn_with_socket_internal(Host, Port, Transport, Socket, Options) ->
%% Build connect_options including protocols for ALPN
BaseConnectOpts = proplists:get_value(connect_options, Options, []),
Protocols = proplists:get_value(protocols, Options, undefined),
ConnectOpts = case Protocols of
undefined -> BaseConnectOpts;
_ -> [{protocols, Protocols} | BaseConnectOpts]
end,
%% Check if this is a proxy tunnel connection (should not be reused)
NoReuse = proplists:get_value(no_reuse, Options, false),
ConnOpts = #{
host => Host,
port => Port,
transport => Transport,
socket => Socket,
connect_timeout => proplists:get_value(connect_timeout, Options, 8000),
recv_timeout => proplists:get_value(recv_timeout, Options, 5000),
connect_options => ConnectOpts,
ssl_options => proplists:get_value(ssl_options, Options, []),
no_reuse => NoReuse
},
case hackney_conn_sup:start_conn(ConnOpts) of
{ok, ConnPid} ->
hackney_manager:start_request(Host),
{ok, ConnPid};
{error, Reason} ->
{error, Reason}
end.
%% Normalize transport atoms (e.g., ssl -> hackney_ssl, gen_tcp -> hackney_tcp)
normalize_transport(hackney_tcp) -> hackney_tcp;
normalize_transport(hackney_ssl) -> hackney_ssl;
normalize_transport(gen_tcp) -> hackney_tcp;
normalize_transport(ssl) -> hackney_ssl;
normalize_transport(Other) -> Other.
%% @doc Get the remote address and port.
-spec peername(conn()) -> {ok, {inet:ip_address(), inet:port_number()}} | {error, term()}.
peername(ConnPid) when is_pid(ConnPid) ->
hackney_conn:peername(ConnPid).
%% @doc Get the peer SSL certificate.
%% Returns the DER-encoded certificate of the peer, or an error if the connection
%% is not SSL or the certificate is unavailable.
-spec peercert(conn()) -> {ok, binary()} | {error, term()}.
peercert(ConnPid) when is_pid(ConnPid) ->
hackney_conn:peercert(ConnPid).
%% @doc Get the local address and port.
-spec sockname(conn()) -> {ok, {inet:ip_address(), inet:port_number()}} | {error, term()}.
sockname(ConnPid) when is_pid(ConnPid) ->
hackney_conn:sockname(ConnPid).
%% @doc Set socket options.
-spec setopts(conn(), list()) -> ok | {error, term()}.
setopts(ConnPid, Options) when is_pid(ConnPid) ->
hackney_conn:setopts(ConnPid, Options).
%%====================================================================
%% Request API
%%====================================================================
%% @doc Make a request.
-spec request(url()) -> request_ret().
request(URL) ->
request(get, URL).
-spec request(atom() | binary(), url()) -> request_ret().
request(Method, URL) ->
request(Method, URL, [], <<>>, []).
-spec request(atom() | binary(), url(), list()) -> request_ret().
request(Method, URL, Headers) ->
request(Method, URL, Headers, <<>>, []).
-spec request(atom() | binary(), url(), list(), term()) -> request_ret().
request(Method, URL, Headers, Body) ->
request(Method, URL, Headers, Body, []).
%% @doc Make a request.
%%
%% Args:
%% - Method: HTTP method (get, post, put, delete, etc.)
%% - URL: Full URL or parsed hackney_url record
%% - Headers: List of headers
%% - Body: Request body (binary, iolist, {form, KVs}, {file, Path}, etc.)
%% - Options: Request options
%%
%% Options:
%% - async: true | once - Receive response asynchronously
%% - stream_to: PID to receive async messages
%% - follow_redirect: Follow redirects automatically
%% - max_redirect: Maximum number of redirects (default 5)
%% - location_trusted: If true, forward auth credentials on cross-host redirects (default false)
%% - pool: Pool name or false for no pooling
%% - connect_timeout: Connection timeout in ms (default 8000)
%% - recv_timeout: Receive timeout in ms (default 5000)
%%
%% Returns:
%% - {ok, Status, Headers, Body}: Success with response body
%% - {ok, Status, Headers}: HEAD request
%% - {ok, Ref}: Async mode - use stream_next/1 to receive messages
%% - {ok, ConnPid}: Streaming body mode (body = stream) - use send_body/2, finish_send_body/1
%% - {error, Reason}: Error
%%
%% Note: The `with_body' option is deprecated and ignored. Body is always returned directly.
-spec request(atom() | binary(), url(), list(), term(), list()) -> request_ret().
request(Method, URL, Headers, Body, Options) when is_binary(URL) orelse is_list(URL) ->
request(Method, hackney_url:parse_url(URL), Headers, Body, Options);
request(Method, #hackney_url{}=URL0, Headers0, Body, Options0) ->
PathEncodeFun = proplists:get_value(path_encode_fun, Options0,
fun hackney_url:pathencode/1),
%% Normalize the URL
URL = hackney_url:normalize(URL0, PathEncodeFun),
?report_trace("request", [{method, Method},
{url, URL},
{headers, Headers0},
{body, Body},
{options, Options0}]),
#hackney_url{transport=Transport,
scheme = Scheme,
host = Host,
port = Port,
user = User,
password = Password,
path = Path,
qs = Query} = URL,
%% Check for unsupported URL schemes
case Transport of
undefined ->
{error, {unsupported_scheme, Scheme}};
_ ->
request_with_transport(Method, URL, Headers0, Body, Options0,
Transport, Host, Port, User, Password, Path, Query)
end.
%% @private Continue request processing after transport validation
request_with_transport(Method, URL, Headers0, Body, Options0,
Transport, Host, Port, User, Password, Path, Query) ->
Options = case User of
<<>> -> Options0;
_ -> lists:keystore(basic_auth, 1, Options0, {basic_auth, {User, Password}})
end,
%% Build final path
FinalPath = case Query of
<<>> -> Path;
_ -> <<Path/binary, "?", Query/binary>>
end,
%% Check for proxy
case maybe_proxy(Transport, URL#hackney_url.scheme, Host, Port, Options) of
{ok, ConnPid} ->
do_request(ConnPid, Method, FinalPath, Headers0, Body, Options, URL, Host);
{ok, ConnPid, {http_proxy, TargetScheme, TargetHost, TargetPort, ProxyAuth}} ->
%% HTTP proxy mode - use absolute URLs
AbsolutePath = build_absolute_url(TargetScheme, TargetHost, TargetPort, FinalPath),
Headers1 = add_proxy_auth_header(Headers0, ProxyAuth),
do_request(ConnPid, Method, AbsolutePath, Headers1, Body, Options, URL, Host);
Error ->
Error
end.
%% @doc Send a request on an existing connection.
-spec send_request(conn(), {atom(), binary(), list(), term()}) ->
{ok, integer(), list(), conn()} | {ok, integer(), list()} | {error, term()}.
send_request(ConnPid, {Method, Path, Headers, Body}) when is_pid(ConnPid) ->
%% Convert method to binary
MethodBin = hackney_bstr:to_upper(hackney_bstr:to_binary(Method)),
case hackney_conn:request(ConnPid, MethodBin, Path, Headers, Body) of
{ok, Status, RespHeaders} ->
%% HEAD request or no body
case MethodBin of
<<"HEAD">> -> {ok, Status, RespHeaders};
_ -> {ok, Status, RespHeaders, ConnPid}
end;
{error, Reason} ->
{error, Reason}
end.
%%====================================================================
%% Streaming Request Body API
%%====================================================================
%% @doc Send a chunk of the request body.
%% Used when request was initiated with body = stream.
-spec send_body(conn(), iodata()) -> ok | {error, term()}.
send_body(ConnPid, Data) when is_pid(ConnPid) ->
hackney_conn:send_body_chunk(ConnPid, Data).
%% @doc Finish sending the streaming request body.
-spec finish_send_body(conn()) -> ok | {error, term()}.
finish_send_body(ConnPid) when is_pid(ConnPid) ->
hackney_conn:finish_send_body(ConnPid).
%% @doc Start receiving the response after sending the full body.
%% Returns {ok, Status, Headers, ConnPid}.
-spec start_response(conn()) -> {ok, integer(), list(), conn()} | {error, term()}.
start_response(ConnPid) when is_pid(ConnPid) ->
hackney_conn:start_response(ConnPid).
%%====================================================================
%% Async Streaming API
%%====================================================================
%% @doc Request next chunk in {async, once} mode.
-spec stream_next(conn()) -> ok.
stream_next(ConnPid) when is_pid(ConnPid) ->
hackney_conn:stream_next(ConnPid).
%% @doc Stop async mode and return to sync mode.
-spec stop_async(conn()) -> ok | {error, term()}.
stop_async(ConnPid) when is_pid(ConnPid) ->
hackney_conn:stop_async(ConnPid).
%% @doc Pause async streaming.
-spec pause_stream(conn()) -> ok.
pause_stream(ConnPid) when is_pid(ConnPid) ->
hackney_conn:pause_stream(ConnPid).
%% @doc Resume async streaming.
-spec resume_stream(conn()) -> ok.
resume_stream(ConnPid) when is_pid(ConnPid) ->
hackney_conn:resume_stream(ConnPid).
%%====================================================================
%% WebSocket API
%%====================================================================
%% @doc Connect to a WebSocket server.
%% URL should use ws:// or wss:// scheme.
%%
%% Options:
%% <ul>
%% <li>active: false | true | once (default false)</li>
%% <li>headers: Extra headers for upgrade request</li>
%% <li>protocols: Sec-WebSocket-Protocol values</li>
%% <li>connect_timeout: Connection timeout in ms (default 8000)</li>
%% <li>recv_timeout: Receive timeout in ms (default infinity)</li>
%% <li>connect_options: Options passed to transport connect</li>
%% <li>ssl_options: Additional SSL options</li>
%% </ul>
%%
%% Returns `{ok, WsPid}' on success, where WsPid is the hackney_ws process.
-spec ws_connect(binary() | string()) -> {ok, pid()} | {error, term()}.
ws_connect(URL) ->
ws_connect(URL, []).
-spec ws_connect(binary() | string(), list()) -> {ok, pid()} | {error, term()}.
ws_connect(URL, Options) when is_binary(URL) orelse is_list(URL) ->
#hackney_url{
transport = Transport,
scheme = Scheme,
host = Host,
port = Port,
path = Path0,
qs = Query
} = hackney_url:parse_url(URL),
%% Validate scheme
case Scheme of
ws -> ok;
wss -> ok;
_ -> error({invalid_websocket_scheme, Scheme})
end,
%% Build path with query string
Path = case Query of
<<>> -> Path0;
_ -> <<Path0/binary, "?", Query/binary>>
end,
%% Get proxy configuration (WebSocket always uses tunnel mode)
ProxyConfig = get_ws_proxy_config(Scheme, Host, Options),
%% Build connection options
WsOpts = #{
host => Host,
port => Port,
transport => Transport,
path => Path,
connect_timeout => proplists:get_value(connect_timeout, Options, 8000),
recv_timeout => proplists:get_value(recv_timeout, Options, infinity),
connect_options => proplists:get_value(connect_options, Options, []),
ssl_options => proplists:get_value(ssl_options, Options, []),
active => proplists:get_value(active, Options, false),
headers => normalize_ws_headers(proplists:get_value(headers, Options, [])),
protocols => proplists:get_value(protocols, Options, []),
proxy => ProxyConfig
},
%% Start WebSocket process and connect
case hackney_ws:start_link(WsOpts) of
{ok, WsPid} ->
Timeout = maps:get(connect_timeout, WsOpts),
try hackney_ws:connect(WsPid, Timeout) of
ok ->
{ok, WsPid};
{error, Reason} ->
catch exit(WsPid, shutdown),
{error, Reason}
catch
exit:{timeout, _} ->
catch exit(WsPid, shutdown),
{error, connect_timeout};
exit:{noproc, _} ->
{error, {ws_process_died, noproc}}
end;
{error, Reason} ->
{error, Reason}
end.
%% @doc Send a WebSocket frame.
%% Frame types:
%% - {text, Data} - Text message
%% - {binary, Data} - Binary message
%% - ping | {ping, Data} - Ping frame
%% - pong | {pong, Data} - Pong frame
%% - close | {close, Code, Reason} - Close frame
-spec ws_send(pid(), hackney_ws:ws_frame()) -> ok | {error, term()}.
ws_send(WsPid, Frame) when is_pid(WsPid) ->
hackney_ws:send(WsPid, Frame).
%% @doc Receive a WebSocket frame (passive mode only).
%% Blocks until a frame is received or timeout.
%% Returns {ok, Frame} or {error, Reason}.
-spec ws_recv(pid()) -> {ok, hackney_ws:ws_frame()} | {error, term()}.
ws_recv(WsPid) when is_pid(WsPid) ->
hackney_ws:recv(WsPid).
-spec ws_recv(pid(), timeout()) -> {ok, hackney_ws:ws_frame()} | {error, term()}.
ws_recv(WsPid, Timeout) when is_pid(WsPid) ->
hackney_ws:recv(WsPid, Timeout).
%% @doc Set WebSocket options.
%% Supported options: [{active, true | false | once}]
-spec ws_setopts(pid(), list()) -> ok | {error, term()}.
ws_setopts(WsPid, Opts) when is_pid(WsPid) ->
hackney_ws:setopts(WsPid, Opts).
%% @doc Close WebSocket connection gracefully.
-spec ws_close(pid()) -> ok.
ws_close(WsPid) when is_pid(WsPid) ->
hackney_ws:close(WsPid).
-spec ws_close(pid(), {integer(), binary()}) -> ok.
ws_close(WsPid, {Code, Reason}) when is_pid(WsPid) ->
hackney_ws:close(WsPid, {Code, Reason}).
%% @private Normalize WebSocket headers to {binary(), binary()} format
normalize_ws_headers(Headers) ->
[{hackney_bstr:to_binary(Name), hackney_bstr:to_binary(Value)}
|| {Name, Value} <- Headers].
%% @private Get proxy configuration for WebSocket.
%% WebSocket always uses tunnel mode (CONNECT or SOCKS5), never simple HTTP proxy.
get_ws_proxy_config(Scheme, Host, Options) ->
%% Map ws/wss to http/https for proxy env var lookup
HttpScheme = case Scheme of
ws -> http;
wss -> https
end,
case get_proxy_config(HttpScheme, Host, Options) of
false ->
false;
{http, ProxyHost, ProxyPort, ProxyAuth, ProxyTransport} ->
%% Simple HTTP proxy - convert to CONNECT tunnel for WebSocket
{connect, ProxyHost, ProxyPort, ProxyAuth, ProxyTransport};
{connect, _, _, _, _} = Config ->
Config;
{socks5, _, _, _, _} = Config ->
Config
end.
%%====================================================================
%% Helpers
%%====================================================================
%% @doc Parse cookies from response headers.
-spec cookies(list()) -> list().
cookies(Headers) ->
lists:foldl(fun({K, V}, Acc) ->
case hackney_bstr:to_lower(K) of
<<"set-cookie">> ->
case hackney_cookie:parse_cookie(V) of
{error, _} -> Acc;
[{Name, _} | _]=Cookie ->
[{Name, Cookie} | Acc]
end;
_ ->
Acc
end
end, [], Headers).
%% @doc Get redirect location from headers.
redirect_location(Headers) when is_list(Headers) ->
redirect_location(hackney_headers:from_list(Headers));
redirect_location(Headers) ->
hackney_headers:get_value(<<"location">>, Headers).
%% @doc Get the final URL after following redirects.
%% First checks the stored location (set after redirects),
%% then falls back to the Location header from the last response.
-spec location(conn()) -> binary() | undefined.
location(ConnPid) when is_pid(ConnPid) ->
case hackney_conn:get_location(ConnPid) of
undefined ->
%% No stored location, check response headers
case hackney_conn:response_headers(ConnPid) of
undefined -> undefined;
Headers -> redirect_location(Headers)
end;
Location ->
Location
end.
%%====================================================================
%% Internal functions
%%====================================================================
do_request(ConnPid, Method, Path, Headers0, Body, Options, URL, Host) ->
%% Build headers
Headers1 = hackney_headers:new(Headers0),
Headers2 = add_host_header(URL, Headers1),
%% Add default headers (User-Agent, Authorization, Cookies)
Headers3 = add_default_headers(Headers2, Options, URL),
%% Check for async mode
Async = proplists:get_value(async, Options, false),
StreamTo = proplists:get_value(stream_to, Options, self()),
%% DEPRECATED: The with_body option is now ignored.
%% Body is always returned directly for consistent behavior between HTTP/1.1 and HTTP/2.
%% For incremental body streaming, use async mode instead.
_ = proplists:get_value(with_body, Options, true), %% Read but ignored
WithBody = true, %% Always return body directly
FollowRedirect = proplists:get_value(follow_redirect, Options, false),
MaxRedirect = proplists:get_value(max_redirect, Options, 5),
RedirectCount = proplists:get_value(redirect_count, Options, 0),
%% Convert method to binary
MethodBin = hackney_bstr:to_upper(hackney_bstr:to_binary(Method)),
StartTime = os:timestamp(),
Result = case Async of
false ->
%% Sync request with redirect handling
sync_request_with_redirect(ConnPid, MethodBin, Path, Headers3, Body, WithBody,
Options, URL, FollowRedirect, MaxRedirect, RedirectCount);
_ ->
%% Async request with optional redirect handling
async_request(ConnPid, MethodBin, Path, Headers3, Body, Async, StreamTo, FollowRedirect, Options)
end,
case Result of
{ok, _, _, _} ->
hackney_manager:finish_request(Host, StartTime),
Result;
{ok, _, _} ->
hackney_manager:finish_request(Host, StartTime),
Result;
{ok, _} ->
Result; % Async - don't finish yet
{error, _} ->
hackney_manager:finish_request(Host, StartTime),
Result
end.
sync_request_with_redirect(ConnPid, Method, Path, Headers, Body, WithBody, Options, URL,
FollowRedirect, MaxRedirect, RedirectCount) ->
%% Handle body encoding
{FinalHeaders, FinalBody} = encode_body(Headers, Body, Options),
HeadersList = hackney_headers:to_list(FinalHeaders),
%% Check if this is a streaming body request
case FinalBody of
stream ->
%% For streaming body, just send headers and return immediately
case hackney_conn:send_request_headers(ConnPid, Method, Path, HeadersList) of
ok -> {ok, ConnPid};
{error, Reason} -> {error, Reason}
end;
_ ->
sync_request_with_redirect_body(ConnPid, Method, Path, HeadersList, FinalBody,
WithBody, Options, URL, FollowRedirect, MaxRedirect, RedirectCount)
end.
sync_request_with_redirect_body(ConnPid, Method, Path, HeadersList, FinalBody,
WithBody, Options, URL, FollowRedirect, MaxRedirect, RedirectCount) ->
%% Extract request options for 1xx informational responses and auto_decompress
ReqOpts0 = case proplists:get_value(inform_fun, Options) of
undefined -> [];
InformFun -> [{inform_fun, InformFun}]
end,
ReqOpts1 = case proplists:get_value(auto_decompress, Options, false) of
true -> [{auto_decompress, true} | ReqOpts0];
false -> ReqOpts0
end,
%% Pass recv_timeout through to the connection so it's applied per-request
ReqOpts = case proplists:get_value(recv_timeout, Options) of
undefined -> ReqOpts1;
RecvTimeout -> [{recv_timeout, RecvTimeout} | ReqOpts1]
end,
case hackney_conn:request(ConnPid, Method, Path, HeadersList, FinalBody, infinity, ReqOpts) of
%% HTTP/2 returns body directly - handle 4-tuple first
{ok, Status, RespHeaders, RespBody} when Status >= 301, Status =< 303; Status =:= 307; Status =:= 308 ->
%% HTTP/2 redirect status
case FollowRedirect of
true when RedirectCount < MaxRedirect ->
follow_redirect(ConnPid, Method, FinalBody, WithBody, Options, URL,
RespHeaders, Status, MaxRedirect, RedirectCount);
true ->
{error, {max_redirect, RedirectCount}};
false ->
{ok, Status, RespHeaders, RespBody}
end;
{ok, Status, RespHeaders, RespBody} ->
%% HTTP/2 response with body - already have body
case Method of
<<"HEAD">> ->
{ok, Status, RespHeaders};
_ ->
{ok, Status, RespHeaders, RespBody}
end;
%% HTTP/1.1 returns 3-tuple, body fetched separately
{ok, Status, RespHeaders} when Status >= 301, Status =< 303; Status =:= 307; Status =:= 308 ->
%% Redirect status
case FollowRedirect of
true when RedirectCount < MaxRedirect ->
%% Skip the body if any
_ = hackney_conn:body(ConnPid),
%% Follow redirect
follow_redirect(ConnPid, Method, FinalBody, WithBody, Options, URL,
RespHeaders, Status, MaxRedirect, RedirectCount);
true ->
{error, {max_redirect, RedirectCount}};
false ->
%% Return the redirect response with body
case hackney_conn:body(ConnPid) of
{ok, RespBody} ->
{ok, Status, RespHeaders, RespBody};
{error, Reason} ->
{error, Reason}
end
end;
{ok, Status, RespHeaders} ->
case Method of
<<"HEAD">> ->
%% HEAD responses have no body - call body() to trigger auto-release
%% (body returns immediately for HEAD with empty response)
_ = hackney_conn:body(ConnPid),
{ok, Status, RespHeaders};
_ ->
%% Always fetch body for consistent response format
case hackney_conn:body(ConnPid) of
{ok, RespBody} ->
%% Body read - connection auto-released to pool
{ok, Status, RespHeaders, RespBody};
{error, Reason} ->
{error, Reason}
end
end;
{error, Reason} ->
{error, Reason}
end.
follow_redirect(ConnPid, Method, Body, WithBody, Options, CurrentURL, RespHeaders, Status,
MaxRedirect, RedirectCount) ->
%% Get the Location header
Location = redirect_location(RespHeaders),
case Location of
undefined ->
{error, no_location_header};
LocationBin ->
%% Parse the new URL (could be relative or absolute)
NewURL = resolve_redirect_url(CurrentURL, LocationBin),
%% Get the full URL as a binary for storing
FinalLocation = hackney_url:unparse_url(NewURL),
%% Determine method for redirect (301, 302, 303 -> GET, 307, 308 -> same method)
NewMethod = case Status of
S when S =:= 301; S =:= 302; S =:= 303 ->
<<"GET">>;
_ ->
Method
end,
NewBody = case NewMethod of
<<"GET">> -> <<>>;
_ -> Body
end,
%% Make new request to the redirect URL
%% Remove old redirect_count and add incremented one
Options1 = proplists:delete(redirect_count, Options),
%% CVE-2018-1000007: Strip sensitive auth options when redirecting to different host
%% unless force_redirect is set (similar to curl's --location-trusted)
Options2 = maybe_strip_auth_on_redirect(CurrentURL, NewURL, Options1),
case request(NewMethod, NewURL, [], NewBody,
[{follow_redirect, true}, {max_redirect, MaxRedirect},
{redirect_count, RedirectCount + 1}, {with_body, WithBody} | Options2]) of
{ok, Status2, Headers2, Body2} ->
%% Store the final location in the connection
hackney_conn:set_location(ConnPid, FinalLocation),
{ok, Status2, Headers2, Body2};
{ok, Status2, Headers2} ->
%% Store the final location in the connection
hackney_conn:set_location(ConnPid, FinalLocation),
{ok, Status2, Headers2};
Error ->
Error
end
end.
resolve_redirect_url(CurrentURL, Location) when is_binary(Location) ->
case Location of
<<"http://", _/binary>> -> hackney_url:parse_url(Location);
<<"https://", _/binary>> -> hackney_url:parse_url(Location);
<<"ws://", _/binary>> -> hackney_url:parse_url(Location);
<<"wss://", _/binary>> -> hackney_url:parse_url(Location);
<<"//", _/binary>> ->
%% Network-path reference (RFC 3986 Section 4.2)
%% Use the current scheme with the new authority and path
Scheme = CurrentURL#hackney_url.scheme,
SchemePrefix = atom_to_binary(Scheme, utf8),
hackney_url:parse_url(<<SchemePrefix/binary, ":", Location/binary>>);
<<"/", _/binary>> ->
%% Absolute-path reference - parse query string from Location
{Path, Qs} = parse_path_qs(Location),
CurrentURL#hackney_url{path = Path, qs = Qs};
_ ->
%% Relative-path reference (RFC 3986 Section 5.2.3)
%% Parse query string from Location first
{RelPath, Qs} = parse_path_qs(Location),
CurrentPath = CurrentURL#hackney_url.path,
NewPath = merge_paths(CurrentPath, RelPath),
CurrentURL#hackney_url{path = NewPath, qs = Qs}
end.
%% @private Parse path and query string from a path-like string
parse_path_qs(PathLike) ->
case binary:split(PathLike, <<"?">>) of
[Path] -> {Path, <<>>};
[Path, Qs] -> {Path, Qs}
end.