Update copyright.
[shibboleth/opensaml2.git] / saml / saml2 / binding / impl / SAML2POSTEncoder.cpp
index 9dace84..32c8e9c 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  Copyright 2001-2006 Internet2
+ *  Copyright 2001-2007 Internet2
  * 
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 #include "saml2/binding/SAML2POSTEncoder.h"
 #include "saml2/core/Protocols.h"
 
+#include <fstream>
+#include <sstream>
 #include <log4cpp/Category.hh>
 #include <xercesc/util/Base64.hpp>
 #include <xmltooling/util/NDC.h>
+#include <xmltooling/util/TemplateEngine.h>
 
 using namespace opensaml::saml2p;
 using namespace opensaml;
@@ -40,18 +43,33 @@ namespace opensaml {
     namespace saml2p {              
         MessageEncoder* SAML_DLLLOCAL SAML2POSTEncoderFactory(const DOMElement* const & e)
         {
-            return new SAML2POSTEncoder(e);
+            return new SAML2POSTEncoder(e, false);
+        }
+
+        MessageEncoder* SAML_DLLLOCAL SAML2POSTSimpleSignEncoderFactory(const DOMElement* const & e)
+        {
+            return new SAML2POSTEncoder(e, true);
         }
     };
 };
 
-SAML2POSTEncoder::SAML2POSTEncoder(const DOMElement* e) {}
+static const XMLCh templat[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
 
-SAML2POSTEncoder::~SAML2POSTEncoder() {}
+SAML2POSTEncoder::SAML2POSTEncoder(const DOMElement* e, bool simple) : m_simple(simple)
+{
+    if (e) {
+        auto_ptr_char t(e->getAttributeNS(NULL, templat));
+        if (t.get())
+            m_template = t.get();
+    }
+    if (m_template.empty())
+        throw XMLToolingException("SAML2POSTEncoder requires template attribute.");
+}
 
-void SAML2POSTEncoder::encode(
-    map<string,string>& outputFields,
+long SAML2POSTEncoder::encode(
+    GenericResponse& genericResponse,
     XMLObject* xmlObject,
+    const char* destination,
     const char* recipientID,
     const char* relayState,
     const CredentialResolver* credResolver,
@@ -62,21 +80,22 @@ void SAML2POSTEncoder::encode(
     xmltooling::NDC ndc("encode");
 #endif
     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
+
     log.debug("validating input");
-    
-    outputFields.clear();
     if (xmlObject->getParent())
         throw BindingException("Cannot encode XML content with parent.");
     
     StatusResponseType* response = NULL;
     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
-    if (!request)
+    if (!request) {
         response = dynamic_cast<StatusResponseType*>(xmlObject);
-    if (!response)
-        throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
+        if (!response)
+            throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
+    }
     
     DOMElement* rootElement = NULL;
-    if (credResolver) {
+    vector<Signature*> sigs;
+    if (credResolver && !m_simple) {
         // Signature based on native XML signing.
         if (request ? request->getSignature() : response->getSignature()) {
             log.debug("message already signed, skipping signature operation");
@@ -91,35 +110,67 @@ void SAML2POSTEncoder::encode(
             request ? request->setSignature(sig) : response->setSignature(sig);    
         
             // Sign response while marshalling.
-            vector<Signature*> sigs(1,sig);
-            rootElement = xmlObject->marshall((DOMDocument*)NULL,&sigs);
+            sigs.push_back(sig);
         }
     }
     else {
         log.debug("marshalling the message");
-        rootElement = xmlObject->marshall();
     }
     
-    string xmlbuf;
-    XMLHelper::serialize(rootElement, xmlbuf);
-    unsigned int len=0;
-    XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(xmlbuf.data()),xmlbuf.size(),&len);
-    if (out) {
-        xmlbuf.erase();
-        xmlbuf.append(reinterpret_cast<char*>(out),len);
-        XMLString::release(&out);
+    rootElement = xmlObject->marshall((DOMDocument*)NULL,&sigs);
+    
+    // Start tracking data.
+    TemplateEngine::TemplateParameters pmap;
+    if (relayState)
+        pmap.m_map["RelayState"] = relayState;
+
+    // Serialize the message.
+    string& msg = pmap.m_map[(request ? "SAMLRequest" : "SAMLResponse")];
+    XMLHelper::serialize(rootElement, msg);
+
+    // SimpleSign.
+    if (credResolver && m_simple) {
+        log.debug("applying simple signature to message data");
+        string input = (request ? "SAMLRequest=" : "SAMLResponse=") + msg;
+        if (relayState)
+            input = input + "&RelayState=" + relayState;
+        if (!sigAlgorithm)
+            sigAlgorithm = DSIGConstants::s_unicodeStrURIRSA_SHA1;
+        auto_ptr_char alg(sigAlgorithm);
+        pmap.m_map["SigAlg"] = alg.get();
+        input = input + "&SigAlg=" + alg.get();
+
+        char sigbuf[1024];
+        memset(sigbuf,0,sizeof(sigbuf));
+        auto_ptr<XSECCryptoKey> key(credResolver->getKey());
+        Signature::createRawSignature(key.get(), sigAlgorithm, input.c_str(), input.length(), sigbuf, sizeof(sigbuf)-1);
+        pmap.m_map["Signature"] = sigbuf;
     }
-    else {
+    
+    // Base64 the message.
+    unsigned int len=0;
+    XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(msg.data()),msg.size(),&len);
+    if (!out)
         throw BindingException("Base64 encoding of XML failed.");
-    }
+    msg.erase();
+    msg.append(reinterpret_cast<char*>(out),len);
+    XMLString::release(&out);
     
-    // Pass back output fields.
-    outputFields[request ? "SAMLRequest" : "SAMLResponse"] = xmlbuf;
-    if (relayState)
-        outputFields["RelayState"] = relayState;
+    // Push message into template and send result to client.
+    log.debug("message encoded, sending HTML form template to client");
+    TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
+    if (!engine)
+        throw BindingException("Encoding message using POST requires a TemplateEngine instance.");
+    ifstream infile(m_template.c_str());
+    if (!infile)
+        throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
+    pmap.m_map["action"] = destination;
+    stringstream s;
+    engine->run(infile, s, pmap);
+    genericResponse.setContentType("text/html");
+    long ret = genericResponse.sendResponse(s);
 
     // Cleanup by destroying XML.
     delete xmlObject;
-
-    log.debug("message encoded");
+    return ret;
 }