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


/* SAMLSubject.cpp - SAML subject implementation

   Scott Cantor
   5/8/02

   $History:$
*/

#include "internal.h"

using namespace saml;
using namespace std;


SAMLSubject::SAMLSubject(const XMLCh* name, const XMLCh* nameQualifier, const XMLCh* format,
                         const Iterator<const XMLCh*>& confirmationMethods, const XMLCh* confirmationData,
                         DOMElement* keyInfo)

{
    RTTI(SAMLSubject);
    if (!name || !*name)
        throw MalformedException("SAMLSubject() requires name");
    m_name=XMLString::replicate(name);
    m_nameQualifier=XMLString::replicate(nameQualifier);
    m_format=XMLString::replicate(format);
    while (confirmationMethods.hasNext())
        m_confirmationMethods.push_back(XMLString::replicate(confirmationMethods.next()));
    m_confirmationData=XMLString::replicate(confirmationData);
    m_keyInfo=keyInfo;
    if (m_keyInfo)
        setDocument(m_keyInfo->getOwnerDocument());
}

SAMLSubject::SAMLSubject(DOMElement* e)
    : m_name(NULL), m_nameQualifier(NULL), m_format(NULL), m_confirmationData(NULL), m_keyInfo(NULL)
{
    RTTI(SAMLSubject);
    fromDOM(e);
}

SAMLSubject::SAMLSubject(istream& in)
    : SAMLObject(in), m_name(NULL), m_nameQualifier(NULL), m_format(NULL), m_confirmationData(NULL), m_keyInfo(NULL)
{
    RTTI(SAMLSubject);
    fromDOM(m_document->getDocumentElement());
}

SAMLSubject::~SAMLSubject()
{
    if (m_bOwnStrings)
    {
        delete[] const_cast<XMLCh*>(m_name);
        delete[] const_cast<XMLCh*>(m_nameQualifier);
        delete[] const_cast<XMLCh*>(m_format);
        for (vector<const XMLCh*>::const_iterator i=m_confirmationMethods.begin(); i!=m_confirmationMethods.end(); i++)
            delete[] const_cast<XMLCh*>(*i);
        delete[] const_cast<XMLCh*>(m_confirmationData);
    }
}

SAMLObject* SAMLSubject::clone() const
{
    return new SAMLSubject(m_name,m_nameQualifier,m_format,m_confirmationMethods,m_confirmationData,m_keyInfo);
}

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

    if (SAMLConfig::getConfig().strict_dom_checking &&
        (XMLString::compareString(XML::SAML_NS,e->getNamespaceURI()) || XMLString::compareString(L(Subject),e->getLocalName())))
        throw MalformedException("SAMLSubject() requires saml:Subject at root");
    m_root=e;
    m_bOwnStrings=false;

    // Look for NameIdentifier.
    DOMNode* n = e->getFirstChild();
    while (n && n->getNodeType() != DOMNode::ELEMENT_NODE)
        n = n->getNextSibling();
    if (n && !XMLString::compareString(XML::SAML_NS,n->getNamespaceURI()) && !XMLString::compareString(L(NameIdentifier),n->getLocalName()))
    {
        m_nameQualifier = (static_cast<DOMElement*>(n))->getAttributeNS(NULL,L(NameQualifier));
        m_format = (static_cast<DOMElement*>(n))->getAttributeNS(NULL,L(Format));
        m_name = n->getFirstChild()->getNodeValue();

        n = n->getNextSibling();
        while (n && n->getNodeType() != DOMNode::ELEMENT_NODE)
            n = n->getNextSibling();
    }

    // Look for SubjectConfirmation.
    if (n && !XMLString::compareString(XML::SAML_NS,n->getNamespaceURI()) && !XMLString::compareString(L(SubjectConfirmation),n->getLocalName()))
    {
        // Iterate over ConfirmationMethods.
        DOMNodeList* nlist = (static_cast<DOMElement*>(n))->getElementsByTagNameNS(XML::SAML_NS,L(ConfirmationMethod));
        for (int i=0; i<nlist->getLength(); i++)
            m_confirmationMethods.push_back(nlist->item(i)->getFirstChild()->getNodeValue());

        // Extract optional SubjectConfirmationData.
        nlist=(static_cast<DOMElement*>(n))->getElementsByTagNameNS(XML::SAML_NS,L(SubjectConfirmationData));
        if (nlist && nlist->getLength()==1)
            m_confirmationData=nlist->item(0)->getFirstChild()->getNodeValue();
        
        // Extract optional ds:KeyInfo.
        nlist=(static_cast<DOMElement*>(n))->getElementsByTagNameNS(XML::XMLSIG_NS,L(KeyInfo));
        if (nlist && nlist->getLength()==1)
            m_keyInfo=static_cast<DOMElement*>(nlist->item(0));
    }
}

