<commit_before>use collections::str::{from_utf8};

/// Checks if the nickname is valid
pub fn valid_nick(nick: &str) -> bool {
    // <nick>       ::= <letter> { <letter> | <number> | <special> }
    //<special>    ::= '-' | '[' | ']' | '\' | '`' | '^' | '{' | '}'
    //
    // As of http://tools.ietf.org/html/rfc2812#section-2.3.1
    // nickname   =  ( letter / special ) *8( letter / digit / special / "-" )
    // special    =  %x5B-60 / %x7B-7D
    for (i, char) in nick.chars().enumerate() {
        if i == 9 {
            return false
        }
        match char {
            'a'..'z' | 'A'..'Z' | '\x5B'..'\x60' | '\x7B'..'\x7D'
                if i == 0 => {},
            'a'..'z' | 'A'..'Z' | '0'..'9' | '\x5B'..'\x60' | '\x7B'..'\x7D' | '-'
                if i != 0 => {},
            _ => return false
        }
    }
    true
}

/// Validates the raw nickname and converts it into a string.
pub fn verify_nick<'a>(nick: &'a [u8]) -> Option<&'a str> {
    match from_utf8(nick) {
        None => None,
        Some(nick) => if valid_nick(nick) { Some(nick) } else { None }
    }
}

pub fn valid_channel(channel: &str) -> bool {
    for (i, char) in channel.chars().enumerate() {
        match char {
            '#' | '&' if i == 0 => {},
            _ if i == 0 => { return false },
            ' ' | '\x07' | ',' => { return false }
            _ => {}
        }
    }
    true
}

/// Validates the raw channel name and converts it into a string.
pub fn verify_channel<'a>(channel: &'a [u8]) -> Option<&'a str> {
    match from_utf8(channel) {
        None => None,
        Some(channel) =>
            if valid_channel(channel) {
                Some(channel)
            } else { None }
    }
}

pub enum Receiver<'a> {
    ChannelName(&'a str),
    NickName(&'a str),
    InvalidReceiver(&'a [u8])
}

/// Validates the raw channel name and converts it into a string.
pub fn verify_receiver<'a>(recv: &'a [u8]) -> Receiver<'a> {
    match from_utf8(recv) {
        None => InvalidReceiver(recv),
        Some(name) =>
            if valid_channel(name) {
                ChannelName(name)
            } else if valid_nick(name) {
                NickName(name)
            } else { InvalidReceiver(recv) }
    }
}

#[deriving(Hash, PartialEq, Eq)]
pub struct HostMask {
    mask: String
}

impl HostMask {
    pub fn new(mask: String) -> HostMask {
        HostMask {
            mask: mask
        }
    }
    fn matches(&self, hostname: &str) -> bool {
        let mut name_chars = hostname.chars().peekable();
        let mask = self.mask.as_slice();
        for (c, next) in mask.chars().zip({let mut n = mask.chars(); n.next(); n}) {
            match c {
                '*' => { while match name_chars.peek() {
                    Some(&name_cha) => name_cha != next,
                    None => false } { let _ = name_chars.next(); }
                },
                cha => match name_chars.next() {
                    None => return false,
                    Some(name_cha) => if cha != name_cha { return false }
                }
            }
        }
        true
    }
}

#[cfg(test)]
mod tests {
	use super::{valid_nick, valid_channel, HostMask};
	#[test]
	/// Test the nickname validation function
	fn test_nickname_validation() {
		assert!(valid_nick("FooBar123"))
		assert_eq!(valid_nick("FooBar1234"), false)
		assert_eq!(valid_nick("1FooBar12"), false)
	}
	#[test]
	/// Test the nickname validation function
	fn test_channel_name_validation() {
		assert!(valid_channel("#Foobar"))
		assert_eq!(valid_channel("Foobar"), false)
		assert_eq!(valid_channel("#Foo,bar"), false)
		assert_eq!(valid_channel("Foo bar"), false)
	}

    #[test]
    /// Test the hostname masks
	fn test_masks() {
		assert!(HostMask::new("*!*@*.com".to_string()).matches("a!b@example.com"))
		assert!(!HostMask::new("*!*@*.com".to_string()).matches("*!*@*.edu"))
		assert!(HostMask::new("*!*@example.com".to_string()).matches("a!b@example.com"))
		assert!(HostMask::new("foo!*@*.com".to_string()).matches("foo!bar@example.com"))
		assert!(!HostMask::new("foo!*@*.com".to_string()).matches("baz!bar@example.com"))
		assert!(HostMask::new("*!bar@*.com".to_string()).matches("foo!bar@example.com"))
		assert!(!HostMask::new("*!bar@*.com".to_string()).matches("foo!baz@example.com"))
	}

}
<commit_msg>fix host mask matcher<commit_after>use collections::str::{from_utf8};

/// Checks if the nickname is valid
pub fn valid_nick(nick: &str) -> bool {
    // <nick>       ::= <letter> { <letter> | <number> | <special> }
    //<special>    ::= '-' | '[' | ']' | '\' | '`' | '^' | '{' | '}'
    //
    // As of http://tools.ietf.org/html/rfc2812#section-2.3.1
    // nickname   =  ( letter / special ) *8( letter / digit / special / "-" )
    // special    =  %x5B-60 / %x7B-7D
    for (i, char) in nick.chars().enumerate() {
        if i == 9 {
            return false
        }
        match char {
            'a'..'z' | 'A'..'Z' | '\x5B'..'\x60' | '\x7B'..'\x7D'
                if i == 0 => {},
            'a'..'z' | 'A'..'Z' | '0'..'9' | '\x5B'..'\x60' | '\x7B'..'\x7D' | '-'
                if i != 0 => {},
            _ => return false
        }
    }
    true
}

/// Validates the raw nickname and converts it into a string.
pub fn verify_nick<'a>(nick: &'a [u8]) -> Option<&'a str> {
    match from_utf8(nick) {
        None => None,
        Some(nick) => if valid_nick(nick) { Some(nick) } else { None }
    }
}

pub fn valid_channel(channel: &str) -> bool {
    for (i, char) in channel.chars().enumerate() {
        match char {
            '#' | '&' if i == 0 => {},
            _ if i == 0 => { return false },
            ' ' | '\x07' | ',' => { return false }
            _ => {}
        }
    }
    true
}

/// Validates the raw channel name and converts it into a string.
pub fn verify_channel<'a>(channel: &'a [u8]) -> Option<&'a str> {
    match from_utf8(channel) {
        None => None,
        Some(channel) =>
            if valid_channel(channel) {
                Some(channel)
            } else { None }
    }
}

pub enum Receiver<'a> {
    ChannelName(&'a str),
    NickName(&'a str),
    InvalidReceiver(&'a [u8])
}

/// Validates the raw channel name and converts it into a string.
pub fn verify_receiver<'a>(recv: &'a [u8]) -> Receiver<'a> {
    match from_utf8(recv) {
        None => InvalidReceiver(recv),
        Some(name) =>
            if valid_channel(name) {
                ChannelName(name)
            } else if valid_nick(name) {
                NickName(name)
            } else { InvalidReceiver(recv) }
    }
}

#[deriving(Hash, PartialEq, Eq)]
/// A host mask in the form "*!*@*.*"
pub struct HostMask {
    mask: String
}

impl HostMask {
    pub fn new(mask: String) -> HostMask {
        HostMask {
            mask: mask
        }
    }
    /// checks if the host mask matches another mask
    ///
    /// "*!*@*.com" would match "a!b@example.com"
    pub fn matches(&self, mask: &str) -> bool {
        let mut mask_chars = mask.chars().peekable();
        let mut chars = self.mask.as_slice().chars().peekable();
        for c in chars {
            match c {
                '*' => match chars.peek() {
                    // Consume all chars until next match is found
                    Some(next) => while match mask_chars.peek() {
                        Some(mask_cha) => mask_cha != next,
                        None => false } { let _ = mask_chars.next(); },
                    // * at end of the string matches the whole rest
                    None => return true
                },
                cha => match mask_chars.next() {
                    None => return false,
                    Some(mask_cha) => if cha != mask_cha { return false }
                }
            }
        }
        !mask_chars.next().is_some()
    }
}

#[cfg(test)]
mod tests {
	use super::{valid_nick, valid_channel, HostMask};
	#[test]
	/// Test the nickname validation function
	fn test_nickname_validation() {
		assert!(valid_nick("FooBar123"))
		assert_eq!(valid_nick("FooBar1234"), false)
		assert_eq!(valid_nick("1FooBar12"), false)
	}
	#[test]
	/// Test the nickname validation function
	fn test_channel_name_validation() {
		assert!(valid_channel("#Foobar"))
		assert_eq!(valid_channel("Foobar"), false)
		assert_eq!(valid_channel("#Foo,bar"), false)
		assert_eq!(valid_channel("Foo bar"), false)
	}

    #[test]
    /// Test the hostname masks
	fn test_masks() {
		assert!(HostMask::new("*!*@*.com".to_string()).matches("a!b@example.com"))
		assert!(!HostMask::new("*!*@*.com".to_string()).matches("*!*@*.edu"))
		assert!(!HostMask::new("*!*@*.com".to_string()).matches("*!*@*.cop"))
		assert!(!HostMask::new("*!*@*.com".to_string()).matches("*!*@*.coma"))
		assert!(HostMask::new("*!*@example.com".to_string()).matches("a!b@example.com"))
		assert!(HostMask::new("foo!*@*.com".to_string()).matches("foo!bar@example.com"))
		assert!(!HostMask::new("foo!*@*.com".to_string()).matches("baz!bar@example.com"))
		assert!(HostMask::new("*!bar@*.com".to_string()).matches("foo!bar@example.com"))
		assert!(!HostMask::new("*!bar@*.com".to_string()).matches("foo!baz@example.com"))
	}

}
<|endoftext|>


<commit_before>extern crate security_framework;
extern crate security_framework_sys;
extern crate tempdir;

use self::security_framework::base;
use self::security_framework::certificate::SecCertificate;
use self::security_framework::identity::SecIdentity;
use self::security_framework::import_export::Pkcs12ImportOptions;
use self::security_framework::secure_transport::{self, SslContext, ProtocolSide, ConnectionType,
                                                 SslProtocol, ClientBuilder};
use self::security_framework::os::macos::keychain::{self, KeychainSettings};
use self::security_framework_sys::base::errSecIO;
use self::tempdir::TempDir;
use std::fmt;
use std::io;
use std::error;

use Protocol;

fn convert_protocol(protocol: Protocol) -> SslProtocol {
    match protocol {
        Protocol::Sslv3 => SslProtocol::Ssl3,
        Protocol::Tlsv10 => SslProtocol::Tls1,
        Protocol::Tlsv11 => SslProtocol::Tls11,
        Protocol::Tlsv12 => SslProtocol::Tls12,
        Protocol::__NonExhaustive => unreachable!(),
    }
}

fn protocol_min_max(protocols: &[Protocol]) -> (SslProtocol, SslProtocol) {
    let mut min = Protocol::Tlsv12;
    let mut max = Protocol::Sslv3;
    for protocol in protocols {
        if (*protocol as usize) < (min as usize) {
            min = *protocol;
        }
        if (*protocol as usize) > (max as usize) {
            max = *protocol;
        }
    }
    (convert_protocol(min), convert_protocol(max))
}

pub struct Error(base::Error);

impl error::Error for Error {
    fn description(&self) -> &str {
        error::Error::description(&self.0)
    }

