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