Reducing header overuse, non-inlining selected methods (CPPOST-35).
[shibboleth/cpp-opensaml.git] / saml / saml1 / binding / impl / SAML1POSTEncoder.cpp
1 /*
2  *  Copyright 2001-2007 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  * SAML1POSTEncoder.cpp
19  * 
20  * SAML 1.x POST binding/profile message encoder
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/MessageEncoder.h"
26 #include "signature/ContentReference.h"
27 #include "saml1/core/Protocols.h"
28
29 #include <fstream>
30 #include <sstream>
31 #include <xercesc/util/Base64.hpp>
32 #include <xmltooling/io/HTTPResponse.h>
33 #include <xmltooling/logging.h>
34 #include <xmltooling/XMLToolingConfig.h>
35 #include <xmltooling/util/NDC.h>
36 #include <xmltooling/util/PathResolver.h>
37 #include <xmltooling/util/TemplateEngine.h>
38
39 using namespace opensaml::saml1p;
40 using namespace opensaml::saml2md;
41 using namespace opensaml;
42 using namespace xmlsignature;
43 using namespace xmltooling::logging;
44 using namespace xmltooling;
45 using namespace std;
46
47 namespace opensaml {
48     namespace saml1p {              
49         class SAML_DLLLOCAL SAML1POSTEncoder : public MessageEncoder
50         {
51         public:
52             SAML1POSTEncoder(const DOMElement* e, const XMLCh* ns);
53             virtual ~SAML1POSTEncoder() {}
54             
55             long encode(
56                 GenericResponse& genericResponse,
57                 XMLObject* xmlObject,
58                 const char* destination,
59                 const EntityDescriptor* recipient=NULL,
60                 const char* relayState=NULL,
61                 const ArtifactGenerator* artifactGenerator=NULL,
62                 const Credential* credential=NULL,
63                 const XMLCh* signatureAlg=NULL,
64                 const XMLCh* digestAlg=NULL
65                 ) const;
66
67         protected:
68             /** Pathname of HTML template for transmission of message via POST. */
69             string m_template;
70         };
71
72         MessageEncoder* SAML_DLLLOCAL SAML1POSTEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
73         {
74             return new SAML1POSTEncoder(p.first, p.second);
75         }
76     };
77 };
78
79 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
80
81 SAML1POSTEncoder::SAML1POSTEncoder(const DOMElement* e, const XMLCh* ns)
82 {
83     if (e) {
84         auto_ptr_char t(e->getAttributeNS(ns, _template));
85         if (t.get() && *t.get())
86             m_template = t.get();
87     }
88     if (m_template.empty())
89         throw XMLToolingException("SAML1POSTEncoder requires template XML attribute.");
90     XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
91 }
92
93 long SAML1POSTEncoder::encode(
94     GenericResponse& genericResponse,
95     XMLObject* xmlObject,
96     const char* destination,
97     const EntityDescriptor* recipient,
98     const char* relayState,
99     const ArtifactGenerator* artifactGenerator,
100     const Credential* credential,
101     const XMLCh* signatureAlg,
102     const XMLCh* digestAlg
103     ) const
104 {
105 #ifdef _DEBUG
106     xmltooling::NDC ndc("encode");
107 #endif
108     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML1POST");
109
110     TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
111     if (!engine)
112         throw BindingException("Encoding response using POST requires a TemplateEngine instance.");
113     
114     log.debug("validating input");
115     if (xmlObject->getParent())
116         throw BindingException("Cannot encode XML content with parent.");
117     Response* response = dynamic_cast<Response*>(xmlObject);
118     if (!response)
119         throw BindingException("XML content for SAML 1.x POST Encoder must be a SAML 1.x <Response>.");
120     if (!relayState)
121         throw BindingException("SAML 1.x POST Encoder requires relay state (TARGET) value.");
122     
123     DOMElement* rootElement = NULL;
124     if (credential) {
125         // Signature based on native XML signing.
126         if (response->getSignature()) {
127             log.debug("response already signed, skipping signature operation");
128         }
129         else {
130             log.debug("signing and marshalling the response");
131
132             // Build a Signature.
133             Signature* sig = SignatureBuilder::buildSignature();
134             response->setSignature(sig);
135             if (signatureAlg)
136                 sig->setSignatureAlgorithm(signatureAlg);
137             if (digestAlg) {
138                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
139                 if (cr)
140                     cr->setDigestAlgorithm(digestAlg);
141             }
142     
143             // Sign response while marshalling.
144             vector<Signature*> sigs(1,sig);
145             rootElement = response->marshall((DOMDocument*)NULL,&sigs,credential);
146         }
147     }
148     else {
149         log.debug("marshalling the response");
150         rootElement = response->marshall();
151     }
152
153     // Push message into template.
154     TemplateEngine::TemplateParameters pmap;
155     string& xmlbuf = pmap.m_map["SAMLResponse"];
156     XMLHelper::serialize(rootElement, xmlbuf);
157     log.debug("marshalled response:\n%s", xmlbuf.c_str());
158     
159     // Replace with base-64 encoded version.
160     xsecsize_t len=0;
161     XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(xmlbuf.data()),xmlbuf.size(),&len);
162     if (out) {
163         xmlbuf.erase();
164         xmlbuf.append(reinterpret_cast<char*>(out),len);
165 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
166         XMLString::release(&out);
167 #else
168         XMLString::release((char**)&out);
169 #endif
170     }
171     else {
172         throw BindingException("Base64 encoding of XML failed.");
173     }
174
175     // Fill in the rest of the data and send to the client.
176     log.debug("message encoded, sending HTML form template to client");
177     ifstream infile(m_template.c_str());
178     if (!infile)
179         throw BindingException("Failed to open HTML template for POST response ($1).", params(1,m_template.c_str()));
180     pmap.m_map["action"] = destination;
181     pmap.m_map["TARGET"] = relayState;
182     stringstream s;
183     engine->run(infile, s, pmap);
184     genericResponse.setContentType("text/html");
185     HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
186     if (httpResponse) {
187         httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
188         httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
189         httpResponse->setResponseHeader("Pragma", "no-cache");
190     }
191     long ret = genericResponse.sendResponse(s);
192
193     // Cleanup by destroying XML.
194     delete xmlObject;
195     return ret;
196 }