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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
use std::io::Read;
use std::sync::{Arc, Mutex};
use std::time;

use qstring::QString;
use url::{form_urlencoded, Url};

#[cfg(feature = "tls")]
use std::fmt;

#[cfg(all(feature = "native-tls", not(feature = "tls")))]
use std::fmt;

use crate::agent::{self, Agent, AgentState};
use crate::body::{Payload, SizedReader};
use crate::error::Error;
use crate::header::{self, Header};
use crate::pool;
use crate::unit::{self, Unit};
use crate::Response;

#[cfg(feature = "json")]
use super::SerdeValue;

/// Request instances are builders that creates a request.
///
/// ```
/// let mut request = ureq::get("https://www.google.com/");
///
/// let response = request
///     .query("foo", "bar baz") // add ?foo=bar%20baz
///     .call();                 // run the request
/// ```
#[derive(Clone, Default)]
pub struct Request {
    pub(crate) agent: Arc<Mutex<Option<AgentState>>>,

    // via agent
    pub(crate) method: String,
    url: String,

    // from request itself
    pub(crate) headers: Vec<Header>,
    pub(crate) query: QString,
    pub(crate) timeout_connect: u64,
    pub(crate) timeout_read: u64,
    pub(crate) timeout_write: u64,
    pub(crate) timeout: Option<time::Duration>,
    pub(crate) redirects: u32,
    pub(crate) proxy: Option<crate::proxy::Proxy>,
    #[cfg(feature = "tls")]
    pub(crate) tls_config: Option<TLSClientConfig>,
    #[cfg(all(feature = "native-tls", not(feature = "tls")))]
    pub(crate) tls_connector: Option<TLSConnector>,
}

impl ::std::fmt::Debug for Request {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error> {
        let (path, query) = self
            .to_url()
            .map(|u| {
                let query = unit::combine_query(&u, &self.query, true);
                (u.path().to_string(), query)
            })
            .unwrap_or_else(|_| ("BAD_URL".to_string(), "BAD_URL".to_string()));
        write!(
            f,
            "Request({} {}{}, {:?})",
            self.method, path, query, self.headers
        )
    }
}

impl Request {
    pub(crate) fn new(agent: &Agent, method: String, url: String) -> Request {
        Request {
            agent: Arc::clone(&agent.state),
            method,
            url,
            headers: agent.headers.clone(),
            redirects: 5,
            ..Default::default()
        }
    }

    /// "Builds" this request which is effectively the same as cloning.
    /// This is needed when we use a chain of request builders, but
    /// don't want to send the request at the end of the chain.
    ///
    /// ```
    /// let r = ureq::get("/my_page")
    ///     .set("X-Foo-Bar", "Baz")
    ///     .build();
    /// ```
    pub fn build(&self) -> Request {
        self.clone()
    }

    /// Executes the request and blocks the caller until done.
    ///
    /// Use `.timeout_connect()` and `.timeout_read()` to avoid blocking forever.
    ///
    /// ```
    /// let r = ureq::get("/my_page")
    ///     .timeout_connect(10_000) // max 10 seconds
    ///     .call();
    ///
    /// println!("{:?}", r);
    /// ```
    pub fn call(&mut self) -> Response {
        self.do_call(Payload::Empty)
    }

    fn do_call(&mut self, payload: Payload) -> Response {
        self.to_url()
            .and_then(|url| {
                let reader = payload.into_read();
                let unit = Unit::new(&self, &url, true, &reader);
                unit::connect(&self, unit, true, 0, reader, false)
            })
            .unwrap_or_else(|e| e.into())
    }

    /// Send data a json value.
    ///
    /// Requires feature `ureq = { version = "*", features = ["json"] }`
    ///
    /// The `Content-Length` header is implicitly set to the length of the serialized value.
    ///
    /// ```
    /// #[macro_use]
    /// extern crate ureq;
    ///
    /// fn main() {
    /// let r = ureq::post("/my_page")
    ///     .send_json(json!({ "name": "martin", "rust": true }));
    /// println!("{:?}", r);
    /// }
    /// ```
    #[cfg(feature = "json")]
    pub fn send_json(&mut self, data: SerdeValue) -> Response {
        if self.header("Content-Type").is_none() {
            self.set("Content-Type", "application/json");
        }
        self.do_call(Payload::JSON(data))
    }