    fn cause(&self) -> Option<&error::Error> {
        error::Error::cause(&self.0)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.0, fmt)
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.0, fmt)
    }
}

impl From<base::Error> for Error {
    fn from(error: base::Error) -> Error {
        Error(error)
    }
}

pub struct Pkcs12 {
    identity: SecIdentity,
    chain: Vec<SecCertificate>,
}

impl Pkcs12 {
    pub fn from_der(buf: &[u8], pass: &str) -> Result<Pkcs12, Error> {
        let dir = match TempDir::new("native-tls") {
            Ok(dir) => dir,
            Err(_) => return Err(Error(base::Error::from(errSecIO))),
        };

        let mut keychain = try!(keychain::CreateOptions::new()
            .password(pass)
            .create(dir.path().join("tmp.keychain")));
        // disable lock on sleep and timeouts
        try!(keychain.set_settings(&KeychainSettings::new()));

        let mut imports = try!(Pkcs12ImportOptions::new()
            .passphrase(pass)
            .keychain(keychain)
            .import(buf));
        let import = imports.pop().unwrap();

        // FIXME: Compare the certificates for equality using CFEqual
        let identity_cert = try!(import.identity.certificate()).to_der();

        Ok(Pkcs12 {
            identity: import.identity,
            chain: import.cert_chain
                .into_iter()
                .filter(|c| c.to_der() != identity_cert)
                .collect(),
        })
    }
}

pub struct Certificate(SecCertificate);

impl Certificate {
    pub fn from_der(buf: &[u8]) -> Result<Certificate, Error> {
        let cert = try!(SecCertificate::from_der(buf));
        Ok(Certificate(cert))
    }
}

pub enum HandshakeError<S> {
    Interrupted(MidHandshakeTlsStream<S>),
    Failure(Error),
}

impl<S> From<secure_transport::HandshakeError<S>> for HandshakeError<S> {
    fn from(e: secure_transport::HandshakeError<S>) -> HandshakeError<S> {
        match e {
            secure_transport::HandshakeError::Failure(e) => HandshakeError::Failure(e.into()),
            secure_transport::HandshakeError::Interrupted(s) => {
                HandshakeError::Interrupted(MidHandshakeTlsStream::Server(s))
            }
        }
    }
}

impl<S> From<secure_transport::ClientHandshakeError<S>> for HandshakeError<S> {
    fn from(e: secure_transport::ClientHandshakeError<S>) -> HandshakeError<S> {
        match e {
            secure_transport::ClientHandshakeError::Failure(e) => HandshakeError::Failure(e.into()),
            secure_transport::ClientHandshakeError::Interrupted(s) => {
                HandshakeError::Interrupted(MidHandshakeTlsStream::Client(s))
            }
        }
    }
}

impl<S> From<base::Error> for HandshakeError<S> {
    fn from(e: base::Error) -> HandshakeError<S> {
        HandshakeError::Failure(e.into())
    }
}

pub enum MidHandshakeTlsStream<S> {
    Server(secure_transport::MidHandshakeSslStream<S>),
    Client(secure_transport::MidHandshakeClientBuilder<S>),
}

impl<S> fmt::Debug for MidHandshakeTlsStream<S>
    where S: fmt::Debug
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            MidHandshakeTlsStream::Server(ref s) => s.fmt(fmt),
            MidHandshakeTlsStream::Client(ref s) => s.fmt(fmt),
        }
    }
}

impl<S> MidHandshakeTlsStream<S>
    where S: io::Read + io::Write
{
    pub fn get_ref(&self) -> &S {
        match *self {
            MidHandshakeTlsStream::Server(ref s) => s.get_ref(),
            MidHandshakeTlsStream::Client(ref s) => s.get_ref(),
        }
    }

    pub fn get_mut(&mut self) -> &mut S {
        match *self {
            MidHandshakeTlsStream::Server(ref mut s) => s.get_mut(),
            MidHandshakeTlsStream::Client(ref mut s) => s.get_mut(),
        }
    }

    pub fn handshake(self) -> Result<TlsStream<S>, HandshakeError<S>> {
        match self {
            MidHandshakeTlsStream::Server(s) => {
                match s.handshake() {
                    Ok(s) => Ok(TlsStream(s)),
                    Err(e) => Err(e.into()),
                }
            }
            MidHandshakeTlsStream::Client(s) => {
                match s.handshake() {
                    Ok(s) => Ok(TlsStream(s)),
                    Err(e) => Err(e.into()),
                }
            }
        }
    }
}

pub struct TlsConnectorBuilder(TlsConnector);

impl TlsConnectorBuilder {
    pub fn identity(&mut self, pkcs12: Pkcs12) -> Result<(), Error> {
        self.0.pkcs12 = Some(pkcs12);
        Ok(())
    }

    pub fn add_root_certificate(&mut self, cert: Certificate) -> Result<(), Error> {
        self.0.roots.push(cert.0);
        Ok(())
    }

    pub fn supported_protocols(&mut self, protocols: &[Protocol]) -> Result<(), Error> {
        self.0.protocols = protocols.to_vec();
        Ok(())
    }

    pub fn build(self) -> Result<TlsConnector, Error> {
        Ok(self.0)
    }
}

#[derive(Clone)]
pub struct TlsConnector {
    pkcs12: Option<Pkcs12>,
    protocols: Vec<Protocol>,
    roots: Vec<SecCertificate>,
}

impl TlsConnector {
    pub fn builder() -> Result<TlsConnectorBuilder, Error> {
        Ok(TlsConnectorBuilder(TlsConnector {
            pkcs12: None,
            protocols: vec![Protocol::Tlsv10, Protocol::Tlsv11, Protocol::Tlsv12],
            roots: vec![],
        }))
    }

    pub fn connect<S>(&self,
                      domain: &str,
                      stream: S)
                      -> Result<TlsStream<S>, HandshakeError<S>>
        where S: io::Read + io::Write
    {
        self.connect_inner(Some(domain), stream)
    }

    pub fn connect_no_domain<S>(&self, stream: S) -> Result<TlsStream<S>, HandshakeError<S>>
        where S: io::Read + io::Write
    {
        self.connect_inner(None, stream)
    }

    fn connect_inner<S>(&self,
                   domain: Option<&str>,
                   stream: S)
                   -> Result<TlsStream<S>, HandshakeError<S>>
        where S: io::Read + io::Write
    {
        let mut builder = ClientBuilder::new();
        let (min, max) = protocol_min_max(&self.protocols);
        builder.protocol_min(min);
        builder.protocol_max(max);
        if let Some(pkcs12) = self.pkcs12.as_ref() {
            builder.identity(&pkcs12.identity, &pkcs12.chain);
        }
        builder.anchor_certificates(&self.roots);

        let r = match domain {
            Some(domain) => builder.handshake2(domain, stream),
            None => builder.danger_handshake_without_providing_domain_for_certificate_validation_and_server_name_indication(stream),
        };
        match r {
            Ok(s) => Ok(TlsStream(s)),
            Err(e) => Err(e.into()),
        }
    }
}

pub struct TlsAcceptorBuilder(TlsAcceptor);

impl TlsAcceptorBuilder {
    pub fn supported_protocols(&mut self, protocols: &[Protocol]) -> Result<(), Error> {
        self.0.protocols = protocols.to_vec();
        Ok(())
    }

    pub fn build(self) -> Result<TlsAcceptor, Error> {
        Ok(self.0)
    }
}

#[derive(Clone)]
pub struct TlsAcceptor {
    pkcs12: Pkcs12,
    protocols: Vec<Protocol>,
}

impl TlsAcceptor {
    pub fn builder(pkcs12: Pkcs12) -> Result<TlsAcceptorBuilder, Error> {
        Ok(TlsAcceptorBuilder(TlsAcceptor {
            pkcs12: pkcs12,
            protocols: vec![Protocol::Tlsv10, Protocol::Tlsv11, Protocol::Tlsv12],
        }))
    }

    pub fn accept<S>(&self, stream: S) -> Result<TlsStream<S>, HandshakeError<S>>
        where S: io::Read + io::Write
    {
        let mut ctx = try!(SslContext::new(ProtocolSide::Server, ConnectionType::Stream));

        let (min, max) = protocol_min_max(&self.protocols);
        try!(ctx.set_protocol_version_min(min));
        try!(ctx.set_protocol_version_max(max));
        try!(ctx.set_certificate(&self.pkcs12.identity, &self.pkcs12.chain));
        match ctx.handshake(stream) {
            Ok(s) => Ok(TlsStream(s)),
            Err(e) => Err(e.into()),
        }
    }
}

pub struct TlsStream<S>(secure_transport::SslStream<S>);

impl<S: fmt::Debug> fmt::Debug for TlsStream<S> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.0, fmt)
    }
}

impl<S: io::Read + io::Write> TlsStream<S> {
    pub fn get_ref(&self) -> &S {
        self.0.get_ref()
    }

    pub fn get_mut(&mut self) -> &mut S {
        self.0.get_mut()
    }

    pub fn buffered_read_size(&self) -> Result<usize, Error> {
        Ok(try!(self.0.context().buffered_read_size()))
    }

    pub fn shutdown(&mut self) -> io::Result<()> {
        try!(self.0.close());
        Ok(())
    }
}

impl<S: io::Read + io::Write> io::Read for TlsStream<S> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }
}

impl<S: io::Read + io::Write> io::Write for TlsStream<S> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.0.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.0.flush()
    }
}

/// Security Framework-specific extensions to `TlsStream`.
pub trait TlsStreamExt<S> {
    /// Returns a shared reference to the Security Framework `SslStream`.
    fn raw_stream(&self) -> &secure_transport::SslStream<S>;

    /// Returns a mutable reference to the Security Framework `SslStream`.
    fn raw_stream_mut(&mut self) -> &mut secure_transport::SslStream<S>;
}

impl<S> TlsStreamExt<S> for ::TlsStream<S> {
    fn raw_stream(&self) -> &secure_transport::SslStream<S> {
        &(self.0).0
    }

    fn raw_stream_mut(&mut self) -> &mut secure_transport::SslStream<S> {
        &mut (self.0).0
    }
}

/// Security Framework-specific extensions to `TlsConnectorBuilder`.
pub trait TlsConnectorBuilderExt {
    /// Deprecated
    #[deprecated(since = "0.1.2", note = "use add_root_certificate")]
    fn anchor_certificates(&mut self, certs: &[SecCertificate]) -> &mut Self;
}

impl TlsConnectorBuilderExt for ::TlsConnectorBuilder {
    fn anchor_certificates(&mut self, certs: &[SecCertificate]) -> &mut Self {
        (self.0).0.roots = certs.to_owned();
        self
    }
}

/// Security Framework-specific extensions to `Error`
pub trait ErrorExt {
    /// Extract the underlying Security Framework error for inspection.
    fn security_framework_error(&self) -> &base::Error;
}

impl ErrorExt for ::Error {
    fn security_framework_error(&self) -> &base::Error {
        &(self.0).0
    }
}
<commit_msg>Make security_framework Pkcs12 Cloneable<commit_after>extern crate security_framework;
extern crate security_framework_sys;
extern crate tempdir;

use self::security_framework::base;
use self::security_framework::certificate::SecCertificate;
use self::security_framework::identity::SecIdentity;
use self::security_framework::import_export::Pkcs12ImportOptions;
use self::security_framework::secure_transport::{self, SslContext, ProtocolSide, ConnectionType,
                                                 SslProtocol, ClientBuilder};
