/*
 * 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.
 */


/* SAMLAssertion.cpp - SAML assertion implementation

   Scott Cantor
   5/27/02

   $History:$
*/

#include "internal.h"

#include <ctime>
using namespace std;
using namespace saml;

SAMLAssertion::SAMLAssertion(const XMLCh* issuer, const XMLDateTime* notBefore, const XMLDateTime* notOnOrAfter,
                             const Iterator<SAMLCondition*>& conditions, const Iterator<SAMLStatement*>& statements)
    : m_issuer(NULL), m_notBefore(NULL), m_notOnOrAfter(NULL)
{
    RTTI(SAMLAssertion);
    if (!issuer || !*issuer || statements.size()==0)
        throw SAMLException(SAMLException::RESPONDER,"SAMLAssertion() requires issuer and at least one statement");

    m_issuer=XMLString::replicate(issuer);
    if (notBefore)
    {
        m_notBefore=new XMLDateTime(*notBefore);
        m_notBefore->parseDateTime();
    }
    if (notOnOrAfter)
    {
        m_notOnOrAfter=new XMLDateTime(*notOnOrAfter);
        m_notOnOrAfter->parseDateTime();
    }

    while (conditions.hasNext())
        m_conditions.push_back(conditions.next());

    while (statements.hasNext())
        m_statements.push_back(statements.next());
}

SAMLAssertion::SAMLAssertion(DOMElement* e) : m_issuer(NULL), m_notBefore(NULL), m_notOnOrAfter(NULL)
{
    RTTI(SAMLAssertion);
    fromDOM(e);
}

SAMLAssertion::SAMLAssertion(istream& in) : SAMLSignedObject(in), m_issuer(NULL), m_notBefore(NULL), m_notOnOrAfter(NULL)
{
    RTTI(SAMLAssertion);
    fromDOM(m_document->getDocumentElement());
}

SAMLAssertion::~SAMLAssertion()
{
    if (m_bOwnStrings)
        delete[] const_cast<XMLCh*>(m_issuer);
    delete m_notBefore;
    delete m_notOnOrAfter;
    for (vector<SAMLCondition*>::const_iterator i=m_conditions.begin(); i!=m_conditions.end(); i++)
        delete (*i);
    for (vector<SAMLStatement*>::const_iterator j=m_statements.begin(); j!=m_statements.end(); j++)
        delete (*j);
}

SAMLObject* SAMLAssertion::clone() const
{
    return new SAMLAssertion(m_issuer,m_notBefore,m_notOnOrAfter,getConditions().clone(),getStatements().clone());
}

void SAMLAssertion::fromDOM(DOMElement* e)
{
    saml::NDC ndc("fromDOM");
    SAMLObject::fromDOM(e);

    if (SAMLConfig::getConfig().strict_dom_checking &&
        (XMLString::compareString(XML::SAML_NS,e->getNamespaceURI()) || XMLString::compareString(L(Assertion),e->getLocalName())))
        throw MalformedException(SAMLException::RESPONDER,"SAMLAssertion::fromDOM() missing saml:Assertion at root");
    m_root=e;
    m_bOwnStrings=false;
    
    if (XMLString::parseInt(e->getAttributeNS(NULL,L(MajorVersion)))!=1)
        throw MalformedException(SAMLException::VERSIONMISMATCH,"SAMLAssertion::fromDOM() detected incompatible assertion major version");
    
    m_assertionId=e->getAttributeNS(NULL,L(AssertionID));
    m_issuer=e->getAttributeNS(NULL,L(Issuer));
    m_issueInstant=new XMLDateTime(e->getAttributeNS(NULL,L(IssueInstant)));
    m_issueInstant->parseDateTime();

    DOMNode* n=e->getFirstChild();
    while (n)
    {
        // The top level children may be one of three different types.
        if (n->getNodeType()==DOMNode::ELEMENT_NODE &&
            !XMLString::compareString(XML::SAML_NS,n->getNamespaceURI()) &&
            !XMLString::compareString(L(Conditions),n->getLocalName()))
        {
            e=static_cast<DOMElement*>(n);

            if (e->hasAttributeNS(NULL,L(NotBefore)))
            {
                m_notBefore=new XMLDateTime(e->getAttribute(L(NotBefore)));
                m_notBefore->parseDateTime();
            }

            if (e->hasAttributeNS(NULL,L(NotOnOrAfter)))
            {
                m_notOnOrAfter=new XMLDateTime(e->getAttribute(L(NotOnOrAfter)));
                m_notOnOrAfter->parseDateTime();
            }
            
            // Iterate over conditions.
            DOMNode* cond=e->getFirstChild();
            while (cond)
            {
                if (cond->getNodeType()==DOMNode::ELEMENT_NODE)
                {
                    SAMLCondition* pcond=SAMLCondition::getInstance(static_cast<DOMElement*>(cond));
                    if (!pcond)
                        throw UnsupportedExtensionException("SAMLAssertion::fromDOM() unable to locate implementation for condition type");
                    m_conditions.push_back(pcond);
                }
                cond=cond->getNextSibling();
            }
        }
        else if (n->getNodeType()==DOMNode::ELEMENT_NODE &&
                 !XMLString::compareString(XML::SAML_NS,n->getNamespaceURI()) &&
                 !XMLString::compareString(L(Advice),n->getLocalName()))
        {
        }
        else if (n->getNodeType()==DOMNode::ELEMENT_NODE &&
                 !XMLString::compareString(XML::XMLSIG_NS,n->getNamespaceURI()) &&
                 !XMLString::compareString(L(Signature),n->getLocalName()))
        {
            SAMLInternalConfig& conf=dynamic_cast<SAMLInternalConfig&>(SAMLConfig::getConfig());
            m_signature=conf.m_xsec->newSignatureFromDOM(n->getOwnerDocument(),static_cast<DOMElement*>(n));
            m_signature->load();
            m_sigElement=static_cast<DOMElement*>(n);
        }
        else if (n->getNodeType()==DOMNode::ELEMENT_NODE)
        {
            SAMLStatement* pstate=SAMLStatement::getInstance(static_cast<DOMElement*>(n));
            if (!pstate)
                throw UnsupportedExtensionException("SAMLAssertion::fromDOM() unable to locate implementation for statement type");
            m_statements.push_back(pstate);
        }
        n=n->getNextSibling();
    }
}

