f20e49d1d4c487d215dcaec25f43b271e211777a
[shibboleth/cpp-opensaml.git] / saml / saml1 / binding / impl / SAML1SOAPEncoder.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  * 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/util/NDC.h>
33 #include <xmltooling/soap/SOAP.h>
34
35 using namespace opensaml::saml1p;
36 using namespace opensaml::saml2md;
37 using namespace opensaml;
38 using namespace xmlsignature;
39 using namespace soap11;
40 using namespace xmltooling::logging;
41 using namespace xmltooling;
42 using namespace std;
43
44 namespace opensaml {
45     namespace saml1p {              
46         class SAML_DLLLOCAL SAML1SOAPEncoder : public MessageEncoder
47         {
48         public:
49             SAML1SOAPEncoder() {}
50             virtual ~SAML1SOAPEncoder() {}
51
52             bool isUserAgentPresent() const {
53                 return false;
54             }
55
56             long encode(
57                 GenericResponse& genericResponse,
58                 XMLObject* xmlObject,
59                 const char* destination,
60                 const EntityDescriptor* recipient=NULL,
61                 const char* relayState=NULL,
62                 const ArtifactGenerator* artifactGenerator=NULL,
63                 const Credential* credential=NULL,
64                 const XMLCh* signatureAlg=NULL,
65                 const XMLCh* digestAlg=NULL
66                 ) const;
67         };
68
69         MessageEncoder* SAML_DLLLOCAL SAML1SOAPEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
70         {
71             return new SAML1SOAPEncoder();
72         }
73     };
74 };
75
76 long SAML1SOAPEncoder::encode(
77     GenericResponse& genericResponse,
78     XMLObject* xmlObject,
79     const char* destination,
80     const EntityDescriptor* recipient,
81     const char* relayState,
82     const ArtifactGenerator* artifactGenerator,
83     const Credential* credential,
84     const XMLCh* signatureAlg,
85     const XMLCh* digestAlg
86     ) const
87 {
88 #ifdef _DEBUG
89     xmltooling::NDC ndc("encode");
90 #endif
91     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML1SOAP");
92
93     log.debug("validating input");
94     if (xmlObject->getParent())
95         throw BindingException("Cannot encode XML content with parent.");
96
97     genericResponse.setContentType("text/xml");
98     HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
99     if (httpResponse) {
100         httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
101         httpResponse->setResponseHeader("Pragma", "no-cache");
102     }
103
104     bool detachOnFailure = false;
105     DOMElement* rootElement = NULL;
106     
107     // Check for a naked Response.
108     Response* response = dynamic_cast<Response*>(xmlObject);
109     if (response) {
110         // Wrap it in a SOAP envelope and point xmlObject at that.
111         detachOnFailure = true;
112         Envelope* env = EnvelopeBuilder::buildEnvelope();
113         Body* body = BodyBuilder::buildBody();
114         env->setBody(body);
115         body->getUnknownXMLObjects().push_back(response);
116         xmlObject = env;
117     }
118
119     // Now check for a full Envelope (which might have just been created).
120     Envelope* env = dynamic_cast<Envelope*>(xmlObject);
121     if (env) {
122         if (!response) {
123             response = (env->getBody() && env->getBody()->hasChildren()) ?
124                 dynamic_cast<Response*>(env->getBody()->getUnknownXMLObjects().front()) : NULL;
125         }
126         try {
127             // Now check for signing requirements.
128             if (response && credential) {
129                 if (response->getSignature()) {
130                     log.debug("response already signed, skipping signature operation");
131                     rootElement = env->marshall();
132                 }
133                 else {
134                     log.debug("signing the response and marshalling the envelope");
135         
136                     // Build a Signature.
137                     Signature* sig = SignatureBuilder::buildSignature();
138                     response->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 = (!response && 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 (response && detachOnFailure) {
174                 // A bit weird...we have to "revert" things so that the response is isolated
175                 // so the caller can free it.
176                 if (response->getParent()) {
177                     response->getParent()->detach();
178                     response->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 1.x SOAP Encoder must be a SAML 1.x <Response> or SOAP Fault/Envelope.");
220 }