Header clearing infrastructure.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / RemotedHandler.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  * RemotedHandler.cpp
19  * 
20  * Base class for handlers that need SP request/response layer to be remoted. 
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "ServiceProvider.h"
26 #include "handler/RemotedHandler.h"
27
28 #include <algorithm>
29 #include <log4cpp/Category.hh>
30 #include <xmltooling/unicode.h>
31
32 #ifndef SHIBSP_LITE
33 # include <saml/util/CGIParser.h>
34 # include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
35 # include <xsec/enc/XSECCryptoException.hpp>
36 # include <xsec/framework/XSECException.hpp>
37 # include <xsec/framework/XSECProvider.hpp>
38 #endif
39
40 using namespace shibsp;
41 using namespace opensaml;
42 using namespace xmltooling;
43 using namespace log4cpp;
44 using namespace xercesc;
45 using namespace std;
46
47 #ifndef SHIBSP_LITE
48 namespace shibsp {
49     class SHIBSP_DLLLOCAL RemotedRequest : public virtual HTTPRequest 
50     {
51         DDF& m_input;
52         mutable CGIParser* m_parser;
53         mutable vector<XSECCryptoX509*> m_certs;
54     public:
55         RemotedRequest(DDF& input) : m_input(input), m_parser(NULL) {}
56         virtual ~RemotedRequest() {
57             for_each(m_certs.begin(), m_certs.end(), xmltooling::cleanup<XSECCryptoX509>());
58             delete m_parser;
59         }
60
61         // GenericRequest
62         const char* getScheme() const {
63             return m_input["scheme"].string();
64         }
65         const char* getHostname() const {
66             return m_input["hostname"].string();
67         }
68         int getPort() const {
69             return m_input["port"].integer();
70         }
71         std::string getContentType() const {
72             DDF s = m_input["content_type"];
73             return s.string() ? s.string() : "";
74         }
75         long getContentLength() const {
76             return m_input["content_length"].integer();
77         }
78         const char* getRequestBody() const {
79             return m_input["body"].string();
80         }
81
82         const char* getParameter(const char* name) const;
83         std::vector<const char*>::size_type getParameters(const char* name, std::vector<const char*>& values) const;
84         
85         std::string getRemoteUser() const {
86             DDF s = m_input["remote_user"];
87             return s.string() ? s.string() : "";
88         }
89         std::string getRemoteAddr() const {
90             DDF s = m_input["client_addr"];
91             return s.string() ? s.string() : "";
92         }
93
94         const std::vector<XSECCryptoX509*>& getClientCertificates() const;
95         
96         // HTTPRequest
97         const char* getMethod() const {
98             return m_input["method"].string();
99         }
100         const char* getRequestURI() const {
101             return m_input["uri"].string();
102         }
103         const char* getRequestURL() const {
104             return m_input["url"].string();
105         }
106         const char* getQueryString() const {
107             return m_input["query"].string();
108         }
109         std::string getHeader(const char* name) const {
110             DDF s = m_input["headers"][name];
111             return s.string() ? s.string() : "";
112         }
113     };
114
115     class SHIBSP_DLLLOCAL RemotedResponse : public virtual HTTPResponse 
116     {
117         DDF& m_output;
118     public:
119         RemotedResponse(DDF& output) : m_output(output) {}
120         virtual ~RemotedResponse() {}
121        
122         // GenericResponse
123         long sendResponse(std::istream& inputStream, long status);
124         
125         // HTTPResponse
126         void setResponseHeader(const char* name, const char* value);
127         long sendRedirect(const char* url);
128     };
129 }
130
131 const char* RemotedRequest::getParameter(const char* name) const
132 {
133     if (!m_parser)
134         m_parser=new CGIParser(*this);
135     
136     pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
137     return (bounds.first==bounds.second) ? NULL : bounds.first->second;
138 }
139
140 std::vector<const char*>::size_type RemotedRequest::getParameters(const char* name, std::vector<const char*>& values) const
141 {
142     if (!m_parser)
143         m_parser=new CGIParser(*this);
144
145     pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
146     while (bounds.first!=bounds.second) {
147         values.push_back(bounds.first->second);
148         ++bounds.first;
149     }
150     return values.size();
151 }
152
153 const std::vector<XSECCryptoX509*>& RemotedRequest::getClientCertificates() const
154 {
155     if (m_certs.empty()) {
156         DDF cert = m_input["certificates"].first();
157         while (cert.isstring()) {
158             try {
159                 auto_ptr<XSECCryptoX509> x509(XSECPlatformUtils::g_cryptoProvider->X509());
160                 x509->loadX509Base64Bin(cert.string(), cert.strlen());
161                 m_certs.push_back(x509.release());
162             }
163             catch(XSECException& e) {
164                 auto_ptr_char temp(e.getMsg());
165                 Category::getInstance(SHIBSP_LOGCAT".SPRequest").error("XML-Security exception loading client certificate: %s", temp.get());
166             }
167             catch(XSECCryptoException& e) {
168                 Category::getInstance(SHIBSP_LOGCAT".SPRequest").error("XML-Security exception loading client certificate: %s", e.getMsg());
169             }
170             cert = cert.next();
171         }
172     }
173     return m_certs;
174 }
175
176 long RemotedResponse::sendResponse(std::istream& in, long status)
177 {
178     string msg;
179     char buf[1024];
180     while (in) {
181         in.read(buf,1024);
182         msg.append(buf,in.gcount());
183     }
184     if (!m_output.isstruct())
185         m_output.structure();
186     m_output.addmember("response.data").string(msg.c_str());
187     m_output.addmember("response.status").integer(status);
188     return status;
189 }
190
191 void RemotedResponse::setResponseHeader(const char* name, const char* value)
192 {
193     if (!m_output.isstruct())
194         m_output.structure();
195     DDF hdrs = m_output["headers"];
196     if (hdrs.isnull())
197         hdrs = m_output.addmember("headers").structure();
198     hdrs.addmember(name).string(value);
199 }
200
201 long RemotedResponse::sendRedirect(const char* url)
202 {
203     if (!m_output.isstruct())
204         m_output.structure();
205     m_output.addmember("redirect").string(url);
206     return HTTPResponse::XMLTOOLING_HTTP_STATUS_MOVED;
207 }
208
209 #endif
210
211 void RemotedHandler::setAddress(const char* address)
212 {
213     if (!m_address.empty())
214         throw ConfigurationException("Cannot register a remoting address twice for the same Handler.");
215     m_address = address;
216     SPConfig& conf = SPConfig::getConfig();
217     if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess)) {
218         ListenerService* listener = conf.getServiceProvider()->getListenerService(false);
219         if (listener)
220             listener->regListener(m_address.c_str(),this);
221         else
222             Category::getInstance(SHIBSP_LOGCAT".Handler").info("no ListenerService available, handler remoting disabled");
223     }
224 }
225
226 RemotedHandler::~RemotedHandler()
227 {
228     SPConfig& conf = SPConfig::getConfig();
229     ListenerService* listener=conf.getServiceProvider()->getListenerService(false);
230     if (listener && conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess))
231         listener->unregListener(m_address.c_str(),this);
232 }
233
234 DDF RemotedHandler::wrap(const SPRequest& request, const vector<string>* headers, bool certs) const
235 {
236     DDF in = DDF(m_address.c_str()).structure();
237     in.addmember("scheme").string(request.getScheme());
238     in.addmember("hostname").string(request.getHostname());
239     in.addmember("port").integer(request.getPort());
240     in.addmember("content_type").string(request.getContentType().c_str());
241     in.addmember("content_length").integer(request.getContentLength());
242     in.addmember("body").string(request.getRequestBody());
243     in.addmember("remote_user").string(request.getRemoteUser().c_str());
244     in.addmember("client_addr").string(request.getRemoteAddr().c_str());
245     in.addmember("method").string(request.getMethod());
246     in.addmember("uri").string(request.getRequestURI());
247     in.addmember("url").string(request.getRequestURL());
248     in.addmember("query").string(request.getQueryString());
249
250     if (headers) {
251         string hdr;
252         DDF hin = in.addmember("headers").structure();
253         for (vector<string>::const_iterator h = headers->begin(); h!=headers->end(); ++h) {
254             hdr = request.getHeader(h->c_str());
255             if (!hdr.empty())
256                 hin.addmember(h->c_str()).string(hdr.c_str());
257         }
258     }
259
260     if (certs) {
261 #ifndef SHIBSP_LITE
262         const vector<XSECCryptoX509*>& xvec = request.getClientCertificates();
263         if (!xvec.empty()) {
264             DDF clist = in.addmember("certificates").list();
265             for (vector<XSECCryptoX509*>::const_iterator x = xvec.begin(); x!=xvec.end(); ++x) {
266                 DDF x509 = DDF(NULL).string((*x)->getDEREncodingSB().rawCharBuffer());
267                 clist.add(x509);
268             }
269         }
270 #else
271         const vector<string>& xvec = request.getClientCertificates();
272         if (!xvec.empty()) {
273             DDF clist = in.addmember("certificates").list();
274             for (vector<string>::const_iterator x = xvec.begin(); x!=xvec.end(); ++x) {
275                 DDF x509 = DDF(NULL).string(x->c_str());
276                 clist.add(x509);
277             }
278         }
279 #endif
280     }
281
282     return in;
283 }
284
285 pair<bool,long> RemotedHandler::unwrap(SPRequest& request, DDF& out) const
286 {
287     DDF h = out["headers"];
288     h = h.first();
289     while (h.isstring()) {
290         request.setResponseHeader(h.name(), h.string());
291         h = h.next();
292     }
293     h = out["redirect"];
294     if (h.isstring())
295         return make_pair(true, request.sendRedirect(h.string()));
296     h = out["response"];
297     if (h.isstruct()) {
298         istringstream s(h["data"].string());
299         return make_pair(true, request.sendResponse(s, h["status"].integer()));
300     }
301     return make_pair(false,0);
302 }
303
304 HTTPRequest* RemotedHandler::getRequest(DDF& in) const
305 {
306 #ifndef SHIBSP_LITE
307     return new RemotedRequest(in);
308 #else
309     throw ConfigurationException("Cannot process message using lite version of shibsp library.");
310 #endif
311 }
312
313 HTTPResponse* RemotedHandler::getResponse(DDF& out) const
314 {
315 #ifndef SHIBSP_LITE
316     return new RemotedResponse(out);
317 #else
318     throw ConfigurationException("Cannot process message using lite version of shibsp library.");
319 #endif
320 }