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
macro_rules! pub_request_impl {
    ($import:literal $($prefix:tt $suffix:tt)?) =>
{
    /// Borrows the inner `Request` as seen by Rocket.
    ///
    /// Note that no routing has occurred and that there is no remote
    /// address unless one has been explicitly set with
    /// [`set_remote()`](Request::set_remote()).
    ///
    /// # Example
    ///
    /// ```rust
    #[doc = $import]
    ///
    /// # Client::_test(|_, request, _| {
    /// let request: LocalRequest = request;
    /// let inner: &rocket::Request = request.inner();
    /// # });
    /// ```
    #[inline(always)]
    pub fn inner(&self) -> &Request<'c> {
        self._request()
    }

    /// Mutably borrows the inner `Request` as seen by Rocket.
    ///
    /// Note that no routing has occurred and that there is no remote
    /// address unless one has been explicitly set with
    /// [`set_remote()`](Request::set_remote()).
    ///
    /// # Example
    ///
    /// ```rust
    #[doc = $import]
    ///
    /// # Client::_test(|_, request, _| {
    /// let mut request: LocalRequest = request;
    /// let inner: &mut rocket::Request = request.inner_mut();
    /// # });
    /// ```
    #[inline(always)]
    pub fn inner_mut(&mut self) -> &mut Request<'c> {
        self._request_mut()
    }

    /// Add a header to this request.
    ///
    /// Any type that implements `Into<Header>` can be used here. Among
    /// others, this includes [`ContentType`] and [`Accept`].
    ///
    /// [`ContentType`]: crate::http::ContentType
    /// [`Accept`]: crate::http::Accept
    ///
    /// # Examples
    ///
    /// Add the Content-Type header:
    ///
    /// ```rust
    #[doc = $import]
    /// use rocket::http::Header;
    /// use rocket::http::ContentType;
    ///
    /// # Client::_test(|_, request, _| {
    /// let request: LocalRequest = request;
    /// let req = request
    ///     .header(ContentType::JSON)
    ///     .header(Header::new("X-Custom", "custom-value"));
    /// # });
    /// ```
    #[inline]
    pub fn header<H>(mut self, header: H) -> Self
        where H: Into<crate::http::Header<'static>>
    {
        self._request_mut().add_header(header.into());
        self
    }

    /// Adds a header to this request without consuming `self`.
    ///
    /// # Examples
    ///
    /// Add the Content-Type header:
    ///
    /// ```rust
    #[doc = $import]
    /// use rocket::http::ContentType;
    ///
    /// # Client::_test(|_, mut request, _| {
    /// let mut request: LocalRequest = request;
    /// request.add_header(ContentType::JSON);
    /// # });
    /// ```
    #[inline]
    pub fn add_header<H>(&mut self, header: H)
        where H: Into<crate::http::Header<'static>>
    {
        self._request_mut().add_header(header.into());
    }

    /// Set the remote address of this request to `address`.
    ///
    /// `address` may be any type that [can be converted into a `Endpoint`].
    /// If `address` fails to convert, the remote is left unchanged.
    ///
    /// [can be converted into a `Endpoint`]: crate::listener::Endpoint#conversions
    ///
    /// # Examples
    ///
    /// Set the remote address to "8.8.8.8:80":
    ///
    /// ```rust
    /// use std::net::Ipv4Addr;
    ///
    #[doc = $import]
    ///
    /// # Client::_test(|_, request, _| {
    /// let request: LocalRequest = request;
    /// let req = request.remote("tcp:8.8.8.8:80");
    ///
    /// let remote = req.inner().remote().unwrap().tcp().unwrap();
    /// assert_eq!(remote.ip(), Ipv4Addr::new(8, 8, 8, 8));
    /// assert_eq!(remote.port(), 80);
    /// # });
    /// ```
    #[inline]
    pub fn remote<T>(mut self, endpoint: T) -> Self
        where T: TryInto<crate::listener::Endpoint>
    {
        if let Ok(endpoint) = endpoint.try_into() {
            self.set_remote(endpoint);
        } else {
            warn!("remote failed to convert");
        }

        self
    }

    /// Add a cookie to this request.
    ///
    /// # Examples
    ///
    /// Add `user_id` cookie:
    ///
    /// ```rust
    #[doc = $import]
    /// use rocket::http::Cookie;
    ///
    /// # Client::_test(|_, request, _| {
    /// let request: LocalRequest = request;
    /// let req = request
    ///     .cookie(("username", "sb"))
    ///     .cookie(("user_id", "12"));
    /// # });
    /// ```
    #[inline]
    pub fn cookie<'a, C>(mut self, cookie: C) -> Self
        where C: Into<crate::http::Cookie<'a>>
    {
        self._request_mut().cookies_mut().add_original(cookie.into().into_owned());
        self
    }

    /// Add all of the cookies in `cookies` to this request.
    ///
    /// # Example
    ///
    /// ```rust
    #[doc = $import]
    /// use rocket::http::Cookie;
    ///
    /// # Client::_test(|_, request, _| {
    /// let request: LocalRequest = request;
    /// let cookies = vec![("a", "b"), ("c", "d")];
    /// let req = request.cookies(cookies);
    /// # });
    /// ```
    #[inline]
    pub fn cookies<'a, C, I>(mut self, cookies: I) -> Self
        where C: Into<crate::http::Cookie<'a>>,
              I: IntoIterator<Item = C>
    {
        for cookie in cookies {
            let cookie: crate::http::Cookie<'_> = cookie.into();
            self._request_mut().cookies_mut().add_original(cookie.into_owned());
        }

        self
    }

    /// Add a [private cookie] to this request.
    ///
    /// [private cookie]: crate::http::CookieJar::add_private()
    ///
    /// # Examples
    ///
    /// Add `user_id` as a private cookie:
    ///
    /// ```rust
    #[doc = $import]
    /// use rocket::http::Cookie;
    ///
    /// # Client::_test(|_, request, _| {
    /// let request: LocalRequest = request;
    /// let req = request.private_cookie(("user_id", "sb"));
    /// # });
    /// ```
    #[cfg(feature = "secrets")]
    #[cfg_attr(nightly, doc(cfg(feature = "secrets")))]
    #[inline]
    pub fn private_cookie<C>(mut self, cookie: C) -> Self
        where C: Into<crate::http::Cookie<'static>>
    {
        self._request_mut().cookies_mut().add_original_private(cookie.into());
        self
    }

    /// Set mTLS client certificates to send along with the request.
    ///
    /// If the request already contained certificates, they are replaced with
    /// those in `reader.`
    ///
    /// `reader` is expected to be PEM-formatted and contain X509 certificates.
    /// If it contains more than one certificate, the entire chain is set on the
    /// request. If it contains items other than certificates, the certificate
    /// chain up to the first non-certificate item is set on the request. If
    /// `reader` is syntactically invalid PEM, certificates are cleared on the
    /// request.
    ///
    /// The type `C` can be anything that implements [`std::io::Read`]. This
    /// includes: `&[u8]`, `File`, `&File`, `Stdin`, and so on. To read a file
    /// in at compile-time, use [`include_bytes!()`].
    ///
    /// ```rust
    /// use std::fs::File;
    ///
    #[doc = $import]
    /// use rocket::fs::relative;
    ///
    /// # Client::_test(|_, request, _| {
    /// let request: LocalRequest = request;
    /// let path = relative!("../../examples/tls/private/ed25519_cert.pem");
    /// let req = request.identity(File::open(path).unwrap());
    /// # });
    /// ```
    #[cfg(feature = "mtls")]
    #[cfg_attr(nightly, doc(cfg(feature = "mtls")))]
    pub fn identity<C: std::io::Read>(mut self, reader: C) -> Self {
        use std::sync::Arc;
        use crate::listener::Certificates;

        let mut reader = std::io::BufReader::new(reader);
        self._request_mut().connection.peer_certs = rustls_pemfile::certs(&mut reader)
            .collect::<Result<Vec<_>, _>>()
            .map(|certs| Arc::new(Certificates::from(certs)))
            .ok();

        self
    }

    /// Sets the body data of the request.
    ///core/lib/src/local/request.rs
    /// # Examples
    ///
    /// ```rust
    #[doc = $import]
    /// use rocket::http::ContentType;
    ///
    /// # Client::_test(|_, request, _| {
    /// let request: LocalRequest = request;
    /// let req = request
    ///     .header(ContentType::Text)
    ///     .body("Hello, world!");
    /// # });
    /// ```
    #[inline]
    pub fn body<S: AsRef<[u8]>>(mut self, body: S) -> Self {
        // TODO: For CGI, we want to be able to set the body to be stdin
        // without actually reading everything into a vector. Can we allow
        // that here while keeping the simplicity? Looks like it would
        // require us to reintroduce a NetStream::Local(Box<Read>) or
        // something like that.
        *self._body_mut() = body.as_ref().into();
        self
    }

    /// Sets the body to `value` serialized as JSON with `Content-Type`
    /// [`ContentType::JSON`](crate::http::ContentType::JSON).
    ///
    /// If `value` fails to serialize, the body is set to empty. The
    /// `Content-Type` header is _always_ set.
    ///
    /// # Examples
    ///
    /// ```rust
    #[doc = $import]
    /// use rocket::serde::Serialize;
    /// use rocket::http::ContentType;
    ///
    /// #[derive(Serialize)]
    /// struct Task {
    ///     id: usize,
    ///     complete: bool,
    /// }
    ///
    /// # Client::_test(|_, request, _| {
    /// let task = Task { id: 10, complete: false };
    ///
    /// let request: LocalRequest = request;
    /// let req = request.json(&task);
    /// assert_eq!(req.content_type(), Some(&ContentType::JSON));
    /// # });
    /// ```
    #[cfg(feature = "json")]
    #[cfg_attr(nightly, doc(cfg(feature = "json")))]
    pub fn json<T: crate::serde::Serialize>(self, value: &T) -> Self {
        let json = serde_json::to_vec(&value).unwrap_or_default();
        self.header(crate::http::ContentType::JSON).body(json)
    }

    /// Sets the body to `value` serialized as MessagePack with `Content-Type`
    /// [`ContentType::MsgPack`](crate::http::ContentType::MsgPack).
    ///
    /// If `value` fails to serialize, the body is set to empty. The
    /// `Content-Type` header is _always_ set.
    ///
    /// # Examples
    ///
    /// ```rust
    #[doc = $import]
    /// use rocket::serde::Serialize;
    /// use rocket::http::ContentType;
    ///
    /// #[derive(Serialize)]
    /// struct Task {
    ///     id: usize,
    ///     complete: bool,
    /// }
    ///
    /// # Client::_test(|_, request, _| {
    /// let task = Task { id: 10, complete: false };
    ///
    /// let request: LocalRequest = request;
    /// let req = request.msgpack(&task);
    /// assert_eq!(req.content_type(), Some(&ContentType::MsgPack));
    /// # });
    /// ```
    #[cfg(feature = "msgpack")]
    #[cfg_attr(nightly, doc(cfg(feature = "msgpack")))]
    pub fn msgpack<T: crate::serde::Serialize>(self, value: &T) -> Self {
        let msgpack = rmp_serde::to_vec(value).unwrap_or_default();
        self.header(crate::http::ContentType::MsgPack).body(msgpack)
    }

    /// Set the body (data) of the request without consuming `self`.
    ///
    /// # Examples
    ///
    /// Set the body to be a JSON structure; also sets the Content-Type.
    ///
    /// ```rust
    #[doc = $import]
    /// use rocket::http::ContentType;
    ///
    /// # Client::_test(|_, request, _| {
    /// let request: LocalRequest = request;
    /// let mut request = request.header(ContentType::JSON);
    /// request.set_body(r#"{ "key": "value", "array": [1, 2, 3] }"#);
    /// # });
    /// ```
    #[inline]
    pub fn set_body<S: AsRef<[u8]>>(&mut self, body: S) {
        *self._body_mut() = body.as_ref().into();
    }

    /// Dispatches the request, returning the response.
    ///
    /// This method consumes `self` and is the preferred mechanism for
    /// dispatching.
    ///
    /// # Example
    ///
    /// ```rust
    #[doc = $import]
    ///
    /// # Client::_test(|_, request, _| {
    /// let request: LocalRequest = request;
    /// let response = request.dispatch();
    /// # });
    /// ```
    #[inline(always)]
    pub $($prefix)? fn dispatch(self) -> LocalResponse<'c> {
        self._dispatch()$(.$suffix)?
    }

    #[cfg(test)]
    #[allow(dead_code)]
    fn _ensure_impls_exist() {
        fn is_clone_debug<T: Clone + std::fmt::Debug>() {}
        is_clone_debug::<Self>();

        fn is_deref_req<'a, T: std::ops::Deref<Target = Request<'a>>>() {}
        is_deref_req::<Self>();

        fn is_deref_mut_req<'a, T: std::ops::DerefMut<Target = Request<'a>>>() {}
        is_deref_mut_req::<Self>();
    }
}}