Revamped encoders to produce the actual HTTP responses.
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2POSTEncoder.cpp
1 /*
2  *  Copyright 2001-2006 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * SAML2POSTEncoder.cpp
19  * 
20  * SAML 2.0 HTTP-POST binding message encoder
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "saml2/binding/SAML2POSTEncoder.h"
26 #include "saml2/core/Protocols.h"
27
28 #include <fstream>
29 #include <sstream>
30 #include <log4cpp/Category.hh>
31 #include <xercesc/util/Base64.hpp>
32 #include <xmltooling/util/NDC.h>
33 #include <xmltooling/util/TemplateEngine.h>
34
35 using namespace opensaml::saml2p;
36 using namespace opensaml;
37 using namespace xmlsignature;
38 using namespace xmltooling;
39 using namespace log4cpp;
40 using namespace std;
41
42 namespace opensaml {
43     namespace saml2p {              
44         MessageEncoder* SAML_DLLLOCAL SAML2POSTEncoderFactory(const DOMElement* const & e)
45         {
46             return new SAML2POSTEncoder(e);
47         }
48     };
49 };
50
51 static const XMLCh templat[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
52
53 SAML2POSTEncoder::SAML2POSTEncoder(const DOMElement* e)
54 {
55     if (e) {
56         auto_ptr_char t(e->getAttributeNS(NULL, templat));
57         if (t.get())
58             m_template = t.get();
59     }
60     if (m_template.empty())
61         throw XMLToolingException("SAML2POSTEncoder requires template attribute.");
62 }
63
64 SAML2POSTEncoder::~SAML2POSTEncoder() {}
65
66 long SAML2POSTEncoder::encode(
67     HTTPResponse& httpResponse,
68     XMLObject* xmlObject,
69     const char* destination,
70     const char* recipientID,
71     const char* relayState,
72     const CredentialResolver* credResolver,
73     const XMLCh* sigAlgorithm
74     ) const
75 {
76 #ifdef _DEBUG
77     xmltooling::NDC ndc("encode");
78 #endif
79     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
80     log.debug("validating input");
81     
82     if (xmlObject->getParent())
83         throw BindingException("Cannot encode XML content with parent.");
84     
85     StatusResponseType* response = NULL;
86     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
87     if (!request) {
88         response = dynamic_cast<StatusResponseType*>(xmlObject);
89         if (!response)
90             throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
91     }
92     
93     DOMElement* rootElement = NULL;
94     if (credResolver) {
95         // Signature based on native XML signing.
96         if (request ? request->getSignature() : response->getSignature()) {
97             log.debug("message already signed, skipping signature operation");
98         }
99         else {
100             log.debug("signing and marshalling the message");
101
102             // Build a Signature.
103             Signature* sig = buildSignature(credResolver, sigAlgorithm);
104             
105             // Append Signature.
106             request ? request->setSignature(sig) : response->setSignature(sig);    
107         
108             // Sign response while marshalling.
109             vector<Signature*> sigs(1,sig);
110             rootElement = xmlObject->marshall((DOMDocument*)NULL,&sigs);
111         }
112     }
113     else {
114         log.debug("marshalling the message");
115         rootElement = xmlObject->marshall();
116     }
117     
118     string xmlbuf;
119     XMLHelper::serialize(rootElement, xmlbuf);
120     unsigned int len=0;
121     XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(xmlbuf.data()),xmlbuf.size(),&len);
122     if (out) {
123         xmlbuf.erase();
124         xmlbuf.append(reinterpret_cast<char*>(out),len);
125         XMLString::release(&out);
126     }
127     else {
128         throw BindingException("Base64 encoding of XML failed.");
129     }
130     
131     // Push message into template and send result to client.
132     log.debug("message encoded, sending HTML form template to client");
133     TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
134     if (!engine)
135         throw BindingException("Encoding message using POST requires a TemplateEngine instance.");
136     ifstream infile(m_template.c_str());
137     if (!infile)
138         throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
139     map<string,string> params;
140     params["action"] = destination;
141     params[request ? "SAMLRequest" : "SAMLResponse"] = xmlbuf;
142     if (relayState)
143         params["RelayState"] = relayState;
144     stringstream s;
145     engine->run(infile, s, params);
146     long ret = httpResponse.sendResponse(s);
147
148     // Cleanup by destroying XML.
149     delete xmlObject;
150     return ret;
151 }