-
-
Notifications
You must be signed in to change notification settings - Fork 456
Expand file tree
/
Copy pathhackney.erl
More file actions
2152 lines (1962 loc) · 83.2 KB
/
Copy pathhackney.erl
File metadata and controls
2152 lines (1962 loc) · 83.2 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,
body/1, body/2, stream_body/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]).
%% WebTransport API
-export([wt_connect/1, wt_connect/2,
wt_send/2,
wt_recv/1, wt_recv/2,
wt_setopts/2,
wt_close/1, wt_close/2,
wt_open_stream/2,
wt_stream_send/3, wt_stream_send/4,
wt_stream_recv/2, wt_stream_recv/3,
wt_close_stream/2,
wt_reset_stream/3,
wt_stop_sending/3,
wt_send_datagram/2,
wt_session_info/1]).
%% HTTP/2 bidirectional (gRPC-style) stream API
-export([h2_open/2, h2_open/3, h2_open/4,
h2_send/2, h2_send/3,
h2_send_trailers/2,
h2_recv/1, h2_recv/2,
h2_consume/2,
h2_setopts/2,
h2_close/1]).
-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, conn()} | %% async mode or streaming body upload (body = stream)
{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() | binary(), inet:port_number(), list()) ->
{ok, conn()} | {error, term()}.
connect(Transport, Host, Port, Options) when is_binary(Host) ->
connect(Transport, binary_to_list(Host), Port, Options);
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),
%% Single-owner connection: seed the conn-level send_timeout so
%% hackney:send_request/2 (which has no options channel) honors it.
%% Pooled connections deliberately skip this (shared conns keep the
%% constant default; per-request ReqOpts override there).
send_timeout => proplists:get_value(send_timeout, Options, 30000),
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 ->
{ok, ConnPid};
{error, Reason} ->
stop_conn(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 ->
%% Compute the exact TLS handshake options once; their hash keys the
%% shared HTTP/2 connection so requests with different ssl_options
%% never share a connection. FinalSslOpts is passed alongside Options
%% (not inside it) to keep the large CA material out of the pool state.
{FinalSslOpts, TlsKey} = effective_ssl_opts(Host, Options),
Options2 = [{tls_key, TlsKey} | Options],
%% Check HTTP/3 first if allowed
case H3Allowed andalso try_h3_connection(Host, Port, Transport, Options, PoolHandler) of
{ok, H3Pid} ->
{ok, H3Pid};
_ when H2Allowed ->
%% Try HTTP/2 multiplexing
case PoolHandler:checkout_h2(Host, Port, Transport, Options2) of
{ok, H2Pid} ->
%% Verify connection is actually in connected state
%% (OTP 28 on FreeBSD may have timing issues with SSL connections).
%% The probe is a gen_statem:call, which exits if the pooled
%% connection is terminating (idle teardown, GOAWAY, keepalive
%% close) at checkout time; treat that as unusable and fall
%% through to a fresh connection instead of crashing the caller.
%% Mirrors maybe_register_h2/maybe_upgrade_ssl.
GetState = try hackney_conn:get_state(H2Pid)
catch exit:_ -> {error, terminated} end,
case GetState of
{ok, connected} ->
{ok, H2Pid};
_ ->
%% Connection not ready, unregister and create new
PoolHandler:unregister_h2(H2Pid, Options2),
connect_pool_new(Transport, Host, Port, Options2, FinalSslOpts, PoolHandler)
end;
none ->
connect_pool_new(Transport, Host, Port, Options2, FinalSslOpts, PoolHandler)
end;
_ ->
%% No multiplexed protocols allowed or available
connect_pool_new(Transport, Host, Port, Options2, FinalSslOpts, PoolHandler)
end;
_ ->
%% Non-SSL, use normal pool
connect_pool_new(Transport, Host, Port, Options, undefined, PoolHandler)
end.
%% @private Build the exact TLS handshake options for a pooled SSL request,
%% plus their memoized pool key hash. Single source of truth: replicates
%% what maybe_upgrade_ssl used to build inline, including the optional
%% protocols entry for ALPN.
effective_ssl_opts(Host, Options) ->
SslOpts = proplists:get_value(ssl_options, Options, []),
SslOpts2 = case proplists:get_value(protocols, Options, undefined) of
undefined -> SslOpts;
Protocols -> [{protocols, Protocols} | SslOpts]
end,
ConnectOpts = proplists:get_value(connect_options, Options, []),
hackney_ssl:effective_opts_and_key(Host, SslOpts2, ConnectOpts).
%% @private Try to get or establish an HTTP/3 connection
try_h3_connection(Host, Port, Transport, Options, PoolHandler) ->
%% Hash the QUIC trust projection once; it keys both the shared H3
%% connection and the 0-RTT ticket cache so requests with differing
%% trust configs never share either.
ConnectOpts = proplists:get_value(connect_options, Options, []),
SslOpts = proplists:get_value(ssl_options, Options, []),
K3 = hackney_ssl:h3_options_key(ConnectOpts, SslOpts),
Options2 = [{h3_tls_key, K3} | Options],
%% 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, Options2) of
{ok, H3Pid} ->
%% Verify connection is actually in connected state. The probe is a
%% gen_statem:call, which exits if the pooled connection is
%% terminating at checkout time; treat that as unusable and fall
%% through to a fresh connection instead of crashing the caller.
GetState = try hackney_conn:get_state(H3Pid)
catch exit:_ -> {error, terminated} end,
case GetState of
{ok, connected} ->
{ok, H3Pid};
_ ->
%% Connection not ready, unregister and try new connection
PoolHandler:unregister_h3(H3Pid, Options2),
try_new_h3_connection(Host, Port, Transport, Options2, 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, Options2, 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, Options2, 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),
BaseConnectOpts = proplists:get_value(connect_options, Options, []),
SslOpts = proplists:get_value(ssl_options, Options, []),
%% Forward the caller's connect_options (e.g. {family, inet6}) and resolve the
%% 0-RTT session ticket (explicit option beats the pool cache).
ConnectOpts0 = [{protocols, [http3]} | proplists:delete(protocols, BaseConnectOpts)],
ConnectOpts = maybe_inject_h3_session(ConnectOpts0, SslOpts, Host, Port, Transport,
Options, PoolHandler),
PoolName = proplists:get_value(pool, Options, default),
ConnOpts = #{
host => Host,
port => Port,
transport => Transport,
connect_timeout => ConnectTimeout,
recv_timeout => proplists:get_value(recv_timeout, Options, 5000),
connect_options => ConnectOpts,
ssl_options => SslOpts,
pool_name => PoolName,
pool_handler => PoolHandler
},
case hackney_conn_sup:start_conn(ConnOpts) of
{ok, ConnPid} ->
case hackney_conn:connect(ConnPid, ConnectTimeout) of
ok ->
%% Verify it's HTTP/3
try hackney_conn:get_protocol(ConnPid) of
http3 ->
%% Register for multiplexing
PoolHandler:register_h3(Host, Port, Transport, ConnPid, Options),
{ok, ConnPid};
_ ->
%% Not HTTP/3, close and fail
stop_conn(ConnPid),
hackney_altsvc:mark_h3_blocked(Host, Port),
false
catch
_:_ ->
%% Connection terminated before we could check
hackney_altsvc:mark_h3_blocked(Host, Port),
false
end;
{error, _Reason} ->
stop_conn(ConnPid),
hackney_altsvc:mark_h3_blocked(Host, Port),
false
end;
{error, _Reason} ->
hackney_altsvc:mark_h3_blocked(Host, Port),
false
end.
%% @private Resolve the 0-RTT session ticket for a new H3 connection.
%% Precedence: an explicit `session_ticket' in connect_options or ssl_options
%% wins; otherwise, unless `zero_rtt' is disabled, a pool-cached ticket for
%% {Host, Port, Transport} is injected. The pool lookup is guarded so a custom
%% pool handler without the callback degrades to no reuse rather than crashing.
maybe_inject_h3_session(ConnectOpts, SslOpts, Host, Port, Transport, Options, PoolHandler) ->
ZeroRtt = proplists:get_value(zero_rtt, Options, true),
Explicit = proplists:get_value(session_ticket, ConnectOpts,
proplists:get_value(session_ticket, SslOpts, undefined)),
case {ZeroRtt, Explicit} of
{false, _} -> ConnectOpts;
{_, T} when T =/= undefined -> ConnectOpts;
_ ->
case erlang:function_exported(PoolHandler, get_h3_session, 4) of
false -> ConnectOpts;
true ->
case PoolHandler:get_h3_session(Host, Port, Transport, Options) of
{ok, Cached} -> [{session_ticket, Cached} | ConnectOpts];
_ -> ConnectOpts
end
end
end.
connect_pool_new(Transport, Host, Port, Options, FinalSslOpts, 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
SslPooling = proplists:get_value(ssl_pooling, Options,
hackney_app:get_app_env(ssl_pooling, false)),
case Transport =:= hackney_ssl andalso SslPooling =:= true
andalso erlang:function_exported(PoolHandler, checkout_ssl, 4) of
true ->
%% Opt-in ssl_pooling: pooled HTTPS/1.1 connections are reused on
%% an exact match of the TLS options hash (tls_key in Options)
connect_pool_ssl(Transport, Host, Port, Options, FinalSslOpts, PoolHandler);
false ->
%% 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, FinalSslOpts) of
ok ->
%% Check if HTTP/2 was negotiated, register for multiplexing
maybe_register_h2(ConnPid, Host, Port, Transport, Options, PoolHandler),
{ok, ConnPid};
{error, Reason} ->
%% Upgrade failed - release slot and close connection
hackney_load_regulation:release(Host, Port),
stop_conn(ConnPid),
{error, Reason}
end;
{error, Reason} ->
%% Checkout failed - release slot
hackney_load_regulation:release(Host, Port),
{error, Reason}
end
end;
{error, timeout} ->
{error, checkout_timeout}
end.
%% @private SSL-pooling checkout. A `ready' conn is an already-upgraded
%% HTTPS/1.1 connection reused on an exact tls_key match; it was registered
%% for h2 at creation if applicable, so it is not re-registered here. A
%% `needs_upgrade' conn is a TCP connection upgraded with pool_ssl so it can
%% return to the pool at checkin.
connect_pool_ssl(Transport, Host, Port, Options, FinalSslOpts, PoolHandler) ->
case PoolHandler:checkout_ssl(Host, Port, Transport, Options) of
{ok, _PoolRef, ConnPid, ready} ->
{ok, ConnPid};
{ok, _PoolRef, ConnPid, needs_upgrade} ->
case hackney_conn:upgrade_to_ssl(ConnPid, FinalSslOpts,
#{final => true, pool_ssl => true}) of
ok ->
maybe_register_h2(ConnPid, Host, Port, Transport, Options, PoolHandler),
{ok, ConnPid};
{error, Reason} ->
hackney_load_regulation:release(Host, Port),
stop_conn(ConnPid),
{error, Reason}
end;
{error, Reason} ->
hackney_load_regulation:release(Host, Port),
{error, Reason}
end.
%% @private Register HTTP/2 connection for multiplexing if applicable
%% Wrapped in try to handle a race where the connection terminates before the call
maybe_register_h2(ConnPid, Host, Port, Transport, Options, PoolHandler) ->
try 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
catch
_:_ ->
%% Connection terminated before we could check - ignore
ok
end.
%% @private Upgrade TCP connection to SSL if needed.
%% FinalSslOpts is precomputed by effective_ssl_opts/2 so the handshake uses
%% exactly the options hashed into the pool tls_key.
maybe_upgrade_ssl(hackney_ssl, ConnPid, FinalSslOpts) ->
%% Check if connection is already SSL (e.g., reused SSL connection)
try 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, FinalSslOpts, #{final => true})
catch
_:_ ->
%% Connection terminated, attempt upgrade anyway
hackney_conn:upgrade_to_ssl(ConnPid, FinalSslOpts, #{final => true})
end;
maybe_upgrade_ssl(_, _ConnPid, _FinalSslOpts) ->
%% Not SSL, no upgrade needed
ok.
%% @private Stop a connection, tolerating an already-dead process.
stop_conn(ConnPid) ->
try hackney_conn:stop(ConnPid) catch _:_ -> ok end.
%% @private Signal the websocket process to shut down, ignoring errors.
shutdown_ws(WsPid) ->
try exit(WsPid, shutdown) catch _:_ -> ok end.
%% @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),
%% Single-owner tunneled connection: same seeding as connect_direct.
send_timeout => proplists:get_value(send_timeout, Options, 30000),
connect_options => ConnectOpts,
ssl_options => proplists:get_value(ssl_options, Options, []),
no_reuse => NoReuse
},
case hackney_conn_sup:start_conn(ConnOpts) of
{ok, ConnPid} ->
{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, query, etc.).
%% `query' is the RFC 10008 QUERY method: safe and idempotent, with a
%% request body allowed like post.
%% - 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}]),
Req = #{method => Method,
url => URL,
headers => Headers0,
body => Body,
options => Options0},
Chain = hackney_middleware:resolve_chain(Options0),
hackney_middleware:apply_chain(Chain, Req, fun do_dispatch/1).
%% @private Terminal of the middleware chain: the actual request dispatch.
do_dispatch(#{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).
%% @doc Read the full response body after start_response/1.
%% Consumes the response stream and returns it as a single binary.
-spec body(conn()) -> {ok, binary()} | {error, term()}.
body(ConnPid) when is_pid(ConnPid) ->
hackney_conn:body(ConnPid).
%% @doc Same as body/1 with a receive timeout.
-spec body(conn(), timeout()) -> {ok, binary()} | {error, term()}.
body(ConnPid, Timeout) when is_pid(ConnPid) ->
hackney_conn:body(ConnPid, Timeout).
%% @doc Read the response body one chunk at a time after start_response/1.
%% Returns {ok, Chunk} per chunk and done when the body is fully consumed.
-spec stream_body(conn()) -> {ok, binary()} | done | {error, term()}.
stream_body(ConnPid) when is_pid(ConnPid) ->
hackney_conn:stream_body(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} ->
shutdown_ws(WsPid),
{error, Reason}
catch
exit:{timeout, _} ->
shutdown_ws(WsPid),
{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}).
%%====================================================================
%% WebTransport API
%%====================================================================
%% @doc Connect to a WebTransport server.
%%
%% The URL must use the https:// scheme (wss:// is accepted as an alias so
%% existing ws_* code can switch over by changing only the function name).
%% WebTransport always runs over TLS.
%%
%% Options:
%% <ul>
%% <li>transport: h3 (default) or h2</li>
%% <li>active: false | true | once (default false)</li>
%% <li>headers: extra headers for the CONNECT request</li>
%% <li>connect_timeout: connection timeout in ms (default 8000)</li>
%% <li>recv_timeout: default receive timeout in ms (default infinity)</li>
%% <li>ssl_options: TLS options (verify, cacerts/cacertfile, cert/certfile,
%% key/keyfile)</li>
%% <li>verify: verify_peer (default) | verify_none</li>
%% <li>compat_mode: latest (default) | legacy_browser_compat</li>
%% <li>max_recv_buffer: passive buffer cap in bytes (default 64 MiB)</li>
%% </ul>
%%
%% Returns `{ok, WtPid}' on success, where WtPid is the hackney_wt process.
-spec wt_connect(binary() | string()) -> {ok, pid()} | {error, term()}.
wt_connect(URL) ->
wt_connect(URL, []).
-spec wt_connect(binary() | string(), list()) -> {ok, pid()} | {error, term()}.
wt_connect(URL, Options) when is_binary(URL) orelse is_list(URL) ->
#hackney_url{
scheme = Scheme,
host = Host,
port = Port,
path = Path0,
qs = Query
} = hackney_url:parse_url(URL),
%% WebTransport runs over HTTP/3 or HTTP/2, both TLS-only.
case Scheme of
https -> ok;
wss -> ok;
_ -> error({invalid_webtransport_scheme, Scheme})
end,
Path = case Query of
<<>> -> Path0;
_ -> <<Path0/binary, "?", Query/binary>>
end,
Headers = normalize_ws_headers(proplists:get_value(headers, Options, [])),
%% Mirror the WebSocket GHSA-f9vr guard: reject CR/LF/NUL in the request
%% path or in any caller-supplied header before it reaches the wire.
case valid_wt_fields(Host, Path, Headers) of
ok ->
Transport = proplists:get_value(transport, Options, h3),
ConnectTimeout = proplists:get_value(connect_timeout, Options, 8000),
WtOpts = #{
host => Host,
port => Port,
path => Path,
transport => Transport,
connect_opts => build_wt_connect_opts(Options, Headers),
connect_timeout => ConnectTimeout,
recv_timeout => proplists:get_value(recv_timeout, Options, infinity),
active => proplists:get_value(active, Options, false),
max_recv_buffer => proplists:get_value(max_recv_buffer, Options, 16#4000000)
},
case hackney_wt:start_link(WtOpts) of
{ok, WtPid} ->
try hackney_wt:connect(WtPid, ConnectTimeout) of
ok ->
{ok, WtPid};
{error, Reason} ->
shutdown_wt(WtPid),
{error, Reason}
catch
exit:{noproc, _} ->
{error, {wt_process_died, noproc}}
end;
{error, Reason} ->
{error, Reason}
end;
{error, _} = Err ->
Err
end.
%% @doc Send on a WebTransport connection.
%% Frame forms: `{text, Data}', `{binary, Data}', `Data' (write to the
%% default stream); `{datagram, Data}'; `{stream, StreamId, Data}' or
%% `{stream, StreamId, Data, fin|nofin}'.
-spec wt_send(pid(), hackney_wt:wt_frame()) -> ok | {error, term()}.
wt_send(WtPid, Frame) when is_pid(WtPid) ->
hackney_wt:send(WtPid, Frame).
%% @doc Receive the next message on the default channel (passive mode).
-spec wt_recv(pid()) -> {ok, hackney_wt:wt_msg()} | {error, term()}.
wt_recv(WtPid) when is_pid(WtPid) ->
hackney_wt:recv(WtPid).
-spec wt_recv(pid(), timeout()) -> {ok, hackney_wt:wt_msg()} | {error, term()}.
wt_recv(WtPid, Timeout) when is_pid(WtPid) ->
hackney_wt:recv(WtPid, Timeout).
%% @doc Set WebTransport options. Supported: [{active, true | false | once}]
-spec wt_setopts(pid(), list()) -> ok | {error, term()}.
wt_setopts(WtPid, Opts) when is_pid(WtPid) ->
hackney_wt:setopts(WtPid, Opts).
%% @doc Close a WebTransport session gracefully.
-spec wt_close(pid()) -> ok.
wt_close(WtPid) when is_pid(WtPid) ->
hackney_wt:close(WtPid).