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 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
pub use fastly_shared::{CacheOverride, ClientCertVerifyResult, FramingHeadersMode};
use fastly_sys::fastly_http_req::SendErrorDetail;
pub use fastly_sys::ContentEncodings;
use super::pending::handle::PendingRequestHandle;
use crate::abi::{self, FastlyStatus, MultiValueHostcallError};
use crate::error::{BufferSizeError, HandleError, HandleKind};
use crate::handle::{BodyHandle, ResponseHandle, StreamingBodyHandle};
use crate::http::request::SendErrorCause;
use bytes::{BufMut, BytesMut};
use http::header::{HeaderName, HeaderValue};
use http::{Method, Version};
use lazy_static::lazy_static;
use std::mem::ManuallyDrop;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::atomic::{AtomicBool, Ordering};
use url::Url;
// This import is just to get `Request` into scope for intradoc linking.
#[allow(unused)]
use super::Request;
/// The low-level interface to HTTP requests.
///
/// For most applications, you should use [`Request`] instead of this
/// interface. See the top-level [`handle`][`crate::handle`] documentation for more details.
///
/// # Getting the client request
///
/// Call [`RequestHandle::from_client()`] to get the client request being handled by this execution
/// of the Compute program.
///
/// # Creation and conversion
///
/// New requests can be created programmatically with [`RequestHandle::new()`]. In addition, you can
/// convert to and from [`Request`] using [`Request::from_handles()`] and
/// [`Request::into_handles()`].
///
/// # Sending backend requests
///
/// Requests can be sent to a backend in blocking or asynchronous fashion using
/// [`send()`][`Self::send()`], [`send_async()`][`Self::send_async()`], or
/// [`send_async_streaming()`][`Self::send_async_streaming()`].
#[derive(Debug, Eq, Hash, PartialEq)]
#[repr(transparent)]
pub struct RequestHandle {
handle: u32,
}
/// A flag representing whether or not the request has been taken from the client.
pub(crate) static GOT_CLIENT_REQ: AtomicBool = AtomicBool::new(false);
impl RequestHandle {
/// An invalid handle.
///
/// This is primarily useful to represent uninitialized values when using the interfaces in
/// [`fastly_sys`].
pub const INVALID: Self = RequestHandle {
handle: fastly_shared::INVALID_REQUEST_HANDLE,
};
/// Returns `true` if the request handle is valid.
pub const fn is_valid(&self) -> bool {
!self.is_invalid()
}
/// Returns `true` if the request handle is invalid.
pub const fn is_invalid(&self) -> bool {
self.handle == fastly_shared::INVALID_REQUEST_HANDLE
}
/// Get the underlying representation of the handle.
///
/// This should only be used when calling the raw ABI directly, and care should be taken not to
/// reuse or alias handle values.
pub fn as_u32(&self) -> u32 {
self.handle
}
/// Get a mutable reference to the underlying `u32` representation of the handle.
///
/// This should only be used when calling the raw ABI directly, and care should be taken not to
/// reuse or alias handle values.
pub fn as_u32_mut(&mut self) -> &mut u32 {
&mut self.handle
}
/// Turn a handle into its representation without closing the underlying resource.
///
/// This should only be used when calling the raw ABI directly, and care should be taken not to
/// reuse or alias handle values.
pub fn into_u32(self) -> u32 {
ManuallyDrop::new(self).as_u32()
}
/// Set `GOT_CLIENT_REQ` flag to show we've taken the client request.
///
/// This will panic if the flag has already been set by someone else.
pub(crate) fn set_got_client() {
if GOT_CLIENT_REQ.swap(true, Ordering::SeqCst) {
panic!("cannot get more than one handle to the client request per execution",);
}
}
/// Get a handle to the client request being handled by this execution of the Compute program.
///
/// # Panics
///
/// This method panics if the client request has already been retrieved by this method,
/// [`client_request_and_body()`], or [`Request::from_client()`].
pub fn from_client() -> Self {
Self::set_got_client();
let mut handle = RequestHandle::INVALID;
let status = unsafe {
abi::fastly_http_req::body_downstream_get(handle.as_u32_mut(), std::ptr::null_mut())
};
match status.result().map(|_| handle) {
Ok(h) if h.is_valid() => h,
_ => panic!("fastly_http_req::body_downstream_get failed"),
}
}
/// Acquire a new request handle.
///
/// By default, the request will have a `GET` method, a URL of `/`, and empty headers.
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
let mut handle = RequestHandle::INVALID;
let status = unsafe { abi::fastly_http_req::new(handle.as_u32_mut()) };
match status.result().map(|_| handle) {
Ok(h) if h.is_valid() => h,
_ => panic!("fastly_http_req::new failed"),
}
}
/// Read the request's header names via a buffer of the provided size.
///
/// If there is a header name that is longer than `buf_size`, this will return a
/// [`BufferSizeError`]; you can retry with a larger buffer size if necessary.
pub fn get_header_names<'a>(
&'a self,
buf_size: usize,
) -> impl Iterator<Item = Result<HeaderName, BufferSizeError>> + 'a {
self.get_header_names_impl(buf_size, Some(buf_size))
}
pub(crate) fn get_header_names_impl<'a>(
&'a self,
mut initial_buf_size: usize,
max_buf_size: Option<usize>,
) -> impl Iterator<Item = Result<HeaderName, BufferSizeError>> + 'a {
if let Some(max) = max_buf_size {
initial_buf_size = std::cmp::min(initial_buf_size, max);
}
abi::MultiValueHostcall::new(
b'\0',
initial_buf_size,
max_buf_size,
move |buf, buf_size, cursor, ending_cursor, nwritten| unsafe {
abi::fastly_http_req::header_names_get(
self.as_u32(),
buf,
buf_size,
cursor,
ending_cursor,
nwritten,
)
},
)
.map(move |res| {
use MultiValueHostcallError::{BufferTooSmall, ClosureError};
match res {
// we trust that the hostcall is giving us valid header bytes
Ok(name_bytes) => Ok(HeaderName::from_bytes(&name_bytes).unwrap()),
// return an error if the buffer was not large enough
Err(BufferTooSmall { needed_buf_size }) => Err(BufferSizeError::header_name(
max_buf_size
.expect("maximum buffer size must exist if a buffer size error occurs"),
needed_buf_size,
)),
// panic if the hostcall failed for some other reason
Err(ClosureError(e)) => {
panic!("fastly_http_req::header_names_get returned error: {:?}", e)
}
}
})
}
/// Get the header values for the given name via a buffer of the provided size.
///
/// If there is a header value that is longer than the buffer, this will return a
/// [`BufferSizeError`]; you can retry with a larger buffer size if necessary.
///
/// # Examples
///
/// Collect all the header values into a [`Vec`]:
///
/// ```no_run
/// # use fastly::error::Error;
/// # use fastly::handle::RequestHandle;
/// # use http::header::{HeaderName, HeaderValue};
/// #
/// # fn main() -> Result<(), Error> {
/// # let request = RequestHandle::new();
/// let name = HeaderName::from_static("My-App-Header");
/// let buf_size = 128;
/// let header_values: Vec<HeaderValue> = request
/// .get_header_values(&name, buf_size)
/// .collect::<Result<Vec<HeaderValue>, _>>()?;
/// # Ok(())
/// # }
/// ```
///
/// To try again with a larger buffer if the first call fails, you can use
/// [`unwrap_or_else()`][`Result::unwrap_or_else()`]:
///
/// ```no_run
/// # use fastly::error::BufferSizeError;
/// # use fastly::handle::RequestHandle;
/// # use http::header::{HeaderName, HeaderValue};
/// # let request = RequestHandle::new();
/// let name = HeaderName::from_static("My-App-Header");
/// let buf_size = 128;
///
/// // Collect header values into a `Vec<HeaderValue>`, with a buffer size of `128`.
/// // If the first call fails, print our error and then try to collect header values
/// // again. The second call will use a larger buffer size of `1024`.
/// let header_values: Vec<HeaderValue> = request
/// .get_header_values(&name, buf_size)
/// .collect::<Result<_, _>>()
/// .unwrap_or_else(|err: BufferSizeError| {
/// let larger_buf_size = 1024;
/// request
/// .get_header_values(&name, larger_buf_size)
/// .collect::<Result<_, _>>()
/// .unwrap()
/// });
/// ```
pub fn get_header_values<'a>(
&'a self,
name: &'a HeaderName,
buf_size: usize,
) -> impl Iterator<Item = Result<HeaderValue, BufferSizeError>> + 'a {
self.get_header_values_impl(name, buf_size, Some(buf_size))
}
pub(crate) fn get_header_values_impl<'a>(
&'a self,
name: &'a HeaderName,
mut initial_buf_size: usize,
max_buf_size: Option<usize>,
) -> impl Iterator<Item = Result<HeaderValue, BufferSizeError>> + 'a {
if let Some(max) = max_buf_size {
initial_buf_size = std::cmp::min(initial_buf_size, max);
}
abi::MultiValueHostcall::new(
b'\0',
initial_buf_size,
max_buf_size,
move |buf, buf_size, cursor, ending_cursor, nwritten| unsafe {
let name: &[u8] = name.as_ref();
abi::fastly_http_req::header_values_get(
self.as_u32(),
name.as_ptr(),
name.len(),
buf,
buf_size,
cursor,
ending_cursor,
nwritten,
)
},
)
.map(move |res| {
use MultiValueHostcallError::{BufferTooSmall, ClosureError};
match res {
// we trust that the hostcall is giving us valid header bytes
Ok(value_bytes) => {
let header_value =
unsafe { HeaderValue::from_maybe_shared_unchecked(value_bytes) };
Ok(header_value)
}
// return an error if the buffer was not large enough
Err(BufferTooSmall { needed_buf_size }) => Err(BufferSizeError::header_value(
max_buf_size
.expect("maximum buffer size must exist if a buffer size error occurs"),
needed_buf_size,
)),
// panic if the hostcall failed for some other reason
Err(ClosureError(e)) => {
panic!("fastly_http_req::header_values_get returned error: {:?}", e)
}
}
})
}
/// Set the values for the given header name, replacing any headers that previously existed for
/// that name.
pub fn set_header_values<'a, I>(&mut self, name: &HeaderName, values: I)
where
I: IntoIterator<Item = &'a HeaderValue>,
{
// build a buffer of all the values, each terminated by a nul byte
let mut buf = vec![];
for value in values {
buf.put(value.as_bytes());
buf.put_u8(b'\0');
}
let name: &[u8] = name.as_ref();
unsafe {
abi::fastly_http_req::header_values_set(
self.as_u32(),
name.as_ptr(),
name.len(),
buf.as_ptr(),
buf.len(),
)
}
.result()
.expect("fastly_http_req::header_values_set failed");
}
#[doc = include_str!("../../../docs/snippets/handle-get-header-value.md")]
pub fn get_header_value(
&self,
name: &HeaderName,
max_len: usize,
) -> Result<Option<HeaderValue>, BufferSizeError> {
let name: &[u8] = name.as_ref();
let mut buf = BytesMut::with_capacity(max_len);
let mut nwritten = 0;
let status = unsafe {
abi::fastly_http_req::header_value_get(
self.as_u32(),
name.as_ptr(),
name.len(),
buf.as_mut_ptr(),
buf.capacity(),
&mut nwritten,
)
};
match status.result().map(|_| nwritten) {
Ok(nwritten) => {
assert!(nwritten <= buf.capacity(), "hostcall wrote too many bytes");
unsafe {
buf.set_len(nwritten);
}
// we trust that the hostcall is giving us valid header bytes
let value = HeaderValue::from_bytes(&buf).expect("bytes from host are valid");
Ok(Some(value))
}
Err(FastlyStatus::INVAL) => Ok(None),
Err(FastlyStatus::BUFLEN) => Err(BufferSizeError::header_value(max_len, nwritten)),
_ => panic!("fastly_http_req::header_value_get returned error"),
}
}
/// Set a request header to the given value, discarding any previous values for the given header
/// name.
pub fn insert_header(&mut self, name: &HeaderName, value: &HeaderValue) {
let name_bytes: &[u8] = name.as_ref();
let value_bytes: &[u8] = value.as_ref();
let status = unsafe {
abi::fastly_http_req::header_insert(
self.as_u32(),
name_bytes.as_ptr(),
name_bytes.len(),
value_bytes.as_ptr(),
value_bytes.len(),
)
};
if status.is_err() {
panic!("fastly_http_req::header_insert returned error");
}
}
/// Add a request header with given value.
///
/// Unlike [`insert_header()`][`Self::insert_header()`], this does not discard existing values
/// for the same header name.
pub fn append_header(&mut self, name: &HeaderName, value: &HeaderValue) {
let name_bytes: &[u8] = name.as_ref();
let value_bytes: &[u8] = value.as_ref();
unsafe {
abi::fastly_http_req::header_append(
self.as_u32(),
name_bytes.as_ptr(),
name_bytes.len(),
value_bytes.as_ptr(),
value_bytes.len(),
)
}
.result()
.expect("fastly_http_req::header_append returned error");
}
/// Remove all request headers of the given name, and return whether any headers were removed.
pub fn remove_header(&mut self, name: &HeaderName) -> bool {
let name_bytes: &[u8] = name.as_ref();
let status = unsafe {
abi::fastly_http_req::header_remove(
self.as_u32(),
name_bytes.as_ptr(),
name_bytes.len(),
)
};
match status.result() {
Ok(_) => true,
Err(FastlyStatus::INVAL) => false,
_ => panic!("fastly_http_req::header_remove returned error"),
}
}
/// Get the HTTP version of this request.
pub fn get_version(&self) -> Version {
let mut version = 0;
let status = unsafe { abi::fastly_http_req::version_get(self.as_u32(), &mut version) };
if status.is_err() {
panic!("fastly_http_req::version_get failed");
} else {
abi::HttpVersion::try_from(version)
.map(Into::into)
.expect("HTTP version must be valid")
}
}
/// Set the HTTP version of this request.
pub fn set_version(&mut self, v: Version) {
unsafe {
abi::fastly_http_req::version_set(self.as_u32(), abi::HttpVersion::from(v) as u32)
}
.result()
.expect("fastly_http_req::version_get failed");
}
/// Get the request method.
///
/// If the method is longer than `max_length`, this will return a [`BufferSizeError`]; you can
/// retry with a larger buffer size if necessary.
pub fn get_method(&self, max_length: usize) -> Result<Method, BufferSizeError> {
let mut method_bytes = Vec::with_capacity(max_length);
let mut nwritten = 0;
let status = unsafe {
abi::fastly_http_req::method_get(
self.as_u32(),
method_bytes.as_mut_ptr(),
method_bytes.capacity(),
&mut nwritten,
)
};
match status.result() {
Ok(_) => {
assert!(
nwritten <= method_bytes.capacity(),
"fastly_http_req::method_get wrote too many bytes"
);
unsafe {
method_bytes.set_len(nwritten);
}
Ok(Method::from_bytes(&method_bytes).expect("HTTP method must be valid"))
}
Err(FastlyStatus::BUFLEN) => Err(BufferSizeError::http_method(max_length, nwritten)),
_ => panic!("fastly_http_req::method_get failed"),
}
}
pub(crate) fn get_method_impl(
&self,
mut initial_buf_size: usize,
max_buf_size: Option<usize>,
) -> Result<Method, BufferSizeError> {
if let Some(max) = max_buf_size {
initial_buf_size = std::cmp::min(initial_buf_size, max);
}
match self.get_method(initial_buf_size) {
Ok(method) => Ok(method),
Err(mut err) => {
if let Some(max) = max_buf_size {
// if there's a max size, enforce it
if err.needed_buf_size <= max {
self.get_method(err.needed_buf_size)
} else {
// report the maximum that was exceeded, not what we tried
err.buf_size = max;
Err(err)
}
} else {
// otherwise just get as much as is needed
self.get_method(err.needed_buf_size)
}
}
}
}
/// Set the request method.
pub fn set_method(&self, method: &Method) {
let method_bytes = method.as_str().as_bytes();
unsafe {
abi::fastly_http_req::method_set(
self.as_u32(),
method_bytes.as_ptr(),
method_bytes.len(),
)
}
.result()
.expect("fastly_http_req::method_set failed");
}
/// Get the request URL.
///
/// If the URL is longer than `max_length`, this will return a [`BufferSizeError`]; you can
/// retry with a larger buffer size if necessary.
pub fn get_url(&self, max_length: usize) -> Result<Url, BufferSizeError> {
let mut url_bytes = BytesMut::with_capacity(max_length);
let mut nwritten = 0;
let status = unsafe {
abi::fastly_http_req::uri_get(
self.as_u32(),
url_bytes.as_mut_ptr(),
url_bytes.capacity(),
&mut nwritten,
)
};
match status.result() {
Ok(_) => {
assert!(
nwritten <= url_bytes.capacity(),
"fastly_http_req::uri_get wrote too many bytes"
);
unsafe {
url_bytes.set_len(nwritten);
}
// TODO ACF 2020-08-28: use the `TryFrom<&[u8]>` impl once this change is merged and
// released: https://github.com/servo/rust-url/pull/638
let url_str =
std::str::from_utf8(&url_bytes).expect("host provided invalid request url");
let url = Url::parse(url_str).expect("host provided invalid request url");
Ok(url)
}
Err(FastlyStatus::BUFLEN) => Err(BufferSizeError::url(max_length, nwritten)),
_ => panic!("fastly_http_req::uri_get failed"),
}
}
pub(crate) fn get_url_impl(
&self,
mut initial_buf_size: usize,
max_buf_size: Option<usize>,
) -> Result<Url, BufferSizeError> {
if let Some(max) = max_buf_size {
initial_buf_size = std::cmp::min(initial_buf_size, max);
}
match self.get_url(initial_buf_size) {
Ok(url) => Ok(url),
Err(mut err) => {
if let Some(max) = max_buf_size {
// if there's a max size, enforce it
if err.needed_buf_size <= max {
self.get_url(err.needed_buf_size)
} else {
// report the maximum that was exceeded, not what we tried
err.buf_size = max;
Err(err)
}
} else {
// otherwise just get as much as is needed
self.get_url(err.needed_buf_size)
}
}
}
}
/// Set the request URL.
pub fn set_url(&mut self, url: &Url) {
let url_bytes = url.as_str().as_bytes();
unsafe {
abi::fastly_http_req::uri_set(self.as_u32(), url_bytes.as_ptr(), url_bytes.len())
}
.result()
.expect("fastly_http_req::uri_set failed");
}
/// Send the request to the given backend server, and return once the response headers have been
/// received, or an error occurs.
pub fn send(
self,
body: BodyHandle,
backend: &str,
) -> Result<(ResponseHandle, BodyHandle), SendErrorCause> {
let mut resp_handle = ResponseHandle::INVALID;
let mut resp_body_handle = BodyHandle::INVALID;
let mut error_detail = SendErrorDetail::uninitialized_all();
let status = unsafe {
abi::fastly_http_req::send_v2(
self.into_u32(),
body.into_u32(),
backend.as_ptr(),
backend.len(),
&mut error_detail,
resp_handle.as_u32_mut(),
resp_body_handle.as_u32_mut(),
)
};
SendErrorCause::detail_and_status(error_detail, Some(status))?;
if resp_handle.is_invalid() || resp_body_handle.is_invalid() {
panic!("fastly_http_req::send returned invalid handles");
} else {
Ok((resp_handle, resp_body_handle))
}
}
/// Send a request asynchronously via the given backend, returning as soon as the request has
/// begun sending.
///
/// The resulting [`PendingRequestHandle`] can be evaluated using
/// [`PendingRequestHandle::poll()`], [`PendingRequestHandle::wait()`], or
/// [`select_handles()`][`crate::handle::select_handles()`]. It can also be discarded if the
/// request was sent for effects it might have, and the response is unimportant.
pub fn send_async(
self,
body: BodyHandle,
backend: &str,
) -> Result<PendingRequestHandle, SendErrorCause> {
let mut pending_req_handle = PendingRequestHandle::INVALID;
let status = unsafe {
abi::fastly_http_req::send_async(
self.into_u32(),
body.into_u32(),
backend.as_ptr(),
backend.len(),
pending_req_handle.as_u32_mut(),
)
};
if status.is_err() {
Err(SendErrorCause::status(status))
} else if pending_req_handle.is_invalid() {
panic!("fastly_http_req::send_async returned an invalid handle");
} else {
Ok(pending_req_handle)
}
}
/// Send a request asynchronously via the given backend, and return a [`StreamingBodyHandle`] to
/// allow continued writes to the request body.
///
/// [`StreamingBodyHandle::finish()`] must be called in order to finish sending the request.
pub fn send_async_streaming(
self,
body: BodyHandle,
backend: &str,
) -> Result<(StreamingBodyHandle, PendingRequestHandle), SendErrorCause> {
let mut pending_req_handle = PendingRequestHandle::INVALID;
let status = unsafe {
abi::fastly_http_req::send_async_streaming(
self.into_u32(),
body.as_u32(),
backend.as_ptr(),
backend.len(),
pending_req_handle.as_u32_mut(),
)
};
if status.is_err() {
Err(SendErrorCause::status(status))
} else if pending_req_handle.is_invalid() {
panic!("fastly_http_req::send_async_streaming returned an invalid handle");
} else {
Ok((
StreamingBodyHandle::from_body_handle(body),
pending_req_handle,
))
}
}
/// Set the cache override behavior for this request.
///
/// This setting will override any cache directive headers returned in response to this request.
pub fn set_cache_override(&mut self, cache_override: &CacheOverride) {
let (tag, ttl, swr, sk) = cache_override.to_abi();
let (sk_ptr, sk_len) = match sk {
Some(sk) if sk.len() > 0 => (sk.as_ptr(), sk.len()),
_ => (std::ptr::null(), 0),
};
unsafe {
abi::fastly_http_req::cache_override_v2_set(
self.as_u32(),
tag,
ttl,
swr,
sk_ptr,
sk_len,
)
}
.result()
.expect("fastly_http_req::cache_override_v2_set failed");
}
/// Close the RequestHandle by removing it from the host Session. If the handle has already
/// been closed an error will be returned. When calling
/// send/send_async/send_async_streaming the RequestHandle is consumed and
/// it's cleaned up. You should only call `close` if you have not sent a
/// request yet and want to clean up the resources if not being used.
///
/// # Examples
///
/// ```no_run
/// # use fastly::handle::RequestHandle;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let request = RequestHandle::new();
/// // The handle is not being used so we can close it out without any
/// // trouble
/// request.close()?;
/// # Ok(())
/// # }
/// ```
pub fn close(self) -> Result<(), HandleError> {
match unsafe { abi::fastly_http_req::close(self.as_u32()) } {
FastlyStatus::OK => Ok(()),
_ => Err(HandleError::ClosedHandle(HandleKind::Request)),
}
}
/// Set the content encodings to automatically decompress responses to this request.
///
/// If the response to this request is encoded by one of the encodings set by this method, the
/// response will be presented to the Compute program in decompressed form with the
/// `Content-Encoding` and `Content-Length` headers removed.
pub fn set_auto_decompress_response(&mut self, content_encodings: ContentEncodings) {
unsafe {
abi::fastly_http_req::auto_decompress_response_set(self.as_u32(), content_encodings)
}
.result()
.expect("fastly_http_req::auto_decompress_response_set failed")
}
/// Sets the way that framing headers are determined for this request.
pub fn set_framing_headers_mode(&mut self, mode: FramingHeadersMode) {
unsafe { abi::fastly_http_req::framing_headers_mode_set(self.as_u32(), mode) }
.result()
.expect("fastly_http_req::framing_headers_mode_set failed")
}
/// Pass the WebSocket directly to a backend.
///
/// This can only be used on services that have the WebSockets feature enabled and on requests
/// that are valid WebSocket requests.
///
/// The sending completes in the background. Once this method has been called, no other
/// response can be sent to this request, and the application can exit without affecting the
/// send.
pub fn handoff_websocket(&mut self, backend: &str) -> Result<(), SendErrorCause> {
match unsafe {
abi::fastly_http_req::redirect_to_websocket_proxy_v2(
self.as_u32(),
backend.as_ptr(),
backend.len(),
)
} {
FastlyStatus::OK => Ok(()),
status => Err(SendErrorCause::status(status)),
}
}
/// Pass the request through the Fanout GRIP proxy and on to a backend.
///
/// This can only be used on services that have the Fanout feature enabled.
///
/// The sending completes in the background. Once this method has been called, no other
/// response can be sent to this request, and the application can exit without affecting the
/// send.
pub fn handoff_fanout(&mut self, backend: &str) -> Result<(), SendErrorCause> {
match unsafe {
abi::fastly_http_req::redirect_to_grip_proxy_v2(
self.as_u32(),
backend.as_ptr(),
backend.len(),
)
} {
FastlyStatus::OK => Ok(()),
status => Err(SendErrorCause::status(status)),
}
}
}
impl Drop for RequestHandle {
fn drop(&mut self) {
if self.is_valid() {
unsafe { abi::fastly_http_req::close(self.as_u32()) }
.result()
.expect("fastly_http_req::close failed");
}
}
}
/// Get handles to the client request headers and body at the same time.
///
/// This will panic if either the parts of the body have already been retrieved.
pub fn client_request_and_body() -> (RequestHandle, BodyHandle) {
RequestHandle::set_got_client();
BodyHandle::set_got_client();
let result = {
let mut req_handle = RequestHandle::INVALID;
let mut body_handle = BodyHandle::INVALID;
let status = unsafe {
abi::fastly_http_req::body_downstream_get(
req_handle.as_u32_mut(),
body_handle.as_u32_mut(),
)
};
status.result().map(|_| (req_handle, body_handle))
};
match result {
Ok((r, b)) if r.is_valid() && b.is_valid() => (r, b),
_ => panic!("fastly_http_req::body_downstream_get failed"),
}
}
/// Returns the client request's header names exactly as they were originally received.
///
/// This includes both the original header name characters' cases, as well as the original order of
/// the received headers.
///
/// If there is a header name that is longer than the provided buffer, this will return a
/// [`BufferSizeError`]; you can retry with a larger buffer size if necessary.
pub fn client_original_header_names(
buf_size: usize,
) -> impl Iterator<Item = Result<String, BufferSizeError>> {
client_original_header_names_impl(buf_size, Some(buf_size))
}
pub(crate) fn client_original_header_names_impl(
mut initial_buf_size: usize,
max_buf_size: Option<usize>,
) -> impl Iterator<Item = Result<String, BufferSizeError>> {
if let Some(max) = max_buf_size {
initial_buf_size = std::cmp::min(initial_buf_size, max);
}
abi::MultiValueHostcall::new(
b'\0',
initial_buf_size,
max_buf_size,
move |buf, buf_size, cursor, ending_cursor, nwritten| unsafe {
abi::fastly_http_req::original_header_names_get(
buf,
buf_size,
cursor,
ending_cursor,
nwritten,
)
},
)
.map(move |res| {
use MultiValueHostcallError::{BufferTooSmall, ClosureError};
match res {
// we trust that the hostcall is giving us valid header bytes
Ok(name_bytes) => Ok(String::from_utf8(name_bytes.to_vec()).unwrap()),
// return an error if the buffer was not large enough
Err(BufferTooSmall { needed_buf_size }) => Err(BufferSizeError::header_value(
max_buf_size.expect("maximum buffer size must exist if a buffer size error occurs"),
needed_buf_size,
)),
// panic if the hostcall failed for some other reason
Err(ClosureError(e)) => {
panic!("fastly_http_req::header_values_get returned error: {:?}", e)
}
}
})
}
/// Returns the number of headers in the client request as originally received.
pub fn client_original_header_count() -> u32 {
let mut count = 0;
let status = unsafe { abi::fastly_http_req::original_header_count(&mut count) };
if status.is_err() || count == 0 {
panic!("downstream_original_header_count failed")
}
count
}
/// Returns whether or not a valid Fastly-Key for this service was received.
pub fn fastly_key_is_valid() -> bool {
let mut is_valid = 0;
let status = unsafe { abi::fastly_http_req::fastly_key_is_valid(&mut is_valid) };
if status.is_err() {
panic!("fastly_key_is_valid failed")
}
// Just in case more information needs to be conveyed by fastly_key_is_valid in the future, we
// can at least establish that any authenticated key will have at least the lowest bit set.
(is_valid & 1) != 0
}
/// Returns the IP address of the client making the HTTP request.
pub fn client_ip_addr() -> Option<IpAddr> {
let mut octets = [0; 16];
let mut nwritten = 0;
let status = unsafe {
abi::fastly_http_req::downstream_client_ip_addr(octets.as_mut_ptr(), &mut nwritten)
};
if status.is_err() {
panic!("downstream_client_ip_addr failed");
}
match nwritten {
4 => {
let octets: [u8; 4] = octets[0..4]
.try_into()
.expect("octets is at least 4 bytes long");
let addr: Ipv4Addr = octets.into();
Some(addr.into())
}
16 => {
let addr: Ipv6Addr = octets.into();
Some(addr.into())
}
_ => panic!("downstream_client_ip_addr wrote an unexpected number of bytes"),
}
}
/// Returns the IP address on which this server received the HTTP request.
pub fn server_ip_addr() -> Option<IpAddr> {
let mut octets = [0; 16];
let mut nwritten = 0;
let status = unsafe {
abi::fastly_http_req::downstream_server_ip_addr(octets.as_mut_ptr(), &mut nwritten)
};
if status.is_err() {
panic!("downstream_server_ip_addr failed");
}
match nwritten {
4 => {
let octets: [u8; 4] = octets[0..4]
.try_into()
.expect("octets is at least 4 bytes long");
let addr: Ipv4Addr = octets.into();
Some(addr.into())
}
16 => {
let addr: Ipv6Addr = octets.into();
Some(addr.into())
}
_ => panic!("downstream_server_ip_addr wrote an unexpected number of bytes"),
}
}
pub fn redirect_to_websocket_proxy(h: RequestHandle, backend: &str) -> FastlyStatus {
unsafe {
abi::fastly_http_req::redirect_to_websocket_proxy_v2(
h.as_u32(),
backend.as_ptr(),
backend.len(),
)
}
}
pub fn redirect_to_grip_proxy(h: RequestHandle, backend: &str) -> FastlyStatus {
unsafe {
abi::fastly_http_req::redirect_to_grip_proxy_v2(h.as_u32(), backend.as_ptr(), backend.len())
}
}
/// Get the HTTP/2 fingerprint of client request if available
#[doc(hidden)]
pub fn client_h2_fingerprint() -> Option<&'static str> {
lazy_static! {
static ref H2FP: Option<String> = {
let name = "downstream HTTP/2 fingerprint";
get_bytes_adaptive(
abi::fastly_http_req::downstream_client_h2_fingerprint,
512,
name,
)
.map(|buf| {
String::from_utf8(buf).unwrap_or_else(|_| panic!("{} must be valid UTF-8", name))
})
};
}
H2FP.as_ref().map(|x| x.as_str())
}
/// Get the id of the current equest if available
#[doc(hidden)]
pub fn client_request_id() -> Option<&'static str> {
lazy_static! {
static ref REQID: Option<String> = {
let name = "downstream request id";
get_bytes_adaptive(
abi::fastly_http_req::downstream_client_request_id,
512,
name,
)
.map(|buf| {
String::from_utf8(buf).unwrap_or_else(|_| panic!("{} must be valid UTF-8", name))
})
};
}
REQID.as_ref().map(|x| x.as_str())
}
/// Get the fingerprint of client request headers if available
#[doc(hidden)]
pub fn client_oh_fingerprint() -> Option<&'static str> {
lazy_static! {
static ref OHFP: Option<String> = {
let name = "downstream original header fingerprint";
get_bytes_adaptive(
abi::fastly_http_req::downstream_client_oh_fingerprint,
512,
name,
)
.map(|buf| {
String::from_utf8(buf).unwrap_or_else(|_| panic!("{} must be valid UTF-8", name))
})
};
}
OHFP.as_ref().map(|x| x.as_str())
}
/// Get the raw bytes sent by the client in the TLS ClientHello message.
///
/// See [RFC 5246](https://tools.ietf.org/html/rfc5246#section-7.4.1.2) for details.
pub fn client_tls_client_hello() -> Option<&'static [u8]> {
lazy_static! {
static ref CLIENT_HELLO: Option<Vec<u8>> = {
get_bytes_adaptive(
abi::fastly_http_req::downstream_tls_client_hello,
512,
"downstream TLS ClientHello",
)
};
}
CLIENT_HELLO.as_ref().map(|x| x.as_ref())
}
/// Get the JA3 hash of the TLS ClientHello message.
pub fn client_tls_ja3_md5() -> Option<[u8; 16]> {
let mut ja3_md5 = [0; 16];
let mut nwritten = 0;
let status = unsafe {
abi::fastly_http_req::downstream_tls_ja3_md5(ja3_md5.as_mut_ptr(), &mut nwritten)
};
match status {
FastlyStatus::OK => match nwritten {
16 => Some(ja3_md5),
_ => panic!("downstream_tls_ja3_md5 wrote an unexpected number of bytes"),
},
FastlyStatus::NONE => {
// Non-ssl connection
None
}
_ => {
panic!("downstream_tls_ja3_md5 failed");
}
}
}
/// Get the JA4 hash of the TLS ClientHello message.
pub fn client_tls_ja4() -> Option<&'static str> {
lazy_static! {
static ref JA4: Option<String> = {
let name = "downstream tls ja4";
get_bytes_adaptive(abi::fastly_http_req::downstream_tls_ja4, 512, name).map(|buf| {
String::from_utf8(buf).unwrap_or_else(|_| panic!("{} must be valid UTF-8", name))
})
};
}
JA4.as_ref().map(|x| x.as_str())
}
/// Get the client certificate used to secure the downstream client mTLS connection,
/// as a string, panicking if it is not UTF-8.
///
/// The value returned will be based on PEM format.
pub fn client_tls_client_raw_certificate() -> Option<&'static str> {
client_tls_client_raw_certificate_bytes().map(|buf| {
std::str::from_utf8(buf)
.unwrap_or_else(|_| panic!("downstream TLS client raw certificate must be valid UTF-8"))
})
}
/// Like [`client_tls_client_raw_certificate`], but supports non-UTF-8 byte sequences.
pub fn client_tls_client_raw_certificate_bytes() -> Option<&'static [u8]> {
lazy_static! {
static ref CLIENT_CERTIFICATE: Option<Vec<u8>> = {
let name = "downstream TLS client raw certificate";
get_bytes_adaptive(
abi::fastly_http_req::downstream_tls_raw_client_certificate,
4096,
name,
).filter(|buf| {
// we can get `Some("")` rather than `None` sometimes, which is just `None` by
// another name. filter for it here.
buf.len() > 0
})
};
}
CLIENT_CERTIFICATE.as_ref().map(|x| x.as_ref())
}
/// Returns the [`ClientCertVerifyResult`] from the downstream client mTLS handshake.
///
/// Returns `None` if not available.
pub fn client_tls_client_cert_verify_result() -> Option<ClientCertVerifyResult> {
let mut raw_verify_result = 0;
let status = unsafe {
abi::fastly_http_req::downstream_tls_client_cert_verify_result(&mut raw_verify_result)
};
if status.is_err() {
return None;
}
let verify_result = ClientCertVerifyResult::from_u32(raw_verify_result);
Some(verify_result)
}
/// Get the cipher suite used to secure the downstream client TLS connection, as a string,
/// panicking if it is not UTF-8.
///
/// The value returned will be consistent with the [OpenSSL
/// name](https://testssl.sh/openssl-iana.mapping.html) for the cipher suite.
///
/// # Examples
///
/// ```no_run
/// assert_eq!(
/// fastly::handle::client_tls_cipher_openssl_name().unwrap(),
/// "ECDHE-RSA-AES128-GCM-SHA256"
/// );
/// ```
pub fn client_tls_cipher_openssl_name() -> Option<&'static str> {
client_tls_cipher_openssl_name_bytes().map(|buf| {
std::str::from_utf8(buf)
.unwrap_or_else(|_| panic!("downstream TLS cipher OpenSSL name must be valid UTF-8"))
})
}
/// Like [`client_tls_cipher_openssl_name`], but supports non-UTF-8 byte string.
pub fn client_tls_cipher_openssl_name_bytes() -> Option<&'static [u8]> {
lazy_static! {
static ref OPENSSL_NAME: Option<Vec<u8>> = {
let name = "downstream TLS cipher OpenSSL name";
get_bytes_adaptive(
abi::fastly_http_req::downstream_tls_cipher_openssl_name,
128,
name,
)
};
}
OPENSSL_NAME.as_ref().map(|x| x.as_ref())
}
/// Get the TLS protocol version used to secure the downstream client TLS connection, as a
/// string, panicking if it is not UTF-8.
///
/// # Examples
///
/// ```no_run
/// # use fastly::Request;
/// assert_eq!(Request::from_client().get_tls_protocol().unwrap(), "TLSv1.2");
/// ```
pub fn client_tls_protocol() -> Option<&'static str> {
client_tls_protocol_bytes().map(|buf| {
std::str::from_utf8(buf)
.unwrap_or_else(|_| panic!("downstream TLS cipher protocol must be valid UTF-8"))
})
}
/// Like [`client_tls_protocol`], but supports non-UTF-8 byte sequences.
pub fn client_tls_protocol_bytes() -> Option<&'static [u8]> {
lazy_static! {
static ref PROTOCOL: Option<Vec<u8>> = {
let name = "downstream TLS cipher protocol";
get_bytes_adaptive(abi::fastly_http_req::downstream_tls_protocol, 32, name)
};
}
PROTOCOL.as_deref()
}
fn get_bytes_adaptive(
hostcall: unsafe extern "C" fn(*mut u8, usize, *mut usize) -> FastlyStatus,
default_buf_size: usize,
name: &str,
) -> Option<Vec<u8>> {
let mut buf = Vec::with_capacity(default_buf_size);
let mut nwritten = 0;
let status = unsafe { hostcall(buf.as_mut_ptr(), buf.capacity(), &mut nwritten) };
match status {
FastlyStatus::OK => (),
FastlyStatus::BUFLEN if nwritten != 0 => {
buf.reserve_exact(nwritten);
let status = unsafe { hostcall(buf.as_mut_ptr(), buf.capacity(), &mut nwritten) };
if status.is_err() {
panic!("couldn't get the {}", name);
}
}
FastlyStatus::ERROR => {
// ERROR can indicate that TLS metadata simply isn't present. This is the case when the
// client request is non-TLS.
return None;
}
FastlyStatus::NONE => {
return None;
}
_ => panic!("couldn't get the {}", name),
};
unsafe {
buf.set_len(nwritten);
}
Some(buf)
}