use self::security_framework::os::macos::keychain::{self, KeychainSettings};
use self::security_framework_sys::base::errSecIO;
use self::tempdir::TempDir;
use std::fmt;
use std::io;
use std::error;

use Protocol;

fn convert_protocol(protocol: Protocol) -> SslProtocol {
    match protocol {
        Protocol::Sslv3 => SslProtocol::Ssl3,
        Protocol::Tlsv10 => SslProtocol::Tls1,
        Protocol::Tlsv11 => SslProtocol::Tls11,
        Protocol::Tlsv12 => SslProtocol::Tls12,
        Protocol::__NonExhaustive => unreachable!(),
    }
}

fn protocol_min_max(protocols: &[Protocol]) -> (SslProtocol, SslProtocol) {
    let mut min = Protocol::Tlsv12;
    let mut max = Protocol::Sslv3;
    for protocol in protocols {
        if (*protocol as usize) < (min as usize) {
            min = *protocol;
        }
        if (*protocol as usize) > (max as usize) {
            max = *protocol;
        }
    }
    (convert_protocol(min), convert_protocol(max))
}

pub struct Error(base::Error);

impl error::Error for Error {
    fn description(&self) -> &str {
        error::Error::description(&self.0)
    }

    fn cause(&self) -> Option<&error::Error> {
        error::Error::cause(&self.0)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.0, fmt)
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.0, fmt)
    }
}

impl From<base::Error> for Error {
    fn from(error: base::Error) -> Error {
        Error(error)
    }
}

#[derive(Clone)]
pub struct Pkcs12 {
    identity: SecIdentity,
    chain: Vec<SecCertificate>,
}

impl Pkcs12 {
    pub fn from_der(buf: &[u8], pass: &str) -> Result<Pkcs12, Error> {
        let dir = match TempDir::new("native-tls") {
            Ok(dir) => dir,
            Err(_) => return Err(Error(base::Error::from(errSecIO))),
        };

        let mut keychain = try!(keychain::CreateOptions::new()
            .password(pass)
            .create(dir.path().join("tmp.keychain")));
        // disable lock on sleep and timeouts
        try!(keychain.set_settings(&KeychainSettings::new()));

        let mut imports = try!(Pkcs12ImportOptions::new()
            .passphrase(pass)
            .keychain(keychain)
            .import(buf));
        let import = imports.pop().unwrap();

        // FIXME: Compare the certificates for equality using CFEqual
        let identity_cert = try!(import.identity.certificate()).to_der();

        Ok(Pkcs12 {
            identity: import.identity,
            chain: import.cert_chain
                .into_iter()
                .filter(|c| c.to_der() != identity_cert)
                .collect(),
        })
    }
}

pub struct Certificate(SecCertificate);

impl Certificate {
    pub fn from_der(buf: &[u8]) -> Result<Certificate, Error> {
        let cert = try!(SecCertificate::from_der(buf));
        Ok(Certificate(cert))
    }
}

pub enum HandshakeError<S> {
    Interrupted(MidHandshakeTlsStream<S>),
    Failure(Error),
}

impl<S> From<secure_transport::HandshakeError<S>> for HandshakeError<S> {
    fn from(e: secure_transport::HandshakeError<S>) -> HandshakeError<S> {
        match e {
            secure_transport::HandshakeError::Failure(e) => HandshakeError::Failure(e.into()),
            secure_transport::HandshakeError::Interrupted(s) => {
                HandshakeError::Interrupted(MidHandshakeTlsStream::Server(s))
            }
        }
    }
}

impl<S> From<secure_transport::ClientHandshakeError<S>> for HandshakeError<S> {
    fn from(e: secure_transport::ClientHandshakeError<S>) -> HandshakeError<S> {
        match e {
            secure_transport::ClientHandshakeError::Failure(e) => HandshakeError::Failure(e.into()),
            secure_transport::ClientHandshakeError::Interrupted(s) => {
                HandshakeError::Interrupted(MidHandshakeTlsStream::Client(s))
            }
        }
    }
}

impl<S> From<base::Error> for HandshakeError<S> {
    fn from(e: base::Error) -> HandshakeError<S> {
        HandshakeError::Failure(e.into())
    }
}

pub enum MidHandshakeTlsStream<S> {
    Server(secure_transport::MidHandshakeSslStream<S>),
    Client(secure_transport::MidHandshakeClientBuilder<S>),
}

impl<S> fmt::Debug for MidHandshakeTlsStream<S>
    where S: fmt::Debug
{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            MidHandshakeTlsStream::Server(ref s) => s.fmt(fmt),
            MidHandshakeTlsStream::Client(ref s) => s.fmt(fmt),
        }
    }
}

impl<S> MidHandshakeTlsStream<S>
    where S: io::Read + io::Write
{
    pub fn get_ref(&self) -> &S {
        match *self {
            MidHandshakeTlsStream::Server(ref s) => s.get_ref(),
            MidHandshakeTlsStream::Client(ref s) => s.get_ref(),
        }
    }

    pub fn get_mut(&mut self) -> &mut S {
        match *self {
            MidHandshakeTlsStream::Server(ref mut s) => s.get_mut(),
            MidHandshakeTlsStream::Client(ref mut s) => s.get_mut(),
        }
    }

    pub fn handshake(self) -> Result<TlsStream<S>, HandshakeError<S>> {
        match self {
            MidHandshakeTlsStream::Server(s) => {
                match s.handshake() {
                    Ok(s) => Ok(TlsStream(s)),
                    Err(e) => Err(e.into()),
                }
            }
            MidHandshakeTlsStream::Client(s) => {
                match s.handshake() {
                    Ok(s) => Ok(TlsStream(s)),
                    Err(e) => Err(e.into()),
                }
            }
        }
    }
}

pub struct TlsConnectorBuilder(TlsConnector);

impl TlsConnectorBuilder {
    pub fn identity(&mut self, pkcs12: Pkcs12) -> Result<(), Error> {
        self.0.pkcs12 = Some(pkcs12);
        Ok(())
    }

    pub fn add_root_certificate(&mut self, cert: Certificate) -> Result<(), Error> {
        self.0.roots.push(cert.0);
        Ok(())
    }

    pub fn supported_protocols(&mut self, protocols: &[Protocol]) -> Result<(), Error> {
        self.0.protocols = protocols.to_vec();
        Ok(())
    }

    pub fn build(self) -> Result<TlsConnector, Error> {
        Ok(self.0)
    }
}

#[derive(Clone)]
pub struct TlsConnector {
    pkcs12: Option<Pkcs12>,
    protocols: Vec<Protocol>,
    roots: Vec<SecCertificate>,
}

impl TlsConnector {
    pub fn builder() -> Result<TlsConnectorBuilder, Error> {
        Ok(TlsConnectorBuilder(TlsConnector {
            pkcs12: None,
            protocols: vec![Protocol::Tlsv10, Protocol::Tlsv11, Protocol::Tlsv12],
            roots: vec![],
        }))
    }

    pub fn connect<S>(&self,
                      domain: &str,
                      stream: S)
                      -> Result<TlsStream<S>, HandshakeError<S>>
        where S: io::Read + io::Write
    {
        self.connect_inner(Some(domain), stream)
    }

    pub fn connect_no_domain<S>(&self, stream: S) -> Result<TlsStream<S>, HandshakeError<S>>
        where S: io::Read + io::Write
    {
        self.connect_inner(None, stream)
    }

    fn connect_inner<S>(&self,
                   domain: Option<&str>,
                   stream: S)
                   -> Result<TlsStream<S>, HandshakeError<S>>
        where S: io::Read + io::Write
    {
        let mut builder = ClientBuilder::new();
        let (min, max) = protocol_min_max(&self.protocols);
        builder.protocol_min(min);
        builder.protocol_max(max);
        if let Some(pkcs12) = self.pkcs12.as_ref() {
            builder.identity(&pkcs12.identity, &pkcs12.chain);
        }
        builder.anchor_certificates(&self.roots);

        let r = match domain {
            Some(domain) => builder.handshake2(domain, stream),
            None => builder.danger_handshake_without_providing_domain_for_certificate_validation_and_server_name_indication(stream),
        };
        match r {
            Ok(s) => Ok(TlsStream(s)),
            Err(e) => Err(e.into()),
        }
    }
}

pub struct TlsAcceptorBuilder(TlsAcceptor);

impl TlsAcceptorBuilder {
    pub fn supported_protocols(&mut self, protocols: &[Protocol]) -> Result<(), Error> {
        self.0.protocols = protocols.to_vec();
        Ok(())
    }

    pub fn build(self) -> Result<TlsAcceptor, Error> {
        Ok(self.0)
    }
}

#[derive(Clone)]
pub struct TlsAcceptor {
    pkcs12: Pkcs12,
    protocols: Vec<Protocol>,
}

impl TlsAcceptor {
    pub fn builder(pkcs12: Pkcs12) -> Result<TlsAcceptorBuilder, Error> {
        Ok(TlsAcceptorBuilder(TlsAcceptor {
            pkcs12: pkcs12,
            protocols: vec![Protocol::Tlsv10, Protocol::Tlsv11, Protocol::Tlsv12],
        }))
    }

    pub fn accept<S>(&self, stream: S) -> Result<TlsStream<S>, HandshakeError<S>>
        where S: io::Read + io::Write
    {
        let mut ctx = try!(SslContext::new(ProtocolSide::Server, ConnectionType::Stream));

        let (min, max) = protocol_min_max(&self.protocols);
        try!(ctx.set_protocol_version_min(min));
        try!(ctx.set_protocol_version_max(max));
        try!(ctx.set_certificate(&self.pkcs12.identity, &self.pkcs12.chain));
        match ctx.handshake(stream) {
            Ok(s) => Ok(TlsStream(s)),
            Err(e) => Err(e.into()),
        }
    }
}

pub struct TlsStream<S>(secure_transport::SslStream<S>);

impl<S: fmt::Debug> fmt::Debug for TlsStream<S> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.0, fmt)
    }
}

impl<S: io::Read + io::Write> TlsStream<S> {
    pub fn get_ref(&self) -> &S {
        self.0.get_ref()
    }

    pub fn get_mut(&mut self) -> &mut S {
        self.0.get_mut()
    }

    pub fn buffered_read_size(&self) -> Result<usize, Error> {
        Ok(try!(self.0.context().buffered_read_size()))
    }

    pub fn shutdown(&mut self) -> io::Result<()> {
        try!(self.0.close());
        Ok(())
    }
}

impl<S: io::Read + io::Write> io::Read for TlsStream<S> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }
}

impl<S: io::Read + io::Write> io::Write for TlsStream<S> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.0.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.0.flush()
    }
}

/// Security Framework-specific extensions to `TlsStream`.
pub trait TlsStreamExt<S> {
    /// Returns a shared reference to the Security Framework `SslStream`.
    fn raw_stream(&self) -> &secure_transport::SslStream<S>;

    /// Returns a mutable reference to the Security Framework `SslStream`.
    fn raw_stream_mut(&mut self) -> &mut secure_transport::SslStream<S>;
}

impl<S> TlsStreamExt<S> for ::TlsStream<S> {
    fn raw_stream(&self) -> &secure_transport::SslStream<S> {
        &(self.0).0
    }

    fn raw_stream_mut(&mut self) -> &mut secure_transport::SslStream<S> {
        &mut (self.0).0
    }
}

