use url::Url;
use std::io::IoResult;
use time::{Tm, strptime};
use rfc2616::{is_token_item, is_separator, CR, LF, SP, HT, COLON};
use method::Method;
use self::serialization_utils::{normalise_header_name};
use self::ConsumeCommaLWSResult::{CommaConsumed, EndOfValue, ErrCommaNotFound};
use self::HeaderLineErr::{EndOfFile, EndOfHeaders, MalformedHeaderValue,
MalformedHeaderSyntax};
use self::HeaderValueByteIteratorState::{Normal, GotLF, Finished};
pub enum HeaderLineErr { EndOfFile, EndOfHeaders, MalformedHeaderValue, MalformedHeaderSyntax }
pub mod test_utils;
pub mod serialization_utils;
pub mod accept_ranges;
pub mod connection;
pub mod content_type;
pub mod etag;
pub mod host;
pub mod transfer_encoding;
pub type DeltaSeconds = u64;
#[deriving(Clone, PartialEq, Eq)]
pub enum ConsumeCommaLWSResult {
CommaConsumed,
EndOfValue,
ErrCommaNotFound,
}
pub trait HeaderEnum {
fn header_name(&self) -> String;
fn header_value(&self) -> String;
fn write_header<W: Writer>(&self, writer: &mut W) -> IoResult<()>;
fn value_from_stream<R: Reader>(name: String, input: &mut HeaderValueByteIterator<R>)
-> Option<Self>;
}
pub fn header_enum_from_stream<R: Reader, E: HeaderEnum>(reader: &mut R)
-> (Result<E, HeaderLineErr>, Option<u8>) {
enum State { Start, ReadingName, NameFinished, GotCR }
let mut state = State::Start;
let mut header_name = String::new();
loop {
state = match (state, reader.read_byte()) {
(State::Start, Ok(b)) | (State::ReadingName, Ok(b)) if is_token_item(b) => {
header_name.push(b as char);
State::ReadingName
},
(State::Start, Ok(b)) if b == CR => State::GotCR,
(State::Start, Ok(b)) | (State::GotCR, Ok(b)) if b == LF => {
return (Err(EndOfHeaders), None);
},
(_, Ok(b)) if b == SP => State::NameFinished,
(_, Ok(b)) if b == COLON => break,
(_, Ok(_)) => return (Err(MalformedHeaderSyntax), None),
(_, Err(_)) => return (Err(EndOfFile), None),
}
}
let mut iter = HeaderValueByteIterator::new(reader);
let header = HeaderEnum::value_from_stream(normalise_header_name(&header_name), &mut iter);
for _ in iter { }
match header {
Some(h) => (Ok(h), iter.next_byte),
None => {
debug!("malformed header value for {}", header_name[]);
(Err(MalformedHeaderValue), iter.next_byte)
},
}
}
#[deriving(PartialEq, Eq)]
enum HeaderValueByteIteratorState {
Normal, GotLF, Finished, }
pub struct HeaderValueByteIterator<'a, R: 'a> {
pub reader: &'a mut R,
pub next_byte: Option<u8>,
pub at_start: bool,
state: HeaderValueByteIteratorState,
}
impl<'a, R: Reader> HeaderValueByteIterator<'a, R> {
pub fn new(reader: &'a mut R) -> HeaderValueByteIterator<'a, R> {
HeaderValueByteIterator {
reader: reader,
next_byte: None,
at_start: true,
state: Normal,
}
}
#[inline]
pub fn verify_consumed(&mut self) -> bool {
self.consume_optional_lws();
self.next() == None
}
#[inline]
pub fn some_if_consumed<T>(&mut self, t: T) -> Option<T> {
if self.verify_consumed() {
Some(t)
} else {
None
}
}
fn collect_to_string(&mut self) -> String {
let mut out = String::new();
loop {
match self.next() {
None => break,
Some(b) => out.push(b as char),
}
}
out
}
pub fn consume_optional_lws(&mut self) {
let _ = self.consume_lws();
}
pub fn consume_lws(&mut self) -> bool {
let mut the_savages_gobbled_up_at_least_one_white_space_char = false;
loop {
match self.next() {
Some(b) if b == SP || b == HT => (),
Some(b) => {
assert_eq!(self.next_byte, None); self.next_byte = Some(b);
break;
},
None => break, };
the_savages_gobbled_up_at_least_one_white_space_char = true;
}
the_savages_gobbled_up_at_least_one_white_space_char
}
pub fn consume_comma_lws(&mut self) -> ConsumeCommaLWSResult {
self.consume_optional_lws();
match self.next() {
Some(b',') => {
self.consume_optional_lws();
CommaConsumed
},
Some(_) => {
ErrCommaNotFound
},
None => {
EndOfValue
}
}
}
pub fn read_quoted_string(&mut self, already_opened: bool) -> Option<String> {
enum State { Start, Normal, Escaping }
let mut state =
if already_opened { State::Normal } else { State::Start };
let mut output = String::new();
loop {
match self.next() {
None => return None,
Some(b) => {
state = match state {
State::Start if b == b'"' => State::Normal,
State::Start => return None,
State::Normal if b == b'\\' => State::Escaping,
State::Normal if b == b'"' => break,
State::Normal | State::Escaping => {
output.push(b as char);
State::Normal
},
}
}
}
}
Some(output)
}
fn read_parameter(&mut self, already_read_semicolon: bool) -> Option<(String, String)> {
if !already_read_semicolon && self.next() != Some(b';') {
return None;
}
self.consume_optional_lws();
let key = match self.read_token() {
Some(t) => t,
None => return None,
};
self.consume_optional_lws();
if self.next() != Some(b'=') {
return None;
}
self.consume_optional_lws();
let value = match self.read_token_or_quoted_string() {
Some(t) => t,
None => return None,
};
self.consume_optional_lws();
Some((key, value))
}
fn read_parameters(&mut self) -> Option<Vec<(String, String)>> {
let mut result = Vec::new();
loop {
match self.next() {
Some(b) if b == SP || b == HT => (),
Some(b) if b == b';' => {
match self.read_parameter(true) {
Some(parameter) => result.push(parameter),
None => return None,
}
},
Some(b) => {
assert_eq!(self.next_byte, None);
self.next_byte = Some(b);
return Some(result);
},
None => return Some(result),
}
}
}
pub fn read_token_or_quoted_string(&mut self) -> Option<String> {
let mut output = String::new();
match self.next() {
Some(b'"') => {
enum State { Normal, Escaping }
let mut state = State::Normal;
loop {
match self.next() {
None => return None,
Some(b) => state = match state {
State::Normal if b == b'\\' => State::Escaping,
State::Normal if b == b'"' => break,
State::Normal | State::Escaping => {
output.push(b as char);
State::Normal
},
}
}
}
return Some(output);
},
Some(b) => self.next_byte = Some(b),
None => return None,
}
loop {
match self.next() {
None => break,
Some(b) if is_separator(b) => {
assert_eq!(self.next_byte, None);
self.next_byte = Some(b);
break;
},
Some(b) if is_token_item(b) => {
output.push(b as char);
},
Some(b) => {
println!("TODO: what should be done with a token ended with a non-separator? \
(With token {}, {} was read.)", output, b as char);
}
}
}
if output.len() == 0 {
None
} else {
Some(output)
}
}
pub fn read_token(&mut self) -> Option<String> {
let mut output = String::new();
loop {
match self.next() {
None => break,
Some(b) if is_separator(b) => {
assert_eq!(self.next_byte, None);
self.next_byte = Some(b);
break;
},
Some(b) if is_token_item(b) => {
output.push(b as char);
},
Some(b) => {
println!("TODO: what should be done with a token ended with a non-separator? \
(With token {}, {} was read.)", output, b as char);
}
}
}
if output.len() == 0 {
None
} else {
Some(output)
}
}
}
impl<'a, R: Reader> Iterator<u8> for HeaderValueByteIterator<'a, R> {
fn next(&mut self) -> Option<u8> {
if self.state == Finished {
return None;
}
loop {
let b = match self.next_byte {
Some(b) => {
self.next_byte = None;
b
},
None => match self.reader.read_byte() {
Err(_) => {
self.state = Finished;
return None
},
Ok(b) => b,
}
};
match self.state {
Normal if b == SP || b == HT => {
if self.at_start {
continue;
} else {
return Some(b);
}
},
Normal if b == CR => {
continue;
},
Normal if b == LF => {
self.state = GotLF;
continue;
},
GotLF if b == SP || b == HT => {
self.state = Normal;
return Some(b);
},
GotLF => {
self.next_byte = Some(b);
self.state = Finished;
return None;
},
Normal => {
self.at_start = false;
return Some(b);
},
Finished => unreachable!(),
}
}
}
}
pub trait HeaderConvertible: PartialEq + Clone {
fn from_stream<R: Reader>(reader: &mut HeaderValueByteIterator<R>) -> Option<Self>;
fn to_stream<W: Writer>(&self, writer: &mut W) -> IoResult<()> {
let s = self.http_value();
writer.write(s.as_bytes())
}
fn http_value(&self) -> String;
}
pub trait CommaListHeaderConvertible: HeaderConvertible {}
impl<T: CommaListHeaderConvertible> HeaderConvertible for Vec<T> {
fn from_stream<R: Reader>(reader: &mut HeaderValueByteIterator<R>) -> Option<Vec<T>> {
let mut result = Vec::new();
loop {
match HeaderConvertible::from_stream(reader) {
Some(h) => result.push(h),
None => return None,
};
match reader.consume_comma_lws() {
CommaConsumed => continue,
EndOfValue => break,
ErrCommaNotFound => return None,
}
}
Some(result)
}
fn to_stream<W: Writer>(&self, writer: &mut W) -> IoResult<()> {
for (i, item) in self.iter().enumerate() {
if i != 0 {
try!(writer.write(b", "))
}
try!(item.to_stream(writer))
}
Ok(())
}
fn http_value(&self) -> String {
let mut out = String::new();
for (i, item) in self.iter().enumerate() {
if i != 0 {
out.push_str(", ");
}
out.push_str(item.http_value()[])
}
out
}
}
impl HeaderConvertible for String {
fn from_stream<R: Reader>(reader: &mut HeaderValueByteIterator<R>) -> Option<String> {
Some(reader.collect_to_string())
}
fn to_stream<W: Writer>(&self, writer: &mut W) -> IoResult<()> {
writer.write(self.as_bytes())
}
fn http_value(&self) -> String {
self.clone()
}
}
impl HeaderConvertible for uint {
fn from_stream<R: Reader>(reader: &mut HeaderValueByteIterator<R>) -> Option<uint> {
from_str(reader.collect_to_string()[])
}
fn http_value(&self) -> String {
format!("{}", self)
}
}
impl HeaderConvertible for Url {
fn from_stream<R: Reader>(reader: &mut HeaderValueByteIterator<R>) -> Option<Url> {
Url::parse(reader.collect_to_string()[]).ok()
}
fn http_value(&self) -> String {
format!("{}", self)
}
}
impl CommaListHeaderConvertible for Method {}
impl HeaderConvertible for Method {
fn from_stream<R: Reader>(reader: &mut HeaderValueByteIterator<R>) -> Option<Method> {
match reader.read_token() {
Some(s) => Method::from_str_or_new(s[]),
None => None,
}
}
fn http_value(&self) -> String {
format!("{}", self)
}
}
impl HeaderConvertible for Tm {
fn from_stream<R: Reader>(reader: &mut HeaderValueByteIterator<R>) -> Option<Tm> {
let value = reader.collect_to_string();
match strptime(value[], "%a, %d %b %Y %T %Z") { Ok(time) => return Some(time),
Err(_) => ()
}
match strptime(value[], "%A, %d-%b-%y %T %Z") { Ok(time) => return Some(time),
Err(_) => ()
}
match strptime(value[], "%c") { Ok(time) => Some(time),
Err(_) => None
}
}
fn http_value(&self) -> String {
self.to_utc().strftime("%a, %d %b %Y %T GMT").unwrap().to_string()
}
}
#[cfg(test)]
mod test {
use time::Tm;
use headers::test_utils::{from_stream_with_str, to_stream_into_str};
use super::HeaderConvertible;
#[test]
fn test_from_stream_str() {
assert_eq!(from_stream_with_str(""), Some(String::new()));
assert_eq!(from_stream_with_str("foo \"bar baz\", yay"),
Some(String::from_str("foo \"bar baz\", yay")));
}
#[test]
fn test_http_value_str() {
assert_eq!((String::new()).http_value(), String::new());
assert_eq!((String::from_str("foo \"bar baz\", yay")).http_value(), String::from_str("foo \"bar baz\", yay"));
}
#[test]
fn test_to_stream_str() {
let s = String::new();
assert_eq!(to_stream_into_str(&s), String::new());
let s = String::from_str("foo \"bar baz\", yay");
assert_eq!(to_stream_into_str(&s), String::from_str("foo \"bar baz\", yay"));
}
#[test]
fn test_from_stream_uint() {
assert_eq!(from_stream_with_str::<uint>("foo bar"), None);
assert_eq!(from_stream_with_str::<uint>("-1"), None);
assert_eq!(from_stream_with_str("0"), Some(0u));
assert_eq!(from_stream_with_str("123456789"), Some(123456789u));
}
#[test]
fn test_http_value_uint() {
assert_eq!(0u.http_value(), String::from_str("0"));
assert_eq!(123456789u.http_value(), String::from_str("123456789"));
}
#[test]
fn test_to_stream_uint() {
assert_eq!(to_stream_into_str(&0u), String::from_str("0"));
assert_eq!(to_stream_into_str(&123456789u), String::from_str("123456789"));
}
fn sample_tm() -> Tm {
Tm {
tm_sec: 37,
tm_min: 49,
tm_hour: 8,
tm_mday: 6,
tm_mon: 10,
tm_year: 94,
tm_wday: 0,
tm_yday: 0,
tm_isdst: 0,
tm_utcoff: 0,
tm_nsec: 0
}
}
#[test]
fn test_from_stream_rfc822() {
assert_eq!(from_stream_with_str("Sun, 06 Nov 1994 08:49:37 GMT"), Some(sample_tm()));
}
#[test]
fn test_from_stream_rfc850() {
assert_eq!(from_stream_with_str("Sunday, 06-Nov-94 08:49:37 GMT"), Some(sample_tm()));
}
#[test]
fn test_from_stream_asctime() {
assert_eq!(from_stream_with_str("Sun Nov 6 08:49:37 1994"), Some(sample_tm()));
}
#[test]
fn test_from_stream_asctime_remove_lws() {
assert_eq!(from_stream_with_str::<Tm>("Sun Nov 6 08:49:37 1994"), None);
}
#[test]
fn test_from_stream_asctime_double_digit_date() {
let mut tm = sample_tm();
tm.tm_mday = 13;
assert_eq!(from_stream_with_str("Sun Nov 13 08:49:37 1994"), Some(tm));
}
#[test]
fn test_http_value() {
assert_eq!(sample_tm().http_value(), String::from_str("Sun, 06 Nov 1994 08:49:37 GMT"));
}
#[test]
fn test_to_stream() {
assert_eq!(to_stream_into_str(&sample_tm()), String::from_str("Sun, 06 Nov 1994 08:49:37 GMT"));
}
}
macro_rules! headers_mod {
{
#[$attr:meta]
pub mod $mod_name:ident;
num_headers: $num_headers:pat;
$(
$num_id:pat,
$output_name:expr,
$input_name:pat,
$caps_ident:ident,
$lower_ident:ident,
$htype:ty;
)*
} => {
pub mod $mod_name {
#[$attr]
#[allow(unused_imports)]
use std::io::{BufReader, IoResult};
use std::ascii::OwnedAsciiExt;
use time;
use collections::tree_map::{TreeMap, Entries};
use headers;
use headers::{HeaderEnum, HeaderConvertible, HeaderValueByteIterator};
use self::Header::{$($caps_ident),+};
use self::Header::ExtensionHeader;
pub enum Header {
$($caps_ident($htype),)*
ExtensionHeader(String, String),
}
#[deriving(Clone)]
pub struct HeaderCollection {
$(pub $lower_ident: Option<$htype>,)*
pub extensions: TreeMap<String, String>,
}
impl HeaderCollection {
pub fn new() -> HeaderCollection {
HeaderCollection {
$($lower_ident: None,)*
extensions: TreeMap::new(),
}
}
pub fn insert(&mut self, header: Header) {
match header {
$($caps_ident(value) => self.$lower_ident = Some(value),)*
ExtensionHeader(key, value) => { self.extensions.insert(key, value); },
}
}
pub fn insert_raw(&mut self, name: String, value: &[u8]) -> Result<(), ()> {
let mut reader = BufReader::new(value);
let mut value_iter = HeaderValueByteIterator::new(&mut reader);
match HeaderEnum::value_from_stream(name, &mut value_iter) {
Some(h) => {
self.insert(h);
Ok(())
},
None => Err(())
}
}
pub fn iter<'a>(&'a self) -> HeaderCollectionIterator<'a> {
HeaderCollectionIterator {
pos: 0,
coll: self,
ext_iter: None
}
}
pub fn write_all<W: Writer>(&self, writer: &mut W) -> IoResult<()> {
for header in self.iter() {
try!(header.write_header(&mut *writer));
}
writer.write(b"\r\n")
}
}
pub struct HeaderCollectionIterator<'a> {
pos: uint,
coll: &'a HeaderCollection,
ext_iter: Option<Entries<'a, String, String>>
}
impl<'a> Iterator<Header> for HeaderCollectionIterator<'a> {
fn next(&mut self) -> Option<Header> {
loop {
self.pos += 1;
match self.pos - 1 {
$($num_id => match self.coll.$lower_ident {
Some(ref v) => return Some($caps_ident(v.clone())),
None => continue,
},)*
$num_headers => {
self.ext_iter = Some(self.coll.extensions.iter());
continue
},
_ => match self.ext_iter.as_mut().unwrap().next() {
Some((k, v)) =>
return Some(ExtensionHeader(k.clone(), v.clone())),
None => return None,
},
}
}
}
}
impl HeaderEnum for Header {
fn header_name(&self) -> String {
match *self {
$($caps_ident(_) => String::from_str($output_name),)*
ExtensionHeader(ref name, _) => name.clone(),
}
}
fn header_value(&self) -> String {
match *self {
$($caps_ident(ref h) => h.http_value(),)*
ExtensionHeader(_, ref value) => value.clone(),
}
}
fn write_header<W: Writer>(&self, writer: &mut W) -> IoResult<()> {
match *self {
ExtensionHeader(ref name, ref value) => {
return write!(&mut *writer as &mut Writer,
"{}: {}\r\n", *name, *value);
},
_ => (),
}
try!(write!(&mut *writer as &mut Writer, "{}: ", match *self {
$($caps_ident(_) => $output_name,)*
ExtensionHeader(..) => unreachable!(), }));
try!(match *self {
$($caps_ident(ref h) => h.to_stream(writer),)*
ExtensionHeader(..) => unreachable!(), });
write!(&mut *writer as &mut Writer, "\r\n")
}
fn value_from_stream<R: Reader>(name: String, value: &mut HeaderValueByteIterator<R>)
-> Option<Header> {
match name.clone().into_ascii_lower()[] {
$($input_name => match HeaderConvertible::from_stream(value) {
Some(v) => Some($caps_ident(v)),
None => None,
},)*
_ => Some(ExtensionHeader(name, value.collect_to_string())),
}
}
}
}
}
}
headers_mod! {
#[doc = "Request whatnottery."]
pub mod request;
num_headers: 38;
0, "Cache-Control", "cache-control", CacheControl, cache_control, String;
1, "Connection", "connection", Connection, connection, Vec<headers::connection::Connection>;
2, "Date", "date", Date, date, time::Tm;
3, "Pragma", "pragma", Pragma, pragma, String;
4, "Trailer", "trailer", Trailer, trailer, String;
5, "Transfer-Encoding", "transfer-encoding", TransferEncoding, transfer_encoding, Vec<headers::transfer_encoding::TransferCoding>;
6, "Upgrade", "upgrade", Upgrade, upgrade, String;
7, "Via", "via", Via, via, String;
8, "Warning", "warning", Warning, warning, String;
9, "Accept", "accept", Accept, accept, String;
10, "Accept-Charset", "accept-charset", AcceptCharset, accept_charset, String;
11, "Accept-Encoding", "accept-encoding", AcceptEncoding, accept_encoding, String;
12, "Accept-Language", "accept-language", AcceptLanguage, accept_language, String;
13, "Authorization", "authorization", Authorization, authorization, String;
14, "Expect", "expect", Expect, expect, String;
15, "From", "from", From, from, String;
16, "Host", "host", Host, host, headers::host::Host;
17, "If-Match", "if-match", IfMatch, if_match, String;
18, "If-Modified-Since", "if-modified-since", IfModifiedSince, if_modified_since, time::Tm;
19, "If-None-Match", "if-none-match", IfNoneMatch, if_none_match, String;
20, "If-Range", "if-range", IfRange, if_range, String;
21, "If-Unmodified-Since", "if-unmodified-since", IfUnmodifiedSince, if_unmodified_since, time::Tm;
22, "Max-Forwards", "max-forwards", MaxForwards, max_forwards, uint;
23, "Proxy-Authorization", "proxy-authorization", ProxyAuthorization, proxy_authorization, String;
24, "Range", "range", Range, range, String;
25, "Referer", "referer", Referer, referer, String;
26, "TE", "te", Te, te, String;
27, "User-Agent", "user-agent", UserAgent, user_agent, String;
28, "Allow", "allow", Allow, allow, Vec<::method::Method>;
29, "Content-Encoding", "content-encoding", ContentEncoding, content_encoding, String;
30, "Content-Language", "content-language", ContentLanguage, content_language, String;
31, "Content-Length", "content-length", ContentLength, content_length, uint;
32, "Content-Location", "content-location", ContentLocation, content_location, String;
33, "Content-MD5", "content-md5", ContentMd5, content_md5, String;
34, "Content-Range", "content-range", ContentRange, content_range, String;
35, "Content-Type", "content-type", ContentType, content_type, headers::content_type::MediaType;
36, "Expires", "expires", Expires, expires, time::Tm;
37, "Last-Modified", "last-modified", LastModified, last_modified, time::Tm;
}
headers_mod! {
#[doc = "Response whatnottery."]
pub mod response;
num_headers: 30;
0, "Cache-Control", "cache-control", CacheControl, cache_control, String;
1, "Connection", "connection", Connection, connection, Vec<headers::connection::Connection>;
2, "Date", "date", Date, date, time::Tm;
3, "Pragma", "pragma", Pragma, pragma, String;
4, "Trailer", "trailer", Trailer, trailer, String;
5, "Transfer-Encoding", "transfer-encoding", TransferEncoding, transfer_encoding, Vec<headers::transfer_encoding::TransferCoding>;
6, "Upgrade", "upgrade", Upgrade, upgrade, String;
7, "Via", "via", Via, via, String;
8, "Warning", "warning", Warning, warning, String;
9, "Accept-Patch", "accept-patch", AcceptPatch, accept_patch, String;
10, "Accept-Ranges", "accept-ranges", AcceptRanges, accept_ranges, headers::accept_ranges::AcceptableRanges;
11, "Age", "age", Age, age, String;
12, "ETag", "etag", ETag, etag, headers::etag::EntityTag;
13, "Location", "location", Location, location, ::url::Url;
14, "Proxy-Authenticate", "proxy-authenticate", ProxyAuthenticate, proxy_authenticate, String;
15, "Retry-After", "retry-after", RetryAfter, retry_after, String;
16, "Server", "server", Server, server, String;
17, "Vary", "vary", Vary, vary, String;
18, "WWW-Authenticate", "www-authenticate", WwwAuthenticate, www_authenticate, String;
19, "Allow", "allow", Allow, allow, Vec<::method::Method>;
20, "Content-Encoding", "content-encoding", ContentEncoding, content_encoding, String;
21, "Content-Language", "content-language", ContentLanguage, content_language, String;
22, "Content-Length", "content-length", ContentLength, content_length, uint;
23, "Content-Location", "content-location", ContentLocation, content_location, String;
24, "Content-MD5", "content-md5", ContentMd5, content_md5, String;
25, "Content-Range", "content-range", ContentRange, content_range, String;
26, "Content-Type", "content-type", ContentType, content_type, headers::content_type::MediaType;
27, "Expires", "expires", Expires, expires, String; 28, "Last-Modified", "last-modified", LastModified, last_modified, time::Tm;
29, "Access-Control-Allow-Origin", "access-control-allow-origin", AccessControlAllowOrigin, access_control_allow_origin, String;
}