    /// Send data as bytes.
    ///
    /// The `Content-Length` header is implicitly set to the length of the serialized value.
    ///
    /// ```
    /// let body = b"Hello world!";
    /// let r = ureq::post("/my_page")
    ///     .send_bytes(body);
    /// println!("{:?}", r);
    /// ```
    pub fn send_bytes(&mut self, data: &[u8]) -> Response {
        self.do_call(Payload::Bytes(data.to_owned()))
    }

    /// Send data as a string.
    ///
    /// The `Content-Length` header is implicitly set to the length of the serialized value.
    /// Defaults to `utf-8`
    ///
    /// ## Charset support
    ///
    /// Requires feature `ureq = { version = "*", features = ["charset"] }`
    ///
    /// If a `Content-Type` header is present and it contains a charset specification, we
    /// attempt to encode the string using that character set. If it fails, we fall back
    /// on utf-8.
    ///
    /// ```
    /// // this example requires features = ["charset"]
    ///
    /// let r = ureq::post("/my_page")
    ///     .set("Content-Type", "text/plain; charset=iso-8859-1")
    ///     .send_string("Hällo Wörld!");
    /// println!("{:?}", r);
    /// ```
    pub fn send_string(&mut self, data: &str) -> Response {
        let text = data.into();
        let charset =
            crate::response::charset_from_content_type(self.header("content-type")).to_string();
        self.do_call(Payload::Text(text, charset))
    }

    /// Send a sequence of (key, value) pairs as form-urlencoded data.
    ///
    /// The `Content-Type` header is implicitly set to application/x-www-form-urlencoded.
    /// The `Content-Length` header is implicitly set to the length of the serialized value.
    ///
    /// ```
    /// #[macro_use]
    /// extern crate ureq;
    ///
    /// fn main() {
    /// let r = ureq::post("/my_page")
    ///     .send_form(&[("foo", "bar"),("foo2", "bar2")]);
    /// println!("{:?}", r);
    /// }
    /// ```
    pub fn send_form(&mut self, data: &[(&str, &str)]) -> Response {
        if self.header("Content-Type").is_none() {
            self.set("Content-Type", "application/x-www-form-urlencoded");
        }
        let encoded = form_urlencoded::Serializer::new(String::new())
            .extend_pairs(data)
            .finish();
        self.do_call(Payload::Bytes(encoded.into_bytes()))
    }

    /// Send data from a reader.
    ///
    /// This uses [chunked transfer encoding](https://tools.ietf.org/html/rfc7230#section-4.1).
    /// The caller is responsible for setting the Transfer-Encoding: chunked header.
    ///
    /// The input from the reader is buffered into chunks of size 16,384, the max size of a TLS fragment.
    ///
    /// ```
    /// use std::io::Cursor;
    ///
    /// let read = Cursor::new(vec![0x20; 100_000]);
    ///
    /// let resp = ureq::post("http://localhost/example-upload")
    ///     .set("Content-Type", "text/plain")
    ///     .set("Transfer-Encoding", "chunked")
    ///     .send(read);
    /// ```
    pub fn send(&mut self, reader: impl Read + 'static) -> Response {
        self.do_call(Payload::Reader(Box::new(reader)))
    }

    /// Set a header field.
    ///
    /// ```
    /// let r = ureq::get("/my_page")
    ///     .set("X-API-Key", "foobar")
    ///     .set("Accept", "text/plain")
    ///     .call();
    ///
    ///  if r.ok() {
    ///      println!("yay got {}", r.into_string().unwrap());
    ///  } else {
    ///      println!("Oh no error!");
    ///  }
    /// ```
    pub fn set(&mut self, header: &str, value: &str) -> &mut Request {
        header::add_header(&mut self.headers, Header::new(header, value));
        self
    }

    /// Returns the value for a set header.
    ///
    /// ```
    /// let req = ureq::get("/my_page")
    ///     .set("X-API-Key", "foobar")
    ///     .build();
    /// assert_eq!("foobar", req.header("x-api-Key").unwrap());
    /// ```
    pub fn header(&self, name: &str) -> Option<&str> {
        header::get_header(&self.headers, name)
    }

