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


/* SAMLRequest.cpp - SAML request implementation

   Scott Cantor
   5/21/02

   $History:$
*/

#include "internal.h"

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


SAMLRequest::SAMLRequest(const Iterator<saml::QName>& respondWiths, SAMLQuery* query,
                         const Iterator<const XMLCh*>& assertionIdRefs, const Iterator<const XMLCh*>& artifacts)
    : m_requestId(NULL), m_issueInstant(NULL), m_query(query)
{
    RTTI(SAMLRequest);

    while (respondWiths.hasNext())
        m_respondWiths.push_back(respondWiths.next());
    if (query)
        return;

    if (assertionIdRefs.size()>0)
    {    
        while (assertionIdRefs.hasNext())
            m_assertionIdRefs.push_back(XMLString::replicate(assertionIdRefs.next()));
    }
    else
    {
        while (artifacts.hasNext())
            m_artifacts.push_back(XMLString::replicate(artifacts.next()));
    }
}

SAMLRequest::SAMLRequest(DOMElement* e) : m_query(NULL), m_requestId(NULL), m_issueInstant(NULL)
{
    RTTI(SAMLRequest);
    fromDOM(e);
}

SAMLRequest::SAMLRequest(istream& in) : SAMLSignedObject(in), m_requestId(NULL), m_issueInstant(NULL), m_query(NULL)
{
    RTTI(SAMLRequest);
    fromDOM(m_document->getDocumentElement());
}

SAMLRequest::~SAMLRequest()
{
    delete m_issueInstant;
    delete m_query;
    if (m_bOwnStrings)
    {
        for (vector<const XMLCh*>::const_iterator i=m_assertionIdRefs.begin(); i!=m_assertionIdRefs.end(); i++)
            delete[] const_cast<XMLCh*>(*i);
        for (vector<const XMLCh*>::const_iterator j=m_artifacts.begin(); j!=m_artifacts.end(); j++)
            delete[] const_cast<XMLCh*>(*j);
    }
}

SAMLObject* SAMLRequest::clone() const
{
    return new SAMLRequest(
        m_respondWiths,
        m_query ? static_cast<SAMLQuery*>(m_query->clone()) : NULL,
        m_assertionIdRefs,
        m_artifacts
        );
}

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

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

    m_root=e;
    m_bOwnStrings=false;

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

    m_requestId=e->getAttributeNS(NULL,L(RequestID));
    m_issueInstant=new XMLDateTime(e->getAttributeNS(NULL,L(IssueInstant)));
    m_issueInstant->parseDateTime();

    DOMNodeList* nlist=e->getElementsByTagNameNS(XML::SAMLP_NS,L(RespondWith));
    for (int i=0; nlist && i<nlist->getLength(); i++)
    {
        auto_ptr<saml::QName> rw(saml::QName::getQNameTextNode(static_cast<DOMText*>(nlist->item(i)->getFirstChild())));
        m_respondWiths.push_back(*rw);
    }

    // Look for assertion references.
    nlist = e->getElementsByTagNameNS(XML::SAML_NS,L(AssertionIDRef));
    if (nlist && nlist->getLength() > 0)
    {
        for (int i = 0; i < nlist->getLength(); i++)
            m_assertionIdRefs.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
    }
    else
    {
        // Look for artifacts.
        nlist = e->getElementsByTagNameNS(XML::SAMLP_NS,L(AssertionArtifact));
        if (nlist && nlist->getLength() > 0)
        {
            for (int i = 0; i < nlist->getLength(); i++)
                m_artifacts.push_back(nlist->item(i)->getFirstChild()->getNodeValue());
        }
        else
        {
            // The query is the last child element.
            DOMNode* n=e->getLastChild();
            while (n->getNodeType()!=DOMNode::ELEMENT_NODE)
                n=n->getPreviousSibling();
        
            m_query=SAMLQuery::getInstance(static_cast<DOMElement*>(n));
            if (!m_query)
                throw UnsupportedExtensionException("SAMLRequest::fromDOM() unable to locate implementation for query type");
        }
    }

    // Check for an XML Signature.
    nlist = e->getElementsByTagNameNS(XML::XMLSIG_NS,L(Signature));
    if (nlist && nlist->getLength() == 1)
    {
        SAMLInternalConfig& conf=dynamic_cast<SAMLInternalConfig&>(SAMLConfig::getConfig());
        m_signature=conf.m_xsec->newSignatureFromDOM(nlist->item(0)->getOwnerDocument(),static_cast<DOMElement*>(nlist->item(0)));
        m_signature->load();
        m_sigElement=static_cast<DOMElement*>(nlist->item(0));
    }
}

void SAMLRequest::insertSignature()
{
    // Goes after any RespondWith elements.
    DOMNode* n=m_root->getFirstChild();
    while (n && n->getNodeType()==DOMNode::ELEMENT_NODE &&
            !XMLString::compareString(XML::SAMLP_NS,n->getNamespaceURI()) &&
            !XMLString::compareString(L(RespondWith),n->getLocalName()))
        n=n->getNextSibling();
    m_root->insertBefore(getSignatureElement(),n);
}

DOMNode* SAMLRequest::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);
        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 Request.
    static const XMLCh One[]={chDigit_1, chNull};
    static const XMLCh Zero[]={chDigit_0, chNull};
    DOMElement* r=doc->createElementNS(XML::SAMLP_NS,L(Request));
    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(RequestID),id);
    r->setIdAttributeNS(NULL,L(RequestID));

    for (vector<saml::QName>::const_iterator i=m_respondWiths.begin(); i!=m_respondWiths.end(); i++)
    {
        DOMElement* rw=doc->createElementNS(XML::SAMLP_NS,L(RespondWith));
        const XMLCh* rwns=i->getNamespaceURI();
        if (XMLString::compareString(XML::SAML_NS,rwns ? rwns : &chNull))
        {
            static const XMLCh nsdecl[]=
                {chLatin_x, chLatin_m, chLatin_l, chLatin_n, chLatin_s, chColon, chLatin_r, chLatin_w, chNull};
            rw->setAttributeNS(XML::XMLNS_NS,nsdecl,rwns);
            static const XMLCh rwpre[]={chLatin_r, chLatin_w, chColon, chNull};
            rwns=rwpre;
        }
        else
        {
            static const XMLCh samlpre[]={chLatin_s, chLatin_a, chLatin_m, chLatin_l, chColon, chNull};
            rwns=samlpre;
        }
        xstring qval(rwns);
        qval+=i->getLocalName();
        rw->appendChild(doc->createTextNode(qval.c_str()));
        r->appendChild(rw);
    }

    if (m_query)
        r->appendChild(m_query->toDOM(doc,false));
    else if (m_assertionIdRefs.size()>0)
    {
        for (vector<const XMLCh*>::const_iterator i=m_assertionIdRefs.begin(); i!=m_assertionIdRefs.end(); i++)
            r->appendChild(doc->createElementNS(XML::SAML_NS,L_QNAME(saml,AssertionIDRef)))->appendChild(doc->createTextNode(*i));
    }
    else
    {
        for (vector<const XMLCh*>::const_iterator i=m_artifacts.begin(); i!=m_artifacts.end(); i++)
            r->appendChild(doc->createElementNS(XML::SAML_NS,L(AssertionArtifact)))->appendChild(doc->createTextNode(*i));
    }

    return m_root=r;
}
