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