/// Security Framework-specific extensions to `TlsConnectorBuilder`.
pub trait TlsConnectorBuilderExt {
    /// Deprecated
    #[deprecated(since = "0.1.2", note = "use add_root_certificate")]
    fn anchor_certificates(&mut self, certs: &[SecCertificate]) -> &mut Self;
}

impl TlsConnectorBuilderExt for ::TlsConnectorBuilder {
    fn anchor_certificates(&mut self, certs: &[SecCertificate]) -> &mut Self {
        (self.0).0.roots = certs.to_owned();
        self
    }
}

/// Security Framework-specific extensions to `Error`
pub trait ErrorExt {
    /// Extract the underlying Security Framework error for inspection.
    fn security_framework_error(&self) -> &base::Error;
}

impl ErrorExt for ::Error {
    fn security_framework_error(&self) -> &base::Error {
        &(self.0).0
    }
}
<|endoftext|>


<commit_before>use synom::IResult;
use syn;
use syn::parse::{ident, string};

use hints::{Hint};
use options::{Options};

#[derive(PartialEq, Debug)]
pub struct MacroInput {
    pub name: String,
    pub sample_source: String,
    pub options: Options,
}

macro_rules! fail {
    ($base:expr, $input:expr) => {
        return Err(format!("{}, but remaining input was '{}'", $base, $input.trim()));
    };
}

named!(string_or_ident -> String,
    alt!(
        ident => { |ident: syn::Ident| ident.to_string() }
        |
        string => { |lit: syn::StrLit| lit.value }
    )
);

pub fn full_macro(input: &str) -> Result<MacroInput, String> {
    let input = input.trim();

    let prefix = "json_typegen!(";
    if !input.starts_with(prefix) {
        fail!("Unable to parse macro. Expected 'json_typegen!('", input)
    }

    let suffix = ");";
    if !input.ends_with(suffix) {
        fail!("Unable to parse macro. Expected it to end with ');'", input)
    }

    let input = &input[prefix.len() .. input.len() - suffix.len()].trim();

    macro_input(input)
}

pub fn macro_input(input: &str) -> Result<MacroInput, String> {
    let (input, name) = match string(input) {
        IResult::Done(input, lit) => (input, lit.value),
        IResult::Error => {
            fail!("First argument must be a string literal", input)
        }
    };

    let input = skip(input, ",", "Expected a comma after first argument")?;

    let (input, sample_source) = match string(input) {
        IResult::Done(input, lit) => (input, lit.value),
        IResult::Error => {
            fail!("Second argument must be a string literal", input)
        }
    };

    if input.trim().is_empty() {
        return Ok(MacroInput { name, sample_source, options: Options::default() });
    }

    let input = skip(input, ",", "Expected a comma or end of input after second argument")?;

    let options = match string(input) {
        IResult::Done(_, lit) => options(&lit.value)?,
        IResult::Error => options(input)?,
    };

    Ok(MacroInput { name, sample_source, options })
}

pub fn options(input: &str) -> Result<Options, String> {
    let mut options = Options::default();

    let input_after_block = block(input, |remaining, option_name| {
        match option_name.as_ref() {
            "derives" => string_option(remaining, "derives", |val| {
                options.derives = val;
            }),
            key if key.is_empty() || key.starts_with("/") => {
                let (rem, hints) = pointer_block(remaining)?;
                for hint in hints {
                    options.hints.push((key.to_string(), hint));
                }
                Ok(rem)
            },
            _ => Err(format!("Unknown option: {}", option_name)),
        }
    })?;

    if !input_after_block.trim().is_empty() {
        fail!("Expected no further tokens after options block", input);
    }

    Ok(options)
}

fn pointer_block(input: &str) -> Result<(&str, Vec<Hint>), String> {
    let mut hints = Vec::new();

    let input = skip_colon(input)?;

    let input_after_block = block(input, |input_after_key, key| {
        match key.as_ref() {
            "use_map" => {
                hints.push(Hint::default_map());
                Ok(input_after_key)
            },
            "use_name" => string_option(input_after_key, "use_name", |val| {
                hints.push(Hint::use_name(val));
            }),
            _ => return Err(format!("Unknown option: {}", key)),
        }
    })?;

    Ok((input_after_block, hints))
}

fn string_option<'a, F: FnMut(String)>(
    input: &'a str,
    name: &'static str,
    mut consumer: F,
) -> Result<&'a str, String> {
    let input = skip_colon(input)?;

    match string(input) {
        IResult::Done(rem, lit) => {
            consumer(lit.value);
            Ok(rem)
        }
        IResult::Error => fail!(
            format!("The argument to '{}' has to be a string literal", name),
            input
        ),
    }
}

fn block<'input, F>(input: &'input str, mut field_parser: F) -> Result<&'input str, String>
    where F: FnMut(&'input str, String) -> Result<&'input str, String>
{
    let mut input = skip(input, "{", "Expected an opening brace")?;

    loop {
        if let IResult::Done(rem, _) = punct!(input, "}") {
            break Ok(rem);
        }

        let (remaining, key) = match string_or_ident(input) {
            IResult::Done(rem, value) => (rem, value),
            IResult::Error => fail!("Expected an option name", input),
        };

        let remaining = field_parser(remaining, key)?;

        if let IResult::Done(rem, _) = punct!(remaining, "}") {
            break Ok(rem);
        }

        input = skip(remaining, ",", "Expected a comma or a closing brace")?;
    }
}

fn skip_colon(input: &str) -> Result<&str, String> {
    skip(input, ":", "Expected a colon")
}

fn skip<'a>(input: &'a str, symbol: &'static str, msg: &str) -> Result<&'a str, String> {
    match punct!(input, symbol) {
        IResult::Done(rem, _) => Ok(rem),
        IResult::Error => {
            fail!(msg, input);
        }
    }
}

#[cfg(test)]
mod macro_input_tests {
    use super::*;

    #[test]
    fn barebones_input() {
        assert_eq!(macro_input(r#" "Bob", "{}" "#), Ok(MacroInput {
            name: "Bob".to_string(),
            sample_source: "{}".to_string(),
            options: Options::default(),
        }));
    }

    #[test]
    fn barebones_input_with_empty_options() {
        assert_eq!(macro_input(r#" "Bob", "{}", {} "#), Ok(MacroInput {
            name: "Bob".to_string(),
            sample_source: "{}".to_string(),
            options: Options::default(),
        }));
    }

    #[test]
    fn barebones_input_with_options_as_string_literal() {
        assert_eq!(macro_input(r#" "Bob", "{}", "{}" "#), Ok(MacroInput {
            name: "Bob".to_string(),
            sample_source: "{}".to_string(),
            options: Options::default(),
        }));
    }
}

#[cfg(test)]
mod options_tests {
    use super::*;

    #[test]
    fn parses_derives() {
        let mut expected = Options::default();
        expected.derives = "Foo, Bar".into();

        assert_eq!(
            options(r#"{
                "derives": "Foo, Bar",
            }"#),
            Ok(expected)
        );
    }

    #[test]
    fn rejects_unknown_options() {
        let result = options(r#"{
            "foo_opt": {},
        }"#);

        assert!(result.is_err(), "Parse result was not Err, but:\n{:?}", result);
        if let Err(message) = result {
            assert!(message.contains("foo_opt"), "Error message was:\n'{}'", message);
        }
    }

    #[test]
    fn parses_empty_pointer_block() {
        let expected = Options::default();

        assert_eq!(
            options(r#"{
                "/foo/bar": {},
            }"#),
            Ok(expected)
        );
    }

    #[test]
    fn parses_use_map_hint() {
        let mut expected = Options::default();
        expected.hints.push(("/foo/bar".to_string(), Hint::default_map()));

        assert_eq!(
            options(r#"{
                "/foo/bar": {
                    use_map
                },
            }"#),
            Ok(expected)
        );
    }

    #[test]
    fn parses_use_name_hint() {
        let mut expected = Options::default();
        expected.hints.push(("/baz".to_string(), Hint::use_name("some_name")));

        assert_eq!(
            options(r#"{
                "/baz": {
                    use_name: "some_name"
                },
            }"#),
            Ok(expected)
        );
    }

    #[test]
    fn parses_pointer_to_root() {
        let expected = Options::default();

        assert_eq!(
            options(r#"{
                "": {},
            }"#),
            Ok(expected)
        );
    }

    #[test]
    fn parses_keys_given_as_bare_identifiers() {
        let mut expected = Options::default();
        expected.derives = "Foo, Bar".into();

        assert_eq!(
            options(r#"{
                derives: "Foo, Bar",
            }"#),
            Ok(expected)
        );
    }

    #[test]
    fn trailing_comma_is_optional() {
        let mut expected = Options::default();
        expected.derives = "Foo, Bar".into();

        assert_eq!(
            options(r#"{
                "derives": "Foo, Bar"
            }"#),
            Ok(expected.clone())
        );

        assert_eq!(
            options(r#"{
                "derives": "Foo, Bar",
            }"#),
            Ok(expected)
        );
    }
}

#[cfg(test)]
mod full_macro_tests {
    use super::*;

    #[test]
    fn full_macro_accepts_barebones_macro() {
        assert_eq!(full_macro(r#"json_typegen!("Bob", "{}");"#), Ok(MacroInput {
            name: "Bob".to_string(),
            sample_source: "{}".to_string(),
            options: Options::default(),
        }));
    }

    #[test]
    fn full_macro_accepts_barebones_macro_with_options() {
        assert_eq!(full_macro(r#"json_typegen!("Bob", "{}", {});"#), Ok(MacroInput {
            name: "Bob".to_string(),
            sample_source: "{}".to_string(),
            options: Options::default(),
        }));
    }
}
<commit_msg>Partially implement boolean_option parsing<commit_after>use synom::IResult;
use syn;
use syn::parse::{ident, string, boolean};

use hints::{Hint};
use options::{Options, MissingFields};

#[derive(PartialEq, Debug)]
pub struct MacroInput {
    pub name: String,
    pub sample_source: String,
    pub options: Options,
}

macro_rules! fail {
    ($base:expr, $input:expr) => {
        return Err(format!("{}, but remaining input was '{}'", $base, $input.trim()));
    };
}

named!(string_or_ident -> String,
    alt!(
        ident => { |ident: syn::Ident| ident.to_string() }
        |
        string => { |lit: syn::StrLit| lit.value }
    )
);

pub fn full_macro(input: &str) -> Result<MacroInput, String> {
    let input = input.trim();

    let prefix = "json_typegen!(";
    if !input.starts_with(prefix) {
        fail!("Unable to parse macro. Expected 'json_typegen!('", input)
    }

    let suffix = ");";
    if !input.ends_with(suffix) {
        fail!("Unable to parse macro. Expected it to end with ');'", input)
    }

    let input = &input[prefix.len() .. input.len() - suffix.len()].trim();

    macro_input(input)
}

pub fn macro_input(input: &str) -> Result<MacroInput, String> {
    let (input, name) = match string(input) {
        IResult::Done(input, lit) => (input, lit.value),
        IResult::Error => {
            fail!("First argument must be a string literal", input)
        }
    };

    let input = skip(input, ",", "Expected a comma after first argument")?;

    let (input, sample_source) = match string(input) {
        IResult::Done(input, lit) => (input, lit.value),
        IResult::Error => {
            fail!("Second argument must be a string literal", input)
        }
    };

    if input.trim().is_empty() {
        return Ok(MacroInput { name, sample_source, options: Options::default() });
    }

    let input = skip(input, ",", "Expected a comma or end of input after second argument")?;

    let options = match string(input) {
        IResult::Done(_, lit) => options(&lit.value)?,
        IResult::Error => options(input)?,
    };

    Ok(MacroInput { name, sample_source, options })
}

