-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathh2c_client.rs
More file actions
377 lines (331 loc) · 8.21 KB
/
h2c_client.rs
File metadata and controls
377 lines (331 loc) · 8.21 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
//! Example toy h2c client using libnghttp2.
use libnghttp2::*;
use std::io::{self, Read, Write};
use std::net::TcpStream;
use std::{ptr, slice};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
struct Response {
status: u16,
headers: Vec<(String, String)>,
body: Vec<u8>,
}
impl Response {
fn body_str(&self) -> Result<&str> {
Ok(std::str::from_utf8(&self.body)?)
}
}
struct Request {
authority: String,
path: String,
}
impl Request {
fn builder() -> RequestBuilder {
RequestBuilder::default()
}
}
#[derive(Default)]
struct RequestBuilder {
authority: Option<String>,
path: Option<String>,
}
impl RequestBuilder {
fn authority(mut self, authority: impl Into<String>) -> Self {
self.authority = Some(authority.into());
self
}
fn path(mut self, path: impl Into<String>) -> Self {
self.path = Some(path.into());
self
}
fn build(self) -> Result<Request> {
Ok(Request {
authority: self.authority.ok_or("authority is required")?,
path: self.path.unwrap_or_else(|| "/".into()),
})
}
}
struct Session {
ptr: *mut nghttp2_session,
callbacks: *mut nghttp2_session_callbacks,
}
impl Session {
fn new(user_data: *mut std::os::raw::c_void) -> Result<Self> {
unsafe {
let mut callbacks = ptr::null_mut();
check(nghttp2_session_callbacks_new(&mut callbacks))?;
nghttp2_session_callbacks_set_send_callback(callbacks, Some(send_cb));
nghttp2_session_callbacks_set_on_frame_recv_callback(
callbacks,
Some(frame_recv_cb),
);
nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
callbacks,
Some(data_cb),
);
nghttp2_session_callbacks_set_on_header_callback(
callbacks,
Some(header_cb),
);
nghttp2_session_callbacks_set_on_stream_close_callback(
callbacks,
Some(stream_close_cb),
);
let mut session_ptr = ptr::null_mut();
check(nghttp2_session_client_new(
&mut session_ptr,
callbacks,
user_data,
))?;
check(nghttp2_submit_settings(
session_ptr,
NGHTTP2_FLAG_NONE as u8,
ptr::null(),
0,
))?;
Ok(Self {
ptr: session_ptr,
callbacks,
})
}
}
fn submit(&mut self, req: &Request) -> Result<i32> {
unsafe {
let headers = [
header(":method", "GET"),
header(":scheme", "http"),
header(":authority", &req.authority),
header(":path", &req.path),
];
let stream_id = nghttp2_submit_request(
self.ptr,
ptr::null(),
headers.as_ptr(),
headers.len(),
ptr::null(),
ptr::null_mut(),
);
check(stream_id)?;
check(nghttp2_session_send(self.ptr))?;
Ok(stream_id)
}
}
fn wants_io(&self) -> bool {
unsafe {
nghttp2_session_want_read(self.ptr) != 0
|| nghttp2_session_want_write(self.ptr) != 0
}
}
fn recv(&mut self, data: &[u8]) -> Result<()> {
unsafe {
check(
nghttp2_session_mem_recv(self.ptr, data.as_ptr(), data.len()) as i32,
)?;
check(nghttp2_session_send(self.ptr))
}
}
}
impl Drop for Session {
fn drop(&mut self) {
unsafe {
if !self.ptr.is_null() {
nghttp2_session_del(self.ptr);
}
if !self.callbacks.is_null() {
nghttp2_session_callbacks_del(self.callbacks);
}
}
}
}
struct Context {
stream: TcpStream,
response: Response,
stream_id: i32,
done: bool,
}
struct Client {
context: Box<Context>,
session: Session,
}
impl Client {
fn connect(host: &str) -> Result<Self> {
let stream = TcpStream::connect(format!("{}:80", host))?;
let mut context = Box::new(Context {
stream,
response: Response {
status: 0,
headers: Vec::new(),
body: Vec::new(),
},
stream_id: -1,
done: false,
});
let user_data = context.as_mut() as *mut Context as *mut _;
let session = Session::new(user_data)?;
Ok(Self { context, session })
}
fn execute(mut self, request: Request) -> Result<Response> {
self.context.stream_id = self.session.submit(&request)?;
let mut buf = [0u8; 16384];
while !self.context.done && self.session.wants_io() {
match self.context.stream.read(&mut buf) {
Ok(0) => break,
Ok(n) => self.session.recv(&buf[..n])?,
Err(e) if e.kind() == io::ErrorKind::WouldBlock => continue,
Err(e) => return Err(e.into()),
}
}
Ok(std::mem::replace(
&mut self.context.response,
Response {
status: 0,
headers: Vec::new(),
body: Vec::new(),
},
))
}
}
fn check(code: i32) -> Result<()> {
if code < 0 {
Err(format!("nghttp2 error: {}", code).into())
} else {
Ok(())
}
}
fn header(name: &str, value: &str) -> nghttp2_nv {
let name = name.as_bytes();
let value = value.as_bytes();
nghttp2_nv {
name: name.as_ptr() as *mut u8,
value: value.as_ptr() as *mut u8,
namelen: name.len(),
valuelen: value.len(),
flags: NGHTTP2_NV_FLAG_NONE as u8,
}
}
unsafe fn to_str(ptr: *const u8, len: usize) -> String {
String::from_utf8_lossy(unsafe { slice::from_raw_parts(ptr, len) }).into()
}
#[cfg(windows)]
unsafe extern "C" fn send_cb(
_: *mut nghttp2_session,
data: *const u8,
len: usize,
_: i32,
user_data: *mut std::os::raw::c_void,
) -> i64 {
unsafe {
let ctx = &mut *(user_data as *mut Context);
match ctx.stream.write_all(slice::from_raw_parts(data, len)) {
Ok(_) => len as i64,
Err(_) => NGHTTP2_ERR_CALLBACK_FAILURE as i64,
}
}
}
#[cfg(not(windows))]
unsafe extern "C" fn send_cb(
_: *mut nghttp2_session,
data: *const u8,
len: usize,
_: i32,
user_data: *mut std::os::raw::c_void,
) -> isize {
unsafe {
let ctx = &mut *(user_data as *mut Context);
match ctx.stream.write_all(slice::from_raw_parts(data, len)) {
Ok(_) => len as isize,
Err(_) => NGHTTP2_ERR_CALLBACK_FAILURE as isize,
}
}
}
unsafe extern "C" fn data_cb(
_: *mut nghttp2_session,
_: u8,
stream_id: i32,
data: *const u8,
len: usize,
user_data: *mut std::os::raw::c_void,
) -> i32 {
unsafe {
let ctx = &mut *(user_data as *mut Context);
if stream_id == ctx.stream_id {
ctx
.response
.body
.extend_from_slice(slice::from_raw_parts(data, len));
}
0
}
}
unsafe extern "C" fn frame_recv_cb(
_: *mut nghttp2_session,
frame: *const nghttp2_frame,
user_data: *mut std::os::raw::c_void,
) -> i32 {
unsafe {
let ctx = &mut *(user_data as *mut Context);
if (*frame).hd.stream_id == ctx.stream_id
&& ((*frame).hd.flags & NGHTTP2_FLAG_END_STREAM as u8) != 0
{
ctx.done = true;
}
0
}
}
unsafe extern "C" fn header_cb(
_: *mut nghttp2_session,
frame: *const nghttp2_frame,
name: *const u8,
namelen: usize,
value: *const u8,
valuelen: usize,
_: u8,
user_data: *mut std::os::raw::c_void,
) -> i32 {
unsafe {
let ctx = &mut *(user_data as *mut Context);
if (*frame).hd.stream_id == ctx.stream_id {
let name_str = to_str(name, namelen);
let value_str = to_str(value, valuelen);
if name_str == ":status" {
ctx.response.status = value_str.parse().unwrap_or(0);
}
ctx.response.headers.push((name_str, value_str));
}
0
}
}
unsafe extern "C" fn stream_close_cb(
_: *mut nghttp2_session,
stream_id: i32,
_: u32,
user_data: *mut std::os::raw::c_void,
) -> i32 {
unsafe {
let ctx = &mut *(user_data as *mut Context);
if stream_id == ctx.stream_id {
ctx.done = true;
}
0
}
}
fn main() -> Result<()> {
let request = Request::builder()
.authority("nghttp2.org")
.path("/")
.build()?;
let client = Client::connect("nghttp2.org")?;
let response = client.execute(request)?;
println!("Status: {}", response.status);
println!("\nHeaders:");
for (name, value) in
response.headers.iter().filter(|(n, _)| !n.starts_with(':'))
{
println!(" {}: {}", name, value);
}
println!("\nBody ({} bytes):", response.body.len());
if let Ok(body) = response.body_str() {
let preview = body.chars().take(500).collect::<String>();
println!("{}{}", preview, if body.len() > 500 { "..." } else { "" });
}
Ok(())
}