Revert "Replace time with std::time in components/net (#31079)" (#31120)

This reverts commit 580062228b.
This commit is contained in:
Martin Robinson 2024-01-18 16:10:48 +01:00 committed by GitHub
parent c3fd27c225
commit 8e5f28839c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 123 additions and 161 deletions

View file

@ -7,13 +7,13 @@
use std::borrow::ToOwned;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use hyper_serde::Serde;
use net_traits::pub_domains::is_pub_domain;
use net_traits::CookieSource;
use serde::{Deserialize, Serialize};
use servo_url::ServoUrl;
use time::{at, now, Duration, Tm};
/// A stored cookie that wraps the definition in cookie-rs. This is used to implement
/// various behaviours defined in the spec that rely on an associated request URL,
@ -31,13 +31,13 @@ pub struct Cookie {
deserialize_with = "hyper_serde::deserialize",
serialize_with = "hyper_serde::serialize"
)]
pub creation_time: SystemTime,
pub creation_time: Tm,
#[serde(
deserialize_with = "hyper_serde::deserialize",
serialize_with = "hyper_serde::serialize"
)]
pub last_access: SystemTime,
pub expiry_time: Option<Serde<SystemTime>>,
pub last_access: Tm,
pub expiry_time: Option<Serde<Tm>>,
}
impl Cookie {
@ -62,16 +62,11 @@ impl Cookie {
let (persistent, expiry_time) = match (cookie.max_age(), cookie.expires()) {
(Some(max_age), _) => (
true,
Some(SystemTime::now() + Duration::from_secs(max_age.num_seconds() as u64)),
),
(_, Some(expires)) => (
true,
Some(
UNIX_EPOCH +
Duration::from_secs(expires.to_timespec().sec as u64) +
Duration::from_nanos(expires.to_timespec().nsec as u64),
),
Some(at(
now().to_timespec() + Duration::seconds(max_age.num_seconds())
)),
),
(_, Some(expires)) => (true, Some(expires)),
_ => (false, None),
};
@ -140,18 +135,18 @@ impl Cookie {
cookie,
host_only,
persistent,
creation_time: SystemTime::now(),
last_access: SystemTime::now(),
creation_time: now(),
last_access: now(),
expiry_time: expiry_time.map(Serde),
})
}
pub fn touch(&mut self) {
self.last_access = SystemTime::now();
self.last_access = now();
}
pub fn set_expiry_time_negative(&mut self) {
self.expiry_time = Some(Serde(SystemTime::now() - Duration::from_secs(1)));
self.expiry_time = Some(Serde(now() - Duration::seconds(1)));
}
// http://tools.ietf.org/html/rfc6265#section-5.1.4

View file

