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