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