void SAMLAssertion::insertSignature()
{
    m_root->appendChild(getSignatureElement());
}

DOMNode* SAMLAssertion::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);
            static_cast<DOMElement*>(m_root)->setAttributeNS(XML::XMLNS_NS,L_QNAME(xmlns,saml),XML::SAML_NS);
            static_cast<DOMElement*>(m_root)->setAttributeNS(XML::XMLNS_NS,L_QNAME(xmlns,samlp),XML::SAMLP_NS);
            static_cast<DOMElement*>(m_root)->setAttributeNS(XML::XMLNS_NS,L_QNAME(xmlns,xsi),XML::XSI_NS);
            static_cast<DOMElement*>(m_root)->setAttributeNS(XML::XMLNS_NS,L_QNAME(xmlns,xsd),XML::XSD_NS);
        }
        return m_root;
    }

    if (m_statements.empty())
        throw MalformedException(SAMLException::RESPONDER,"SAMLAssertion::toDOM() requires that at least one statement exist");

    if (!doc)
        doc=m_document;

    time_t now=time(NULL);
#ifndef HAVE_GMTIME_R
    struct tm* ptime=gmtime(&now);
#else
    struct tm res;
    struct tm* ptime=gmtime_r(&now,&res);
#endif
    char timebuf[32];
    strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);
    auto_ptr<XMLCh> timeptr(XMLString::transcode(timebuf));

    // Construct an Assertion.
    static const XMLCh One[]={chDigit_1, chNull};
    static const XMLCh Zero[]={chDigit_0, chNull};
    DOMElement* a=doc->createElementNS(XML::SAML_NS,L(Assertion));
    a->setAttributeNS(XML::XMLNS_NS,L(xmlns),XML::SAML_NS);
    a->setAttributeNS(XML::XMLNS_NS,L_QNAME(xmlns,saml),XML::SAML_NS);
    a->setAttributeNS(XML::XMLNS_NS,L_QNAME(xmlns,samlp),XML::SAMLP_NS);
    a->setAttributeNS(NULL,L(MajorVersion),One);
    a->setAttributeNS(NULL,L(MinorVersion),SAMLConfig::getConfig().compatibility_mode ? Zero : One);

    SAMLIdentifier id;
    a->setAttributeNS(NULL,L(AssertionID),id);
    a->setIdAttributeNS(NULL,L(AssertionID));

    a->setAttributeNS(NULL,L(Issuer),m_issuer);
    a->setAttributeNS(NULL,L(IssueInstant),timeptr.get());

    if (m_notBefore || m_notOnOrAfter || !m_conditions.empty())
    {
        DOMElement* c=doc->createElementNS(XML::SAML_NS,L(Conditions));
        if (m_notBefore)
        {
            auto_ptr<XMLCh> nb(m_notBefore->toString());
            c->setAttributeNS(NULL,L(NotBefore),nb.get());
        }
        if (m_notOnOrAfter)
        {
            auto_ptr<XMLCh> na(m_notOnOrAfter->toString());
            c->setAttributeNS(NULL,L(NotOnOrAfter),na.get());
        }
        for (vector<SAMLCondition*>::const_iterator i=m_conditions.begin(); i!=m_conditions.end(); i++)
            c->appendChild((*i)->toDOM(doc,false));
        a->appendChild(c);
    }

    for (vector<SAMLStatement*>::const_iterator j=m_statements.begin(); j!=m_statements.end(); j++)
        a->appendChild((*j)->toDOM(doc,false));

    return m_root=a;
}
