Reducing header overuse, non-inlining selected methods (CPPOST-35).
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2RedirectEncoder.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  * SAML2RedirectEncoder.cpp
19  * 
20  * SAML 2.0 HTTP-POST binding message encoder
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/MessageEncoder.h"
26 #include "saml2/binding/SAML2Redirect.h"
27 #include "saml2/core/Protocols.h"
28
29 #include <fstream>
30 #include <sstream>
31 #include <xercesc/util/Base64.hpp>
32 #include <xsec/dsig/DSIGConstants.hpp>
33 #include <xmltooling/logging.h>
34 #include <xmltooling/XMLToolingConfig.h>
35 #include <xmltooling/io/HTTPResponse.h>
36 #include <xmltooling/security/Credential.h>
37 #include <xmltooling/util/NDC.h>
38 #include <xmltooling/util/URLEncoder.h>
39
40 using namespace opensaml::saml2p;
41 using namespace opensaml::saml2md;
42 using namespace opensaml;
43 using namespace xmlsignature;
44 using namespace xmltooling::logging;
45 using namespace xmltooling;
46 using namespace std;
47
48 namespace opensaml {
49     namespace saml2p {              
50         class SAML_DLLLOCAL SAML2RedirectEncoder : public MessageEncoder
51         {
52         public:
53             SAML2RedirectEncoder() {}
54             virtual ~SAML2RedirectEncoder() {}
55
56             bool isCompact() const {
57                 return true;
58             }
59             
60             long encode(
61                 GenericResponse& genericResponse,
62                 XMLObject* xmlObject,
63                 const char* destination,
64                 const EntityDescriptor* recipient=NULL,
65                 const char* relayState=NULL,
66                 const ArtifactGenerator* artifactGenerator=NULL,
67                 const Credential* credential=NULL,
68                 const XMLCh* signatureAlg=NULL,
69                 const XMLCh* digestAlg=NULL
70                 ) const;
71         };
72
73         MessageEncoder* SAML_DLLLOCAL SAML2RedirectEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
74         {
75             return new SAML2RedirectEncoder();
76         }
77     };
78 };
79
80 long SAML2RedirectEncoder::encode(
81     GenericResponse& genericResponse,
82     XMLObject* xmlObject,
83     const char* destination,
84     const EntityDescriptor* recipient,
85     const char* relayState,
86     const ArtifactGenerator* artifactGenerator,
87     const Credential* credential,
88     const XMLCh* signatureAlg,
89     const XMLCh* digestAlg
90     ) const
91 {
92 #ifdef _DEBUG
93     xmltooling::NDC ndc("encode");
94 #endif
95     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2Redirect");
96
97     log.debug("validating input");
98     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
99     if (!httpResponse)
100         throw BindingException("Unable to cast response interface to HTTPResponse type.");
101     if (xmlObject->getParent())
102         throw BindingException("Cannot encode XML content with parent.");
103     
104     StatusResponseType* response = NULL;
105     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
106     if (!request) {
107         response = dynamic_cast<StatusResponseType*>(xmlObject);
108         if (!response)
109             throw BindingException("XML content for SAML 2.0 HTTP-Redirect Encoder must be a SAML 2.0 protocol message.");
110     }
111     
112     // Check for XML signature.
113     if (request ? request->getSignature() : response->getSignature()) {
114         log.debug("message already signed, removing native signature due to size considerations");
115         request ? request->setSignature(NULL) : response->setSignature(NULL);
116     }
117     
118     log.debug("marshalling, deflating, base64-encoding the message");
119     DOMElement* rootElement = xmlObject->marshall();
120     string xmlbuf;
121     XMLHelper::serialize(rootElement, xmlbuf);
122     log.debug("marshalled message:\n%s", xmlbuf.c_str());
123     
124     unsigned int len;
125     char* deflated = deflate(const_cast<char*>(xmlbuf.c_str()), xmlbuf.length(), &len);
126     if (!deflated)
127         throw BindingException("Failed to deflate message.");
128     
129     xsecsize_t xlen;
130     XMLByte* encoded=Base64::encode(reinterpret_cast<XMLByte*>(deflated), len, &xlen);
131     delete[] deflated;
132     if (!encoded)
133         throw BindingException("Base64 encoding of XML failed.");
134     
135     // Create beginnings of redirect query string.
136     const URLEncoder* escaper = XMLToolingConfig::getConfig().getURLEncoder();
137     xmlbuf.erase();
138     xmlbuf.append(reinterpret_cast<char*>(encoded), xlen);
139 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
140     XMLString::release(&encoded);
141 #else
142     XMLString::release((char**)&encoded);
143 #endif
144     
145     xmlbuf = (request ? "SAMLRequest=" : "SAMLResponse=") + escaper->encode(xmlbuf.c_str()); 
146     if (relayState && *relayState)
147         xmlbuf = xmlbuf + "&RelayState=" + escaper->encode(relayState);
148   
149     if (credential) {
150         log.debug("signing the message");
151         
152         // Sign the query string after adding the algorithm.
153         if (!signatureAlg)
154             signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
155         auto_ptr_char alg(signatureAlg);
156         xmlbuf = xmlbuf + "&SigAlg=" + escaper->encode(alg.get());
157
158         char sigbuf[1024];
159         memset(sigbuf,0,sizeof(sigbuf));
160         Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, xmlbuf.c_str(), xmlbuf.length(), sigbuf, sizeof(sigbuf)-1);
161         xmlbuf = xmlbuf + "&Signature=" + escaper->encode(sigbuf);
162     }
163     
164     // Generate redirect.
165     log.debug("message encoded, sending redirect to client");
166     xmlbuf.insert((string::size_type)0,(string::size_type)1,(strchr(destination,'?') ? '&' : '?'));
167     xmlbuf.insert(0,destination);
168     long ret = httpResponse->sendRedirect(xmlbuf.c_str());
169
170     // Cleanup by destroying XML.
171     delete xmlObject;
172     
173     return ret;
174 }