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