Add property for protocol family to encoders/decoders.
[shibboleth/cpp-opensaml.git] / saml / saml1 / binding / impl / SAML1SOAPEncoder.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  * SAML1SOAPEncoder.cpp
19  * 
20  * SAML 1.x 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 "saml1/core/Protocols.h"
28
29 #include <sstream>
30 #include <xmltooling/logging.h>
31 #include <xmltooling/io/HTTPResponse.h>
32 #include <xmltooling/signature/Signature.h>
33 #include <xmltooling/util/NDC.h>
34 #include <xmltooling/soap/SOAP.h>
35
36 using namespace opensaml::saml1p;
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 saml1p {              
47         class SAML_DLLLOCAL SAML1SOAPEncoder : public MessageEncoder
48         {
49         public:
50             SAML1SOAPEncoder() {}
51             virtual ~SAML1SOAPEncoder() {}
52
53             bool isUserAgentPresent() const {
54                 return false;
55             }
56
57             const XMLCh* getProtocolFamily() const {
58                 return samlconstants::SAML11_PROTOCOL_ENUM;
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 SAML1SOAPEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
75         {
76             return new SAML1SOAPEncoder();
77         }
78     };
79 };
80
81 long SAML1SOAPEncoder::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.SAML1SOAP");
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 Response.
114     Response* response = dynamic_cast<Response*>(xmlObject);
115     if (response) {
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(response);
122         xmlObject = env;
123     }
124
125     // Now check for a full Envelope (which might have just been created).
126     Envelope* env = dynamic_cast<Envelope*>(xmlObject);
127     if (env) {
128         if (!response) {
129             response = (env->getBody() && env->getBody()->hasChildren()) ?
130                 dynamic_cast<Response*>(env->getBody()->getUnknownXMLObjects().front()) : nullptr;
131         }
132         try {
133             // Now check for signing requirements.
134             if (response && credential) {
135                 if (response->getSignature()) {
136                     log.debug("response already signed, skipping signature operation");
137                     rootElement = env->marshall();
138                 }
139                 else {
140                     log.debug("signing the response and marshalling the envelope");
141         
142                     // Build a Signature.
143                     Signature* sig = SignatureBuilder::buildSignature();
144                     response->setSignature(sig);    
145                     if (signatureAlg)
146                         sig->setSignatureAlgorithm(signatureAlg);
147                     if (digestAlg) {
148                         opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
149                         if (cr)
150                             cr->setDigestAlgorithm(digestAlg);
151                     }
152             
153                     // Sign message while marshalling.
154                     vector<Signature*> sigs(1,sig);
155                     rootElement = env->marshall((DOMDocument*)nullptr,&sigs,credential);
156                 }
157             }
158             else {
159                 log.debug("marshalling the envelope");
160                 rootElement = env->marshall();
161             }
162
163             stringstream s;
164             s << *rootElement;
165             
166             if (log.isDebugEnabled())
167                 log.debug("marshalled envelope:\n%s", s.str().c_str());
168             
169             log.debug("sending serialized envelope");
170             bool error = (!response && env->getBody() && env->getBody()->hasChildren() &&
171                 dynamic_cast<Fault*>(env->getBody()->getUnknownXMLObjects().front()));
172             long ret = error ? genericResponse.sendError(s) : genericResponse.sendResponse(s);
173         
174             // Cleanup by destroying XML.
175             delete env;
176             return ret;
177         }
178         catch (XMLToolingException&) {
179             if (response && detachOnFailure) {
180                 // A bit weird...we have to "revert" things so that the response is isolated
181                 // so the caller can free it.
182                 if (response->getParent()) {
183                     response->getParent()->detach();
184                     response->detach();
185                 }
186             }
187             throw;
188         }
189     }
190
191     Fault* fault = dynamic_cast<Fault*>(xmlObject);
192     if (fault) {
193         try {
194             log.debug("building envelope and marshalling fault");
195             Envelope* env = EnvelopeBuilder::buildEnvelope();
196             Body* body = BodyBuilder::buildBody();
197             env->setBody(body);
198             body->getUnknownXMLObjects().push_back(fault);
199             rootElement = env->marshall();
200
201             stringstream s;
202             s << *rootElement;
203             
204             if (log.isDebugEnabled())
205                 log.debug("marshalled envelope:\n%s", s.str().c_str());
206             
207             log.debug("sending serialized envelope");
208             long ret = genericResponse.sendError(s);
209         
210             // Cleanup by destroying XML.
211             delete env;
212             return ret;
213         }
214         catch (XMLToolingException&) {
215             // A bit weird...we have to "revert" things so that the fault is isolated
216             // so the caller can free it.
217             if (fault->getParent()) {
218                 fault->getParent()->detach();
219                 fault->detach();
220             }
221             throw;
222         }
223     }
224     
225     throw BindingException("XML content for SAML 1.x SOAP Encoder must be a SAML 1.x <Response> or SOAP Fault/Envelope.");
226 }