@ -8,13 +8,13 @@
use std::cmp::Ordering;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};
use log::{debug, info};
use net_traits::pub_domains::reg_suffix;
use net_traits::CookieSource;
use serde::{Deserialize, Serialize};
use servo_url::ServoUrl;
use time::{self, Tm};
use crate::cookie::Cookie;
@ -139,17 +139,8 @@ impl CookieStorage {
let b_path_len = b.cookie.path().as_ref().map_or(0, |p| p.len());
match a_path_len.cmp(&b_path_len) {
Ordering::Equal => {
let a_creation_time = a
.creation_time
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let b_creation_time = b
.creation_time
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let a_creation_time = a.creation_time.to_timespec();
let b_creation_time = b.creation_time.to_timespec();
a_creation_time.cmp(&b_creation_time)
},
// Ensure that longer paths are sorted earlier than shorter paths
@ -238,14 +229,14 @@ fn reg_host<'a>(url: &'a str) -> String {
fn is_cookie_expired(cookie: &Cookie) -> bool {
match cookie.expiry_time {
Some(ref t) => t.0 <= SystemTime::now(),
Some(ref t) => t.to_timespec() <= time::get_time(),
None => false,
}
}
fn evict_one_cookie(is_secure_cookie: bool, cookies: &mut Vec<Cookie>) -> bool {
// Remove non-secure cookie with oldest access time
let oldest_accessed = get_oldest_accessed(false, cookies);
let oldest_accessed: Option<(usize, Tm)> = get_oldest_accessed(false, cookies);
if let Some((index, _)) = oldest_accessed {
cookies.remove(index);
@ -254,7 +245,7 @@ fn evict_one_cookie(is_secure_cookie: bool, cookies: &mut Vec<Cookie>) -> bool {
if !is_secure_cookie {
return false;
}
let oldest_accessed: Option<(usize, SystemTime)> = get_oldest_accessed(true, cookies);
let oldest_accessed: Option<(usize, Tm)> = get_oldest_accessed(true, cookies);
if let Some((index, _)) = oldest_accessed {
cookies.remove(index);
}
@ -262,11 +253,8 @@ fn evict_one_cookie(is_secure_cookie: bool, cookies: &mut Vec<Cookie>) -> bool {
return true;
}
fn get_oldest_accessed(
is_secure_cookie: bool,
cookies: &mut Vec<Cookie>,
) -> Option<(usize, SystemTime)> {
let mut oldest_accessed: Option<(usize, SystemTime)> = None;
fn get_oldest_accessed(is_secure_cookie: bool, cookies: &mut Vec<Cookie>) -> Option<(usize, Tm)> {
let mut oldest_accessed: Option<(usize, Tm)> = None;
for (i, c) in cookies.iter().enumerate() {
if (c.cookie.secure().unwrap_or(false) == is_secure_cookie) &&
oldest_accessed

View file

@ -9,12 +9,11 @@
//! This library will eventually become the core of the Fetch crate
//! with CORSRequest being expanded into FetchRequest (etc)
use std::time::{Duration, SystemTime};
use http::header::HeaderName;
use http::Method;
use net_traits::request::{CredentialsMode, Origin, Request};
use servo_url::ServoUrl;
use time::{self, Timespec};
/// Union type for CORS cache entries
///
@ -46,17 +45,17 @@ impl HeaderOrMethod {
pub struct CorsCacheEntry {
pub origin: Origin,
pub url: ServoUrl,
pub max_age: Duration,
pub max_age: u32,
pub credentials: bool,
pub header_or_method: HeaderOrMethod,
created: SystemTime,
created: Timespec,
}
impl CorsCacheEntry {
fn new(
origin: Origin,
url: ServoUrl,
max_age: Duration,
max_age: u32,
credentials: bool,
header_or_method: HeaderOrMethod,
) -> CorsCacheEntry {
@ -66,7 +65,7 @@ impl CorsCacheEntry {
max_age: max_age,
credentials: credentials,
header_or_method: header_or_method,
created: SystemTime::now(),
created: time::now().to_timespec(),
}
}
}
@ -112,11 +111,10 @@ impl CorsCache {
/// Remove old entries
pub fn cleanup(&mut self) {
let CorsCache(buf) = self.clone();
let now = SystemTime::now();
let now = time::now().to_timespec();
let new_buf: Vec<CorsCacheEntry> = buf
.into_iter()
.filter(|e| now < e.created + e.max_age)
.filter(|e| now.sec < e.created.sec + e.max_age as i64)
.collect();
*self = CorsCache(new_buf);
}
@ -135,7 +133,7 @@ impl CorsCache {
&mut self,
request: &Request,
header_name: &HeaderName,
new_max_age: Duration,
new_max_age: u32,
) -> bool {
match self
.find_entry_by_header(&request, header_name)
@ -169,7 +167,7 @@ impl CorsCache {
&mut self,
request: &Request,
method: Method,
new_max_age: Duration,
new_max_age: u32,
) -> bool {
match self
.find_entry_by_method(&request, method.clone())

View file

@ -4,7 +4,6 @@
use std::collections::HashMap;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use embedder_traits::resources::{self, Resource};
use headers::{HeaderMapExt, StrictTransportSecurity};
@ -20,7 +19,7 @@ use servo_url::{Host, ServoUrl};
pub struct HstsEntry {
pub host: String,
pub include_subdomains: bool,
pub max_age: Option<Duration>,
pub max_age: Option<u64>,
pub timestamp: Option<u64>,
}
@ -28,7 +27,7 @@ impl HstsEntry {
pub fn new(
host: String,
subdomains: IncludeSubdomains,
max_age: Option<Duration>,
max_age: Option<u64>,
) -> Option<HstsEntry> {
if host.parse::<Ipv4Addr>().is_ok() || host.parse::<Ipv6Addr>().is_ok() {
None
@ -37,12 +36,7 @@ impl HstsEntry {
host: host,
include_subdomains: (subdomains == IncludeSubdomains::Included),
max_age: max_age,
timestamp: Some(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs(),
),
timestamp: Some(time::get_time().sec as u64),
})
}
}
@ -50,11 +44,7 @@ impl HstsEntry {
pub fn is_expired(&self) -> bool {
match (self.max_age, self.timestamp) {
(Some(max_age), Some(timestamp)) => {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default() -
Duration::from_secs(timestamp) >=
max_age
(time::get_time().sec as u64) - timestamp >= max_age
},
_ => false,
@ -206,9 +196,11 @@ impl HstsList {
IncludeSubdomains::NotIncluded
};
if let Some(entry) =
HstsEntry::new(host.to_owned(), include_subdomains, Some(header.max_age()))
{
if let Some(entry) = HstsEntry::new(
host.to_owned(),
include_subdomains,
Some(header.max_age().as_secs()),
) {
info!("adding host {} to the strict transport security list", host);
info!("- max-age {}", header.max_age().as_secs());
if header.include_subdomains() {

View file

@ -11,7 +11,7 @@ use std::collections::HashMap;
use std::ops::Bound;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::time::SystemTime;
use headers::{
CacheControl, ContentRange, Expires, HeaderMapExt, LastModified, Pragma, Range, Vary,
@ -30,6 +30,7 @@ use net_traits::{FetchMetadata, Metadata, ResourceFetchTiming};
use servo_arc::Arc;
use servo_config::pref;
use servo_url::ServoUrl;
use time::{Duration, Timespec, Tm};
use tokio::sync::mpsc::{unbounded_channel as unbounded, UnboundedSender as TokioSender};
use crate::fetch::methods::{Data, DoneChannel};
@ -74,7 +75,7 @@ struct MeasurableCachedResource {
raw_status: Option<(u16, Vec<u8>)>,
url_list: Vec<ServoUrl>,
expires: Duration,
last_validated: SystemTime,
last_validated: Tm,
}
impl MallocSizeOf for CachedResource {
@ -180,11 +181,11 @@ fn calculate_response_age(response: &Response) -> Duration {
if let Some(secs) = response.headers.get(header::AGE) {
if let Ok(seconds_string) = secs.to_str() {
if let Ok(secs) = seconds_string.parse::<i64>() {
return Duration::from_secs(secs as u64);
return Duration::seconds(secs);
}
}
}
Duration::ZERO
Duration::seconds(0i64)
}
/// Determine the expiry date from relevant headers,
@ -195,10 +196,14 @@ fn get_response_expiry(response: &Response) -> Duration {
if let Some(directives) = response.headers.typed_get::<CacheControl>() {
if directives.no_cache() {
// Requires validation on first use.
return Duration::ZERO;
return Duration::seconds(0i64);
} else {
if let Some(max_age) = directives.max_age().or(directives.s_max_age()) {
return max_age.checked_sub(age).unwrap_or(Duration::ZERO);
if let Some(secs) = directives.max_age().or(directives.s_max_age()) {
let max_age = Duration::from_std(secs).unwrap();
if max_age < age {
return Duration::seconds(0i64);
}
return max_age - age;
}
}
}
@ -206,15 +211,18 @@ fn get_response_expiry(response: &Response) -> Duration {
Some(t) => {
// store the period of time from now until expiry
let t: SystemTime = t.into();
let desired = t.duration_since(UNIX_EPOCH).unwrap_or_default();
let current = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let t = t.duration_since(SystemTime::UNIX_EPOCH).unwrap();
let desired = Timespec::new(t.as_secs() as i64, 0);
let current = time::now().to_timespec();
return desired.checked_sub(current).unwrap_or(Duration::ZERO);
if desired > current {
return desired - current;
} else {
return Duration::seconds(0i64);
}
},
// Malformed Expires header, shouldn't be used to construct a valid response.
None if response.headers.contains_key(header::EXPIRES) => return Duration::ZERO,
None if response.headers.contains_key(header::EXPIRES) => return Duration::seconds(0i64),
_ => {},
}
// Calculating Heuristic Freshness
@ -223,18 +231,19 @@ fn get_response_expiry(response: &Response) -> Duration {
// <https://tools.ietf.org/html/rfc7234#section-5.5.4>
// Since presently we do not generate a Warning header field with a 113 warn-code,
// 24 hours minus response age is the max for heuristic calculation.
let max_heuristic = Duration::from_secs(24 * 3600) - age;
let max_heuristic = Duration::hours(24) - age;
let heuristic_freshness = if let Some(last_modified) =
// If the response has a Last-Modified header field,
// caches are encouraged to use a heuristic expiration value
// that is no more than some fraction of the interval since that time.
response.headers.typed_get::<LastModified>()
{
let current = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let current = time::now().to_timespec();
let last_modified: SystemTime = last_modified.into();
let last_modified = last_modified.duration_since(UNIX_EPOCH).unwrap();
let last_modified = last_modified
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap();
let last_modified = Timespec::new(last_modified.as_secs() as i64, 0);
// A typical setting of this fraction might be 10%.
let raw_heuristic_calc = (current - last_modified) / 10;
let result = if raw_heuristic_calc < max_heuristic {
@ -259,7 +268,7 @@ fn get_response_expiry(response: &Response) -> Duration {
}
}
// Requires validation upon first use as default.
Duration::ZERO
Duration::seconds(0i64)
}
/// Request Cache-Control Directives
@ -271,19 +280,24 @@ fn get_expiry_adjustment_from_request_headers(request: &Request, expires: Durati
};
if let Some(max_age) = directive.max_stale() {
return expires + max_age;
return expires + Duration::from_std(max_age).unwrap();
}
if let Some(max_age) = directive.max_age() {
let max_age = Duration::from_std(max_age).unwrap();
if expires > max_age {
return Duration::ZERO;
return Duration::min_value();
}
return expires - max_age;
}
if let Some(min_fresh) = directive.min_fresh() {
return expires.checked_sub(min_fresh).unwrap_or(Duration::ZERO);
let min_fresh = Duration::from_std(min_fresh).unwrap();
if expires < min_fresh {
return Duration::min_value();
}
return expires - min_fresh;
}
if directive.no_cache() || directive.no_store() {
return Duration::ZERO;
return Duration::min_value();
}
expires
@ -327,15 +341,8 @@ fn create_cached_response(
response.aborted = cached_resource.aborted.clone();
let expires = cached_resource.data.expires;
let adjusted_expires = get_expiry_adjustment_from_request_headers(request, expires);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let last_validated = cached_resource
.data
.last_validated
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let now = Duration::seconds(time::now().to_timespec().sec);
let last_validated = Duration::seconds(cached_resource.data.last_validated.to_timespec().sec);
let time_since_validated = now - last_validated;
// TODO: take must-revalidate into account <https://tools.ietf.org/html/rfc7234#section-5.2.2.1>
// TODO: if this cache is to be considered shared, take proxy-revalidate into account
@ -806,7 +813,7 @@ impl HttpCache {
let entry_key = CacheKey::from_servo_url(url);
if let Some(cached_resources) = self.entries.get_mut(&entry_key) {
for cached_resource in cached_resources.iter_mut() {
cached_resource.data.expires = Duration::ZERO;
cached_resource.data.expires = Duration::seconds(0i64);
}
}
}
@ -890,7 +897,7 @@ impl HttpCache {
raw_status: response.raw_status.clone(),
url_list: response.url_list.clone(),
expires: expiry,
last_validated: SystemTime::now(),
last_validated: time::now(),
}),
};
let entry = self.entries.entry(entry_key).or_insert_with(|| vec![]);

View file

@ -122,10 +122,7 @@ impl HttpState {
}
fn precise_time_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64
time::precise_time_ns() / (1000 * 1000)
}
// Step 3 of https://fetch.spec.whatwg.org/#concept-fetch.
@ -2111,6 +2108,7 @@ async fn cors_preflight_fetch(
.typed_get::<AccessControlMaxAge>()
.map(|acma| acma.into())
.unwrap_or(Duration::from_secs(5));
let max_age = max_age.as_secs() as u32;
// Substep 10
// TODO: Need to define what an imposed limit on max-age is

View file

@ -3,7 +3,6 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::collections::HashMap;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use net::hsts::{HstsEntry, HstsList};
use net_traits::IncludeSubdomains;
@ -13,7 +12,7 @@ fn test_hsts_entry_is_not_expired_when_it_has_no_timestamp() {
let entry = HstsEntry {
host: "mozilla.org".to_owned(),
include_subdomains: false,
max_age: Some(Duration::from_secs(20)),
max_age: Some(20),
timestamp: None,
};
@ -26,12 +25,7 @@ fn test_hsts_entry_is_not_expired_when_it_has_no_max_age() {
host: "mozilla.org".to_owned(),
include_subdomains: false,
max_age: None,
timestamp: Some(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs(),
),
timestamp: Some(time::get_time().sec as u64),
};
assert!(!entry.is_expired());
@ -42,14 +36,8 @@ fn test_hsts_entry_is_expired_when_it_has_reached_its_max_age() {
let entry = HstsEntry {
host: "mozilla.org".to_owned(),
include_subdomains: false,
max_age: Some(Duration::from_secs(10)),
timestamp: Some(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() -
20u64,
),
max_age: Some(10),
timestamp: Some(time::get_time().sec as u64 - 20u64),
};
assert!(entry.is_expired());
@ -118,7 +106,7 @@ fn test_push_entry_with_0_max_age_evicts_entry_from_list() {
vec![HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
Some(Duration::from_secs(500000u64)),
Some(500000u64),
)
.unwrap()],
);
@ -130,7 +118,7 @@ fn test_push_entry_with_0_max_age_evicts_entry_from_list() {
HstsEntry::new(
"mozilla.org".to_owned(),
IncludeSubdomains::NotIncluded,
Some(Duration::ZERO),
Some(0),
)
.unwrap(),
);
@ -379,14 +367,8 @@ fn test_hsts_list_with_expired_entry_is_not_is_host_secure() {
vec![HstsEntry {
host: "mozilla.org".to_owned(),
include_subdomains: false,
max_age: Some(Duration::from_secs(20)),
timestamp: Some(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() -
100u64,
),
max_age: Some(20),
timestamp: Some(time::get_time().sec as u64 - 100u64),
}],
);
let hsts_list = HstsList {