-
-
Notifications
You must be signed in to change notification settings - Fork 443
Expand file tree
/
Copy pathhackney_conn.erl
More file actions
3462 lines (3112 loc) · 148 KB
/
hackney_conn.erl
File metadata and controls
3462 lines (3112 loc) · 148 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.
%%%
%%% Copyright (c) 2024 Benoit Chesneau
%%%
%%% @doc gen_statem process for managing a single HTTP connection.
%%%
%%% This module implements a state machine for HTTP connections,
%%% handling connection establishment, request/response cycles,
%%% and connection reuse.
%%%
%%% States:
%%% - idle: Process started, not connected
%%% - connecting: TCP/SSL handshake in progress
%%% - connected: Ready for requests
%%% - sending: Sending request data
%%% - receiving: Awaiting/streaming response
%%% - closed: Connection terminated
-module(hackney_conn).
-behaviour(gen_statem).
%% API
-export([
start_link/1,
stop/1,
connect/1,
connect/2,
get_state/1,
%% Request/Response (sync)
request/5,
request/6,
request/7,
request_streaming/5,
body/1,
body/2,
stream_body/1,
%% Streaming body (request body)
send_request_headers/4,
send_body_chunk/2,
finish_send_body/1,
start_response/1,
%% Async streaming
request_async/6,
request_async/7,
request_async/8,
request_async/9,
stream_next/1,
stop_async/1,
pause_stream/1,
resume_stream/1,
%% Socket operations
setopts/2,
peername/1,
peercert/1,
sockname/1,
%% Low-level socket operations (for hackney_request/hackney_response)
send/2,
recv/2,
recv/3,
close/1,
%% Response info
response_headers/1,
get_location/1,
set_location/2,
%% Pool management
release_to_pool/1,
verify_socket/1,
is_ready/1,
%% SSL upgrade
upgrade_to_ssl/2,
is_upgraded_ssl/1,
%% Reuse control
is_no_reuse/1,
%% Owner management
set_owner/2,
set_owner_async/2,
%% Protocol info
get_protocol/1
]).
%% gen_statem callbacks
-export([
init/1,
callback_mode/0,
terminate/3,
code_change/4
]).
%% State functions
-export([
idle/3,
connecting/3,
connected/3,
sending/3,
streaming_body/3,
receiving/3,
streaming/3,
streaming_once/3,
closed/3
]).
-include("hackney.hrl").
-include("hackney_lib.hrl").
-define(CONNECT_TIMEOUT, 8000).
-define(IDLE_TIMEOUT, infinity).
%% State data record
-record(conn_data, {
%% Connection owner
owner :: pid(),
owner_mon :: reference() | undefined,
%% Connection identity
host :: string(),
port :: inet:port_number(),
netloc :: binary() | undefined,
transport :: module(),
%% Socket state
socket :: inet:socket() | ssl:sslsocket() | undefined,
buffer = <<>> :: binary(),
%% Options
connect_timeout = ?CONNECT_TIMEOUT :: timeout(),
recv_timeout = ?RECV_TIMEOUT :: timeout(),
idle_timeout = ?IDLE_TIMEOUT :: timeout(),
connect_options = [] :: list(),
ssl_options = [] :: list(),
inform_fun :: fun((integer(), binary(), list()) -> any()) | undefined,
auto_decompress = false :: boolean(),
%% Pool integration
pool_pid :: pid() | undefined, %% If set, connection is from a pool
%% Request tracking
request_ref :: reference() | undefined,
request_from :: {pid(), reference()} | undefined,
method :: binary() | undefined,
path :: binary() | undefined,
%% Response state
version :: {integer(), integer()} | undefined,
status :: integer() | undefined,
reason :: binary() | undefined,
response_headers :: term() | undefined,
location :: binary() | undefined, %% Stores the final URL after redirects
%% Parser state
parser :: #hparser{} | undefined,
%% Async mode
async = false :: false | true | once | paused,
stream_to :: pid() | undefined,
async_ref :: pid() | undefined, %% Connection PID used as message correlation ref
follow_redirect = false :: boolean(),
%% SSL upgrade tracking - set when TCP connection is upgraded to SSL
%% Upgraded connections should NOT be returned to pool
upgraded_ssl = false :: boolean(),
%% No-reuse flag - set for connections that should never be pooled
%% (e.g., SOCKS5 proxy connections which establish per-request tunnels)
no_reuse = false :: boolean(),
%% HTTP/2 support
%% Protocol negotiated via ALPN (http1, http2, or http3)
protocol = http1 :: http1 | http2 | http3,
%% HTTP/2 connection state machine (from hackney_http2_machine)
h2_machine :: tuple() | undefined,
%% Map of active HTTP/2 streams: StreamId => {From, StreamState}
%% StreamState: waiting_headers | waiting_body | done | {push, Headers}
h2_streams = #{} :: #{pos_integer() => {gen_statem:from() | pid(), atom() | tuple()}},
%% Server push handling: false = reject all (default), pid = send notifications to pid
enable_push = false :: false | pid(),
%% HTTP/3 support (QUIC)
%% QUIC connection reference from hackney_quic
h3_conn :: reference() | undefined,
%% Map of active HTTP/3 streams: StreamId => {From, StreamState}
h3_streams = #{} :: #{non_neg_integer() => {gen_statem:from() | pid(), atom() | tuple()}},
%% Current HTTP/3 stream ID for streaming body mode
h3_stream_id :: non_neg_integer() | undefined,
%% Whether to try HTTP/3 (requires UDP)
try_http3 = false :: boolean()
}).
%%====================================================================
%% API
%%====================================================================
%% @doc Start a connection process.
%% Options:
%% - host: Target host (string)
%% - port: Target port (integer)
%% - transport: hackney_tcp or hackney_ssl
%% - connect_timeout: Connection timeout (default 8000ms)
%% - recv_timeout: Receive timeout (default 5000ms)
%% - idle_timeout: Idle timeout before closing (default infinity)
%% - connect_options: Options passed to transport connect
%% - ssl_options: Additional SSL options
-spec start_link(map()) -> {ok, pid()} | {error, term()}.
start_link(Opts) when is_map(Opts) ->
gen_statem:start_link(?MODULE, [self(), Opts], []).
%% @doc Stop the connection process.
%% Returns ok even if the process has already terminated.
-spec stop(pid()) -> ok.
stop(Pid) ->
try
gen_statem:stop(Pid)
catch
exit:noproc -> ok;
exit:{noproc, _} -> ok;
exit:normal -> ok;
exit:{normal, _} -> ok
end.
%% @doc Connect to the target host. Blocks until connected or timeout.
-spec connect(pid()) -> ok | {error, term()}.
connect(Pid) ->
connect(Pid, ?CONNECT_TIMEOUT).
-spec connect(pid(), timeout()) -> ok | {error, term()}.
connect(Pid, Timeout) ->
gen_statem:call(Pid, connect, Timeout).
%% @doc Get current state name for debugging.
-spec get_state(pid()) -> {ok, atom()} | {error, term()}.
get_state(Pid) ->
gen_statem:call(Pid, get_state).
%% @doc Send an HTTP request and wait for the response status and headers.
%% Returns {ok, Status, Headers} for HTTP/1.1 or {ok, Status, Headers, Body} for HTTP/2.
%% For HTTP/1.1, use body/1 or stream_body/1 to get the response body.
-spec request(pid(), binary(), binary(), list(), binary() | iolist()) ->
{ok, integer(), list()} | {ok, integer(), list(), binary()} | {error, term()}.
request(Pid, Method, Path, Headers, Body) ->
request(Pid, Method, Path, Headers, Body, infinity, []).
-spec request(pid(), binary(), binary(), list(), binary() | iolist(), timeout()) ->
{ok, integer(), list()} | {ok, integer(), list(), binary()} | {error, term()}.
request(Pid, Method, Path, Headers, Body, Timeout) ->
request(Pid, Method, Path, Headers, Body, Timeout, []).
%% @doc Make an HTTP request with additional request options.
%% Options:
%% - inform_fun: fun(Status, Reason, Headers) - callback for 1xx responses
-spec request(pid(), binary(), binary(), list(), binary() | iolist(), timeout(), list()) ->
{ok, integer(), list()} | {ok, integer(), list(), binary()} | {error, term()}.
request(Pid, Method, Path, Headers, Body, Timeout, ReqOpts) ->
gen_statem:call(Pid, {request, Method, Path, Headers, Body, ReqOpts}, Timeout).
%% @doc Send an HTTP/3 request and return headers immediately.
%% Returns {ok, Status, Headers} and allows subsequent stream_body/1 calls.
%% This is for pull-based body streaming over HTTP/3.
-spec request_streaming(pid(), binary(), binary(), list(), binary() | iolist()) ->
{ok, integer(), list()} | {error, term()}.
request_streaming(Pid, Method, Path, Headers, Body) ->
gen_statem:call(Pid, {request_streaming, Method, Path, Headers, Body}, infinity).
%% @doc Send only the request headers (for streaming body mode).
%% After this, use send_body_chunk/2 and finish_send_body/1 to send the body,
%% then start_response/1 to receive the response.
-spec send_request_headers(pid(), binary(), binary(), list()) -> ok | {error, term()}.
send_request_headers(Pid, Method, Path, Headers) ->
gen_statem:call(Pid, {send_headers, Method, Path, Headers}, infinity).
%% @doc Send a chunk of the request body.
-spec send_body_chunk(pid(), iodata()) -> ok | {error, term()}.
send_body_chunk(Pid, Data) ->
gen_statem:call(Pid, {send_body_chunk, Data}, infinity).
%% @doc Finish sending the request body.
-spec finish_send_body(pid()) -> ok | {error, term()}.
finish_send_body(Pid) ->
gen_statem:call(Pid, finish_send_body, infinity).
%% @doc Start receiving the response after sending the full body.
-spec start_response(pid()) -> {ok, integer(), list(), pid()} | {error, term()}.
start_response(Pid) ->
gen_statem:call(Pid, start_response, infinity).
%% @doc Get the full response body.
-spec body(pid()) -> {ok, binary()} | {error, term()}.
body(Pid) ->
body(Pid, infinity).
-spec body(pid(), timeout()) -> {ok, binary()} | {error, term()}.
body(Pid, Timeout) ->
gen_statem:call(Pid, body, Timeout).
%% @doc Stream the response body in chunks.
%% Returns {ok, Data} for each chunk, {done, Pid} when complete.
-spec stream_body(pid()) -> {ok, binary()} | done | {error, term()}.
stream_body(Pid) ->
gen_statem:call(Pid, stream_body).
%% @doc Send an HTTP request asynchronously.
%% Returns {ok, Ref} immediately. Response is sent as messages:
%% - {hackney_response, Ref, {status, Status, Reason}}
%% - {hackney_response, Ref, {headers, Headers}}
%% - {hackney_response, Ref, Data} (body chunks)
%% - {hackney_response, Ref, done}
%% - {hackney_response, Ref, {error, Reason}}
%% When follow_redirect is true and response is a redirect:
%% - {hackney_response, Ref, {redirect, Location, Headers}} for 301,302,307,308
%% - {hackney_response, Ref, {see_other, Location, Headers}} for 303 with POST
%% AsyncMode: true (continuous) or once (one message at a time, use stream_next/1)
-spec request_async(pid(), binary(), binary(), list(), binary() | iolist(), true | once) ->
{ok, reference()} | {error, term()}.
request_async(Pid, Method, Path, Headers, Body, AsyncMode) ->
request_async(Pid, Method, Path, Headers, Body, AsyncMode, self(), false).
-spec request_async(pid(), binary(), binary(), list(), binary() | iolist(), true | once, pid()) ->
{ok, reference()} | {error, term()}.
request_async(Pid, Method, Path, Headers, Body, AsyncMode, StreamTo) ->
request_async(Pid, Method, Path, Headers, Body, AsyncMode, StreamTo, false).
-spec request_async(pid(), binary(), binary(), list(), binary() | iolist(), true | once, pid(), boolean()) ->
{ok, reference()} | {error, term()}.
request_async(Pid, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect) ->
gen_statem:call(Pid, {request_async, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect}).
-spec request_async(pid(), binary(), binary(), list(), binary() | iolist(), true | once, pid(), boolean(), list()) ->
{ok, reference()} | {error, term()}.
request_async(Pid, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect, ReqOpts) ->
gen_statem:call(Pid, {request_async, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect, ReqOpts}).
%% @doc Request the next message in {async, once} mode.
-spec stream_next(pid()) -> ok | {error, term()}.
stream_next(Pid) ->
gen_statem:cast(Pid, stream_next).
%% @doc Stop async mode and return to sync mode.
-spec stop_async(pid()) -> ok | {error, term()}.
stop_async(Pid) ->
gen_statem:call(Pid, stop_async).
%% @doc Pause async streaming (hibernate the stream).
-spec pause_stream(pid()) -> ok | {error, term()}.
pause_stream(Pid) ->
gen_statem:cast(Pid, pause_stream).
%% @doc Resume paused async streaming.
-spec resume_stream(pid()) -> ok | {error, term()}.
resume_stream(Pid) ->
gen_statem:cast(Pid, resume_stream).
%% @doc Set socket options on the underlying socket.
-spec setopts(pid(), list()) -> ok | {error, term()}.
setopts(Pid, Opts) ->
gen_statem:call(Pid, {setopts, Opts}).
%% @doc Get the remote address and port.
-spec peername(pid()) -> {ok, {inet:ip_address(), inet:port_number()}} | {error, term()}.
peername(Pid) ->
gen_statem:call(Pid, peername).
%% @doc Get the peer SSL certificate.
%% Returns {ok, Cert} where Cert is the DER-encoded certificate binary,
%% or {error, Reason} if the connection is not SSL or the certificate is unavailable.
-spec peercert(pid()) -> {ok, binary()} | {error, term()}.
peercert(Pid) ->
gen_statem:call(Pid, peercert).
%% @doc Get the local address and port.
-spec sockname(pid()) -> {ok, {inet:ip_address(), inet:port_number()}} | {error, term()}.
sockname(Pid) ->
gen_statem:call(Pid, sockname).
%% @doc Get the last response headers.
-spec response_headers(pid()) -> list() | undefined.
response_headers(Pid) ->
gen_statem:call(Pid, response_headers).
%% @doc Get the stored location (final URL after redirects).
-spec get_location(pid()) -> binary() | undefined.
get_location(Pid) ->
gen_statem:call(Pid, get_location).
%% @doc Set the location (used after following redirects).
-spec set_location(pid(), binary()) -> ok.
set_location(Pid, Location) ->
gen_statem:call(Pid, {set_location, Location}).
%% @doc Send data through the connection process.
%% This is a low-level function used by hackney_request.
-spec send(pid(), iodata()) -> ok | {error, term()}.
send(Pid, Data) ->
gen_statem:call(Pid, {send, Data}).
%% @doc Receive data from the connection process.
%% This is a low-level function used by hackney_response.
-spec recv(pid(), timeout()) -> {ok, binary()} | {error, term()}.
recv(Pid, Timeout) ->
recv(Pid, 0, Timeout).
-spec recv(pid(), non_neg_integer(), timeout()) -> {ok, binary()} | {error, term()}.
recv(Pid, Length, Timeout) ->
gen_statem:call(Pid, {recv, Length, Timeout}, Timeout + 5000).
%% @doc Close the connection.
%% This is a low-level function that closes the socket but keeps the process.
-spec close(pid()) -> ok.
close(Pid) ->
gen_statem:call(Pid, close_socket).
%% @doc Release the connection back to the pool.
%% This notifies the pool that the connection is available for reuse.
%% Uses a synchronous call to ensure the pool has processed the checkin.
-spec release_to_pool(pid()) -> ok.
release_to_pool(Pid) ->
gen_statem:call(Pid, release_to_pool, 5000).
%% @doc Set a new owner for this connection (sync).
%% This updates the process being monitored - if the new owner crashes,
%% the connection will terminate. Used by the pool when checking out
%% a connection to a new requester.
-spec set_owner(pid(), pid()) -> ok.
set_owner(Pid, NewOwner) ->
gen_statem:call(Pid, {set_owner, NewOwner}, 5000).
%% @doc Set a new owner for this connection (async).
%% Same as set_owner/2 but non-blocking. Used when the caller cannot
%% block (e.g., during pool checkin to avoid deadlock).
-spec set_owner_async(pid(), pid()) -> ok.
set_owner_async(Pid, NewOwner) ->
gen_statem:cast(Pid, {set_owner, NewOwner}).
%% @doc Check if the connection's socket is still healthy.
%% Returns ok if socket is open, {error, closed} otherwise.
-spec verify_socket(pid()) -> ok | {error, closed | term()}.
verify_socket(Pid) ->
gen_statem:call(Pid, verify_socket).
%% @doc Check if the connection is ready for a new request.
%% Returns {ok, connected} if ready, or error/closed status.
%% This combines state check and socket verification in one call.
-spec is_ready(pid()) -> {ok, connected} | {ok, closed} | {error, term()}.
is_ready(Pid) ->
gen_statem:call(Pid, is_ready).
%% @doc Upgrade a TCP connection to SSL.
%% This performs an SSL handshake on the existing TCP socket.
%% After upgrade, the connection is marked as upgraded_ssl and should
%% NOT be returned to the pool (SSL connections are not pooled for security).
-spec upgrade_to_ssl(pid(), list()) -> ok | {error, term()}.
upgrade_to_ssl(Pid, SslOpts) ->
gen_statem:call(Pid, {upgrade_to_ssl, SslOpts}, infinity).
%% @doc Check if this connection was upgraded from TCP to SSL.
%% Upgraded connections should be closed after use, not returned to pool.
-spec is_upgraded_ssl(pid()) -> boolean().
is_upgraded_ssl(Pid) ->
gen_statem:call(Pid, is_upgraded_ssl).
%% @doc Check if this connection should not be reused/pooled.
%% SOCKS5 proxy connections set this flag since each establishes a unique tunnel.
-spec is_no_reuse(pid()) -> boolean().
is_no_reuse(Pid) ->
gen_statem:call(Pid, is_no_reuse).
%% @doc Get the negotiated protocol for this connection.
%% Returns http1, http2, or http3 based on ALPN negotiation (SSL connections),
%% QUIC (HTTP/3), or http1 for plain TCP connections.
-spec get_protocol(pid()) -> http1 | http2 | http3.
get_protocol(Pid) ->
gen_statem:call(Pid, get_protocol).
%%====================================================================
%% gen_statem callbacks
%%====================================================================
callback_mode() -> [state_functions, state_enter].
init([DefaultOwner, Opts]) ->
process_flag(trap_exit, true),
%% Use owner from opts if provided (e.g., from pool), otherwise use default
Owner = maps:get(owner, Opts, DefaultOwner),
OwnerMon = monitor(process, Owner),
Host = maps:get(host, Opts),
Port = maps:get(port, Opts, 80),
Transport = maps:get(transport, Opts, hackney_tcp),
%% Compute netloc for Host header
Netloc = compute_netloc(Host, Port, Transport),
%% Check if a pre-established socket is provided (e.g., from proxy)
Socket = maps:get(socket, Opts, undefined),
Data = #conn_data{
owner = Owner,
owner_mon = OwnerMon,
host = Host,
port = Port,
netloc = Netloc,
transport = Transport,
socket = Socket,
connect_timeout = maps:get(connect_timeout, Opts, ?CONNECT_TIMEOUT),
recv_timeout = maps:get(recv_timeout, Opts, ?RECV_TIMEOUT),
idle_timeout = maps:get(idle_timeout, Opts, ?IDLE_TIMEOUT),
connect_options = maps:get(connect_options, Opts, []),
ssl_options = maps:get(ssl_options, Opts, []),
pool_pid = maps:get(pool_pid, Opts, undefined),
enable_push = maps:get(enable_push, Opts, false),
no_reuse = maps:get(no_reuse, Opts, false),
inform_fun = maps:get(inform_fun, Opts, undefined),
auto_decompress = maps:get(auto_decompress, Opts, false)
},
%% If socket is provided, start in connected state; otherwise start in idle
case Socket of
undefined ->
{ok, idle, Data};
_ ->
{ok, connected, Data}
end.
terminate(_Reason, _State, #conn_data{socket = Socket, transport = Transport, h2_machine = H2Machine, h3_conn = H3Conn}) ->
%% Cancel any HTTP/2 timers to prevent orphaned timer messages
cancel_h2_timers(H2Machine),
%% Close HTTP/3 connection if present
case H3Conn of
undefined -> ok;
_ -> hackney_h3:close(H3Conn)
end,
%% Close socket
case Socket of
undefined -> ok;
_ -> Transport:close(Socket)
end,
ok.
%% @private Cancel HTTP/2 preface and settings timers
cancel_h2_timers(undefined) ->
ok;
cancel_h2_timers(H2Machine) when is_tuple(H2Machine), element(1, H2Machine) =:= http2_machine ->
%% H2Machine is #http2_machine{} record:
%% Element 1: http2_machine (record name)
%% Element 2: mode
%% Element 3: opts
%% Element 4: state
%% Element 5: preface_timer
%% Element 6: settings_timer
try
case element(5, H2Machine) of
undefined -> ok;
PrefaceTimer ->
_ = erlang:cancel_timer(PrefaceTimer, [{async, true}, {info, false}]),
ok
end,
case element(6, H2Machine) of
undefined -> ok;
SettingsTimer ->
_ = erlang:cancel_timer(SettingsTimer, [{async, true}, {info, false}]),
ok
end
catch
_:_ -> ok
end;
cancel_h2_timers(_) ->
ok.
code_change(_OldVsn, State, Data, _Extra) ->
{ok, State, Data}.
%%====================================================================
%% State: idle - Not connected yet
%%====================================================================
idle(enter, _OldState, _Data) ->
keep_state_and_data;
idle({call, From}, connect, Data) ->
%% Perform connection synchronously
#conn_data{
host = Host,
port = Port,
transport = Transport,
connect_timeout = Timeout,
connect_options = ConnectOpts,
try_http3 = TryHttp3
} = Data,
%% Check if we should try HTTP/3 first (SSL transport + http3 in protocols)
Protocols = proplists:get_value(protocols, ConnectOpts, hackney_util:default_protocols()),
ShouldTryHttp3 = TryHttp3 orelse (Transport =:= hackney_ssl andalso lists:member(http3, Protocols)),
case ShouldTryHttp3 of
true ->
%% Try HTTP/3 first
case try_h3_connect(Host, Port, Timeout, ConnectOpts) of
{ok, H3Conn} ->
NewData = Data#conn_data{
h3_conn = H3Conn,
protocol = http3
},
{next_state, connected, NewData, [{reply, From, ok}]};
{error, _H3Reason} ->
%% HTTP/3 failed, fall back to TCP/TLS
do_tcp_connect(From, Data)
end;
false ->
%% Standard TCP/TLS connection
do_tcp_connect(From, Data)
end;
idle({call, From}, get_state, _Data) ->
{keep_state_and_data, [{reply, From, {ok, idle}}]};
idle(info, {'DOWN', Ref, process, _Pid, _Reason}, #conn_data{owner_mon = Ref} = Data) ->
%% Owner died
{stop, normal, Data};
idle(EventType, Event, Data) ->
handle_common(EventType, Event, idle, Data).
%%====================================================================
%% State: connecting - TCP/SSL handshake in progress
%%====================================================================
connecting(enter, _OldState, _Data) ->
keep_state_and_data;
connecting(state_timeout, connect_timeout, Data) ->
reply_and_stop(Data#conn_data.request_from, {error, connect_timeout}, Data);
connecting({call, From}, get_state, _Data) ->
{keep_state_and_data, [{reply, From, {ok, connecting}}]};
connecting(info, {'DOWN', Ref, process, _Pid, _Reason}, #conn_data{owner_mon = Ref} = Data) ->
{stop, normal, Data};
connecting(EventType, Event, Data) ->
handle_common(EventType, Event, connecting, Data).
%%====================================================================
%% State: connected - Ready for requests
%%====================================================================
connected(enter, OldState, #conn_data{transport = Transport, socket = Socket,
idle_timeout = Timeout, pool_pid = PoolPid} = Data) ->
%% Set socket to active mode to receive server close notifications (tcp_closed/ssl_closed)
%% This fixes issue #544: stale connections not being detected when server closes idle connections
%% Only enable active mode when returning from a completed request cycle (receiving, streaming states)
%% NOT on initial connection from 'connecting' state - server might send data before we send request
_ = case {Socket, should_enable_active_mode(OldState)} of
{undefined, _} -> ok;
{_, false} -> ok;
{_, true} -> Transport:setopts(Socket, [{active, once}])
end,
%% Auto-release to pool when body reading is complete
%% This happens when transitioning from receiving state (body fully read)
Data2 = case {PoolPid, should_auto_release(OldState)} of
{undefined, _} ->
Data;
{_, false} ->
Data;
{_, true} ->
%% Transfer ownership back to pool and notify it
auto_release_to_pool(Data)
end,
case Timeout of
infinity -> {keep_state, Data2};
_ -> {keep_state, Data2, [{state_timeout, Timeout, idle_timeout}]}
end;
connected({call, From}, release_to_pool, #conn_data{pool_pid = PoolPid, owner_mon = OldMon,
transport = Transport, socket = Socket} = Data) ->
%% Reset owner to pool before notifying, to avoid deadlock
%% (pool might call set_owner back, but connection is blocked here)
Data2 = case PoolPid of
undefined ->
Data;
_ ->
demonitor(OldMon, [flush]),
NewMon = monitor(process, PoolPid),
Data#conn_data{owner = PoolPid, owner_mon = NewMon}
end,
%% Enable active mode for close detection now that connection is idle in pool
%% This fixes issue #544: detect server-initiated closes while idle
_ = case Socket of
undefined -> ok;
_ -> Transport:setopts(Socket, [{active, once}])
end,
%% Notify pool that connection is available for reuse (sync)
notify_pool_available_sync(Data2),
{keep_state, Data2, [{reply, From, ok}]};
connected({call, From}, {set_owner, NewOwner}, #conn_data{owner_mon = OldMon} = Data) ->
%% Update owner - demonitor old, monitor new
demonitor(OldMon, [flush]),
NewMon = monitor(process, NewOwner),
{keep_state, Data#conn_data{owner = NewOwner, owner_mon = NewMon},
[{reply, From, ok}]};
connected(cast, {set_owner, NewOwner}, #conn_data{owner_mon = OldMon, pool_pid = PoolPid,
transport = Transport, socket = Socket} = Data) ->
%% Async owner update - used by pool during checkin to avoid deadlock
demonitor(OldMon, [flush]),
NewMon = monitor(process, NewOwner),
%% If new owner is the pool, connection is becoming idle - enable active mode for close detection
%% This fixes issue #544: detect server-initiated closes while idle in pool
_ = case {NewOwner, PoolPid, Socket} of
{PoolPid, PoolPid, Socket} when PoolPid =/= undefined, Socket =/= undefined ->
Transport:setopts(Socket, [{active, once}]);
_ ->
ok
end,
{keep_state, Data#conn_data{owner = NewOwner, owner_mon = NewMon}};
connected(state_timeout, idle_timeout, Data) ->
%% Idle timeout - close connection
{next_state, closed, Data};
connected({call, From}, get_state, _Data) ->
{keep_state_and_data, [{reply, From, {ok, connected}}]};
connected({call, From}, verify_socket, #conn_data{socket = undefined} = Data) ->
%% Socket not connected
{next_state, closed, Data, [{reply, From, {error, closed}}]};
connected({call, From}, verify_socket, #conn_data{transport = Transport, socket = Socket} = Data) ->
%% Check if socket has any pending data or close messages
case check_socket_health(Transport, Socket) of
ok -> {keep_state_and_data, [{reply, From, ok}]};
{error, Reason} ->
{next_state, closed, Data#conn_data{socket = undefined}, [{reply, From, {error, Reason}}]}
end;
connected({call, From}, is_ready, #conn_data{socket = undefined} = Data) ->
%% Socket not connected
{next_state, closed, Data, [{reply, From, {ok, closed}}]};
connected({call, From}, is_ready, #conn_data{transport = Transport, socket = Socket} = Data) ->
%% Check for pending close message first (from active mode)
case has_pending_close(Socket) of
true ->
%% Server closed the connection - transition to closed state
{next_state, closed, Data#conn_data{socket = undefined}, [{reply, From, {ok, closed}}]};
false ->
%% No close message pending - check socket health
case check_socket_health(Transport, Socket) of
ok ->
%% Socket is healthy - set to passive mode for checkout
%% This ensures the socket is ready for blocking recv operations
_ = Transport:setopts(Socket, [{active, false}]),
%% Flush any data messages that arrived while in active mode
flush_socket_messages(Socket),
{keep_state_and_data, [{reply, From, {ok, connected}}]};
{error, _} ->
{keep_state_and_data, [{reply, From, {ok, closed}}]}
end
end;
connected({call, From}, {upgrade_to_ssl, _SslOpts}, #conn_data{transport = hackney_ssl} = _Data) ->
%% Already SSL - no upgrade needed
{keep_state_and_data, [{reply, From, ok}]};
connected({call, From}, {upgrade_to_ssl, SslOpts}, #conn_data{socket = Socket, host = Host, connect_options = ConnectOpts} = Data) ->
%% Upgrade TCP socket to SSL (e.g., after CONNECT proxy tunnel)
%% Use ssl_opts/2 to properly merge defaults with user options
%% (handles cacertfile vs cacerts correctly)
MergedSslOpts = hackney_ssl:ssl_opts(Host, [{ssl_options, SslOpts}]),
%% Add ALPN options for HTTP/2 negotiation
%% Check both SslOpts (from upgrade call) and ConnectOpts (from initial config)
AlpnOpts = case hackney_ssl:alpn_opts(SslOpts) of
[] -> hackney_ssl:alpn_opts(ConnectOpts);
Opts -> Opts
end,
FinalSslOpts = hackney_util:merge_opts(MergedSslOpts, AlpnOpts),
case ssl:connect(Socket, FinalSslOpts) of
{ok, SslSocket} ->
%% Detect negotiated protocol
Protocol = hackney_ssl:get_negotiated_protocol(SslSocket),
%% Update connection to use SSL
NewData = Data#conn_data{
transport = hackney_ssl,
socket = SslSocket,
upgraded_ssl = true, % Mark as upgraded - should NOT return to pool
protocol = Protocol
},
%% Initialize HTTP/2 if negotiated
case Protocol of
http2 ->
init_h2_after_upgrade(SslSocket, NewData, From);
http1 ->
{keep_state, NewData, [{reply, From, ok}]}
end;
{error, Reason} ->
{keep_state_and_data, [{reply, From, {error, Reason}}]}
end;
connected({call, From}, is_upgraded_ssl, #conn_data{upgraded_ssl = Upgraded}) ->
{keep_state_and_data, [{reply, From, Upgraded}]};
connected({call, From}, is_no_reuse, #conn_data{no_reuse = NoReuse}) ->
{keep_state_and_data, [{reply, From, NoReuse}]};
connected({call, From}, {request, Method, Path, Headers, Body, ReqOpts}, #conn_data{protocol = http2} = Data) ->
%% HTTP/2 request - use h2_machine (1xx not applicable for HTTP/2)
%% Allow recv_timeout to be overridden per-request (fix for issue #832)
RecvTimeout = proplists:get_value(recv_timeout, ReqOpts, Data#conn_data.recv_timeout),
NewData = Data#conn_data{recv_timeout = RecvTimeout},
do_h2_request(From, Method, Path, Headers, Body, NewData);
connected({call, From}, {request, Method, Path, Headers, Body, ReqOpts}, #conn_data{protocol = http3} = Data) ->
%% HTTP/3 request - use hackney_h3 (1xx not applicable for HTTP/3)
%% Allow recv_timeout to be overridden per-request (fix for issue #832)
RecvTimeout = proplists:get_value(recv_timeout, ReqOpts, Data#conn_data.recv_timeout),
NewData = Data#conn_data{recv_timeout = RecvTimeout},
do_h3_request(From, Method, Path, Headers, Body, NewData);
connected({call, From}, {request_async, Method, Path, Headers, Body, AsyncMode, StreamTo}, #conn_data{protocol = http2} = Data) ->
%% HTTP/2 async request
do_h2_request_async(From, Method, Path, Headers, Body, AsyncMode, StreamTo, false, Data);
connected({call, From}, {request_async, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect}, #conn_data{protocol = http2} = Data) ->
%% HTTP/2 async request with redirect option
do_h2_request_async(From, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect, Data);
connected({call, From}, {request_async, Method, Path, Headers, Body, AsyncMode, StreamTo}, #conn_data{protocol = http3} = Data) ->
%% HTTP/3 async request
do_h3_request_async(From, Method, Path, Headers, Body, AsyncMode, StreamTo, Data);
connected({call, From}, {request_async, Method, Path, Headers, Body, AsyncMode, StreamTo, _FollowRedirect}, #conn_data{protocol = http3} = Data) ->
%% HTTP/3 async request (redirect not yet implemented for H3)
do_h3_request_async(From, Method, Path, Headers, Body, AsyncMode, StreamTo, Data);
connected({call, From}, {request_streaming, Method, Path, Headers, Body}, #conn_data{protocol = http3} = Data) ->
%% HTTP/3 request with streaming body reads (returns headers, then stream_body for chunks)
do_h3_request_streaming(From, Method, Path, Headers, Body, Data);
connected({call, From}, {request, Method, Path, Headers, Body, ReqOpts}, Data) ->
%% HTTP/1.1 request
InformFun = proplists:get_value(inform_fun, ReqOpts, undefined),
AutoDecompress = proplists:get_value(auto_decompress, ReqOpts, false),
%% Allow recv_timeout to be overridden per-request (fix for issue #832)
RecvTimeout = proplists:get_value(recv_timeout, ReqOpts, Data#conn_data.recv_timeout),
NewData = Data#conn_data{
request_from = From,
method = Method,
path = Path,
parser = undefined,
version = undefined,
status = undefined,
reason = undefined,
response_headers = undefined,
buffer = <<>>,
async = false,
async_ref = undefined,
stream_to = undefined,
inform_fun = InformFun,
auto_decompress = AutoDecompress,
recv_timeout = RecvTimeout
},
{next_state, sending, NewData, [{next_event, internal, {send_request, Method, Path, Headers, Body}}]};
connected({call, From}, {request_async, Method, Path, Headers, Body, AsyncMode, StreamTo}, Data) ->
%% Start a new async request (no redirect following)
do_request_async(From, Method, Path, Headers, Body, AsyncMode, StreamTo, false, Data);
connected({call, From}, {request_async, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect}, Data) ->
%% Start a new async request with redirect option (HTTP/1.1)
do_request_async(From, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect, Data);
connected({call, From}, {request_async, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect, ReqOpts}, #conn_data{protocol = http2} = Data) ->
%% HTTP/2 async request with ReqOpts (fix for issue #832)
RecvTimeout = proplists:get_value(recv_timeout, ReqOpts, Data#conn_data.recv_timeout),
NewData = Data#conn_data{recv_timeout = RecvTimeout},
do_h2_request_async(From, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect, NewData);
connected({call, From}, {request_async, Method, Path, Headers, Body, AsyncMode, StreamTo, _FollowRedirect, ReqOpts}, #conn_data{protocol = http3} = Data) ->
%% HTTP/3 async request with ReqOpts (fix for issue #832, redirect not yet implemented for H3)
RecvTimeout = proplists:get_value(recv_timeout, ReqOpts, Data#conn_data.recv_timeout),
NewData = Data#conn_data{recv_timeout = RecvTimeout},
do_h3_request_async(From, Method, Path, Headers, Body, AsyncMode, StreamTo, NewData);
connected({call, From}, {request_async, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect, ReqOpts}, Data) ->
%% HTTP/1.1 async request with ReqOpts (fix for issue #832)
RecvTimeout = proplists:get_value(recv_timeout, ReqOpts, Data#conn_data.recv_timeout),
NewData = Data#conn_data{recv_timeout = RecvTimeout},
do_request_async(From, Method, Path, Headers, Body, AsyncMode, StreamTo, FollowRedirect, NewData);
connected({call, From}, {send_headers, Method, Path, Headers}, #conn_data{protocol = http3} = Data) ->
%% HTTP/3 streaming body - send headers only via QUIC
do_h3_send_headers(From, Method, Path, Headers, Data);
connected({call, From}, {send_headers, Method, Path, Headers}, Data) ->
%% Send only headers for streaming body mode (HTTP/1.1)
NewData = Data#conn_data{
request_from = From,
method = Method,
path = Path,
parser = undefined,
version = undefined,
status = undefined,
reason = undefined,
response_headers = undefined,
buffer = <<>>,
async = false,
async_ref = undefined,
stream_to = undefined
},
%% Transition to streaming_body state
{next_state, streaming_body, NewData, [{next_event, internal, {send_headers_only, Method, Path, Headers}}]};
%% HTTP/2 socket data handling
connected(info, {ssl, Socket, RecvData}, #conn_data{socket = Socket, protocol = http2} = Data) ->
handle_h2_data(RecvData, Data);
connected(info, {tcp, Socket, RecvData}, #conn_data{socket = Socket, protocol = http2} = Data) ->
handle_h2_data(RecvData, Data);
connected(info, {tcp_closed, Socket}, #conn_data{socket = Socket} = Data) ->
{next_state, closed, Data#conn_data{socket = undefined}};
connected(info, {ssl_closed, Socket}, #conn_data{socket = Socket} = Data) ->
{next_state, closed, Data#conn_data{socket = undefined}};
connected(info, {tcp_error, Socket, _Reason}, #conn_data{socket = Socket} = Data) ->
{next_state, closed, Data#conn_data{socket = undefined}};
connected(info, {ssl_error, Socket, _Reason}, #conn_data{socket = Socket} = Data) ->
{next_state, closed, Data#conn_data{socket = undefined}};
%% Unexpected data received while idle (HTTP/1.1 only - HTTP/2 handled above)
%% This could be trailing data from server or protocol violation - close connection
connected(info, {tcp, Socket, _UnexpectedData}, #conn_data{socket = Socket, protocol = Protocol} = Data)
when Protocol =/= http2 ->
{next_state, closed, Data#conn_data{socket = undefined}};
connected(info, {ssl, Socket, _UnexpectedData}, #conn_data{socket = Socket, protocol = Protocol} = Data)
when Protocol =/= http2 ->
{next_state, closed, Data#conn_data{socket = undefined}};
%% HTTP/3 QUIC message handling
connected(info, {quic, ConnRef, {stream_headers, StreamId, Headers, Fin}},
#conn_data{h3_conn = ConnRef, h3_streams = Streams} = Data) ->
handle_h3_headers(StreamId, Headers, Fin, Streams, Data);
connected(info, {quic, ConnRef, {stream_data, StreamId, RecvData, Fin}},
#conn_data{h3_conn = ConnRef, h3_streams = Streams} = Data) ->
handle_h3_data(StreamId, RecvData, Fin, Streams, Data);
connected(info, {quic, ConnRef, {stream_reset, StreamId, ErrorCode}},
#conn_data{h3_conn = ConnRef, h3_streams = Streams} = Data) ->
handle_h3_stream_reset(StreamId, ErrorCode, Streams, Data);
connected(info, {quic, ConnRef, {closed, Reason}},
#conn_data{h3_conn = ConnRef} = Data) ->
%% QUIC connection closed
handle_h3_conn_closed(Reason, Data);
connected(info, {quic, ConnRef, {transport_error, Code, Msg}},
#conn_data{h3_conn = ConnRef} = Data) ->
%% QUIC transport error
handle_h3_error({transport_error, Code, Msg}, Data);
%% QUIC socket ready - drive event loop
connected(info, {select, _Resource, _Ref, ready_input},
#conn_data{h3_conn = ConnRef}) when ConnRef =/= undefined ->
_ = hackney_quic:process(ConnRef),
keep_state_and_data;
connected(info, {'DOWN', Ref, process, _Pid, _Reason}, #conn_data{owner_mon = Ref} = Data) ->
{stop, normal, Data};
%% HTTP/3 stream_body call - returns buffered chunk or waits for data
connected({call, From}, stream_body, #conn_data{protocol = http3, h3_streams = Streams} = Data) ->
handle_h3_stream_body(From, Streams, Data);
connected(EventType, Event, Data) ->
handle_common(EventType, Event, connected, Data).
%%====================================================================
%% State: sending - Sending request data
%%====================================================================
sending(enter, connected, #conn_data{transport = Transport, socket = Socket}) ->
%% Set socket to passive mode for blocking send/recv operations
%% (socket was in active mode while idle in connected state)
%% Note: socket may be undefined for HTTP/3 (QUIC) connections
_ = case Socket of
undefined -> ok;
_ -> Transport:setopts(Socket, [{active, false}])
end,
keep_state_and_data;
sending(internal, {send_request, Method, Path, Headers, Body}, Data) ->
case do_send_request(Method, Path, Headers, Body, Data) of
{ok, NewData} ->
{next_state, receiving, NewData, [{next_event, internal, do_recv_response}]};
{error, Reason} ->
{next_state, closed, Data, [{reply, Data#conn_data.request_from, {error, Reason}}]}
end;
sending(internal, {send_request_async, Method, Path, Headers, Body}, Data) ->
case do_send_request(Method, Path, Headers, Body, Data) of
{ok, NewData} ->