pub fn options(input: &str) -> Result<Options, String> {
    let mut options = Options::default();

    let input_after_block = block(input, |remaining, option_name| {
        match option_name.as_ref() {
            "derives" => string_option(remaining, "derives", |val| {
                options.derives = val;
            }),
            // TODO: "field_visibility"
            "deny_unknown_fields" => boolean_option(remaining, "deny_unknown_fields", |val| {
                options.deny_unknown_fields = val;
            }),
            "use_default_for_missing_fields" => boolean_option(remaining, "use_default_for_missing_fields", |val| {
                options.missing_fields = if val {
                    MissingFields::UseDefault
                } else {
                    MissingFields::Fail
                };
            }),
            "allow_option_vec" => boolean_option(remaining, "allow_option_vec", |val| {
                options.allow_option_vec = val;
            }),
            key if key.is_empty() || key.starts_with("/") => {
                let (rem, hints) = pointer_block(remaining)?;
                for hint in hints {
                    options.hints.push((key.to_string(), hint));
                }
                Ok(rem)
            },
            _ => Err(format!("Unknown option: {}", option_name)),
        }
    })?;

    if !input_after_block.trim().is_empty() {
        fail!("Expected no further tokens after options block", input);
    }

    Ok(options)
}

fn pointer_block(input: &str) -> Result<(&str, Vec<Hint>), String> {
    let mut hints = Vec::new();

    let input = skip_colon(input)?;

    let input_after_block = block(input, |input_after_key, key| {
        match key.as_ref() {
            "use_map" => {
                hints.push(Hint::default_map());
                Ok(input_after_key)
            },
            "use_name" => string_option(input_after_key, "use_name", |val| {
                hints.push(Hint::use_name(val));
            }),
            _ => return Err(format!("Unknown option: {}", key)),
        }
    })?;

    Ok((input_after_block, hints))
}

fn string_option<'a, F: FnMut(String)>(
    input: &'a str,
    name: &'static str,
    mut consumer: F,
) -> Result<&'a str, String> {
    let input = skip_colon(input)?;

    match string(input) {
        IResult::Done(rem, lit) => {
            consumer(lit.value);
            Ok(rem)
        }
        IResult::Error => fail!(
            format!("The argument to '{}' has to be a string literal", name),
            input
        ),
    }
}

fn boolean_option<'a, F: FnMut(bool)>(
    input: &'a str,
    name: &'static str,
    mut consumer: F,
) -> Result<&'a str, String> {
    // TODO: Allow option name only as true

    let input = skip_colon(input)?;

    match boolean(input) {
        IResult::Done(rem, val) => {
            consumer(val);
            Ok(rem)
        }
        IResult::Error => fail!(
            format!("The argument to '{}' has to be a boolean literal", name),
            input
        ),
    }
}

fn block<'input, F>(input: &'input str, mut field_parser: F) -> Result<&'input str, String>
    where F: FnMut(&'input str, String) -> Result<&'input str, String>
{
    let mut input = skip(input, "{", "Expected an opening brace")?;

    loop {
        if let IResult::Done(rem, _) = punct!(input, "}") {
            break Ok(rem);
        }

        let (remaining, key) = match string_or_ident(input) {
            IResult::Done(rem, value) => (rem, value),
            IResult::Error => fail!("Expected an option name", input),
        };

        let remaining = field_parser(remaining, key)?;

        if let IResult::Done(rem, _) = punct!(remaining, "}") {
            break Ok(rem);
        }

        input = skip(remaining, ",", "Expected a comma or a closing brace")?;
    }
}

fn skip_colon(input: &str) -> Result<&str, String> {
    skip(input, ":", "Expected a colon")
}

fn skip<'a>(input: &'a str, symbol: &'static str, msg: &str) -> Result<&'a str, String> {
    match punct!(input, symbol) {
        IResult::Done(rem, _) => Ok(rem),
        IResult::Error => {
            fail!(msg, input);
        }
    }
}

#[cfg(test)]
mod macro_input_tests {
    use super::*;

    #[test]
    fn barebones_input() {
        assert_eq!(macro_input(r#" "Bob", "{}" "#), Ok(MacroInput {
            name: "Bob".to_string(),
            sample_source: "{}".to_string(),
            options: Options::default(),
        }));
    }

    #[test]
    fn barebones_input_with_empty_options() {
        assert_eq!(macro_input(r#" "Bob", "{}", {} "#), Ok(MacroInput {
            name: "Bob".to_string(),
            sample_source: "{}".to_string(),
            options: Options::default(),
        }));
    }

    #[test]
    fn barebones_input_with_options_as_string_literal() {
        assert_eq!(macro_input(r#" "Bob", "{}", "{}" "#), Ok(MacroInput {
            name: "Bob".to_string(),
            sample_source: "{}".to_string(),
            options: Options::default(),
        }));
    }
}

#[cfg(test)]
mod options_tests {
    use super::*;

    #[test]
    fn parses_derives() {
        let mut expected = Options::default();
        expected.derives = "Foo, Bar".into();

        assert_eq!(
            options(r#"{
                "derives": "Foo, Bar",
            }"#),
            Ok(expected)
        );
    }

    #[test]
    fn rejects_unknown_options() {
        let result = options(r#"{
            "foo_opt": {},
        }"#);

        assert!(result.is_err(), "Parse result was not Err, but:\n{:?}", result);
        if let Err(message) = result {
            assert!(message.contains("foo_opt"), "Error message was:\n'{}'", message);
        }
    }

    #[test]
    fn parses_empty_pointer_block() {
        let expected = Options::default();

        assert_eq!(
            options(r#"{
                "/foo/bar": {},
            }"#),
            Ok(expected)
        );
    }

    #[test]
    fn parses_use_map_hint() {
        let mut expected = Options::default();
        expected.hints.push(("/foo/bar".to_string(), Hint::default_map()));

        assert_eq!(
            options(r#"{
                "/foo/bar": {
                    use_map
                },
            }"#),
            Ok(expected)
        );
    }

    #[test]
    fn parses_use_name_hint() {
        let mut expected = Options::default();
        expected.hints.push(("/baz".to_string(), Hint::use_name("some_name")));

        assert_eq!(
            options(r#"{
                "/baz": {
                    use_name: "some_name"
                },
            }"#),
            Ok(expected)
        );
    }

    #[test]
    fn parses_pointer_to_root() {
        let expected = Options::default();

        assert_eq!(
            options(r#"{
                "": {},
            }"#),
            Ok(expected)
        );
    }

    #[test]
    fn parses_keys_given_as_bare_identifiers() {
        let mut expected = Options::default();
        expected.derives = "Foo, Bar".into();

        assert_eq!(
            options(r#"{
                derives: "Foo, Bar",
            }"#),
            Ok(expected)
        );
    }

    #[test]
    fn trailing_comma_is_optional() {
        let mut expected = Options::default();
        expected.derives = "Foo, Bar".into();

        assert_eq!(
            options(r#"{
                "derives": "Foo, Bar"
            }"#),
            Ok(expected.clone())
        );

        assert_eq!(
            options(r#"{
                "derives": "Foo, Bar",
            }"#),
            Ok(expected)
        );
    }
}

#[cfg(test)]
mod full_macro_tests {
    use super::*;

    #[test]
    fn full_macro_accepts_barebones_macro() {
        assert_eq!(full_macro(r#"json_typegen!("Bob", "{}");"#), Ok(MacroInput {
            name: "Bob".to_string(),
            sample_source: "{}".to_string(),
            options: Options::default(),
        }));
    }

    #[test]
    fn full_macro_accepts_barebones_macro_with_options() {
        assert_eq!(full_macro(r#"json_typegen!("Bob", "{}", {});"#), Ok(MacroInput {
            name: "Bob".to_string(),
            sample_source: "{}".to_string(),
            options: Options::default(),
        }));
    }
}
<|endoftext|>


<commit_before>extern crate mime_guess;

use std::convert::TryInto;
use std::path::{Path, PathBuf};
use task_maker_format::ioi;
use turingarena::award::*;
use turingarena::content::*;
use turingarena::evaluation::record::*;
use turingarena::feedback::{table::*, *};
use turingarena::problem::material::*;
use turingarena::submission::form::*;

fn subtasks_of(task: &ioi::Task) -> Vec<&ioi::SubtaskInfo> {
    let mut subtasks: Vec<_> = task.subtasks.values().collect();
    subtasks.sort_by(|a, b| a.id.cmp(&b.id));
    subtasks
}

fn testcases_of(subtask: &ioi::SubtaskInfo) -> Vec<&ioi::TestcaseInfo> {
    let mut testcases: Vec<_> = subtask.testcases.values().collect();
    testcases.sort_by(|a, b| a.id.cmp(&b.id));
    testcases
}

fn submission_form() -> Form {
    Form {
        fields: vec![Field {
            id: FieldId("solution".into()),
            title: vec![TextVariant {
                attributes: vec![],
                value: "Solution".into(),
            }],
            types: vec![FileType {
                id: FileTypeId("cpp".into()),
                title: vec![TextVariant {
                    attributes: vec![],
                    value: "C++".into(),
                }],
                extensions: vec![
                    FileTypeExtension(".cpp".into()),
                    FileTypeExtension(".cc".into()),
                ],
                primary_extension: FileTypeExtension(".cpp".into()),
            }],
        }],
    }
}

fn award_of(subtask: &ioi::SubtaskInfo) -> Award {
    Award {
        name: AwardName(format!("subtask.{}", subtask.id)),
        title: vec![TextVariant {
            attributes: vec![],
            value: format!("Subtask {}", subtask.id),
        }],
        content: if subtask.max_score > 0.0 {
            AwardContent::Score(ScoreAwardContent {
                range: ScoreRange {
                    // TODO: assuming IOI-like tasks have integer scores
                    precision: 0,
                    max: Score(subtask.max_score),
                },
            })
        } else {
            AwardContent::Badge(BadgeAwardContent)
        },
    }
}

fn cols() -> Vec<Col> {
    vec![
        Col {
            title: vec![TextVariant {
                attributes: vec![],
                value: format!("Case"),
            }],
            content: ColContent::RowNumber(RowNumberColContent {}),
        },
        Col {
            title: vec![TextVariant {
                attributes: vec![],
                value: format!("Score"),
            }],
            content: ColContent::Score(ScoreColContent {
                range: ScoreRange {
                    // FIXME: assuming per-test-case score has fixed precision
                    precision: 2,
                    max: Score(1.),
                },
            }),
        },
    ]
}

fn caption() -> Text {
    vec![TextVariant {
        attributes: vec![],
        value: format!("Test case results"),
    }]
}

fn row_group_of(subtask: &ioi::SubtaskInfo) -> RowGroup {
    RowGroup {
        title: vec![TextVariant {
            attributes: vec![],
            value: format!("Subtask {}", subtask.id),
        }],
        rows: testcases_of(subtask).into_iter().map(row_of).collect(),
    }
}

