Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Audit use of unsafe in uri/mod.rs #417

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add comments to uses of unsafe in uri/mod.rs
The two uses of unsafe rely on postconditions in other functions which
are also documented to show this reliance.
  • Loading branch information
sbosnick committed Apr 25, 2020
commit 2850d83855e141d166cd6e6b3b982e271eef61a6
6 changes: 6 additions & 0 deletions src/uri/mod.rs
Original file line number Diff line number Diff line change
@@ -804,6 +804,8 @@ fn parse_full(mut s: Bytes) -> Result<Uri, InvalidUri> {
scheme.truncate(n);

// Allocate the ByteStr
// Safety: the postcondition on Scheme2::parse() means that
// s[0..n+3] is valid UTF-8. scheme is a subslice of s[0..n+3].
let val = unsafe { ByteStr::from_utf8_unchecked(scheme) };

Scheme2::Other(Box::new(val))
@@ -828,6 +830,10 @@ fn parse_full(mut s: Bytes) -> Result<Uri, InvalidUri> {

let authority = s.split_to(authority_end);
let authority = Authority {
// Safety: The postcondition on Authority::parse() means that
// s[0..authority_end] is valid UTF-8 after that call. The call
// to s.split_to() means that authority here is what s[0..authority_end]
// was after the call to Authority::parse().
data: unsafe { ByteStr::from_utf8_unchecked(authority) },
};

9 changes: 9 additions & 0 deletions src/uri/scheme.rs
Original file line number Diff line number Diff line change
@@ -253,6 +253,7 @@ impl Scheme2<usize> {
}
}

// Postcondition: On Ok(Scheme2::Other(n)) return, s[0..n+3] is valid UTF-8
pub(super) fn parse(s: &[u8]) -> Result<Scheme2<usize>, InvalidUri> {
if s.len() >= 7 {
// Check for HTTP
@@ -270,6 +271,9 @@ impl Scheme2<usize> {
}

if s.len() > 3 {
// The only Ok(Scheme2::Option(n)) return from this function is an
// early exit from this loop. This loop checks each byte in s against
// SCHEME_CHARS until until one of the early exit conditions.
for i in 0..s.len() {
let b = s[i];

@@ -290,10 +294,15 @@ impl Scheme2<usize> {
}

// Return scheme
// Postcondition: Every byte in s[0..i] has matched the
// _ arm so is valid UTF-8. s[i..i+3] matches "://" which
// is also valid UTF-8. Thus s[0..i+3] is valid UTF-8.
return Ok(Scheme2::Other(i));
}
// Invald scheme character, abort
0 => break,
// Valid scheme character: imples that b is a valid, single
// byte UTF-8 codepoint.
_ => {}
}
}