-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathhttp2c.erl
271 lines (241 loc) · 10 KB
/
http2c.erl
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
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% PLEASE ONLY USE FOR TESTING
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-module(http2c).
-behaviour(gen_server).
-include("http2.hrl").
-include_lib("eunit/include/eunit.hrl").
-include_lib("common_test/include/ct.hrl").
%% gen_server
%% start on a socket.
%% send the preamble
%% send/recv settings
%% now the gen_server has a connection
%% {request, Headers, Data}
%% {request, [Frames]}
%% A frame that is too big should know how to break itself up.
%% That might mean into Continutations
%% API
-export([
start_link/0,
send_binary/2,
send_unaltered_frames/2,
get_frames/2,
wait_for_n_frames/3
]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(http2c_state, {
socket :: undefined | {gen_tcp, gen_tcp:socket()} | {ssl, ssl:sslsocket()},
send_settings = #settings{} :: settings(),
encode_context = hpack:new_context() :: hpack:context(),
next_available_stream_id = 1 :: pos_integer(),
incoming_frames = [] :: [h2_frame:frame()],
working_frame_header = undefined :: undefined | h2_frame:header(),
working_frame_payload = <<>> :: binary(),
working_length = 0 :: non_neg_integer()
}).
%% Starts a server. Should probably take args eventually
-spec start_link() -> {ok, pid()} | ignore | {error, any()}.
start_link() ->
gen_server:start_link(?MODULE, [], []).
%% Three API levels:
%% 1: lowest: Send a frame or set of frames
%% 2: middle: Here's some hastily constructed frames, do some setup of frame header flags.
%% 3: highest: a semantic http request: **NOT IMPLEMENTED HERE*
%% send_binary/2 is the lowest level API. It just puts bits on the
%% wire
-spec send_binary(pid(), iodata()) -> ok.
send_binary(Pid, Binary) ->
gen_server:cast(Pid, {send_bin, Binary}).
%% send_unaltered_frames is the raw version of the middle level. You
%% can put frames directly as constructed on the wire. This is
%% designed for testing error conditions by giving you the freedom to
%% create bad sets of frames. This will probably only be exported
%% ifdef(TEST)
-spec send_unaltered_frames(pid(), [h2_frame:frame()]) -> ok.
send_unaltered_frames(Pid, Frames) ->
[send_binary(Pid, h2_frame:to_binary(F)) || F <- Frames],
ok.
get_frames(Pid, StreamId) ->
gen_server:call(Pid, {get_frames, StreamId}).
wait_for_n_frames(Pid, StreamId, N) ->
wait_for_n_frames(Pid, StreamId, N, 0, []).
wait_for_n_frames(_Pid, StreamId, N, Attempts, Acc)
when Attempts > 20 ->
ct:pal("Timed out waiting for ~p frames on Stream ~p", [N, StreamId]),
ct:pal("Did receive ~p frames.", [length(Acc)]),
ct:pal(" those frames were ~p", [Acc]),
case length(Acc) == N of
true ->
Acc;
_ ->
%% While this assert is good, it always hid the real error
%%?assertEqual(length(Acc), length([])),
[]
end;
wait_for_n_frames(Pid, StreamId, N, Attempts, Acc) ->
Frames = Acc ++ get_frames(Pid, StreamId),
case length(Frames) >= N of
true ->
?assertEqual(true, length(Frames) >= N),
Frames;
false ->
timer:sleep(100),
wait_for_n_frames(Pid, StreamId, N, Attempts + 1, Frames)
end.
%% gen_server callbacks
%% Initializes the server
-spec init(list()) -> {ok, #http2c_state{}} |
{ok, #http2c_state{}, timeout()} |
ignore |
{stop, any()}.
init([]) ->
Host = "localhost",
{ok, Port} = application:get_env(chatterbox, port),
ClientOptions = [
binary,
{packet, raw},
{active, false}
],
%% TODO: Stealing from the server config here :/
{ok, SSLEnabled} = application:get_env(chatterbox, ssl),
{Transport, Options} = case SSLEnabled of
true ->
{ok, SSLOptions} = application:get_env(chatterbox, ssl_options),
{ssl, ClientOptions ++ SSLOptions ++ [{client_preferred_next_protocols, {client, [<<"h2">>]}}]};
false ->
{gen_tcp, ClientOptions}
end,
{ok, Socket} = Transport:connect(Host, Port, Options),
%% Send the preamble
Transport:send(Socket, <<?PREFACE>>),
%% Settings Handshake
{_SSH, ServerSettings} = h2_frame:read({Transport, Socket}, 1000),
h2_frame_settings:ack({Transport, Socket}),
ClientSettings = chatterbox:settings(client),
ct:pal("[client] settings: ~p", [h2_settings:to_proplist(ClientSettings)]),
BinToSend = h2_frame_settings:send(#settings{}, ClientSettings),
Transport:send(Socket, BinToSend),
{AH, _PAck} = h2_frame:read({Transport, Socket}, 1000),
_ = ?IS_FLAG((AH#frame_header.flags), ?FLAG_ACK),
case Transport of
ssl ->
ssl:setopts(Socket, [{active, true}]);
gen_tcp ->
inet:setopts(Socket, [{active, true}])
end,
{ok, #http2c_state{
socket = {Transport, Socket},
send_settings = h2_frame_settings:overlay(#settings{}, ServerSettings)
}}.
%% Handling call messages
-spec handle_call(term(), {pid(), term()} , #http2c_state{}) ->
{reply, any(), #http2c_state{}} |
{reply, any(), #http2c_state{}, timeout()} |
{noreply, #http2c_state{}} |
{noreply, #http2c_state{}, timeout()} |
{stop, any(), any(), #http2c_state{}} |
{stop, any(), #http2c_state{}}.
handle_call(new_stream_id, _From, #http2c_state{next_available_stream_id=Next}=State) ->
{reply, Next, State#http2c_state{next_available_stream_id=Next+2}};
handle_call(encode_context, _From, #http2c_state{encode_context=EC}=State) ->
{reply, EC, State};
handle_call({get_frames, StreamId}, _From, #http2c_state{incoming_frames=IF}=S) ->
{ToReturn, ToPutBack} = lists:partition(fun({#frame_header{stream_id=SId},_}) -> StreamId =:= SId end, IF),
{reply, ToReturn, S#http2c_state{incoming_frames=ToPutBack}};
handle_call(send_settings, _From, #http2c_state{send_settings=S}) ->
{reply, S};
handle_call(Request, _From, State) ->
{reply, {unknown_request, Request}, State}.
%% Handling cast messages
-spec handle_cast(any(), #http2c_state{}) ->
{noreply, #http2c_state{}} |
{noreply, #http2c_state{}, timeout()} |
{stop, any(), #http2c_state{}}.
handle_cast({send_bin, Bin}, #http2c_state{socket={Transport, Socket}}=State) ->
Transport:send(Socket, Bin),
{noreply, State};
handle_cast(recv, #http2c_state{
socket={Transport, Socket},
incoming_frames = Frames
}=State) ->
RawHeader = Transport:recv(Socket, 9),
{FHeader, <<>>} = h2_frame:read_binary_frame_header(RawHeader),
RawBody = Transport:recv(Socket, FHeader#frame_header.length),
{ok, Payload, <<>>} = h2_frame:read_binary_payload(RawBody, FHeader),
F = {FHeader, Payload},
gen_server:cast(self(), recv),
{noreply, State#http2c_state{incoming_frames = Frames ++ [F]}};
handle_cast({encode_context, EC}, State=#http2c_state{}) ->
{noreply, State#http2c_state{encode_context=EC}};
handle_cast(_Msg, State) ->
{noreply, State}.
%% Handling all non call/cast messages
-spec handle_info(any(), #http2c_state{}) ->
{noreply, #http2c_state{}} |
{noreply, #http2c_state{}, timeout()} |
{stop, any(), #http2c_state{}}.
handle_info({_, _, Bin}, #http2c_state{
incoming_frames = Frames,
working_frame_header = WHeader,
working_frame_payload = WPayload
} = State) ->
{NewFrames, Header, Rem} = process_binary(Bin, WHeader, WPayload, Frames),
{noreply, State#http2c_state{
incoming_frames = NewFrames,
working_frame_header = Header,
working_frame_payload = Rem
}};
handle_info({tcp_closed,_}, State) ->
{noreply, State};
handle_info({ssl_closed,_}, State) ->
{noreply, State};
handle_info(_Info, State) ->
{noreply, State}.
%% This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any
%% necessary cleaning up. When it returns, the gen_server terminates
%% with Reason. The return value is ignored.
-spec terminate(any(), #http2c_state{}) -> any().
terminate(_Reason, _State) ->
ok.
%% Convert process state when code is changed
-spec code_change(any(), #http2c_state{}, any()) ->
{ok, #http2c_state{}}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
%%% Internal functions
%%%===================================================================
-spec process_binary(
binary(),
h2_frame:header() | undefined,
binary(),
[h2_frame:frame()]) -> {[h2_frame:frame()], h2_frame:header() | undefined, binary() | undefined}.
%%OMG probably a monad
process_binary(<<>>, undefined, <<>>, Frames) -> {Frames, undefined, <<>>};
process_binary(<<HeaderBin:9/binary,Bin/binary>>, undefined, <<>>, Frames) ->
{Header, <<>>} = h2_frame:read_binary_frame_header(HeaderBin),
L = Header#frame_header.length,
case byte_size(Bin) >= L of
true ->
{ok, Payload, Rem} = h2_frame:read_binary_payload(Bin, Header),
process_binary(Rem, undefined, <<>>, Frames ++ [{Header,Payload}]);
false ->
{Frames, Header, Bin}
end;
process_binary(Bin, Header, <<>>, Frames) ->
L = Header#frame_header.length,
case byte_size(Bin) >= L of
true ->
{ok, Payload, Rem} = h2_frame:read_binary_payload(Bin, Header),
process_binary(Rem, undefined, <<>>, Frames ++ [{Header,Payload}]);
false ->
{Frames, Header, Bin}
end;
process_binary(Bin, Header, Payload, Frames) ->
process_binary(iolist_to_binary([Payload, Bin]), Header, <<>>, Frames).