fn row_of(testcase: &ioi::TestcaseInfo) -> Row {
    Row {
        content: RowContent::Data,
        cells: vec![
            Cell {
                content: CellContent::RowNumber(RowNumberCellContent {
                    number: testcase.id.try_into().expect("Testcase ID too large"),
                }),
            },
            Cell {
                content: CellContent::Score(ScoreCellContent {
                    range: ScoreRange {
                        precision: 2,
                        max: Score(1.),
                    },
                    r#ref: Key(format!("testcase.{}.score", testcase.id)),
                }),
            },
        ],
    }
}

fn files_in_dir(dir_path: &std::path::PathBuf) -> impl Iterator<Item = std::path::PathBuf> {
    std::fs::read_dir(dir_path)
        .expect("unable to read_dir")
        .map(|entry| entry.expect("unable to read_dir").path())
}

fn attachment_at_path(file_path: std::path::PathBuf) -> Attachment {
    Attachment {
        title: vec![TextVariant {
            attributes: vec![],
            value: file_path
                .file_name()
                .unwrap()
                .to_string_lossy()
                .into_owned(),
        }],
        file: vec![FileVariant {
            attributes: vec![],
            name: Some(FileName(
                file_path
                    .file_name()
                    .unwrap()
                    .to_string_lossy()
                    .into_owned(),
            )),
            r#type: mime_guess::from_path(&file_path)
                .first_raw()
                .map(|t| MediaType(t.to_owned())),
            content: FileContent(std::fs::read(&file_path.to_string_lossy().as_ref()).unwrap()),
        }],
    }
}

/// Mapping (extension, MIME type)
const STATEMENT_FORMATS: [(&'static str, &'static str); 3] = [
    ("pdf", "application/pdf"),
    ("html", "text/html"),
    ("md", "application/markdown"),
];

/// Find the statements directory, as in the italy_yaml task format
/// Searches the paths $task_dir/statement and $task_dir/testo
fn statements_dir(task_dir: &Path) -> Option<PathBuf> {
    for dir in vec!["statement", "testo"] {
        let dir = task_dir.join(dir);
        if dir.exists() && dir.is_dir() {
            return Some(dir);
        }
    }
    None
}

/// Tries to match the filename, returning the mimetype of the
/// matched item, if any
fn match_statement(path: &Path) -> Option<(String, FileName, MediaType)> {
    let ext = path.extension().unwrap().to_str().unwrap();
    let filename = path.file_name().unwrap().to_str().unwrap();
    let language = path.file_stem().unwrap().to_str().unwrap();
    for &(extension, mime_type) in &STATEMENT_FORMATS {
        if ext == extension {
            return Some((
                language.to_owned(),
                FileName(filename.to_owned()),
                MediaType(mime_type.to_owned()),
            ));
        }
    }
    None
}

/// find all the statements in the directory
fn statements_of(task_dir: &Path) -> Vec<FileVariant> {
    let mut result = Vec::new();
    let dir = statements_dir(task_dir);
    if let Some(dir) = dir {
        for file in dir.read_dir().unwrap() {
            let file = file.unwrap().path();
            if let Some((language, filename, mime_type)) = match_statement(&file) {
                result.push(FileVariant {
                    attributes: vec![VariantAttribute {
                        key: "language_name".to_owned(),
                        value: language,
                    }],
                    name: Some(filename),
                    r#type: Some(mime_type),
                    content: FileContent(
                        std::fs::read(file).expect("Unable to read statement file"),
                    ),
                });
            }
        }
    }
    result
}

pub fn gen_material(task: &ioi::Task) -> Material {
    Material {
        title: vec![TextVariant {
            attributes: vec![],
            value: task.title.clone().into(),
        }],
        statement: statements_of(&task.path),
        attachments: files_in_dir(&task.path.join("att"))
            .map(attachment_at_path)
            .collect(),
        submission_form: submission_form(),
        awards: { subtasks_of(task).into_iter().map(award_of).collect() },
        feedback: vec![Section::Table(TableSection {
            caption: caption(),
            cols: cols(),
            row_groups: subtasks_of(task).into_iter().map(row_group_of).collect(),
        })],
    }
}
<commit_msg>task-maker: generate short variants of some titles<commit_after>extern crate mime_guess;

use std::convert::TryInto;
use std::path::{Path, PathBuf};
use task_maker_format::ioi;
use turingarena::award::*;
use turingarena::content::*;
use turingarena::evaluation::record::*;
use turingarena::feedback::{table::*, *};
use turingarena::problem::material::*;
use turingarena::submission::form::*;

fn subtasks_of(task: &ioi::Task) -> Vec<&ioi::SubtaskInfo> {
    let mut subtasks: Vec<_> = task.subtasks.values().collect();
    subtasks.sort_by(|a, b| a.id.cmp(&b.id));
    subtasks
}

fn testcases_of(subtask: &ioi::SubtaskInfo) -> Vec<&ioi::TestcaseInfo> {
    let mut testcases: Vec<_> = subtask.testcases.values().collect();
    testcases.sort_by(|a, b| a.id.cmp(&b.id));
    testcases
}

fn submission_form() -> Form {
    Form {
        fields: vec![Field {
            id: FieldId("solution".into()),
            title: vec![TextVariant {
                attributes: vec![],
                value: "Solution".into(),
            }],
            types: vec![FileType {
                id: FileTypeId("cpp".into()),
                title: vec![TextVariant {
                    attributes: vec![],
                    value: "C++".into(),
                }],
                extensions: vec![
                    FileTypeExtension(".cpp".into()),
                    FileTypeExtension(".cc".into()),
                ],
                primary_extension: FileTypeExtension(".cpp".into()),
            }],
        }],
    }
}

fn award_of(subtask: &ioi::SubtaskInfo) -> Award {
    Award {
        name: AwardName(format!("subtask.{}", subtask.id)),
        title: vec![
            TextVariant {
                attributes: vec![],
                value: format!("Subtask {}", subtask.id),
            },
            TextVariant {
                attributes: vec![VariantAttribute {
                    key: "style".to_owned(),
                    value: "short".to_owned(),
                }],
                value: format!("ST {}", subtask.id),
            },
        ],
        content: if subtask.max_score > 0.0 {
            AwardContent::Score(ScoreAwardContent {
                range: ScoreRange {
                    // TODO: assuming IOI-like tasks have integer scores
                    precision: 0,
                    max: Score(subtask.max_score),
                },
            })
        } else {
            AwardContent::Badge(BadgeAwardContent)
        },
    }
}

fn cols() -> Vec<Col> {
    vec![
        Col {
            title: vec![TextVariant {
                attributes: vec![],
                value: format!("Case"),
            }],
            content: ColContent::RowNumber(RowNumberColContent {}),
        },
        Col {
            title: vec![TextVariant {
                attributes: vec![],
                value: format!("Score"),
            }],
            content: ColContent::Score(ScoreColContent {
                range: ScoreRange {
                    // FIXME: assuming per-test-case score has fixed precision
                    precision: 2,
                    max: Score(1.),
                },
            }),
        },
    ]
}

fn caption() -> Text {
    vec![TextVariant {
        attributes: vec![],
        value: format!("Test case results"),
    }]
}

fn row_group_of(subtask: &ioi::SubtaskInfo) -> RowGroup {
    RowGroup {
        title: vec![TextVariant {
            attributes: vec![],
            value: format!("Subtask {}", subtask.id),
        }],
        rows: testcases_of(subtask).into_iter().map(row_of).collect(),
    }
}

fn row_of(testcase: &ioi::TestcaseInfo) -> Row {
    Row {
        content: RowContent::Data,
        cells: vec![
            Cell {
                content: CellContent::RowNumber(RowNumberCellContent {
                    number: testcase.id.try_into().expect("Testcase ID too large"),
                }),
            },
            Cell {
                content: CellContent::Score(ScoreCellContent {
                    range: ScoreRange {
                        precision: 2,
                        max: Score(1.),
                    },
                    r#ref: Key(format!("testcase.{}.score", testcase.id)),
                }),
            },
        ],
    }
}

fn files_in_dir(dir_path: &std::path::PathBuf) -> impl Iterator<Item = std::path::PathBuf> {
    std::fs::read_dir(dir_path)
        .expect("unable to read_dir")
        .map(|entry| entry.expect("unable to read_dir").path())
}

fn attachment_at_path(file_path: std::path::PathBuf) -> Attachment {
    Attachment {
        title: vec![TextVariant {
            attributes: vec![],
            value: file_path
                .file_name()
                .unwrap()
                .to_string_lossy()
                .into_owned(),
        }],
        file: vec![FileVariant {
            attributes: vec![],
            name: Some(FileName(
                file_path
                    .file_name()
                    .unwrap()
                    .to_string_lossy()
                    .into_owned(),
            )),
            r#type: mime_guess::from_path(&file_path)
                .first_raw()
                .map(|t| MediaType(t.to_owned())),
            content: FileContent(std::fs::read(&file_path.to_string_lossy().as_ref()).unwrap()),
        }],
    }
}

/// Mapping (extension, MIME type)
const STATEMENT_FORMATS: [(&'static str, &'static str); 3] = [
    ("pdf", "application/pdf"),
    ("html", "text/html"),
    ("md", "application/markdown"),
];

/// Find the statements directory, as in the italy_yaml task format
/// Searches the paths $task_dir/statement and $task_dir/testo
fn statements_dir(task_dir: &Path) -> Option<PathBuf> {
    for dir in vec!["statement", "testo"] {
        let dir = task_dir.join(dir);
        if dir.exists() && dir.is_dir() {
            return Some(dir);
        }
    }
    None
}

/// Tries to match the filename, returning the mimetype of the
/// matched item, if any
fn match_statement(path: &Path) -> Option<(String, FileName, MediaType)> {
    let ext = path.extension().unwrap().to_str().unwrap();
    let filename = path.file_name().unwrap().to_str().unwrap();
    let language = path.file_stem().unwrap().to_str().unwrap();
    for &(extension, mime_type) in &STATEMENT_FORMATS {
        if ext == extension {
            return Some((
                language.to_owned(),
                FileName(filename.to_owned()),
                MediaType(mime_type.to_owned()),
            ));
        }
    }
    None
}

/// find all the statements in the directory
fn statements_of(task_dir: &Path) -> Vec<FileVariant> {
    let mut result = Vec::new();
    let dir = statements_dir(task_dir);
    if let Some(dir) = dir {
        for file in dir.read_dir().unwrap() {
            let file = file.unwrap().path();
            if let Some((language, filename, mime_type)) = match_statement(&file) {
                result.push(FileVariant {
                    attributes: vec![VariantAttribute {
                        key: "language_name".to_owned(),
                        value: language,
                    }],
                    name: Some(filename),
                    r#type: Some(mime_type),
                    content: FileContent(
                        std::fs::read(file).expect("Unable to read statement file"),
                    ),
                });
            }
        }
    }
    result
}

pub fn gen_material(task: &ioi::Task) -> Material {
    Material {
        title: vec![
            TextVariant {
                attributes: vec![],
                value: task.title.clone().into(),
            },
            TextVariant {
                attributes: vec![VariantAttribute {
                    key: "style".to_owned(),
                    value: "short".to_owned(),
                }],
                value: task.name.clone().into(),
            },
        ],
        statement: statements_of(&task.path),
        attachments: files_in_dir(&task.path.join("att"))
            .map(attachment_at_path)
            .collect(),
        submission_form: submission_form(),
        awards: { subtasks_of(task).into_iter().map(award_of).collect() },
        feedback: vec![Section::Table(TableSection {
            caption: caption(),
            cols: cols(),
            row_groups: subtasks_of(task).into_iter().map(row_group_of).collect(),
        })],
    }
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::document_loader::{LoadBlocker, LoadType};
use crate::dom::attr::Attr;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::HTMLVideoElementBinding;
use crate::dom::bindings::codegen::Bindings::HTMLVideoElementBinding::HTMLVideoElementMethods;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::document::Document;
use crate::dom::element::{AttributeMutation, Element};
use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlmediaelement::{HTMLMediaElement, ReadyState};
use crate::dom::node::{document_from_node, window_from_node, Node};
use crate::dom::performanceresourcetiming::InitiatorType;
use crate::dom::virtualmethods::VirtualMethods;
use crate::fetch::FetchCanceller;
use crate::image_listener::{add_cache_listener_for_element, ImageCacheListener};
use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener};
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use net_traits::image_cache::UsePlaceholder;
use net_traits::image_cache::{CanRequestImages, ImageCache, ImageOrMetadataAvailable};
use net_traits::image_cache::{ImageResponse, ImageState, PendingImageId};
use net_traits::request::{CredentialsMode, Destination, RequestInit};
use net_traits::{
    CoreResourceMsg, FetchChannels, FetchMetadata, FetchResponseListener, FetchResponseMsg,
};
use net_traits::{NetworkError, ResourceFetchTiming, ResourceTimingType};
use servo_url::ServoUrl;
use std::cell::Cell;
use std::sync::{Arc, Mutex};

const DEFAULT_WIDTH: u32 = 300;
const DEFAULT_HEIGHT: u32 = 150;

#[dom_struct]
pub struct HTMLVideoElement {
    htmlmediaelement: HTMLMediaElement,
    /// https://html.spec.whatwg.org/multipage/#dom-video-videowidth
    video_width: Cell<u32>,
    /// https://html.spec.whatwg.org/multipage/#dom-video-videoheight
    video_height: Cell<u32>,
    /// Incremented whenever tasks associated with this element are cancelled.
    generation_id: Cell<u32>,
    /// Poster frame fetch request canceller.
    poster_frame_canceller: DomRefCell<FetchCanceller>,
    /// Load event blocker. Will block the load event while the poster frame
    /// is being fetched.
    load_blocker: DomRefCell<Option<LoadBlocker>>,
}

impl HTMLVideoElement {
    fn new_inherited(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
    ) -> HTMLVideoElement {
        HTMLVideoElement {
            htmlmediaelement: HTMLMediaElement::new_inherited(local_name, prefix, document),
            video_width: Cell::new(DEFAULT_WIDTH),
            video_height: Cell::new(DEFAULT_HEIGHT),
            generation_id: Cell::new(0),
            poster_frame_canceller: DomRefCell::new(Default::default()),
            load_blocker: Default::default(),
        }
    }

    #[allow(unrooted_must_root)]
    pub fn new(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
    ) -> DomRoot<HTMLVideoElement> {
        Node::reflect_node(
            Box::new(HTMLVideoElement::new_inherited(
                local_name, prefix, document,
            )),
            document,
            HTMLVideoElementBinding::Wrap,
        )
    }

    pub fn get_video_width(&self) -> u32 {
        self.video_width.get()
    }

    pub fn set_video_width(&self, width: u32) {
        self.video_width.set(width);
    }

    pub fn get_video_height(&self) -> u32 {
        self.video_height.get()
    }

    pub fn set_video_height(&self, height: u32) {
        self.video_height.set(height);
    }

    pub fn allow_load_event(&self) {
        LoadBlocker::terminate(&mut *self.load_blocker.borrow_mut());
    }

    /// https://html.spec.whatwg.org/multipage/#poster-frame
    fn fetch_poster_frame(&self, poster_url: &str) {
        // Step 1.
        let cancel_receiver = self.poster_frame_canceller.borrow_mut().initialize();
        self.generation_id.set(self.generation_id.get() + 1);

        // Step 2.
        if poster_url.is_empty() {
            return;
        }

        // Step 3.
        let poster_url = match document_from_node(self).url().join(&poster_url) {
            Ok(url) => url,
            Err(_) => return,
        };

        // Step 4.
        // We use the image cache for poster frames so we save as much
        // network activity as possible.
        let window = window_from_node(self);
        let image_cache = window.image_cache();
        let response = image_cache.find_image_or_metadata(
            poster_url.clone().into(),
            UsePlaceholder::No,
            CanRequestImages::Yes,
        );
        match response {
            Ok(ImageOrMetadataAvailable::ImageAvailable(image, url)) => {
                self.process_image_response(ImageResponse::Loaded(image, url));
            },

            Err(ImageState::Pending(id)) => {
                add_cache_listener_for_element(image_cache, id, self);
            },

            Err(ImageState::NotRequested(id)) => {
                add_cache_listener_for_element(image_cache, id, self);
                self.do_fetch_poster_frame(poster_url, id, cancel_receiver);
            },

            _ => (),
        }
    }

    /// https://html.spec.whatwg.org/multipage/#poster-frame
    fn do_fetch_poster_frame(
        &self,
        poster_url: ServoUrl,
        id: PendingImageId,
        cancel_receiver: ipc::IpcReceiver<()>,
    ) {
        // Continuation of step 4.
        let document = document_from_node(self);
        let request = RequestInit {
            url: poster_url.clone(),
            destination: Destination::Image,
            credentials_mode: CredentialsMode::Include,
            use_url_credentials: true,
            origin: document.origin().immutable().clone(),
            pipeline_id: Some(document.global().pipeline_id()),
            ..RequestInit::default()
        };

        // Step 5.
        // This delay must be independent from the ones created by HTMLMediaElement during
        // its media load algorithm, otherwise a code like
        // <video poster="poster.png"></video>
        // (which triggers no media load algorithm unless a explicit call to .load() is done)
        // will block the document's load event forever.
        let mut blocker = self.load_blocker.borrow_mut();
        *blocker = Some(LoadBlocker::new(
            &document_from_node(self),
            LoadType::Image(poster_url.clone()),
        ));

        let window = window_from_node(self);
        let context = Arc::new(Mutex::new(PosterFrameFetchContext::new(
            self, poster_url, id,
        )));

        let (action_sender, action_receiver) = ipc::channel().unwrap();
        let (task_source, canceller) = window
            .task_manager()
            .networking_task_source_with_canceller();
        let listener = NetworkListener {
            context,
            task_source,
            canceller: Some(canceller),
        };
        ROUTER.add_route(
            action_receiver.to_opaque(),
            Box::new(move |message| {
                listener.notify_fetch(message.to().unwrap());
            }),
        );
        let global = self.global();
        global
            .core_resource_thread()
            .send(CoreResourceMsg::Fetch(
                request,
                FetchChannels::ResponseMsg(action_sender, Some(cancel_receiver)),
            ))
            .unwrap();
    }
}

impl HTMLVideoElementMethods for HTMLVideoElement {
    // https://html.spec.whatwg.org/multipage/#dom-video-videowidth
    fn VideoWidth(&self) -> u32 {
        if self.htmlmediaelement.get_ready_state() == ReadyState::HaveNothing {
            return 0;
        }
        self.video_width.get()
    }

    // https://html.spec.whatwg.org/multipage/#dom-video-videoheight
    fn VideoHeight(&self) -> u32 {
        if self.htmlmediaelement.get_ready_state() == ReadyState::HaveNothing {
            return 0;
        }
        self.video_height.get()
    }

    // https://html.spec.whatwg.org/multipage/#dom-video-poster
    make_getter!(Poster, "poster");

    // https://html.spec.whatwg.org/multipage/#dom-video-poster
    make_setter!(SetPoster, "poster");

    // For testing purposes only. This is not an event from
    // https://html.spec.whatwg.org/multipage/#dom-video-poster
    event_handler!(postershown, GetOnpostershown, SetOnpostershown);
}

impl VirtualMethods for HTMLVideoElement {
    fn super_type(&self) -> Option<&dyn VirtualMethods> {
        Some(self.upcast::<HTMLMediaElement>() as &dyn VirtualMethods)
    }

    fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
        self.super_type().unwrap().attribute_mutated(attr, mutation);

        if let Some(new_value) = mutation.new_value(attr) {
            match attr.local_name() {
                &local_name!("poster") => {
                    self.fetch_poster_frame(&new_value);
                },
                _ => (),
            };
        }
    }
}

impl ImageCacheListener for HTMLVideoElement {
    fn generation_id(&self) -> u32 {
        self.generation_id.get()
    }

    fn process_image_response(&self, response: ImageResponse) {
        self.htmlmediaelement.process_poster_response(response);
    }
}

struct PosterFrameFetchContext {
    /// Reference to the script thread image cache.
    image_cache: Arc<dyn ImageCache>,
    /// The element that initiated the request.
    elem: Trusted<HTMLVideoElement>,
    /// The cache ID for this request.
    id: PendingImageId,
    /// True if this response is invalid and should be ignored.
    cancelled: bool,
    /// Timing data for this resource
    resource_timing: ResourceFetchTiming,
    /// Url for the resource
    url: ServoUrl,
}

impl FetchResponseListener for PosterFrameFetchContext {
    fn process_request_body(&mut self) {}
    fn process_request_eof(&mut self) {}

    fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) {
        self.image_cache
            .notify_pending_response(self.id, FetchResponseMsg::ProcessResponse(metadata.clone()));

        let metadata = metadata.ok().map(|meta| match meta {
            FetchMetadata::Unfiltered(m) => m,
            FetchMetadata::Filtered { unsafe_, .. } => unsafe_,
        });

        let status_is_ok = metadata
            .as_ref()
            .and_then(|m| m.status.as_ref())
            .map_or(true, |s| s.0 >= 200 && s.0 < 300);

        if !status_is_ok {
            self.cancelled = true;
            self.elem
                .root()
                .poster_frame_canceller
                .borrow_mut()
                .cancel();
        }
    }

    fn process_response_chunk(&mut self, payload: Vec<u8>) {
        if self.cancelled {
            // An error was received previously, skip processing the payload.
            return;
        }

        self.image_cache
            .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseChunk(payload));
    }

    fn process_response_eof(&mut self, response: Result<ResourceFetchTiming, NetworkError>) {
        self.elem.root().allow_load_event();
        self.image_cache
            .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseEOF(response));
    }

    fn resource_timing_mut(&mut self) -> &mut ResourceFetchTiming {
        &mut self.resource_timing
    }

    fn resource_timing(&self) -> &ResourceFetchTiming {
        &self.resource_timing
    }

    fn submit_resource_timing(&mut self) {
        network_listener::submit_timing(self)
    }
}

impl ResourceTimingListener for PosterFrameFetchContext {
    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
        let initiator_type = InitiatorType::LocalName(
            self.elem
                .root()
                .upcast::<Element>()
                .local_name()
                .to_string(),
        );
        (initiator_type, self.url.clone())
    }

    fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
        document_from_node(&*self.elem.root()).global()
    }
}

impl PreInvoke for PosterFrameFetchContext {
    fn should_invoke(&self) -> bool {
        true
    }
}

