4de8b7f878cfc44ccf428faef9dc4f5dbff4f8b9
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2SOAPEncoder.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  * 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             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 SAML2SOAPEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
71         {
72             return new SAML2SOAPEncoder();
73         }
74     };
75 };
76
77 long SAML2SOAPEncoder::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.SAML2SOAP");
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 message.
110     SignableObject* msg = dynamic_cast<SignableObject*>(xmlObject);
111     if (msg) {
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(msg);
118         xmlObject = env;
119     }
120
121     Envelope* env = dynamic_cast<Envelope*>(xmlObject);
122     if (env) {
123         if (!msg) {
124             msg = (env->getBody() && env->getBody()->hasChildren()) ?
125                 dynamic_cast<SignableObject*>(env->getBody()->getUnknownXMLObjects().front()) : NULL;
126         }
127         try {
128             if (msg && credential) {
129                 if (msg->getSignature()) {
130                     log.debug("message already signed, skipping signature operation");
131                     rootElement = env->marshall();
132                 }
133                 else {
134                     log.debug("signing the message and marshalling the envelope");
135         
136                     // Build a Signature.
137                     Signature* sig = SignatureBuilder::buildSignature();
138                     msg->setSignature(sig);    
139                     if (signatureAlg)
140                         sig->setSignatureAlgorithm(signatureAlg);
141                     if (digestAlg) {
142                         opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
143                         if (cr)
144                             cr->setDigestAlgorithm(digestAlg);
145                     }
146             
147                     // Sign message while marshalling.
148                     vector<Signature*> sigs(1,sig);
149                     rootElement = env->marshall((DOMDocument*)NULL,&sigs,credential);
150                 }
151             }
152             else {
153                 log.debug("marshalling the envelope");
154                 rootElement = env->marshall();
155             }
156
157             stringstream s;
158             s << *rootElement;
159             
160             if (log.isDebugEnabled())
161                 log.debug("marshalled envelope:\n%s", s.str().c_str());
162
163             log.debug("sending serialized envelope");
164             bool error = (!msg && env->getBody() && env->getBody()->hasChildren() &&
165                 dynamic_cast<Fault*>(env->getBody()->getUnknownXMLObjects().front()));
166             long ret = error ? genericResponse.sendError(s) : genericResponse.sendResponse(s);
167         
168             // Cleanup by destroying XML.
169             delete env;
170             return ret;
171         }
172         catch (XMLToolingException&) {
173             if (msg && detachOnFailure) {
174                 // A bit weird...we have to "revert" things so that the message is isolated
175                 // so the caller can free it.
176                 if (msg->getParent()) {
177                     msg->getParent()->detach();
178                     msg->detach();
179                 }
180             }
181             throw;
182         }
183     }
184
185     Fault* fault = dynamic_cast<Fault*>(xmlObject);
186     if (fault) {
187         try {
188             log.debug("building envelope and marshalling fault");
189             Envelope* env = EnvelopeBuilder::buildEnvelope();
190             Body* body = BodyBuilder::buildBody();
191             env->setBody(body);
192             body->getUnknownXMLObjects().push_back(fault);
193             rootElement = env->marshall();
194     
195             stringstream s;
196             s << *rootElement;
197             
198             if (log.isDebugEnabled())
199                 log.debug("marshalled envelope:\n%s", s.str().c_str());
200
201             log.debug("sending serialized envelope");
202             long ret = genericResponse.sendError(s);
203         
204             // Cleanup by destroying XML.
205             delete env;
206             return ret;
207         }
208         catch (XMLToolingException&) {
209             // A bit weird...we have to "revert" things so that the fault is isolated
210             // so the caller can free it.
211             if (fault->getParent()) {
212                 fault->getParent()->detach();
213                 fault->detach();
214             }
215             throw;
216         }
217     }
218
219     throw BindingException("XML content for SAML 2.0 SOAP Encoder must be a SAML 2.0 message or SOAP Fault/Envelope.");
220 }