    /// A list of the set header names in this request. Lowercased to be uniform.
    ///
    /// ```
    /// let req = ureq::get("/my_page")
    ///     .set("X-API-Key", "foobar")
    ///     .set("Content-Type", "application/json")
    ///     .build();
    /// assert_eq!(req.header_names(), vec!["x-api-key", "content-type"]);
    /// ```
    pub fn header_names(&self) -> Vec<String> {
        self.headers
            .iter()
            .map(|h| h.name().to_ascii_lowercase())
            .collect()
    }

    /// Tells if the header has been set.
    ///
    /// ```
    /// let req = ureq::get("/my_page")
    ///     .set("X-API-Key", "foobar")
    ///     .build();
    /// assert_eq!(true, req.has("x-api-Key"));
    /// ```
    pub fn has(&self, name: &str) -> bool {
        header::has_header(&self.headers, name)
    }

    /// All headers corresponding values for the give name, or empty vector.
    ///
    /// ```
    /// let req = ureq::get("/my_page")
    ///     .set("X-Forwarded-For", "1.2.3.4")
    ///     .set("X-Forwarded-For", "2.3.4.5")
    ///     .build();
    /// assert_eq!(req.all("x-forwarded-for"), vec![
    ///     "1.2.3.4",
    ///     "2.3.4.5",
    /// ]);
    /// ```
    pub fn all(&self, name: &str) -> Vec<&str> {
        header::get_all_headers(&self.headers, name)
    }

    /// Set a query parameter.
    ///
    /// For example, to set `?format=json&dest=/login`
    ///
    /// ```
    /// let r = ureq::get("/my_page")
    ///     .query("format", "json")
    ///     .query("dest", "/login")
    ///     .call();
    ///
    /// println!("{:?}", r);
    /// ```
    pub fn query(&mut self, param: &str, value: &str) -> &mut Request {
        self.query.add_pair((param, value));
        self
    }

    /// Set query parameters as a string.
    ///
    /// For example, to set `?format=json&dest=/login`
    ///
    /// ```
    /// let r = ureq::get("/my_page")
    ///     .query_str("?format=json&dest=/login")
    ///     .call();
    /// println!("{:?}", r);
    /// ```
    pub fn query_str(&mut self, query: &str) -> &mut Request {
        self.query.add_str(query);
        self
    }

    /// Timeout for the socket connection to be successful.
    /// If both this and .timeout() are both set, .timeout_connect()
    /// takes precedence.
    ///
    /// The default is `0`, which means a request can block forever.
    ///
    /// ```
    /// let r = ureq::get("/my_page")
    ///     .timeout_connect(1_000) // wait max 1 second to connect
    ///     .call();
    /// println!("{:?}", r);
    /// ```
    pub fn timeout_connect(&mut self, millis: u64) -> &mut Request {
        self.timeout_connect = millis;
        self
    }

    /// Timeout for the individual reads of the socket.
    /// If both this and .timeout() are both set, .timeout()
    /// takes precedence.
    ///
    /// The default is `0`, which means it can block forever.
    ///
    /// ```
    /// let r = ureq::get("/my_page")
    ///     .timeout_read(1_000) // wait max 1 second for the read
    ///     .call();
    /// println!("{:?}", r);
    /// ```
    pub fn timeout_read(&mut self, millis: u64) -> &mut Request {
        self.timeout_read = millis;
        self
    }

    /// Timeout for the individual writes to the socket.
    /// If both this and .timeout() are both set, .timeout()
    /// takes precedence.
    ///
    /// The default is `0`, which means it can block forever.
    ///
    /// ```
    /// let r = ureq::get("/my_page")
    ///     .timeout_write(1_000)   // wait max 1 second for sending.
    ///     .call();
    /// println!("{:?}", r);
    /// ```
    pub fn timeout_write(&mut self, millis: u64) -> &mut Request {
        self.timeout_write = millis;
        self
    }

    /// Timeout for the overall request, including DNS resolution, connection
    /// time, redirects, and reading the response body. Slow DNS resolution
    /// may cause a request to exceed the timeout, because the DNS request
    /// cannot be interrupted with the available APIs.
    ///
    /// This takes precedence over .timeout_read() and .timeout_write(), but
    /// not .timeout_connect().
    ///
    /// ```
    /// // wait max 1 second for whole request to complete.
    /// let r = ureq::get("/my_page")
    ///     .timeout(std::time::Duration::from_secs(1))
    ///     .call();
    /// println!("{:?}", r);
    /// ```
    pub fn timeout(&mut self, timeout: time::Duration) -> &mut Request {
        self.timeout = Some(timeout);
        self
    }