DOMNode* SAMLSubject::toDOM(DOMDocument* doc, bool xmlns) const
{
    if (m_root)
    {
        if (xmlns)
            static_cast<DOMElement*>(m_root)->setAttributeNS(XML::XMLNS_NS,L(xmlns),XML::SAML_NS);
        return m_root;
    }
    if (!doc)
    {
        if (!m_document)
        {
            DOMImplementation* impl=DOMImplementationRegistry::getDOMImplementation(NULL);
            m_document=impl->createDocument();
        }
        doc=m_document;
    }

    // Construct a Subject.
    DOMElement* s=doc->createElementNS(XML::SAML_NS,L(Subject));
    s->setAttributeNS(XML::XMLNS_NS,L(xmlns),XML::SAML_NS);

    if (m_name && *m_name)
    {
        DOMElement* nameid=doc->createElementNS(XML::SAML_NS,L(NameIdentifier));
        if (m_nameQualifier && *m_nameQualifier)
            nameid->setAttributeNS(NULL,L(NameQualifier), m_nameQualifier);
        if (m_format && *m_format)
            nameid->setAttributeNS(NULL,L(Format), m_format);
        nameid->appendChild(doc->createTextNode(m_name));
        s->appendChild(nameid);
    }

    if (!m_confirmationMethods.empty())
    {
        DOMElement* conf = doc->createElementNS(XML::SAML_NS,L(SubjectConfirmation));
        for (vector<const XMLCh*>::const_iterator i=m_confirmationMethods.begin(); i!=m_confirmationMethods.end(); i++)
            conf->appendChild(doc->createElementNS(XML::SAML_NS,L(ConfirmationMethod)))->appendChild(doc->createTextNode(*i));
        if (m_confirmationData && *m_confirmationData)
            conf->appendChild(doc->createElementNS(XML::SAML_NS,L(SubjectConfirmationData)))->appendChild(doc->createTextNode(m_confirmationData));
        if (m_keyInfo)
            conf->appendChild(m_keyInfo);
        s->appendChild(conf);
    }

    return m_root=s;
}

const XMLCh SAMLSubject::ARTIFACT01[] = // urn:oasis:names:tc:SAML:1.0:cm:artifact-01
{
    chLatin_u, chLatin_r, chLatin_n, chColon, chLatin_o, chLatin_a, chLatin_s, chLatin_i, chLatin_s, chColon,
    chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chColon, chLatin_t, chLatin_c, chColon,
    chLatin_S, chLatin_A, chLatin_M, chLatin_L, chColon, chDigit_1, chPeriod, chDigit_0, chColon,
    chLatin_c, chLatin_m, chColon, chLatin_a, chLatin_r, chLatin_t, chLatin_i, chLatin_f, chLatin_a, chLatin_c, chLatin_t,
        chDash, chDigit_0, chDigit_1, chNull
};

const XMLCh SAMLSubject::CONF_BEARER[] = // urn:oasis:names:tc:SAML:1.0:cm:bearer
{
    chLatin_u, chLatin_r, chLatin_n, chColon, chLatin_o, chLatin_a, chLatin_s, chLatin_i, chLatin_s, chColon,
    chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chColon, chLatin_t, chLatin_c, chColon,
    chLatin_S, chLatin_A, chLatin_M, chLatin_L, chColon, chDigit_1, chPeriod, chDigit_0, chColon,
    chLatin_c, chLatin_m, chColon, chLatin_b, chLatin_e, chLatin_a, chLatin_r, chLatin_e, chLatin_r, chNull
};

const XMLCh SAMLSubject::HOLDER_KEY[] = // urn:oasis:names:tc:SAML:1.0:cm:holder-of-key
{
    chLatin_u, chLatin_r, chLatin_n, chColon, chLatin_o, chLatin_a, chLatin_s, chLatin_i, chLatin_s, chColon,
    chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chColon, chLatin_t, chLatin_c, chColon,
    chLatin_S, chLatin_A, chLatin_M, chLatin_L, chColon, chDigit_1, chPeriod, chDigit_0, chColon,
    chLatin_c, chLatin_m, chColon, chLatin_h, chLatin_o, chLatin_l, chLatin_d, chLatin_e, chLatin_r, chDash,
        chLatin_o, chLatin_f, chDash, chLatin_k, chLatin_e, chLatin_y, chNull
};

const XMLCh SAMLSubject::SENDER_VOUCHES[] = // urn:oasis:names:tc:SAML:1.0:cm:sender-vouches
{
    chLatin_u, chLatin_r, chLatin_n, chColon, chLatin_o, chLatin_a, chLatin_s, chLatin_i, chLatin_s, chColon,
    chLatin_n, chLatin_a, chLatin_m, chLatin_e, chLatin_s, chColon, chLatin_t, chLatin_c, chColon,
    chLatin_S, chLatin_A, chLatin_M, chLatin_L, chColon, chDigit_1, chPeriod, chDigit_0, chColon,
    chLatin_c, chLatin_m, chColon, chLatin_s, chLatin_e, chLatin_n, chLatin_d, chLatin_e, chLatin_r, chDash,
        chLatin_v, chLatin_o, chLatin_u, chLatin_c, chLatin_h, chLatin_e, chLatin_s, chNull
};
