Add property for protocol family to encoders/decoders.
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2SOAPEncoder.cpp
1 /*
2  *  Copyright 2001-2010 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  * SAML2SOAPEncoder.cpp
19  * 
20  * SAML 2.0 SOAP binding message encoder.
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/MessageEncoder.h"
26 #include "signature/ContentReference.h"
27 #include "saml2/core/Protocols.h"
28
29 #include <sstream>
30 #include <xmltooling/logging.h>
31 #include <xmltooling/io/HTTPResponse.h>
32 #include <xmltooling/util/NDC.h>
33 #include <xmltooling/signature/Signature.h>
34 #include <xmltooling/soap/SOAP.h>
35
36 using namespace opensaml::saml2p;
37 using namespace opensaml::saml2md;
38 using namespace opensaml;
39 using namespace xmlsignature;
40 using namespace soap11;
41 using namespace xmltooling::logging;
42 using namespace xmltooling;
43 using namespace std;
44
45 namespace opensaml {
46     namespace saml2p {              
47         class SAML_DLLLOCAL SAML2SOAPEncoder : public MessageEncoder
48         {
49         public:
50             SAML2SOAPEncoder() {}
51             virtual ~SAML2SOAPEncoder() {}
52
53             bool isUserAgentPresent() const {
54                 return false;
55             }
56
57             const XMLCh* getProtocolFamily() const {
58                 return samlconstants::SAML20P_NS;
59             }
60
61             long encode(
62                 GenericResponse& genericResponse,
63                 XMLObject* xmlObject,
64                 const char* destination,
65                 const EntityDescriptor* recipient=nullptr,
66                 const char* relayState=nullptr,
67                 const ArtifactGenerator* artifactGenerator=nullptr,
68                 const Credential* credential=nullptr,
69                 const XMLCh* signatureAlg=nullptr,
70                 const XMLCh* digestAlg=nullptr
71                 ) const;
72         };
73
74         MessageEncoder* SAML_DLLLOCAL SAML2SOAPEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
75         {
76             return new SAML2SOAPEncoder();
77         }
78     };
79 };
80
81 long SAML2SOAPEncoder::encode(
82     GenericResponse& genericResponse,
83     XMLObject* xmlObject,
84     const char* destination,
85     const EntityDescriptor* recipient,
86     const char* relayState,
87     const ArtifactGenerator* artifactGenerator,
88     const Credential* credential,
89     const XMLCh* signatureAlg,
90     const XMLCh* digestAlg
91     ) const
92 {
93 #ifdef _DEBUG
94     xmltooling::NDC ndc("encode");
95 #endif
96     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2SOAP");
97
98     log.debug("validating input");
99     if (xmlObject->getParent())
100         throw BindingException("Cannot encode XML content with parent.");
101
102     genericResponse.setContentType("text/xml");
103     HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
104     if (httpResponse) {
105         httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
106         httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
107         httpResponse->setResponseHeader("Pragma", "no-cache");
108     }
109
110     bool detachOnFailure = false;
111     DOMElement* rootElement = nullptr;
112
113     // Check for a naked message.
114     SignableObject* msg = dynamic_cast<SignableObject*>(xmlObject);
115     if (msg) {
116         // Wrap it in a SOAP envelope and point xmlObject at that.
117         detachOnFailure = true;
118         Envelope* env = EnvelopeBuilder::buildEnvelope();
119         Body* body = BodyBuilder::buildBody();
120         env->setBody(body);
121         body->getUnknownXMLObjects().push_back(msg);
122         xmlObject = env;
123     }
124
125     Envelope* env = dynamic_cast<Envelope*>(xmlObject);
126     if (env) {
127         if (!msg) {
128             msg = (env->getBody() && env->getBody()->hasChildren()) ?
129                 dynamic_cast<SignableObject*>(env->getBody()->getUnknownXMLObjects().front()) : nullptr;
130         }
131         try {
132             if (msg && credential) {
133                 if (msg->getSignature()) {
134                     log.debug("message already signed, skipping signature operation");
135                     rootElement = env->marshall();
136                 }
137                 else {
138                     log.debug("signing the message and marshalling the envelope");
139         
140                     // Build a Signature.
141                     Signature* sig = SignatureBuilder::buildSignature();
142                     msg->setSignature(sig);    
143                     if (signatureAlg)
144                         sig->setSignatureAlgorithm(signatureAlg);
145                     if (digestAlg) {
146                         opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
147                         if (cr)
148                             cr->setDigestAlgorithm(digestAlg);
149                     }
150             
151                     // Sign message while marshalling.
152                     vector<Signature*> sigs(1,sig);
153                     rootElement = env->marshall((DOMDocument*)nullptr,&sigs,credential);
154                 }
155             }
156             else {
157                 log.debug("marshalling the envelope");
158                 rootElement = env->marshall();
159             }
160
161             stringstream s;
162             s << *rootElement;
163             
164             if (log.isDebugEnabled())
165                 log.debug("marshalled envelope:\n%s", s.str().c_str());
166
167             log.debug("sending serialized envelope");
168             bool error = (!msg && env->getBody() && env->getBody()->hasChildren() &&
169                 dynamic_cast<Fault*>(env->getBody()->getUnknownXMLObjects().front()));
170             long ret = error ? genericResponse.sendError(s) : genericResponse.sendResponse(s);
171         
172             // Cleanup by destroying XML.
173             delete env;
174             return ret;
175         }
176         catch (XMLToolingException&) {
177             if (msg && detachOnFailure) {
178                 // A bit weird...we have to "revert" things so that the message is isolated
179                 // so the caller can free it.
180                 if (msg->getParent()) {
181                     msg->getParent()->detach();
182                     msg->detach();
183                 }
184             }
185             throw;
186         }
187     }
188
189     Fault* fault = dynamic_cast<Fault*>(xmlObject);
190     if (fault) {
191         try {
192             log.debug("building envelope and marshalling fault");
193             Envelope* env = EnvelopeBuilder::buildEnvelope();
194             Body* body = BodyBuilder::buildBody();
195             env->setBody(body);
196             body->getUnknownXMLObjects().push_back(fault);
197             rootElement = env->marshall();
198     
199             stringstream s;
200             s << *rootElement;
201             
202             if (log.isDebugEnabled())
203                 log.debug("marshalled envelope:\n%s", s.str().c_str());
204
205             log.debug("sending serialized envelope");
206             long ret = genericResponse.sendError(s);
207         
208             // Cleanup by destroying XML.
209             delete env;
210             return ret;
211         }
212         catch (XMLToolingException&) {
213             // A bit weird...we have to "revert" things so that the fault is isolated
214             // so the caller can free it.
215             if (fault->getParent()) {
216                 fault->getParent()->detach();
217                 fault->detach();
218             }
219             throw;
220         }
221     }
222
223     throw BindingException("XML content for SAML 2.0 SOAP Encoder must be a SAML 2.0 message or SOAP Fault/Envelope.");
224 }