mirror of
https://github.com/servo/servo.git
synced 2025-08-03 20:50:07 +01:00
Rustfmt net_traits crate
This commit is contained in:
parent
f512e262a5
commit
d41be1d56d
10 changed files with 229 additions and 131 deletions
|
@ -114,21 +114,46 @@ pub struct SelectedFile {
|
||||||
#[derive(Debug, Deserialize, Serialize)]
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
pub enum FileManagerThreadMsg {
|
pub enum FileManagerThreadMsg {
|
||||||
/// Select a single file. Last field is pre-selected file path for testing
|
/// Select a single file. Last field is pre-selected file path for testing
|
||||||
SelectFile(Vec<FilterPattern>, IpcSender<FileManagerResult<SelectedFile>>, FileOrigin, Option<String>),
|
SelectFile(
|
||||||
|
Vec<FilterPattern>,
|
||||||
|
IpcSender<FileManagerResult<SelectedFile>>,
|
||||||
|
FileOrigin,
|
||||||
|
Option<String>,
|
||||||
|
),
|
||||||
|
|
||||||
/// Select multiple files. Last field is pre-selected file paths for testing
|
/// Select multiple files. Last field is pre-selected file paths for testing
|
||||||
SelectFiles(Vec<FilterPattern>, IpcSender<FileManagerResult<Vec<SelectedFile>>>, FileOrigin, Option<Vec<String>>),
|
SelectFiles(
|
||||||
|
Vec<FilterPattern>,
|
||||||
|
IpcSender<FileManagerResult<Vec<SelectedFile>>>,
|
||||||
|
FileOrigin,
|
||||||
|
Option<Vec<String>>,
|
||||||
|
),
|
||||||
|
|
||||||
/// Read FileID-indexed file in chunks, optionally check URL validity based on boolean flag
|
/// Read FileID-indexed file in chunks, optionally check URL validity based on boolean flag
|
||||||
ReadFile(IpcSender<FileManagerResult<ReadFileProgress>>, Uuid, bool, FileOrigin),
|
ReadFile(
|
||||||
|
IpcSender<FileManagerResult<ReadFileProgress>>,
|
||||||
|
Uuid,
|
||||||
|
bool,
|
||||||
|
FileOrigin,
|
||||||
|
),
|
||||||
|
|
||||||
/// Add an entry as promoted memory-based blob and send back the associated FileID
|
/// Add an entry as promoted memory-based blob and send back the associated FileID
|
||||||
/// as part of a valid/invalid Blob URL depending on the boolean flag
|
/// as part of a valid/invalid Blob URL depending on the boolean flag
|
||||||
PromoteMemory(BlobBuf, bool, IpcSender<Result<Uuid, BlobURLStoreError>>, FileOrigin),
|
PromoteMemory(
|
||||||
|
BlobBuf,
|
||||||
|
bool,
|
||||||
|
IpcSender<Result<Uuid, BlobURLStoreError>>,
|
||||||
|
FileOrigin,
|
||||||
|
),
|
||||||
|
|
||||||
/// Add a sliced entry pointing to the parent FileID, and send back the associated FileID
|
/// Add a sliced entry pointing to the parent FileID, and send back the associated FileID
|
||||||
/// as part of a valid Blob URL
|
/// as part of a valid Blob URL
|
||||||
AddSlicedURLEntry(Uuid, RelativePos, IpcSender<Result<Uuid, BlobURLStoreError>>, FileOrigin),
|
AddSlicedURLEntry(
|
||||||
|
Uuid,
|
||||||
|
RelativePos,
|
||||||
|
IpcSender<Result<Uuid, BlobURLStoreError>>,
|
||||||
|
FileOrigin,
|
||||||
|
),
|
||||||
|
|
||||||
/// Decrease reference count and send back the acknowledgement
|
/// Decrease reference count and send back the acknowledgement
|
||||||
DecRef(Uuid, FileOrigin, IpcSender<Result<(), BlobURLStoreError>>),
|
DecRef(Uuid, FileOrigin, IpcSender<Result<(), BlobURLStoreError>>),
|
||||||
|
|
|
@ -33,8 +33,11 @@ pub struct Image {
|
||||||
|
|
||||||
impl fmt::Debug for Image {
|
impl fmt::Debug for Image {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
write!(f, "Image {{ width: {}, height: {}, format: {:?}, ..., id: {:?} }}",
|
write!(
|
||||||
self.width, self.height, self.format, self.id)
|
f,
|
||||||
|
"Image {{ width: {}, height: {}, format: {:?}, ..., id: {:?} }}",
|
||||||
|
self.width, self.height, self.format, self.id
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -58,32 +61,29 @@ pub fn load_from_memory(buffer: &[u8]) -> Option<Image> {
|
||||||
debug!("{}", msg);
|
debug!("{}", msg);
|
||||||
None
|
None
|
||||||
},
|
},
|
||||||
Ok(_) => {
|
Ok(_) => match piston_image::load_from_memory(buffer) {
|
||||||
match piston_image::load_from_memory(buffer) {
|
Ok(image) => {
|
||||||
Ok(image) => {
|
let mut rgba = match image {
|
||||||
let mut rgba = match image {
|
DynamicImage::ImageRgba8(rgba) => rgba,
|
||||||
DynamicImage::ImageRgba8(rgba) => rgba,
|
image => image.to_rgba(),
|
||||||
image => image.to_rgba(),
|
};
|
||||||
};
|
pixels::byte_swap_colors_inplace(&mut *rgba);
|
||||||
pixels::byte_swap_colors_inplace(&mut *rgba);
|
Some(Image {
|
||||||
Some(Image {
|
width: rgba.width(),
|
||||||
width: rgba.width(),
|
height: rgba.height(),
|
||||||
height: rgba.height(),
|
format: PixelFormat::BGRA8,
|
||||||
format: PixelFormat::BGRA8,
|
bytes: IpcSharedMemory::from_bytes(&*rgba),
|
||||||
bytes: IpcSharedMemory::from_bytes(&*rgba),
|
id: None,
|
||||||
id: None,
|
})
|
||||||
})
|
},
|
||||||
},
|
Err(e) => {
|
||||||
Err(e) => {
|
debug!("Image decoding error: {:?}", e);
|
||||||
debug!("Image decoding error: {:?}", e);
|
None
|
||||||
None
|
},
|
||||||
},
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img
|
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img
|
||||||
pub fn detect_image_format(buffer: &[u8]) -> Result<ImageFormat, &str> {
|
pub fn detect_image_format(buffer: &[u8]) -> Result<ImageFormat, &str> {
|
||||||
if is_gif(buffer) {
|
if is_gif(buffer) {
|
||||||
|
|
|
@ -101,16 +101,19 @@ pub enum UsePlaceholder {
|
||||||
// ======================================================================
|
// ======================================================================
|
||||||
|
|
||||||
pub trait ImageCache: Sync + Send {
|
pub trait ImageCache: Sync + Send {
|
||||||
fn new(webrender_api: webrender_api::RenderApi) -> Self where Self: Sized;
|
fn new(webrender_api: webrender_api::RenderApi) -> Self
|
||||||
|
where
|
||||||
|
Self: Sized;
|
||||||
|
|
||||||
/// Return any available metadata or image for the given URL,
|
/// Return any available metadata or image for the given URL,
|
||||||
/// or an indication that the image is not yet available if it is in progress,
|
/// or an indication that the image is not yet available if it is in progress,
|
||||||
/// or else reserve a slot in the cache for the URL if the consumer can request images.
|
/// or else reserve a slot in the cache for the URL if the consumer can request images.
|
||||||
fn find_image_or_metadata(&self,
|
fn find_image_or_metadata(
|
||||||
url: ServoUrl,
|
&self,
|
||||||
use_placeholder: UsePlaceholder,
|
url: ServoUrl,
|
||||||
can_request: CanRequestImages)
|
use_placeholder: UsePlaceholder,
|
||||||
-> Result<ImageOrMetadataAvailable, ImageState>;
|
can_request: CanRequestImages,
|
||||||
|
) -> Result<ImageOrMetadataAvailable, ImageState>;
|
||||||
|
|
||||||
/// Add a new listener for the given pending image id. If the image is already present,
|
/// Add a new listener for the given pending image id. If the image is already present,
|
||||||
/// the responder will still receive the expected response.
|
/// the responder will still receive the expected response.
|
||||||
|
|
|
@ -2,7 +2,6 @@
|
||||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||||
|
|
||||||
|
|
||||||
#![deny(unsafe_code)]
|
#![deny(unsafe_code)]
|
||||||
|
|
||||||
extern crate cookie as cookie_rs;
|
extern crate cookie as cookie_rs;
|
||||||
|
@ -14,18 +13,24 @@ extern crate hyper;
|
||||||
extern crate hyper_serde;
|
extern crate hyper_serde;
|
||||||
extern crate image as piston_image;
|
extern crate image as piston_image;
|
||||||
extern crate ipc_channel;
|
extern crate ipc_channel;
|
||||||
#[macro_use] extern crate lazy_static;
|
#[macro_use]
|
||||||
#[macro_use] extern crate log;
|
extern crate lazy_static;
|
||||||
#[macro_use] extern crate malloc_size_of;
|
#[macro_use]
|
||||||
#[macro_use] extern crate malloc_size_of_derive;
|
extern crate log;
|
||||||
|
#[macro_use]
|
||||||
|
extern crate malloc_size_of;
|
||||||
|
#[macro_use]
|
||||||
|
extern crate malloc_size_of_derive;
|
||||||
extern crate mime;
|
extern crate mime;
|
||||||
extern crate msg;
|
extern crate msg;
|
||||||
extern crate num_traits;
|
extern crate num_traits;
|
||||||
extern crate pixels;
|
extern crate pixels;
|
||||||
#[macro_use] extern crate serde;
|
#[macro_use]
|
||||||
|
extern crate serde;
|
||||||
extern crate servo_arc;
|
extern crate servo_arc;
|
||||||
extern crate servo_url;
|
extern crate servo_url;
|
||||||
#[macro_use] extern crate url;
|
#[macro_use]
|
||||||
|
extern crate url;
|
||||||
extern crate uuid;
|
extern crate uuid;
|
||||||
extern crate webrender_api;
|
extern crate webrender_api;
|
||||||
|
|
||||||
|
@ -86,18 +91,26 @@ pub enum LoadContext {
|
||||||
#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
|
#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
|
||||||
pub struct CustomResponse {
|
pub struct CustomResponse {
|
||||||
#[ignore_malloc_size_of = "Defined in hyper"]
|
#[ignore_malloc_size_of = "Defined in hyper"]
|
||||||
#[serde(deserialize_with = "::hyper_serde::deserialize",
|
#[serde(
|
||||||
serialize_with = "::hyper_serde::serialize")]
|
deserialize_with = "::hyper_serde::deserialize",
|
||||||
|
serialize_with = "::hyper_serde::serialize"
|
||||||
|
)]
|
||||||
pub headers: HeaderMap,
|
pub headers: HeaderMap,
|
||||||
#[ignore_malloc_size_of = "Defined in hyper"]
|
#[ignore_malloc_size_of = "Defined in hyper"]
|
||||||
#[serde(deserialize_with = "::hyper_serde::deserialize",
|
#[serde(
|
||||||
serialize_with = "::hyper_serde::serialize")]
|
deserialize_with = "::hyper_serde::deserialize",
|
||||||
|
serialize_with = "::hyper_serde::serialize"
|
||||||
|
)]
|
||||||
pub raw_status: (StatusCode, String),
|
pub raw_status: (StatusCode, String),
|
||||||
pub body: Vec<u8>,
|
pub body: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CustomResponse {
|
impl CustomResponse {
|
||||||
pub fn new(headers: HeaderMap, raw_status: (StatusCode, String), body: Vec<u8>) -> CustomResponse {
|
pub fn new(
|
||||||
|
headers: HeaderMap,
|
||||||
|
raw_status: (StatusCode, String),
|
||||||
|
body: Vec<u8>,
|
||||||
|
) -> CustomResponse {
|
||||||
CustomResponse {
|
CustomResponse {
|
||||||
headers: headers,
|
headers: headers,
|
||||||
raw_status: raw_status,
|
raw_status: raw_status,
|
||||||
|
@ -137,22 +150,18 @@ pub enum ReferrerPolicy {
|
||||||
impl From<ReferrerPolicyHeader> for ReferrerPolicy {
|
impl From<ReferrerPolicyHeader> for ReferrerPolicy {
|
||||||
fn from(policy: ReferrerPolicyHeader) -> Self {
|
fn from(policy: ReferrerPolicyHeader) -> Self {
|
||||||
match policy {
|
match policy {
|
||||||
ReferrerPolicyHeader::NO_REFERRER =>
|
ReferrerPolicyHeader::NO_REFERRER => ReferrerPolicy::NoReferrer,
|
||||||
ReferrerPolicy::NoReferrer,
|
ReferrerPolicyHeader::NO_REFERRER_WHEN_DOWNGRADE => {
|
||||||
ReferrerPolicyHeader::NO_REFERRER_WHEN_DOWNGRADE =>
|
ReferrerPolicy::NoReferrerWhenDowngrade
|
||||||
ReferrerPolicy::NoReferrerWhenDowngrade,
|
},
|
||||||
ReferrerPolicyHeader::SAME_ORIGIN =>
|
ReferrerPolicyHeader::SAME_ORIGIN => ReferrerPolicy::SameOrigin,
|
||||||
ReferrerPolicy::SameOrigin,
|
ReferrerPolicyHeader::ORIGIN => ReferrerPolicy::Origin,
|
||||||
ReferrerPolicyHeader::ORIGIN =>
|
ReferrerPolicyHeader::ORIGIN_WHEN_CROSS_ORIGIN => ReferrerPolicy::OriginWhenCrossOrigin,
|
||||||
ReferrerPolicy::Origin,
|
ReferrerPolicyHeader::UNSAFE_URL => ReferrerPolicy::UnsafeUrl,
|
||||||
ReferrerPolicyHeader::ORIGIN_WHEN_CROSS_ORIGIN =>
|
ReferrerPolicyHeader::STRICT_ORIGIN => ReferrerPolicy::StrictOrigin,
|
||||||
ReferrerPolicy::OriginWhenCrossOrigin,
|
ReferrerPolicyHeader::STRICT_ORIGIN_WHEN_CROSS_ORIGIN => {
|
||||||
ReferrerPolicyHeader::UNSAFE_URL =>
|
ReferrerPolicy::StrictOriginWhenCrossOrigin
|
||||||
ReferrerPolicy::UnsafeUrl,
|
},
|
||||||
ReferrerPolicyHeader::STRICT_ORIGIN =>
|
|
||||||
ReferrerPolicy::StrictOrigin,
|
|
||||||
ReferrerPolicyHeader::STRICT_ORIGIN_WHEN_CROSS_ORIGIN =>
|
|
||||||
ReferrerPolicy::StrictOriginWhenCrossOrigin,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -198,7 +207,7 @@ pub enum FilteredMetadata {
|
||||||
Basic(Metadata),
|
Basic(Metadata),
|
||||||
Cors(Metadata),
|
Cors(Metadata),
|
||||||
Opaque,
|
Opaque,
|
||||||
OpaqueRedirect
|
OpaqueRedirect,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||||
|
@ -244,7 +253,6 @@ impl FetchTaskTarget for IpcSender<FetchResponseMsg> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
pub trait Action<Listener> {
|
pub trait Action<Listener> {
|
||||||
fn process(self, listener: &mut Listener);
|
fn process(self, listener: &mut Listener);
|
||||||
}
|
}
|
||||||
|
@ -271,7 +279,8 @@ pub type IpcSendResult = Result<(), IpcError>;
|
||||||
/// used by net_traits::ResourceThreads to ease the use its IpcSender sub-fields
|
/// used by net_traits::ResourceThreads to ease the use its IpcSender sub-fields
|
||||||
/// XXX: If this trait will be used more in future, some auto derive might be appealing
|
/// XXX: If this trait will be used more in future, some auto derive might be appealing
|
||||||
pub trait IpcSend<T>
|
pub trait IpcSend<T>
|
||||||
where T: serde::Serialize + for<'de> serde::Deserialize<'de>,
|
where
|
||||||
|
T: serde::Serialize + for<'de> serde::Deserialize<'de>,
|
||||||
{
|
{
|
||||||
/// send message T
|
/// send message T
|
||||||
fn send(&self, T) -> IpcSendResult;
|
fn send(&self, T) -> IpcSendResult;
|
||||||
|
@ -342,9 +351,7 @@ pub enum WebSocketDomAction {
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize)]
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
pub enum WebSocketNetworkEvent {
|
pub enum WebSocketNetworkEvent {
|
||||||
ConnectionEstablished {
|
ConnectionEstablished { protocol_in_use: Option<String> },
|
||||||
protocol_in_use: Option<String>,
|
|
||||||
},
|
|
||||||
MessageReceived(MessageData),
|
MessageReceived(MessageData),
|
||||||
Close(Option<u16>, String),
|
Close(Option<u16>, String),
|
||||||
Fail,
|
Fail,
|
||||||
|
@ -353,18 +360,26 @@ pub enum WebSocketNetworkEvent {
|
||||||
#[derive(Debug, Deserialize, Serialize)]
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
/// IPC channels to communicate with the script thread about network or DOM events.
|
/// IPC channels to communicate with the script thread about network or DOM events.
|
||||||
pub enum FetchChannels {
|
pub enum FetchChannels {
|
||||||
ResponseMsg(IpcSender<FetchResponseMsg>, /* cancel_chan */ Option<IpcReceiver<()>>),
|
ResponseMsg(
|
||||||
|
IpcSender<FetchResponseMsg>,
|
||||||
|
/* cancel_chan */ Option<IpcReceiver<()>>,
|
||||||
|
),
|
||||||
WebSocket {
|
WebSocket {
|
||||||
event_sender: IpcSender<WebSocketNetworkEvent>,
|
event_sender: IpcSender<WebSocketNetworkEvent>,
|
||||||
action_receiver: IpcReceiver<WebSocketDomAction>,
|
action_receiver: IpcReceiver<WebSocketDomAction>,
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize)]
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
pub enum CoreResourceMsg {
|
pub enum CoreResourceMsg {
|
||||||
Fetch(RequestInit, FetchChannels),
|
Fetch(RequestInit, FetchChannels),
|
||||||
/// Initiate a fetch in response to processing a redirection
|
/// Initiate a fetch in response to processing a redirection
|
||||||
FetchRedirect(RequestInit, ResponseInit, IpcSender<FetchResponseMsg>, /* cancel_chan */ Option<IpcReceiver<()>>),
|
FetchRedirect(
|
||||||
|
RequestInit,
|
||||||
|
ResponseInit,
|
||||||
|
IpcSender<FetchResponseMsg>,
|
||||||
|
/* cancel_chan */ Option<IpcReceiver<()>>,
|
||||||
|
),
|
||||||
/// Store a cookie for a given originating URL
|
/// Store a cookie for a given originating URL
|
||||||
SetCookieForUrl(ServoUrl, Serde<Cookie<'static>>, CookieSource),
|
SetCookieForUrl(ServoUrl, Serde<Cookie<'static>>, CookieSource),
|
||||||
/// Store a set of cookies for a given originating URL
|
/// Store a set of cookies for a given originating URL
|
||||||
|
@ -372,7 +387,11 @@ pub enum CoreResourceMsg {
|
||||||
/// Retrieve the stored cookies for a given URL
|
/// Retrieve the stored cookies for a given URL
|
||||||
GetCookiesForUrl(ServoUrl, IpcSender<Option<String>>, CookieSource),
|
GetCookiesForUrl(ServoUrl, IpcSender<Option<String>>, CookieSource),
|
||||||
/// Get a cookie by name for a given originating URL
|
/// Get a cookie by name for a given originating URL
|
||||||
GetCookiesDataForUrl(ServoUrl, IpcSender<Vec<Serde<Cookie<'static>>>>, CookieSource),
|
GetCookiesDataForUrl(
|
||||||
|
ServoUrl,
|
||||||
|
IpcSender<Vec<Serde<Cookie<'static>>>>,
|
||||||
|
CookieSource,
|
||||||
|
),
|
||||||
/// Get a history state by a given history state id
|
/// Get a history state by a given history state id
|
||||||
GetHistoryState(HistoryStateId, IpcSender<Option<Vec<u8>>>),
|
GetHistoryState(HistoryStateId, IpcSender<Option<Vec<u8>>>),
|
||||||
/// Set a history state for a given history state id
|
/// Set a history state for a given history state id
|
||||||
|
@ -392,13 +411,20 @@ pub enum CoreResourceMsg {
|
||||||
|
|
||||||
/// Instruct the resource thread to make a new request.
|
/// Instruct the resource thread to make a new request.
|
||||||
pub fn fetch_async<F>(request: RequestInit, core_resource_thread: &CoreResourceThread, f: F)
|
pub fn fetch_async<F>(request: RequestInit, core_resource_thread: &CoreResourceThread, f: F)
|
||||||
where F: Fn(FetchResponseMsg) + Send + 'static,
|
where
|
||||||
|
F: Fn(FetchResponseMsg) + Send + 'static,
|
||||||
{
|
{
|
||||||
let (action_sender, action_receiver) = ipc::channel().unwrap();
|
let (action_sender, action_receiver) = ipc::channel().unwrap();
|
||||||
ROUTER.add_route(action_receiver.to_opaque(),
|
ROUTER.add_route(
|
||||||
Box::new(move |message| f(message.to().unwrap())));
|
action_receiver.to_opaque(),
|
||||||
core_resource_thread.send(
|
Box::new(move |message| f(message.to().unwrap())),
|
||||||
CoreResourceMsg::Fetch(request, FetchChannels::ResponseMsg(action_sender, None))).unwrap();
|
);
|
||||||
|
core_resource_thread
|
||||||
|
.send(CoreResourceMsg::Fetch(
|
||||||
|
request,
|
||||||
|
FetchChannels::ResponseMsg(action_sender, None),
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
|
#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
|
||||||
|
@ -466,7 +492,10 @@ impl Metadata {
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(mime) = content_type {
|
if let Some(mime) = content_type {
|
||||||
self.headers.as_mut().unwrap().typed_insert(ContentType::from(mime.clone()));
|
self.headers
|
||||||
|
.as_mut()
|
||||||
|
.unwrap()
|
||||||
|
.typed_insert(ContentType::from(mime.clone()));
|
||||||
self.content_type = Some(Serde(ContentType::from(mime.clone())));
|
self.content_type = Some(Serde(ContentType::from(mime.clone())));
|
||||||
for (name, value) in mime.params() {
|
for (name, value) in mime.params() {
|
||||||
if mime::CHARSET == name {
|
if mime::CHARSET == name {
|
||||||
|
@ -487,19 +516,23 @@ pub enum CookieSource {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convenience function for synchronously loading a whole resource.
|
/// Convenience function for synchronously loading a whole resource.
|
||||||
pub fn load_whole_resource(request: RequestInit,
|
pub fn load_whole_resource(
|
||||||
core_resource_thread: &CoreResourceThread)
|
request: RequestInit,
|
||||||
-> Result<(Metadata, Vec<u8>), NetworkError> {
|
core_resource_thread: &CoreResourceThread,
|
||||||
|
) -> Result<(Metadata, Vec<u8>), NetworkError> {
|
||||||
let (action_sender, action_receiver) = ipc::channel().unwrap();
|
let (action_sender, action_receiver) = ipc::channel().unwrap();
|
||||||
core_resource_thread.send(
|
core_resource_thread
|
||||||
CoreResourceMsg::Fetch(request, FetchChannels::ResponseMsg(action_sender, None))).unwrap();
|
.send(CoreResourceMsg::Fetch(
|
||||||
|
request,
|
||||||
|
FetchChannels::ResponseMsg(action_sender, None),
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
let mut buf = vec![];
|
let mut buf = vec![];
|
||||||
let mut metadata = None;
|
let mut metadata = None;
|
||||||
loop {
|
loop {
|
||||||
match action_receiver.recv().unwrap() {
|
match action_receiver.recv().unwrap() {
|
||||||
FetchResponseMsg::ProcessRequestBody |
|
FetchResponseMsg::ProcessRequestBody | FetchResponseMsg::ProcessRequestEOF => (),
|
||||||
FetchResponseMsg::ProcessRequestEOF => (),
|
|
||||||
FetchResponseMsg::ProcessResponse(Ok(m)) => {
|
FetchResponseMsg::ProcessResponse(Ok(m)) => {
|
||||||
metadata = Some(match m {
|
metadata = Some(match m {
|
||||||
FetchMetadata::Unfiltered(m) => m,
|
FetchMetadata::Unfiltered(m) => m,
|
||||||
|
@ -534,7 +567,6 @@ impl NetworkError {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// Normalize `slice`, as defined by
|
/// Normalize `slice`, as defined by
|
||||||
/// [the Fetch Spec](https://fetch.spec.whatwg.org/#concept-header-value-normalize).
|
/// [the Fetch Spec](https://fetch.spec.whatwg.org/#concept-header-value-normalize).
|
||||||
pub fn trim_http_whitespace(mut slice: &[u8]) -> &[u8] {
|
pub fn trim_http_whitespace(mut slice: &[u8]) -> &[u8] {
|
||||||
|
@ -569,4 +601,3 @@ pub fn http_percent_encode(bytes: &[u8]) -> String {
|
||||||
|
|
||||||
url::percent_encoding::percent_encode(bytes, HTTP_VALUE).to_string()
|
url::percent_encoding::percent_encode(bytes, HTTP_VALUE).to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -32,7 +32,8 @@ lazy_static! {
|
||||||
|
|
||||||
impl<'a> FromIterator<&'a str> for PubDomainRules {
|
impl<'a> FromIterator<&'a str> for PubDomainRules {
|
||||||
fn from_iter<T>(iter: T) -> Self
|
fn from_iter<T>(iter: T) -> Self
|
||||||
where T: IntoIterator<Item = &'a str>,
|
where
|
||||||
|
T: IntoIterator<Item = &'a str>,
|
||||||
{
|
{
|
||||||
let mut result = PubDomainRules::new();
|
let mut result = PubDomainRules::new();
|
||||||
for item in iter {
|
for item in iter {
|
||||||
|
@ -57,7 +58,8 @@ impl PubDomainRules {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn parse(content: &str) -> PubDomainRules {
|
pub fn parse(content: &str) -> PubDomainRules {
|
||||||
content.lines()
|
content
|
||||||
|
.lines()
|
||||||
.map(str::trim)
|
.map(str::trim)
|
||||||
.filter(|s| !s.is_empty())
|
.filter(|s| !s.is_empty())
|
||||||
.filter(|s| !s.starts_with("//"))
|
.filter(|s| !s.starts_with("//"))
|
||||||
|
@ -99,7 +101,7 @@ impl PubDomainRules {
|
||||||
None => !domain.is_empty(),
|
None => !domain.is_empty(),
|
||||||
Some(index) => {
|
Some(index) => {
|
||||||
!self.exceptions.contains(domain) && self.wildcards.contains(&domain[index + 1..]) ||
|
!self.exceptions.contains(domain) && self.wildcards.contains(&domain[index + 1..]) ||
|
||||||
self.rules.contains(domain)
|
self.rules.contains(domain)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -112,8 +114,9 @@ impl PubDomainRules {
|
||||||
None => false,
|
None => false,
|
||||||
Some(index) => {
|
Some(index) => {
|
||||||
self.exceptions.contains(domain) ||
|
self.exceptions.contains(domain) ||
|
||||||
!self.wildcards.contains(&domain[index + 1..]) && !self.rules.contains(domain) &&
|
!self.wildcards.contains(&domain[index + 1..]) &&
|
||||||
self.is_public_suffix(&domain[index + 1..])
|
!self.rules.contains(domain) &&
|
||||||
|
self.is_public_suffix(&domain[index + 1..])
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -145,7 +148,9 @@ pub fn is_reg_domain(domain: &str) -> bool {
|
||||||
/// Leaves the host name alone if it is an IP address.
|
/// Leaves the host name alone if it is an IP address.
|
||||||
pub fn reg_host(url: &ServoUrl) -> Option<Host> {
|
pub fn reg_host(url: &ServoUrl) -> Option<Host> {
|
||||||
match url.origin() {
|
match url.origin() {
|
||||||
ImmutableOrigin::Tuple(_, Host::Domain(domain), _) => Some(Host::Domain(String::from(reg_suffix(&*domain)))),
|
ImmutableOrigin::Tuple(_, Host::Domain(domain), _) => {
|
||||||
|
Some(Host::Domain(String::from(reg_suffix(&*domain))))
|
||||||
|
},
|
||||||
ImmutableOrigin::Tuple(_, ip, _) => Some(ip),
|
ImmutableOrigin::Tuple(_, ip, _) => Some(ip),
|
||||||
ImmutableOrigin::Opaque(_) => None,
|
ImmutableOrigin::Opaque(_) => None,
|
||||||
}
|
}
|
||||||
|
|
|
@ -70,11 +70,17 @@ where
|
||||||
|
|
||||||
let s = str::from_utf8(&digits[..]).unwrap();
|
let s = str::from_utf8(&digits[..]).unwrap();
|
||||||
fmt.write_str(s.trim_right_matches('0'))
|
fmt.write_str(s.trim_right_matches('0'))
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn quality_to_value(q: Vec<QualityItem<Mime>>) -> HeaderValue {
|
pub fn quality_to_value(q: Vec<QualityItem<Mime>>) -> HeaderValue {
|
||||||
HeaderValue::from_str(&q.iter().map(|q| q.to_string()).collect::<Vec<String>>().join(", ")).unwrap()
|
HeaderValue::from_str(
|
||||||
|
&q.iter()
|
||||||
|
.map(|q| q.to_string())
|
||||||
|
.collect::<Vec<String>>()
|
||||||
|
.join(", "),
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
|
@ -46,9 +46,9 @@ impl Destination {
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn is_script_like(&self) -> bool {
|
pub fn is_script_like(&self) -> bool {
|
||||||
*self == Destination::Script ||
|
*self == Destination::Script ||
|
||||||
*self == Destination::ServiceWorker ||
|
*self == Destination::ServiceWorker ||
|
||||||
*self == Destination::SharedWorker ||
|
*self == Destination::SharedWorker ||
|
||||||
*self == Destination::Worker
|
*self == Destination::Worker
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -75,7 +75,7 @@ pub enum RequestMode {
|
||||||
SameOrigin,
|
SameOrigin,
|
||||||
NoCors,
|
NoCors,
|
||||||
CorsMode,
|
CorsMode,
|
||||||
WebSocket { protocols: Vec<String> }
|
WebSocket { protocols: Vec<String> },
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Request [credentials mode](https://fetch.spec.whatwg.org/#concept-request-credentials-mode)
|
/// Request [credentials mode](https://fetch.spec.whatwg.org/#concept-request-credentials-mode)
|
||||||
|
@ -137,13 +137,17 @@ pub enum CorsSettings {
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
|
#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
|
||||||
pub struct RequestInit {
|
pub struct RequestInit {
|
||||||
#[serde(deserialize_with = "::hyper_serde::deserialize",
|
#[serde(
|
||||||
serialize_with = "::hyper_serde::serialize")]
|
deserialize_with = "::hyper_serde::deserialize",
|
||||||
|
serialize_with = "::hyper_serde::serialize"
|
||||||
|
)]
|
||||||
#[ignore_malloc_size_of = "Defined in hyper"]
|
#[ignore_malloc_size_of = "Defined in hyper"]
|
||||||
pub method: Method,
|
pub method: Method,
|
||||||
pub url: ServoUrl,
|
pub url: ServoUrl,
|
||||||
#[serde(deserialize_with = "::hyper_serde::deserialize",
|
#[serde(
|
||||||
serialize_with = "::hyper_serde::serialize")]
|
deserialize_with = "::hyper_serde::deserialize",
|
||||||
|
serialize_with = "::hyper_serde::serialize"
|
||||||
|
)]
|
||||||
#[ignore_malloc_size_of = "Defined in hyper"]
|
#[ignore_malloc_size_of = "Defined in hyper"]
|
||||||
pub headers: HeaderMap,
|
pub headers: HeaderMap,
|
||||||
pub unsafe_request: bool,
|
pub unsafe_request: bool,
|
||||||
|
@ -259,10 +263,7 @@ pub struct Request {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Request {
|
impl Request {
|
||||||
pub fn new(url: ServoUrl,
|
pub fn new(url: ServoUrl, origin: Option<Origin>, pipeline_id: Option<PipelineId>) -> Request {
|
||||||
origin: Option<Origin>,
|
|
||||||
pipeline_id: Option<PipelineId>)
|
|
||||||
-> Request {
|
|
||||||
Request {
|
Request {
|
||||||
method: Method::GET,
|
method: Method::GET,
|
||||||
local_urls_only: false,
|
local_urls_only: false,
|
||||||
|
@ -294,9 +295,11 @@ impl Request {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_init(init: RequestInit) -> Request {
|
pub fn from_init(init: RequestInit) -> Request {
|
||||||
let mut req = Request::new(init.url.clone(),
|
let mut req = Request::new(
|
||||||
Some(Origin::Origin(init.origin)),
|
init.url.clone(),
|
||||||
init.pipeline_id);
|
Some(Origin::Origin(init.origin)),
|
||||||
|
init.pipeline_id,
|
||||||
|
);
|
||||||
req.method = init.method;
|
req.method = init.method;
|
||||||
req.headers = init.headers;
|
req.headers = init.headers;
|
||||||
req.unsafe_request = init.unsafe_request;
|
req.unsafe_request = init.unsafe_request;
|
||||||
|
@ -350,9 +353,16 @@ impl Request {
|
||||||
/// <https://fetch.spec.whatwg.org/#subresource-request>
|
/// <https://fetch.spec.whatwg.org/#subresource-request>
|
||||||
pub fn is_subresource_request(&self) -> bool {
|
pub fn is_subresource_request(&self) -> bool {
|
||||||
match self.destination {
|
match self.destination {
|
||||||
Destination::Audio | Destination::Font | Destination::Image | Destination::Manifest |
|
Destination::Audio |
|
||||||
Destination::Script | Destination::Style | Destination::Track | Destination::Video |
|
Destination::Font |
|
||||||
Destination::Xslt | Destination::None => true,
|
Destination::Image |
|
||||||
|
Destination::Manifest |
|
||||||
|
Destination::Script |
|
||||||
|
Destination::Style |
|
||||||
|
Destination::Track |
|
||||||
|
Destination::Video |
|
||||||
|
Destination::Xslt |
|
||||||
|
Destination::None => true,
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -46,13 +46,11 @@ impl ResponseBody {
|
||||||
pub fn is_done(&self) -> bool {
|
pub fn is_done(&self) -> bool {
|
||||||
match *self {
|
match *self {
|
||||||
ResponseBody::Done(..) => true,
|
ResponseBody::Done(..) => true,
|
||||||
ResponseBody::Empty |
|
ResponseBody::Empty | ResponseBody::Receiving(..) => false,
|
||||||
ResponseBody::Receiving(..) => false,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// [Cache state](https://fetch.spec.whatwg.org/#concept-response-cache-state)
|
/// [Cache state](https://fetch.spec.whatwg.org/#concept-response-cache-state)
|
||||||
#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
|
#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
|
||||||
pub enum CacheState {
|
pub enum CacheState {
|
||||||
|
@ -79,8 +77,10 @@ pub enum ResponseMsg {
|
||||||
#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
|
#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
|
||||||
pub struct ResponseInit {
|
pub struct ResponseInit {
|
||||||
pub url: ServoUrl,
|
pub url: ServoUrl,
|
||||||
#[serde(deserialize_with = "::hyper_serde::deserialize",
|
#[serde(
|
||||||
serialize_with = "::hyper_serde::serialize")]
|
deserialize_with = "::hyper_serde::deserialize",
|
||||||
|
serialize_with = "::hyper_serde::serialize"
|
||||||
|
)]
|
||||||
#[ignore_malloc_size_of = "Defined in hyper"]
|
#[ignore_malloc_size_of = "Defined in hyper"]
|
||||||
pub headers: HeaderMap,
|
pub headers: HeaderMap,
|
||||||
pub status_code: u16,
|
pub status_code: u16,
|
||||||
|
@ -149,7 +149,9 @@ impl Response {
|
||||||
res.location_url = init.location_url;
|
res.location_url = init.location_url;
|
||||||
res.headers = init.headers;
|
res.headers = init.headers;
|
||||||
res.referrer = init.referrer;
|
res.referrer = init.referrer;
|
||||||
res.status = StatusCode::from_u16(init.status_code).map(|s| (s, s.to_string())).ok();
|
res.status = StatusCode::from_u16(init.status_code)
|
||||||
|
.map(|s| (s, s.to_string()))
|
||||||
|
.ok();
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -292,7 +294,13 @@ impl Response {
|
||||||
pub fn metadata(&self) -> Result<FetchMetadata, NetworkError> {
|
pub fn metadata(&self) -> Result<FetchMetadata, NetworkError> {
|
||||||
fn init_metadata(response: &Response, url: &ServoUrl) -> Metadata {
|
fn init_metadata(response: &Response, url: &ServoUrl) -> Metadata {
|
||||||
let mut metadata = Metadata::default(url.clone());
|
let mut metadata = Metadata::default(url.clone());
|
||||||
metadata.set_content_type(response.headers.typed_get::<ContentType>().map(|v| v.into()).as_ref());
|
metadata.set_content_type(
|
||||||
|
response
|
||||||
|
.headers
|
||||||
|
.typed_get::<ContentType>()
|
||||||
|
.map(|v| v.into())
|
||||||
|
.as_ref(),
|
||||||
|
);
|
||||||
metadata.location_url = response.location_url.clone();
|
metadata.location_url = response.location_url.clone();
|
||||||
metadata.headers = Some(Serde(response.headers.clone()));
|
metadata.headers = Some(Serde(response.headers.clone()));
|
||||||
metadata.status = response.raw_status.clone();
|
metadata.status = response.raw_status.clone();
|
||||||
|
@ -316,26 +324,27 @@ impl Response {
|
||||||
match self.response_type {
|
match self.response_type {
|
||||||
ResponseType::Basic => Ok(FetchMetadata::Filtered {
|
ResponseType::Basic => Ok(FetchMetadata::Filtered {
|
||||||
filtered: FilteredMetadata::Basic(metadata.unwrap()),
|
filtered: FilteredMetadata::Basic(metadata.unwrap()),
|
||||||
unsafe_: unsafe_metadata
|
unsafe_: unsafe_metadata,
|
||||||
}),
|
}),
|
||||||
ResponseType::Cors => Ok(FetchMetadata::Filtered {
|
ResponseType::Cors => Ok(FetchMetadata::Filtered {
|
||||||
filtered: FilteredMetadata::Cors(metadata.unwrap()),
|
filtered: FilteredMetadata::Cors(metadata.unwrap()),
|
||||||
unsafe_: unsafe_metadata
|
unsafe_: unsafe_metadata,
|
||||||
}),
|
}),
|
||||||
ResponseType::Default => unreachable!(),
|
ResponseType::Default => unreachable!(),
|
||||||
ResponseType::Error(ref network_err) =>
|
ResponseType::Error(ref network_err) => Err(network_err.clone()),
|
||||||
Err(network_err.clone()),
|
|
||||||
ResponseType::Opaque => Ok(FetchMetadata::Filtered {
|
ResponseType::Opaque => Ok(FetchMetadata::Filtered {
|
||||||
filtered: FilteredMetadata::Opaque,
|
filtered: FilteredMetadata::Opaque,
|
||||||
unsafe_: unsafe_metadata
|
unsafe_: unsafe_metadata,
|
||||||
}),
|
}),
|
||||||
ResponseType::OpaqueRedirect => Ok(FetchMetadata::Filtered {
|
ResponseType::OpaqueRedirect => Ok(FetchMetadata::Filtered {
|
||||||
filtered: FilteredMetadata::OpaqueRedirect,
|
filtered: FilteredMetadata::OpaqueRedirect,
|
||||||
unsafe_: unsafe_metadata
|
unsafe_: unsafe_metadata,
|
||||||
})
|
}),
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
None => Err(NetworkError::Internal("No url found in unsafe response".to_owned()))
|
None => Err(NetworkError::Internal(
|
||||||
|
"No url found in unsafe response".to_owned(),
|
||||||
|
)),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
assert_eq!(self.response_type, ResponseType::Default);
|
assert_eq!(self.response_type, ResponseType::Default);
|
||||||
|
|
|
@ -27,7 +27,13 @@ pub enum StorageThreadMsg {
|
||||||
GetItem(IpcSender<Option<String>>, ServoUrl, StorageType, String),
|
GetItem(IpcSender<Option<String>>, ServoUrl, StorageType, String),
|
||||||
|
|
||||||
/// sets the value of the given key in the associated storage data
|
/// sets the value of the given key in the associated storage data
|
||||||
SetItem(IpcSender<Result<(bool, Option<String>), ()>>, ServoUrl, StorageType, String, String),
|
SetItem(
|
||||||
|
IpcSender<Result<(bool, Option<String>), ()>>,
|
||||||
|
ServoUrl,
|
||||||
|
StorageType,
|
||||||
|
String,
|
||||||
|
String,
|
||||||
|
),
|
||||||
|
|
||||||
/// removes the key/value pair for the given key in the associated storage data
|
/// removes the key/value pair for the given key in the associated storage data
|
||||||
RemoveItem(IpcSender<Option<String>>, ServoUrl, StorageType, String),
|
RemoveItem(IpcSender<Option<String>>, ServoUrl, StorageType, String),
|
||||||
|
|
|
@ -116,6 +116,9 @@ fn test_reg_suffix() {
|
||||||
#[test]
|
#[test]
|
||||||
fn test_weirdness() {
|
fn test_weirdness() {
|
||||||
// These are weird results, but AFAICT they are spec-compliant.
|
// These are weird results, but AFAICT they are spec-compliant.
|
||||||
assert_ne!(pub_suffix("city.yokohama.jp"), pub_suffix(pub_suffix("city.yokohama.jp")));
|
assert_ne!(
|
||||||
|
pub_suffix("city.yokohama.jp"),
|
||||||
|
pub_suffix(pub_suffix("city.yokohama.jp"))
|
||||||
|
);
|
||||||
assert!(!is_pub_domain(pub_suffix("city.yokohama.jp")));
|
assert!(!is_pub_domain(pub_suffix("city.yokohama.jp")));
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue