/*
 * The OpenSAML License, Version 1.
 * Copyright (c) 2002
 * University Corporation for Advanced Internet Development, Inc.
 * All rights reserved
 *
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution, if any, must include
 * the following acknowledgment: "This product includes software developed by
 * the University Corporation for Advanced Internet Development
 * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
 * may appear in the software itself, if and wherever such third-party
 * acknowledgments normally appear.
 *
 * Neither the name of OpenSAML nor the names of its contributors, nor
 * Internet2, nor the University Corporation for Advanced Internet Development,
 * Inc., nor UCAID may be used to endorse or promote products derived from this
 * software without specific prior written permission. For written permission,
 * please contact opensaml@opensaml.org
 *
 * Products derived from this software may not be called OpenSAML, Internet2,
 * UCAID, or the University Corporation for Advanced Internet Development, nor
 * may OpenSAML appear in their name, without prior written permission of the
 * University Corporation for Advanced Internet Development.
 *
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
 * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
 * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
 * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


/* SAMLAuthenticationStatement.cpp - SAML authentication statement implementation

   Scott Cantor
   5/27/02

   $History:$
*/

#include "internal.h"

using namespace saml;
using namespace std;

SAMLAuthenticationStatement::SAMLAuthenticationStatement(SAMLSubject* subject, const XMLCh* authMethod, const XMLDateTime& authInstant,
                                                         const XMLCh* subjectIP, const XMLCh* subjectDNS,
                                                         const Iterator<SAMLAuthorityBinding*>& bindings)
{
    RTTI(SAMLAuthenticationStatement);
    if (!subject)
        throw MalformedException(SAMLException::RESPONDER,"SAMLAuthenticationStatement() requires subject");
    else if (!authMethod || !*authMethod)
        throw MalformedException(SAMLException::RESPONDER,"SAMLAuthenticationStatement() requires authentication method");
    m_subject=subject;
    m_authMethod=XMLString::replicate(authMethod);
    m_authInstant=new XMLDateTime(authInstant);
    m_subjectIP=XMLString::replicate(subjectIP);
    m_subjectDNS=XMLString::replicate(subjectDNS);
    while (bindings.hasNext())
        m_bindings.push_back(bindings.next());
}

SAMLAuthenticationStatement::SAMLAuthenticationStatement(DOMElement* e)
    : m_subject(NULL), m_subjectIP(NULL), m_subjectDNS(NULL), m_authMethod(NULL), m_authInstant(NULL)
{
    RTTI(SAMLAuthenticationStatement);
    fromDOM(e);
}

SAMLAuthenticationStatement::SAMLAuthenticationStatement(istream& in)
    : SAMLStatement(in), m_subject(NULL), m_subjectIP(NULL), m_subjectDNS(NULL), m_authMethod(NULL), m_authInstant(NULL)
{
    RTTI(SAMLAuthenticationStatement);
    fromDOM(m_document->getDocumentElement());
}

void SAMLAuthenticationStatement::fromDOM(DOMElement* e)
{
    SAMLObject::fromDOM(e);

    if (SAMLConfig::getConfig().strict_dom_checking)
    {
        if (XMLString::compareString(XML::SAML_NS,e->getNamespaceURI()))
            throw MalformedException(SAMLException::RESPONDER,"SAMLAuthenticationStatement::fromDOM() missing saml namespace on root element");

        if (XMLString::compareString(L(AuthenticationStatement),e->getLocalName()))
        {
            auto_ptr<saml::QName> type(saml::QName::getQNameAttribute(e,XML::XSI_NS,L(type)));
            if ((XMLString::compareString(L(Statement),e->getLocalName()) && XMLString::compareString(L(SubjectStatement),e->getLocalName())) ||
                    !type.get() || XMLString::compareString(XML::SAML_NS,type->getNamespaceURI()) ||
                    XMLString::compareString(L(AuthenticationStatementType),type->getLocalName()))
                throw MalformedException(SAMLException::RESPONDER, "SAMLAuthenticationStatement::fromDOM() requires saml:AuthenticationStatement at root");
        }
    }
    m_root=e;
    m_bOwnStrings=false;

    m_authMethod=e->getAttributeNS(NULL,L(AuthenticationMethod));
    m_authInstant=new XMLDateTime(e->getAttributeNS(NULL,L(AuthenticationInstant)));

    DOMNode* n=e->getFirstChild();
    while (n && n->getNodeType()!=DOMNode::ELEMENT_NODE)
        n=n->getNextSibling();

    m_subject=new SAMLSubject(static_cast<DOMElement*>(n));
    
    n=n->getNextSibling();
    while (n && n->getNodeType()!=DOMNode::ELEMENT_NODE)
        n=n->getNextSibling();

    if (n && !XMLString::compareString(XML::SAML_NS,n->getNamespaceURI()) &&
        !XMLString::compareString(L(SubjectLocality),n->getLocalName()))
    {
        m_subjectIP=(static_cast<DOMElement*>(n))->getAttributeNS(NULL,L(IPAddress));
        m_subjectDNS=(static_cast<DOMElement*>(n))->getAttributeNS(NULL,L(DNSAddress));
    }

    DOMNodeList* nlist = e->getElementsByTagNameNS(XML::SAML_NS,L(AuthorityBinding));
    for (int i=0; nlist && i<nlist->getLength(); i++)
        m_bindings.push_back(new SAMLAuthorityBinding(static_cast<DOMElement*>(nlist->item(i))));
}

SAMLAuthenticationStatement::~SAMLAuthenticationStatement()
{
    delete m_subject;
    if (m_bOwnStrings)
    {
        delete[] const_cast<XMLCh*>(m_subjectIP);
        delete[] const_cast<XMLCh*>(m_subjectDNS);
        delete[] const_cast<XMLCh*>(m_authMethod);
    }
    delete m_authInstant;
    for (vector<SAMLAuthorityBinding*>::const_iterator i=m_bindings.begin(); i!=m_bindings.end(); i++)
        delete (*i);
}

SAMLObject* SAMLAuthenticationStatement::clone() const
{
    return new SAMLAuthenticationStatement(
        static_cast<SAMLSubject*>(m_subject->clone()),m_authMethod,*m_authInstant,m_subjectIP,m_subjectDNS,getBindings().clone()
        );
}

DOMNode* SAMLAuthenticationStatement::toDOM(DOMDocument* doc, bool xmlns) const
{
    SAMLObject::toDOM(doc,xmlns);
    if (m_root)
    {
        if (xmlns)
            static_cast<DOMElement*>(m_root)->setAttributeNS(XML::XMLNS_NS,L(xmlns),XML::SAML_NS);
        return m_root;
    }
    if (!doc)
        doc=m_document;

    // Construct an AuthenticationStatement.
    DOMElement* s=doc->createElementNS(XML::SAML_NS,L(AuthenticationStatement));
    if (xmlns)
        s->setAttributeNS(XML::XMLNS_NS,L(xmlns),XML::SAML_NS);
    s->setAttributeNS(NULL,L(AuthenticationMethod),m_authMethod);
    s->setAttributeNS(NULL,L(AuthenticationInstant),m_authInstant->toString());

    s->appendChild(m_subject->toDOM(doc,false));

    if (m_subjectIP || m_subjectDNS)
    {
        DOMElement* loc=doc->createElementNS(XML::SAML_NS,L(SubjectLocality));
        if (m_subjectIP)
            loc->setAttributeNS(NULL,L(IPAddress),m_subjectIP);
        if (m_subjectDNS)
            loc->setAttributeNS(NULL,L(DNSAddress),m_subjectDNS);
        s->appendChild(loc);
    }

    for (vector<SAMLAuthorityBinding*>::const_iterator i=m_bindings.begin(); i!=m_bindings.end(); i++)
        s->appendChild((*i)->toDOM(doc,false));

    return m_root=s;
}