    /// Basic auth.
    ///
    /// These are the same
    ///
    /// ```
    /// let r1 = ureq::get("http://localhost/my_page")
    ///     .auth("martin", "rubbermashgum")
    ///     .call();
    ///  println!("{:?}", r1);
    ///
    /// let r2 = ureq::get("http://martin:rubbermashgum@localhost/my_page").call();
    /// println!("{:?}", r2);
    /// ```
    pub fn auth(&mut self, user: &str, pass: &str) -> &mut Request {
        let pass = agent::basic_auth(user, pass);
        self.auth_kind("Basic", &pass)
    }

    /// Auth of other kinds such as `Digest`, `Token` etc.
    ///
    /// ```
    /// let r = ureq::get("http://localhost/my_page")
    ///     .auth_kind("token", "secret")
    ///     .call();
    /// println!("{:?}", r);
    /// ```
    pub fn auth_kind(&mut self, kind: &str, pass: &str) -> &mut Request {
        let value = format!("{} {}", kind, pass);
        self.set("Authorization", &value);
        self
    }

    /// How many redirects to follow.
    ///
    /// Defaults to `5`. Set to `0` to avoid redirects and instead
    /// get a response object with the 3xx status code.
    ///
    /// If the redirect count hits this limit (and it's > 0), a synthetic 500 error
    /// response is produced.
    ///
    /// ```
    /// let r = ureq::get("/my_page")
    ///     .redirects(10)
    ///     .call();
    /// println!("{:?}", r);
    /// ```
    pub fn redirects(&mut self, n: u32) -> &mut Request {
        self.redirects = n;
        self
    }

    // pub fn retry(&self, times: u16) -> Request {
    //     unimplemented!()
    // }
    // pub fn sortQuery(&self) -> Request {
    //     unimplemented!()
    // }
    // pub fn sortQueryBy(&self, by: Box<Fn(&str, &str) -> usize>) -> Request {
    //     unimplemented!()
    // }
    // pub fn ca<S>(&self, accept: S) -> Request
    //     where S: Into<String> {
    //     unimplemented!()
    // }
    // pub fn cert<S>(&self, accept: S) -> Request
    //     where S: Into<String> {
    //     unimplemented!()
    // }
    // pub fn key<S>(&self, accept: S) -> Request
    //     where S: Into<String> {
    //     unimplemented!()
    // }
    // pub fn pfx<S>(&self, accept: S) -> Request // TODO what type? u8?
    //     where S: Into<String> {
    //     unimplemented!()
    // }

    /// Get the method this request is using.
    ///
    /// Example:
    /// ```
    /// let req = ureq::post("/somewhere")
    ///     .build();
    /// assert_eq!(req.get_method(), "POST");
    /// ```
    pub fn get_method(&self) -> &str {
        &self.method
    }

    /// Get the url this request was created with.
    ///
    /// This value is not normalized, it is exactly as set.
    /// It does not contain any added query parameters.
    ///
    /// Example:
    /// ```
    /// let req = ureq::post("https://cool.server/innit")
    ///     .build();
    /// assert_eq!(req.get_url(), "https://cool.server/innit");
    /// ```
    pub fn get_url(&self) -> &str {
        &self.url
    }

    /// Normalizes and returns the host that will be used for this request.
    ///
    /// Example:
    /// ```
    /// let req1 = ureq::post("https://cool.server/innit")
    ///     .build();
    /// assert_eq!(req1.get_host().unwrap(), "cool.server");
    ///
    /// let req2 = ureq::post("http://localhost/some/path")
    ///     .build();
    /// assert_eq!(req2.get_host().unwrap(), "localhost");
    /// ```
    pub fn get_host(&self) -> Result<String, Error> {
        self.to_url()
            .map(|u| u.host_str().unwrap_or(pool::DEFAULT_HOST).to_string())
    }