impl PosterFrameFetchContext {
    fn new(elem: &HTMLVideoElement, url: ServoUrl, id: PendingImageId) -> PosterFrameFetchContext {
        let window = window_from_node(elem);
        PosterFrameFetchContext {
            image_cache: window.image_cache(),
            elem: Trusted::new(elem),
            id,
            cancelled: false,
            resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource),
            url,
        }
    }
}
<commit_msg>Terminate poster frame load blocker before blocking again<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::document_loader::{LoadBlocker, LoadType};
use crate::dom::attr::Attr;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::HTMLVideoElementBinding;
use crate::dom::bindings::codegen::Bindings::HTMLVideoElementBinding::HTMLVideoElementMethods;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::document::Document;
use crate::dom::element::{AttributeMutation, Element};
use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlmediaelement::{HTMLMediaElement, ReadyState};
use crate::dom::node::{document_from_node, window_from_node, Node};
use crate::dom::performanceresourcetiming::InitiatorType;
use crate::dom::virtualmethods::VirtualMethods;
use crate::fetch::FetchCanceller;
use crate::image_listener::{add_cache_listener_for_element, ImageCacheListener};
use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener};
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use net_traits::image_cache::UsePlaceholder;
use net_traits::image_cache::{CanRequestImages, ImageCache, ImageOrMetadataAvailable};
use net_traits::image_cache::{ImageResponse, ImageState, PendingImageId};
use net_traits::request::{CredentialsMode, Destination, RequestInit};
use net_traits::{
    CoreResourceMsg, FetchChannels, FetchMetadata, FetchResponseListener, FetchResponseMsg,
};
use net_traits::{NetworkError, ResourceFetchTiming, ResourceTimingType};
use servo_url::ServoUrl;
use std::cell::Cell;
use std::sync::{Arc, Mutex};

const DEFAULT_WIDTH: u32 = 300;
const DEFAULT_HEIGHT: u32 = 150;

#[dom_struct]
pub struct HTMLVideoElement {
    htmlmediaelement: HTMLMediaElement,
    /// https://html.spec.whatwg.org/multipage/#dom-video-videowidth
    video_width: Cell<u32>,
    /// https://html.spec.whatwg.org/multipage/#dom-video-videoheight
    video_height: Cell<u32>,
    /// Incremented whenever tasks associated with this element are cancelled.
    generation_id: Cell<u32>,
    /// Poster frame fetch request canceller.
    poster_frame_canceller: DomRefCell<FetchCanceller>,
    /// Load event blocker. Will block the load event while the poster frame
    /// is being fetched.
    load_blocker: DomRefCell<Option<LoadBlocker>>,
}

impl HTMLVideoElement {
    fn new_inherited(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
    ) -> HTMLVideoElement {
        HTMLVideoElement {
            htmlmediaelement: HTMLMediaElement::new_inherited(local_name, prefix, document),
            video_width: Cell::new(DEFAULT_WIDTH),
            video_height: Cell::new(DEFAULT_HEIGHT),
            generation_id: Cell::new(0),
            poster_frame_canceller: DomRefCell::new(Default::default()),
            load_blocker: Default::default(),
        }
    }

    #[allow(unrooted_must_root)]
    pub fn new(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
    ) -> DomRoot<HTMLVideoElement> {
        Node::reflect_node(
            Box::new(HTMLVideoElement::new_inherited(
                local_name, prefix, document,
            )),
            document,
            HTMLVideoElementBinding::Wrap,
        )
    }

    pub fn get_video_width(&self) -> u32 {
        self.video_width.get()
    }

    pub fn set_video_width(&self, width: u32) {
        self.video_width.set(width);
    }

    pub fn get_video_height(&self) -> u32 {
        self.video_height.get()
    }

    pub fn set_video_height(&self, height: u32) {
        self.video_height.set(height);
    }

    pub fn allow_load_event(&self) {
        LoadBlocker::terminate(&mut *self.load_blocker.borrow_mut());
    }

    /// https://html.spec.whatwg.org/multipage/#poster-frame
    fn fetch_poster_frame(&self, poster_url: &str) {
        // Step 1.
        let cancel_receiver = self.poster_frame_canceller.borrow_mut().initialize();
        self.generation_id.set(self.generation_id.get() + 1);

        // Step 2.
        if poster_url.is_empty() {
            return;
        }

        // Step 3.
        let poster_url = match document_from_node(self).url().join(&poster_url) {
            Ok(url) => url,
            Err(_) => return,
        };

        // Step 4.
        // We use the image cache for poster frames so we save as much
        // network activity as possible.
        let window = window_from_node(self);
        let image_cache = window.image_cache();
        let response = image_cache.find_image_or_metadata(
            poster_url.clone().into(),
            UsePlaceholder::No,
            CanRequestImages::Yes,
        );
        match response {
            Ok(ImageOrMetadataAvailable::ImageAvailable(image, url)) => {
                self.process_image_response(ImageResponse::Loaded(image, url));
            },

            Err(ImageState::Pending(id)) => {
                add_cache_listener_for_element(image_cache, id, self);
            },

            Err(ImageState::NotRequested(id)) => {
                add_cache_listener_for_element(image_cache, id, self);
                self.do_fetch_poster_frame(poster_url, id, cancel_receiver);
            },

            _ => (),
        }
    }

    /// https://html.spec.whatwg.org/multipage/#poster-frame
    fn do_fetch_poster_frame(
        &self,
        poster_url: ServoUrl,
        id: PendingImageId,
        cancel_receiver: ipc::IpcReceiver<()>,
    ) {
        // Continuation of step 4.
        let document = document_from_node(self);
        let request = RequestInit {
            url: poster_url.clone(),
            destination: Destination::Image,
            credentials_mode: CredentialsMode::Include,
            use_url_credentials: true,
            origin: document.origin().immutable().clone(),
            pipeline_id: Some(document.global().pipeline_id()),
            ..RequestInit::default()
        };

        // Step 5.
        // This delay must be independent from the ones created by HTMLMediaElement during
        // its media load algorithm, otherwise a code like
        // <video poster="poster.png"></video>
        // (which triggers no media load algorithm unless a explicit call to .load() is done)
        // will block the document's load event forever.
        let mut blocker = self.load_blocker.borrow_mut();
        LoadBlocker::terminate(&mut *blocker);
        *blocker = Some(LoadBlocker::new(
            &document_from_node(self),
            LoadType::Image(poster_url.clone()),
        ));

        let window = window_from_node(self);
        let context = Arc::new(Mutex::new(PosterFrameFetchContext::new(
            self, poster_url, id,
        )));

        let (action_sender, action_receiver) = ipc::channel().unwrap();
        let (task_source, canceller) = window
            .task_manager()
            .networking_task_source_with_canceller();
        let listener = NetworkListener {
            context,
            task_source,
            canceller: Some(canceller),
        };
        ROUTER.add_route(
            action_receiver.to_opaque(),
            Box::new(move |message| {
                listener.notify_fetch(message.to().unwrap());
            }),
        );
        let global = self.global();
        global
            .core_resource_thread()
            .send(CoreResourceMsg::Fetch(
                request,
                FetchChannels::ResponseMsg(action_sender, Some(cancel_receiver)),
            ))
            .unwrap();
    }
}

impl HTMLVideoElementMethods for HTMLVideoElement {
    // https://html.spec.whatwg.org/multipage/#dom-video-videowidth
    fn VideoWidth(&self) -> u32 {
        if self.htmlmediaelement.get_ready_state() == ReadyState::HaveNothing {
            return 0;
        }
        self.video_width.get()
    }

    // https://html.spec.whatwg.org/multipage/#dom-video-videoheight
    fn VideoHeight(&self) -> u32 {
        if self.htmlmediaelement.get_ready_state() == ReadyState::HaveNothing {
            return 0;
        }
        self.video_height.get()
    }

    // https://html.spec.whatwg.org/multipage/#dom-video-poster
    make_getter!(Poster, "poster");

    // https://html.spec.whatwg.org/multipage/#dom-video-poster
    make_setter!(SetPoster, "poster");

    // For testing purposes only. This is not an event from
    // https://html.spec.whatwg.org/multipage/#dom-video-poster
    event_handler!(postershown, GetOnpostershown, SetOnpostershown);
}

impl VirtualMethods for HTMLVideoElement {
    fn super_type(&self) -> Option<&dyn VirtualMethods> {
        Some(self.upcast::<HTMLMediaElement>() as &dyn VirtualMethods)
    }

    fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
        self.super_type().unwrap().attribute_mutated(attr, mutation);

        if let Some(new_value) = mutation.new_value(attr) {
            match attr.local_name() {
                &local_name!("poster") => {
                    self.fetch_poster_frame(&new_value);
                },
                _ => (),
            };
        }
    }
}

impl ImageCacheListener for HTMLVideoElement {
    fn generation_id(&self) -> u32 {
        self.generation_id.get()
    }

    fn process_image_response(&self, response: ImageResponse) {
        self.htmlmediaelement.process_poster_response(response);
    }
}

struct PosterFrameFetchContext {
    /// Reference to the script thread image cache.
    image_cache: Arc<dyn ImageCache>,
    /// The element that initiated the request.
    elem: Trusted<HTMLVideoElement>,
    /// The cache ID for this request.
    id: PendingImageId,
    /// True if this response is invalid and should be ignored.
    cancelled: bool,
    /// Timing data for this resource
    resource_timing: ResourceFetchTiming,
    /// Url for the resource
    url: ServoUrl,
}

impl FetchResponseListener for PosterFrameFetchContext {
    fn process_request_body(&mut self) {}
    fn process_request_eof(&mut self) {}

    fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) {
        self.image_cache
            .notify_pending_response(self.id, FetchResponseMsg::ProcessResponse(metadata.clone()));

        let metadata = metadata.ok().map(|meta| match meta {
            FetchMetadata::Unfiltered(m) => m,
            FetchMetadata::Filtered { unsafe_, .. } => unsafe_,
        });

        let status_is_ok = metadata
            .as_ref()
            .and_then(|m| m.status.as_ref())
            .map_or(true, |s| s.0 >= 200 && s.0 < 300);

        if !status_is_ok {
            self.cancelled = true;
            self.elem
                .root()
                .poster_frame_canceller
                .borrow_mut()
                .cancel();
        }
    }

    fn process_response_chunk(&mut self, payload: Vec<u8>) {
        if self.cancelled {
            // An error was received previously, skip processing the payload.
            return;
        }

        self.image_cache
            .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseChunk(payload));
    }

    fn process_response_eof(&mut self, response: Result<ResourceFetchTiming, NetworkError>) {
        self.elem.root().allow_load_event();
        self.image_cache
            .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseEOF(response));
    }

    fn resource_timing_mut(&mut self) -> &mut ResourceFetchTiming {
        &mut self.resource_timing
    }

    fn resource_timing(&self) -> &ResourceFetchTiming {
        &self.resource_timing
    }

    fn submit_resource_timing(&mut self) {
        network_listener::submit_timing(self)
    }
}

impl ResourceTimingListener for PosterFrameFetchContext {
    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
        let initiator_type = InitiatorType::LocalName(
            self.elem
                .root()
                .upcast::<Element>()
                .local_name()
                .to_string(),
        );
        (initiator_type, self.url.clone())
    }

    fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
        document_from_node(&*self.elem.root()).global()
    }
}

impl PreInvoke for PosterFrameFetchContext {
    fn should_invoke(&self) -> bool {
        true
    }
}

impl PosterFrameFetchContext {
    fn new(elem: &HTMLVideoElement, url: ServoUrl, id: PendingImageId) -> PosterFrameFetchContext {
        let window = window_from_node(elem);
        PosterFrameFetchContext {
            image_cache: window.image_cache(),
            elem: Trusted::new(elem),
            id,
            cancelled: false,
            resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource),
            url,
        }
    }
}
<|endoftext|>