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