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


/* SAMLResponse.cpp - SAML response implementation

   Scott Cantor
   5/28/02

   $History:$
*/

#include "internal.h"

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


SAMLResponse::SAMLResponse(const XMLCh* inResponseTo, const XMLCh* recipient, const Iterator<SAMLAssertion*>& assertions, SAMLException* e)
    : m_responseId(NULL), m_inResponseTo(NULL), m_issueInstant(NULL), m_recipient(NULL), m_exception(e)

{
    RTTI(SAMLResponse);
    if (e)
        return;
    
    if (inResponseTo)
        m_responseId=XMLString::replicate(inResponseTo);
    if (recipient)
        m_recipient=XMLString::replicate(recipient);

    while (assertions.hasNext())
        m_assertions.push_back(assertions.next());
}

SAMLResponse::SAMLResponse(DOMElement* e)
    : m_inResponseTo(NULL), m_responseId(NULL), m_issueInstant(NULL), m_recipient(NULL), m_exception(NULL)
{
    RTTI(SAMLResponse);
    fromDOM(e);
}

SAMLResponse::SAMLResponse(istream& in)
    : SAMLSignedObject(in), m_inResponseTo(NULL), m_responseId(NULL), m_issueInstant(NULL), m_recipient(NULL), m_exception(NULL)
{
    RTTI(SAMLResponse);
    fromDOM(m_document->getDocumentElement());
}

SAMLResponse::~SAMLResponse()
{
    if (m_bOwnStrings)
    {
        delete[] const_cast<XMLCh*>(m_inResponseTo);
        delete[] const_cast<XMLCh*>(m_recipient);
    }
    delete m_issueInstant;
    for (vector<SAMLAssertion*>::const_iterator i=m_assertions.begin(); i!=m_assertions.end(); i++)
        delete (*i);
    delete m_exception;
}

SAMLObject* SAMLResponse::clone() const
{
    return new SAMLResponse(m_inResponseTo,m_recipient,getAssertions().clone(),static_cast<SAMLException*>(m_exception->clone()));
}

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

    if (SAMLConfig::getConfig().strict_dom_checking &&
        (XMLString::compareString(XML::SAMLP_NS,e->getNamespaceURI()) || XMLString::compareString(L(Response),e->getLocalName())))
        throw MalformedException(SAMLException::RESPONDER,"SAMLResponse::fromDOM() requires samlp:Response at root");

    m_root=e;
    m_bOwnStrings=false;

    if (XMLString::parseInt(e->getAttributeNS(NULL,L(MajorVersion)))!=1)
        throw MalformedException(SAMLException::VERSIONMISMATCH,"SAMLResponse::fromDOM() detected incompatible response major version");

    m_responseId=e->getAttributeNS(NULL,L(ResponseID));
    m_issueInstant=new XMLDateTime(e->getAttributeNS(NULL,L(IssueInstant)));
    m_issueInstant->parseDateTime();
    m_inResponseTo=e->getAttributeNS(NULL,L(InResponseTo));
    m_recipient=e->getAttributeNS(NULL,L(Recipient));

    // Move to first child element.
    DOMNode* n=e->getFirstChild();
    while (n && n->getNodeType()!=DOMNode::ELEMENT_NODE)
        n=n->getNextSibling();
    if (!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);

        // Move to Status element.
        n=n->getNextSibling();
        while (n && n->getNodeType()!=DOMNode::ELEMENT_NODE)
            n=n->getNextSibling();
    }

    auto_ptr<SAMLException> excep(SAMLException::getInstance(static_cast<DOMElement*>(n)));

    // If it's an error, toss it out.
    Iterator<saml::QName> codes=excep->getCodes();
    if (codes.hasNext())
    {
        const saml::QName& code=codes.next();
        if (XMLString::compareString(XML::SAMLP_NS,code.getNamespaceURI()) || XMLString::compareString(L(Success),code.getLocalName()))
            throw *excep;
    }
    else
        throw *excep;

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

void SAMLResponse::insertSignature()
{
    m_root->insertBefore(getSignatureElement(),m_root->getFirstChild());
}

DOMNode* SAMLResponse::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::SAMLP_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,saml),XML::SAML_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 (!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 a Response.
    static const XMLCh One[]={chDigit_1, chNull};
    static const XMLCh Zero[]={chDigit_0, chNull};
    DOMElement* r=doc->createElementNS(XML::SAMLP_NS,L(Response));
    if (xmlns)
        r->setAttributeNS(XML::XMLNS_NS,L(xmlns),XML::SAMLP_NS);
    r->setAttributeNS(XML::XMLNS_NS,L_QNAME(xmlns,samlp),XML::SAMLP_NS);
    r->setAttributeNS(XML::XMLNS_NS,L_QNAME(xmlns,saml),XML::SAML_NS);
    r->setAttributeNS(NULL,L(MajorVersion),One);
    r->setAttributeNS(NULL,L(MinorVersion),SAMLConfig::getConfig().compatibility_mode ? Zero : One);
    r->setAttributeNS(NULL,L(IssueInstant),timeptr.get());

    SAMLIdentifier id;
    r->setAttributeNS(NULL,L(ResponseID),id);
    r->setIdAttributeNS(NULL,L(ResponseID));
    if (m_inResponseTo)
        r->setAttributeNS(NULL,L(InResponseTo),m_inResponseTo);
    if (m_recipient)
        r->setAttributeNS(NULL,L(Recipient),m_recipient);

    if (m_exception)
        r->appendChild(m_exception->toDOM(doc,false));
    else
    {
        DOMElement* status=doc->createElementNS(XML::SAMLP_NS,L(Status));
        r->appendChild(status);

        DOMElement* code=doc->createElementNS(XML::SAMLP_NS,L(StatusCode));
        code->setAttributeNS(NULL,L(Value),L(Success));
        status->appendChild(code);
    }

    for (vector<SAMLAssertion*>::const_iterator i=m_assertions.begin(); i!=m_assertions.end(); i++)
        r->appendChild((*i)->toDOM(doc));

    return m_root=r;
}
