-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathe2e.rs
More file actions
234 lines (201 loc) · 8.04 KB
/
Copy pathe2e.rs
File metadata and controls
234 lines (201 loc) · 8.04 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
//! End-to-end integration tests.
//!
//! These spin up the server on a tempdir UDS and drive it from a
//! handcrafted client that uses `recvmsg`/`sendmsg` directly so we can
//! verify cmsg fd-passing semantics.
use std::io::{IoSlice, IoSliceMut};
use std::mem::MaybeUninit;
use std::os::fd::{AsRawFd, BorrowedFd, OwnedFd};
use std::os::unix::net::UnixStream as StdUnixStream;
use http::StatusCode;
use hyper_uds::{Builder, Request, Response, service_fn};
use rustix::net::{
RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, SendAncillaryBuffer,
SendAncillaryMessage, SendFlags,
};
/// Client helper: send a request (head + body + optional fds) over a
/// blocking std UnixStream using rustix sendmsg, then read until we
/// have a complete HTTP/1.1 response.
fn round_trip(
stream: &StdUnixStream,
request_bytes: &[u8],
send_fds: &[BorrowedFd<'_>],
) -> (Vec<u8>, Vec<OwnedFd>) {
// ---- send ----
let bufs = [IoSlice::new(request_bytes)];
if send_fds.is_empty() {
let mut empty_anc = SendAncillaryBuffer::new(&mut []);
rustix::net::sendmsg(stream, &bufs, &mut empty_anc, SendFlags::empty()).unwrap();
} else {
let mut space = [MaybeUninit::<u8>::uninit(); 256];
let mut anc = SendAncillaryBuffer::new(&mut space);
assert!(anc.push(SendAncillaryMessage::ScmRights(send_fds)));
rustix::net::sendmsg(stream, &bufs, &mut anc, SendFlags::empty()).unwrap();
}
// ---- recv until headers and body fully arrive ----
let mut all = Vec::new();
let mut recv_fds: Vec<OwnedFd> = Vec::new();
let mut content_length: Option<usize> = None;
let mut header_end: Option<usize> = None;
loop {
let mut chunk = [0u8; 4096];
let mut iov = [IoSliceMut::new(&mut chunk)];
let mut space = [MaybeUninit::<u8>::uninit(); 256];
let mut anc = RecvAncillaryBuffer::new(&mut space);
let ret = rustix::net::recvmsg(stream, &mut iov, &mut anc, RecvFlags::empty()).unwrap();
for msg in anc.drain() {
if let RecvAncillaryMessage::ScmRights(fds) = msg {
for fd in fds {
recv_fds.push(fd);
}
}
}
if ret.bytes == 0 {
break;
}
all.extend_from_slice(&chunk[..ret.bytes]);
if header_end.is_none()
&& let Some(pos) = find_double_crlf(&all)
{
header_end = Some(pos + 4);
// parse content-length
let head_str = std::str::from_utf8(&all[..pos]).unwrap();
for line in head_str.split("\r\n") {
if let Some(v) = line
.strip_prefix("content-length: ")
.or_else(|| line.strip_prefix("Content-Length: "))
{
content_length = Some(v.trim().parse().unwrap());
}
}
}
if let (Some(he), Some(cl)) = (header_end, content_length)
&& all.len() >= he + cl
{
break;
}
}
(all, recv_fds)
}
fn find_double_crlf(buf: &[u8]) -> Option<usize> {
buf.windows(4).position(|w| w == b"\r\n\r\n")
}
#[test]
fn echo_plain_http() {
let dir = tempfile::tempdir().unwrap();
let sock = dir.path().join("s.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
// Client side: blocking std UnixStream
let client = StdUnixStream::connect(&sock).unwrap();
let req = b"POST /echo HTTP/1.1\r\nhost: localhost\r\ncontent-length: 11\r\n\r\nhello world";
let handle = std::thread::spawn(move || round_trip(&client, req, &[]));
rt.block_on(async move {
listener.set_nonblocking(true).unwrap();
let listener = tokio::net::UnixListener::from_std(listener).unwrap();
let (stream, _) = listener.accept().await.unwrap();
let std_stream = stream.into_std().unwrap();
let svc = service_fn(|req: Request| async move {
assert_eq!(req.method(), &http::Method::POST);
assert_eq!(req.uri().path(), "/echo");
let body = req.into_body();
Ok::<_, std::convert::Infallible>(
Response::builder()
.status(StatusCode::OK)
.body(body)
.build(),
)
});
Builder::new()
.keep_alive(false)
.serve_connection(std_stream, svc)
.await
.unwrap();
});
let (resp_bytes, fds) = handle.join().unwrap();
assert!(fds.is_empty());
let resp = String::from_utf8(resp_bytes).unwrap();
assert!(resp.starts_with("HTTP/1.1 200"), "got: {resp}");
assert!(resp.contains("content-length: 11"));
assert!(resp.ends_with("hello world"));
}
#[test]
fn fd_passing_round_trip() {
let dir = tempfile::tempdir().unwrap();
let sock = dir.path().join("s.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
// Client: prepare an fd pointing at a temp file.
let payload_file = tempfile::NamedTempFile::new().unwrap();
std::fs::write(payload_file.path(), b"hello-from-fd").unwrap();
let payload = std::fs::File::open(payload_file.path()).unwrap();
let client = StdUnixStream::connect(&sock).unwrap();
let req = b"POST /open HTTP/1.1\r\nhost: localhost\r\ncontent-length: 0\r\nx-fd: input\r\n\r\n";
let payload_fd_raw = payload.as_raw_fd();
let handle = std::thread::spawn(move || {
let borrowed = unsafe { BorrowedFd::borrow_raw(payload_fd_raw) };
round_trip(&client, req, &[borrowed])
});
rt.block_on(async move {
listener.set_nonblocking(true).unwrap();
let listener = tokio::net::UnixListener::from_std(listener).unwrap();
let (stream, _) = listener.accept().await.unwrap();
let std_stream = stream.into_std().unwrap();
let svc = service_fn(|mut req: Request| async move {
// Verify we got the fd named "input"
assert_eq!(req.fd_names(), &["input".to_string()]);
assert_eq!(req.fds().len(), 1);
// Read the contents of the fd to confirm it's the
// file we expect.
let mut fds = req.take_fds();
let mut received = Vec::new();
use std::io::Read;
let owned: OwnedFd = fds.remove(0);
let mut f = std::fs::File::from(owned);
f.read_to_end(&mut received).unwrap();
assert_eq!(received, b"hello-from-fd");
// Echo back a *different* fd so we can verify direction
// works both ways.
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), b"server-reply").unwrap();
let f = std::fs::File::open(tmp.path()).unwrap();
let resp_fd: OwnedFd = f.into();
Ok::<_, std::convert::Infallible>(
Response::builder()
.status(StatusCode::OK)
.fd("reply", resp_fd)
.body(bytes::Bytes::from_static(b"ok"))
.build(),
)
});
Builder::new()
.keep_alive(false)
.serve_connection(std_stream, svc)
.await
.unwrap();
});
let (resp_bytes, fds) = handle.join().unwrap();
drop(payload);
assert_eq!(fds.len(), 1, "expected one returned fd");
let resp = String::from_utf8(resp_bytes).unwrap();
assert!(resp.contains("HTTP/1.1 200"), "got: {resp}");
assert!(
resp.to_ascii_lowercase().contains("x-fd: reply"),
"got: {resp}"
);
// Read content of the returned fd to confirm it's the server's
// reply file.
use std::io::Read;
let mut f = std::fs::File::from(fds.into_iter().next().unwrap());
let mut s = Vec::new();
f.read_to_end(&mut s).unwrap();
assert_eq!(s, b"server-reply");
}