7066055f674f445c9c8fd223ca82ba32f265a14f
[shibboleth/cpp-opensaml.git] / saml / saml1 / binding / impl / SAML1SOAPEncoder.cpp
1 /*
2  *  Copyright 2001-2009 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             long encode(
58                 GenericResponse& genericResponse,
59                 XMLObject* xmlObject,
60                 const char* destination,
61                 const EntityDescriptor* recipient=NULL,
62                 const char* relayState=NULL,
63                 const ArtifactGenerator* artifactGenerator=NULL,
64                 const Credential* credential=NULL,
65                 const XMLCh* signatureAlg=NULL,
66                 const XMLCh* digestAlg=NULL
67                 ) const;
68         };
69
70         MessageEncoder* SAML_DLLLOCAL SAML1SOAPEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
71         {
72             return new SAML1SOAPEncoder();
73         }
74     };
75 };
76
77 long SAML1SOAPEncoder::encode(
78     GenericResponse& genericResponse,
79     XMLObject* xmlObject,
80     const char* destination,
81     const EntityDescriptor* recipient,
82     const char* relayState,
83     const ArtifactGenerator* artifactGenerator,
84     const Credential* credential,
85     const XMLCh* signatureAlg,
86     const XMLCh* digestAlg
87     ) const
88 {
89 #ifdef _DEBUG
90     xmltooling::NDC ndc("encode");
91 #endif
92     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML1SOAP");
93
94     log.debug("validating input");
95     if (xmlObject->getParent())
96         throw BindingException("Cannot encode XML content with parent.");
97
98     genericResponse.setContentType("text/xml");
99     HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
100     if (httpResponse) {
101         httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
102         httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
103         httpResponse->setResponseHeader("Pragma", "no-cache");
104     }
105
106     bool detachOnFailure = false;
107     DOMElement* rootElement = NULL;
108     
109     // Check for a naked Response.
110     Response* response = dynamic_cast<Response*>(xmlObject);
111     if (response) {
112         // Wrap it in a SOAP envelope and point xmlObject at that.
113         detachOnFailure = true;
114         Envelope* env = EnvelopeBuilder::buildEnvelope();
115         Body* body = BodyBuilder::buildBody();
116         env->setBody(body);
117         body->getUnknownXMLObjects().push_back(response);
118         xmlObject = env;
119     }
120
121     // Now check for a full Envelope (which might have just been created).
122     Envelope* env = dynamic_cast<Envelope*>(xmlObject);
123     if (env) {
124         if (!response) {
125             response = (env->getBody() && env->getBody()->hasChildren()) ?
126                 dynamic_cast<Response*>(env->getBody()->getUnknownXMLObjects().front()) : NULL;
127         }
128         try {
129             // Now check for signing requirements.
130             if (response && credential) {
131                 if (response->getSignature()) {
132                     log.debug("response already signed, skipping signature operation");
133                     rootElement = env->marshall();
134                 }
135                 else {
136                     log.debug("signing the response and marshalling the envelope");
137         
138                     // Build a Signature.
139                     Signature* sig = SignatureBuilder::buildSignature();
140                     response->setSignature(sig);    
141                     if (signatureAlg)
142                         sig->setSignatureAlgorithm(signatureAlg);
143                     if (digestAlg) {
144                         opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
145                         if (cr)
146                             cr->setDigestAlgorithm(digestAlg);
147                     }
148             
149                     // Sign message while marshalling.
150                     vector<Signature*> sigs(1,sig);
151                     rootElement = env->marshall((DOMDocument*)NULL,&sigs,credential);
152                 }
153             }
154             else {
155                 log.debug("marshalling the envelope");
156                 rootElement = env->marshall();
157             }
158
159             stringstream s;
160             s << *rootElement;
161             
162             if (log.isDebugEnabled())
163                 log.debug("marshalled envelope:\n%s", s.str().c_str());
164             
165             log.debug("sending serialized envelope");
166             bool error = (!response && env->getBody() && env->getBody()->hasChildren() &&
167                 dynamic_cast<Fault*>(env->getBody()->getUnknownXMLObjects().front()));
168             long ret = error ? genericResponse.sendError(s) : genericResponse.sendResponse(s);
169         
170             // Cleanup by destroying XML.
171             delete env;
172             return ret;
173         }
174         catch (XMLToolingException&) {
175             if (response && detachOnFailure) {
176                 // A bit weird...we have to "revert" things so that the response is isolated
177                 // so the caller can free it.
178                 if (response->getParent()) {
179                     response->getParent()->detach();
180                     response->detach();
181                 }
182             }
183             throw;
184         }
185     }
186
187     Fault* fault = dynamic_cast<Fault*>(xmlObject);
188     if (fault) {
189         try {
190             log.debug("building envelope and marshalling fault");
191             Envelope* env = EnvelopeBuilder::buildEnvelope();
192             Body* body = BodyBuilder::buildBody();
193             env->setBody(body);
194             body->getUnknownXMLObjects().push_back(fault);
195             rootElement = env->marshall();
196
197             stringstream s;
198             s << *rootElement;
199             
200             if (log.isDebugEnabled())
201                 log.debug("marshalled envelope:\n%s", s.str().c_str());
202             
203             log.debug("sending serialized envelope");
204             long ret = genericResponse.sendError(s);
205         
206             // Cleanup by destroying XML.
207             delete env;
208             return ret;
209         }
210         catch (XMLToolingException&) {
211             // A bit weird...we have to "revert" things so that the fault is isolated
212             // so the caller can free it.
213             if (fault->getParent()) {
214                 fault->getParent()->detach();
215                 fault->detach();
216             }
217             throw;
218         }
219     }
220     
221     throw BindingException("XML content for SAML 1.x SOAP Encoder must be a SAML 1.x <Response> or SOAP Fault/Envelope.");
222 }