    /// Returns the scheme for this request.
    ///
    /// Example:
    /// ```
    /// let req = ureq::post("https://cool.server/innit")
    ///     .build();
    /// assert_eq!(req.get_scheme().unwrap(), "https");
    /// ```
    pub fn get_scheme(&self) -> Result<String, Error> {
        self.to_url().map(|u| u.scheme().to_string())
    }

    /// The complete query for this request.
    ///
    /// Example:
    /// ```
    /// let req = ureq::post("https://cool.server/innit?foo=bar")
    ///     .query("format", "json")
    ///     .build();
    /// assert_eq!(req.get_query().unwrap(), "?foo=bar&format=json");
    /// ```
    pub fn get_query(&self) -> Result<String, Error> {
        self.to_url()
            .map(|u| unit::combine_query(&u, &self.query, true))
    }

    /// The normalized url of this request.
    ///
    /// Example:
    /// ```
    /// let req = ureq::post("https://cool.server/innit")
    ///     .build();
    /// assert_eq!(req.get_path().unwrap(), "/innit");
    /// ```
    pub fn get_path(&self) -> Result<String, Error> {
        self.to_url().map(|u| u.path().to_string())
    }

    fn to_url(&self) -> Result<Url, Error> {
        Url::parse(&self.url).map_err(|e| Error::BadUrl(format!("{}", e)))
    }

    /// Set the proxy server to use for the connection.
    ///
    /// Example:
    /// ```
    /// let proxy = ureq::Proxy::new("user:password@cool.proxy:9090").unwrap();
    /// let req = ureq::post("https://cool.server")
    ///     .set_proxy(proxy)
    ///     .build();
    /// ```
    pub fn set_proxy(&mut self, proxy: crate::proxy::Proxy) -> &mut Request {
        self.proxy = Some(proxy);
        self
    }

    /// Set the TLS client config to use for the connection.
    ///
    /// See [`ClientConfig`](https://docs.rs/rustls/latest/rustls/struct.ClientConfig.html).
    ///
    /// Example:
    /// ```
    /// let tls_config = std::sync::Arc::new(rustls::ClientConfig::new());
    /// let req = ureq::post("https://cool.server")
    ///     .set_tls_config(tls_config.clone());
    /// ```
    #[cfg(feature = "tls")]
    pub fn set_tls_config(&mut self, tls_config: Arc<rustls::ClientConfig>) -> &mut Request {
        self.tls_config = Some(TLSClientConfig(tls_config));
        self
    }

    /// Sets the TLS connector that will be used for the connection.
    ///
    /// Example:
    /// ```
    /// let tls_connector = std::sync::Arc::new(native_tls::TlsConnector::new());
    /// let req = ureq::post("https://cool.server")
    ///     .set_tls_connector(tls_connector.clone());
    /// ```
    #[cfg(all(feature = "native-tls", not(feature = "tls")))]
    pub fn set_tls_connector(
        &mut self,
        tls_connector: Arc<native_tls::TlsConnector>,
    ) -> &mut Request {
        self.tls_connector = Some(TLSConnector(tls_connector));
        self
    }

    // Returns true if this request, with the provided body, is retryable.
    pub(crate) fn is_retryable(&self, body: &SizedReader) -> bool {
        // Per https://tools.ietf.org/html/rfc7231#section-8.1.3
        // these methods are idempotent.
        let idempotent = match self.method.as_str() {
            "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PUT" | "TRACE" => true,
            _ => false,
        };
        // Unsized bodies aren't retryable because we can't rewind the reader.
        // Sized bodies are retryable only if they are zero-length because of
        // coincidences of the current implementation - the function responsible
        // for retries doesn't have a way to replay a Payload.
        let no_body = body.size.is_none() || body.size.unwrap() > 0;
        idempotent && no_body
    }
}

#[cfg(feature = "tls")]
#[derive(Clone)]
pub(crate) struct TLSClientConfig(pub(crate) Arc<rustls::ClientConfig>);

#[cfg(feature = "tls")]
impl fmt::Debug for TLSClientConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TLSClientConfig").finish()
    }
}

#[cfg(all(feature = "native-tls", not(feature = "tls")))]
#[derive(Clone)]
pub(crate) struct TLSConnector(pub(crate) Arc<native_tls::TlsConnector>);

#[cfg(all(feature = "native-tls", not(feature = "tls")))]
impl fmt::Debug for TLSConnector {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TLSConnector").finish()
    }
}