1 // Copyright (C) 2018-2019, Cloudflare, Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright notice,
9 //       this list of conditions and the following disclaimer.
10 //
11 //     * Redistributions in binary form must reproduce the above copyright
12 //       notice, this list of conditions and the following disclaimer in the
13 //       documentation and/or other materials provided with the distribution.
14 //
15 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16 // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 
27 #[macro_use]
28 extern crate log;
29 
30 use std::net::ToSocketAddrs;
31 
32 use ring::rand::*;
33 
34 const MAX_DATAGRAM_SIZE: usize = 1350;
35 
36 const HTTP_REQ_STREAM_ID: u64 = 4;
37 
main()38 fn main() {
39     let mut buf = [0; 65535];
40     let mut out = [0; MAX_DATAGRAM_SIZE];
41 
42     let mut args = std::env::args();
43 
44     let cmd = &args.next().unwrap();
45 
46     if args.len() != 1 {
47         println!("Usage: {} URL", cmd);
48         println!("\nSee tools/apps/ for more complete implementations.");
49         return;
50     }
51 
52     let url = url::Url::parse(&args.next().unwrap()).unwrap();
53 
54     // Setup the event loop.
55     let poll = mio::Poll::new().unwrap();
56     let mut events = mio::Events::with_capacity(1024);
57 
58     // Resolve server address.
59     let peer_addr = url.to_socket_addrs().unwrap().next().unwrap();
60 
61     // Bind to INADDR_ANY or IN6ADDR_ANY depending on the IP family of the
62     // server address. This is needed on macOS and BSD variants that don't
63     // support binding to IN6ADDR_ANY for both v4 and v6.
64     let bind_addr = match peer_addr {
65         std::net::SocketAddr::V4(_) => "0.0.0.0:0",
66         std::net::SocketAddr::V6(_) => "[::]:0",
67     };
68 
69     // Create the UDP socket backing the QUIC connection, and register it with
70     // the event loop.
71     let socket = std::net::UdpSocket::bind(bind_addr).unwrap();
72     socket.connect(peer_addr).unwrap();
73 
74     let socket = mio::net::UdpSocket::from_socket(socket).unwrap();
75     poll.register(
76         &socket,
77         mio::Token(0),
78         mio::Ready::readable(),
79         mio::PollOpt::edge(),
80     )
81     .unwrap();
82 
83     // Create the configuration for the QUIC connection.
84     let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
85 
86     // *CAUTION*: this should not be set to `false` in production!!!
87     config.verify_peer(false);
88 
89     config
90         .set_application_protos(b"\x05hq-29\x05hq-28\x05hq-27\x08http/0.9")
91         .unwrap();
92 
93     config.set_max_idle_timeout(5000);
94     config.set_max_udp_payload_size(MAX_DATAGRAM_SIZE as u64);
95     config.set_initial_max_data(10_000_000);
96     config.set_initial_max_stream_data_bidi_local(1_000_000);
97     config.set_initial_max_stream_data_bidi_remote(1_000_000);
98     config.set_initial_max_streams_bidi(100);
99     config.set_initial_max_streams_uni(100);
100     config.set_disable_active_migration(true);
101 
102     // Generate a random source connection ID for the connection.
103     let mut scid = [0; quiche::MAX_CONN_ID_LEN];
104     SystemRandom::new().fill(&mut scid[..]).unwrap();
105 
106     // Create a QUIC connection and initiate handshake.
107     let mut conn = quiche::connect(url.domain(), &scid, &mut config).unwrap();
108 
109     info!(
110         "connecting to {:} from {:} with scid {}",
111         peer_addr,
112         socket.local_addr().unwrap(),
113         hex_dump(&scid)
114     );
115 
116     let write = conn.send(&mut out).expect("initial send failed");
117 
118     while let Err(e) = socket.send(&out[..write]) {
119         if e.kind() == std::io::ErrorKind::WouldBlock {
120             debug!("send() would block");
121             continue;
122         }
123 
124         panic!("send() failed: {:?}", e);
125     }
126 
127     debug!("written {}", write);
128 
129     let req_start = std::time::Instant::now();
130 
131     let mut req_sent = false;
132 
133     loop {
134         poll.poll(&mut events, conn.timeout()).unwrap();
135 
136         // Read incoming UDP packets from the socket and feed them to quiche,
137         // until there are no more packets to read.
138         'read: loop {
139             // If the event loop reported no events, it means that the timeout
140             // has expired, so handle it without attempting to read packets. We
141             // will then proceed with the send loop.
142             if events.is_empty() {
143                 debug!("timed out");
144 
145                 conn.on_timeout();
146                 break 'read;
147             }
148 
149             let len = match socket.recv(&mut buf) {
150                 Ok(v) => v,
151 
152                 Err(e) => {
153                     // There are no more UDP packets to read, so end the read
154                     // loop.
155                     if e.kind() == std::io::ErrorKind::WouldBlock {
156                         debug!("recv() would block");
157                         break 'read;
158                     }
159 
160                     panic!("recv() failed: {:?}", e);
161                 },
162             };
163 
164             debug!("got {} bytes", len);
165 
166             // Process potentially coalesced packets.
167             let read = match conn.recv(&mut buf[..len]) {
168                 Ok(v) => v,
169 
170                 Err(e) => {
171                     error!("recv failed: {:?}", e);
172                     continue 'read;
173                 },
174             };
175 
176             debug!("processed {} bytes", read);
177         }
178 
179         debug!("done reading");
180 
181         if conn.is_closed() {
182             info!("connection closed, {:?}", conn.stats());
183             break;
184         }
185 
186         // Send an HTTP request as soon as the connection is established.
187         if conn.is_established() && !req_sent {
188             info!("sending HTTP request for {}", url.path());
189 
190             let req = format!("GET {}\r\n", url.path());
191             conn.stream_send(HTTP_REQ_STREAM_ID, req.as_bytes(), true)
192                 .unwrap();
193 
194             req_sent = true;
195         }
196 
197         // Process all readable streams.
198         for s in conn.readable() {
199             while let Ok((read, fin)) = conn.stream_recv(s, &mut buf) {
200                 debug!("received {} bytes", read);
201 
202                 let stream_buf = &buf[..read];
203 
204                 debug!(
205                     "stream {} has {} bytes (fin? {})",
206                     s,
207                     stream_buf.len(),
208                     fin
209                 );
210 
211                 print!("{}", unsafe {
212                     std::str::from_utf8_unchecked(&stream_buf)
213                 });
214 
215                 // The server reported that it has no more data to send, which
216                 // we got the full response. Close the connection.
217                 if s == HTTP_REQ_STREAM_ID && fin {
218                     info!(
219                         "response received in {:?}, closing...",
220                         req_start.elapsed()
221                     );
222 
223                     conn.close(true, 0x00, b"kthxbye").unwrap();
224                 }
225             }
226         }
227 
228         // Generate outgoing QUIC packets and send them on the UDP socket, until
229         // quiche reports that there are no more packets to be sent.
230         loop {
231             let write = match conn.send(&mut out) {
232                 Ok(v) => v,
233 
234                 Err(quiche::Error::Done) => {
235                     debug!("done writing");
236                     break;
237                 },
238 
239                 Err(e) => {
240                     error!("send failed: {:?}", e);
241 
242                     conn.close(false, 0x1, b"fail").ok();
243                     break;
244                 },
245             };
246 
247             if let Err(e) = socket.send(&out[..write]) {
248                 if e.kind() == std::io::ErrorKind::WouldBlock {
249                     debug!("send() would block");
250                     break;
251                 }
252 
253                 panic!("send() failed: {:?}", e);
254             }
255 
256             debug!("written {}", write);
257         }
258 
259         if conn.is_closed() {
260             info!("connection closed, {:?}", conn.stats());
261             break;
262         }
263     }
264 }
265 
hex_dump(buf: &[u8]) -> String266 fn hex_dump(buf: &[u8]) -> String {
267     let vec: Vec<String> = buf.iter().map(|b| format!("{:02x}", b)).collect();
268 
269     vec.join("")
270 }
271