Imported Upstream version 2.2.1+dfsg
[shibboleth/sp.git] / shibsp / AbstractSPRequest.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  * AbstractSPRequest.cpp
19  *
20  * Abstract base for SPRequest implementations
21  */
22
23 #include "internal.h"
24 #include "AbstractSPRequest.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "SessionCache.h"
28
29 using namespace shibsp;
30 using namespace opensaml;
31 using namespace xmltooling;
32 using namespace std;
33
34 AbstractSPRequest::AbstractSPRequest(const char* category)
35     : m_sp(NULL), m_mapper(NULL), m_app(NULL), m_sessionTried(false), m_session(NULL),
36         m_log(&Category::getInstance(category)), m_parser(NULL)
37 {
38     m_sp=SPConfig::getConfig().getServiceProvider();
39     m_sp->lock();
40 }
41
42 AbstractSPRequest::~AbstractSPRequest()
43 {
44     if (m_session)
45         m_session->unlock();
46     if (m_mapper)
47         m_mapper->unlock();
48     if (m_sp)
49         m_sp->unlock();
50     delete m_parser;
51 }
52
53 RequestMapper::Settings AbstractSPRequest::getRequestSettings() const
54 {
55     if (!m_mapper) {
56         // Map request to application and content settings.
57         m_mapper=m_sp->getRequestMapper();
58         m_mapper->lock();
59         m_settings = m_mapper->getSettings(*this);
60
61         if (reinterpret_cast<Category*>(m_log)->isDebugEnabled()) {
62             reinterpret_cast<Category*>(m_log)->debug(
63                 "mapped %s to %s", getRequestURL(), m_settings.first->getString("applicationId").second
64                 );
65         }
66     }
67     return m_settings;
68 }
69
70 const Application& AbstractSPRequest::getApplication() const
71 {
72     if (!m_app) {
73         // Now find the application from the URL settings
74         m_app=m_sp->getApplication(getRequestSettings().first->getString("applicationId").second);
75         if (!m_app)
76             throw ConfigurationException("Unable to map request to ApplicationOverride settings, check configuration.");
77     }
78     return *m_app;
79 }
80
81 Session* AbstractSPRequest::getSession(bool checkTimeout, bool ignoreAddress, bool cache)
82 {
83     // Only attempt this once.
84     if (cache && m_sessionTried)
85         return m_session;
86     else if (cache)
87         m_sessionTried = true;
88
89     // Need address checking and timeout settings.
90     time_t timeout=3600;
91     if (checkTimeout || !ignoreAddress) {
92         const PropertySet* props=getApplication().getPropertySet("Sessions");
93         if (props) {
94             if (checkTimeout) {
95                 pair<bool,unsigned int> p=props->getUnsignedInt("timeout");
96                 if (p.first)
97                     timeout = p.second;
98             }
99             pair<bool,bool> pcheck=props->getBool("consistentAddress");
100             if (pcheck.first)
101                 ignoreAddress = !pcheck.second;
102         }
103     }
104
105     // The cache will either silently pass a session or NULL back, or throw an exception out.
106     Session* session = getServiceProvider().getSessionCache()->find(
107         getApplication(), *this, ignoreAddress ? NULL : getRemoteAddr().c_str(), checkTimeout ? &timeout : NULL
108         );
109     if (cache)
110         m_session = session;
111     return session;
112 }
113
114 static char _x2c(const char *what)
115 {
116     register char digit;
117
118     digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
119     digit *= 16;
120     digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
121     return(digit);
122 }
123
124 void AbstractSPRequest::setRequestURI(const char* uri)
125 {
126     // Fix for bug 574, secadv 20061002
127     // Unescape URI up to query string delimiter by looking for %XX escapes.
128     // Adapted from Apache's util.c, ap_unescape_url function.
129     if (uri) {
130         while (*uri) {
131             if (*uri == '?') {
132                 m_uri += uri;
133                 break;
134             }
135             else if (*uri != '%') {
136                 m_uri += *uri;
137             }
138             else {
139                 ++uri;
140                 if (!isxdigit(*uri) || !isxdigit(*(uri+1)))
141                     throw ConfigurationException("Bad request, contained unsupported encoded characters.");
142                 m_uri += _x2c(uri);
143                 ++uri;
144             }
145             ++uri;
146         }
147     }
148 }
149
150 const char* AbstractSPRequest::getRequestURL() const
151 {
152     if (m_url.empty()) {
153         // Compute the full target URL
154         int port = getPort();
155         const char* scheme = getScheme();
156         m_url = string(scheme) + "://" + getHostname();
157         if ((!strcmp(scheme,"http") && port!=80) || (!strcmp(scheme,"https") && port!=443)) {
158             ostringstream portstr;
159             portstr << port;
160             m_url += ":" + portstr.str();
161         }
162         m_url += m_uri;
163     }
164     return m_url.c_str();
165 }
166
167 string AbstractSPRequest::getRemoteAddr() const
168 {
169     pair<bool,const char*> addr = getRequestSettings().first->getString("REMOTE_ADDR");
170     return addr.first ? getHeader(addr.second) : "";
171 }
172
173 const char* AbstractSPRequest::getParameter(const char* name) const
174 {
175     if (!m_parser)
176         m_parser=new CGIParser(*this);
177
178     pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
179     return (bounds.first==bounds.second) ? NULL : bounds.first->second;
180 }
181
182 vector<const char*>::size_type AbstractSPRequest::getParameters(const char* name, vector<const char*>& values) const
183 {
184     if (!m_parser)
185         m_parser=new CGIParser(*this);
186
187     pair<CGIParser::walker,CGIParser::walker> bounds=m_parser->getParameters(name);
188     while (bounds.first!=bounds.second) {
189         values.push_back(bounds.first->second);
190         ++bounds.first;
191     }
192     return values.size();
193 }
194
195 const char* AbstractSPRequest::getHandlerURL(const char* resource) const
196 {
197     if (!resource)
198         resource = getRequestURL();
199
200     if (!m_handlerURL.empty() && resource && !strcmp(getRequestURL(),resource))
201         return m_handlerURL.c_str();
202
203 #ifdef HAVE_STRCASECMP
204     if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
205 #else
206     if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
207 #endif
208         throw ConfigurationException("Target resource was not an absolute URL.");
209
210     bool ssl_only=true;
211     const char* handler=NULL;
212     const PropertySet* props=getApplication().getPropertySet("Sessions");
213     if (props) {
214         pair<bool,bool> p=props->getBool("handlerSSL");
215         if (p.first)
216             ssl_only=p.second;
217         pair<bool,const char*> p2=props->getString("handlerURL");
218         if (p2.first)
219             handler=p2.second;
220     }
221
222     // Should never happen...
223     if (!handler || (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)))
224         throw ConfigurationException(
225             "Invalid handlerURL property ($1) in <Sessions> element for Application ($2)",
226             params(2, handler ? handler : "null", m_app->getId())
227             );
228
229     // The "handlerURL" property can be in one of three formats:
230     //
231     // 1) a full URI:       http://host/foo/bar
232     // 2) a hostless URI:   http:///foo/bar
233     // 3) a relative path:  /foo/bar
234     //
235     // #  Protocol  Host        Path
236     // 1  handler   handler     handler
237     // 2  handler   resource    handler
238     // 3  resource  resource    handler
239     //
240     // note: if ssl_only is true, make sure the protocol is https
241
242     const char* path = NULL;
243
244     // Decide whether to use the handler or the resource for the "protocol"
245     const char* prot;
246     if (*handler != '/') {
247         prot = handler;
248     }
249     else {
250         prot = resource;
251         path = handler;
252     }
253
254     // break apart the "protocol" string into protocol, host, and "the rest"
255     const char* colon=strchr(prot,':');
256     colon += 3;
257     const char* slash=strchr(colon,'/');
258     if (!path)
259         path = slash;
260
261     // Compute the actual protocol and store in member.
262     if (ssl_only)
263         m_handlerURL.assign("https://");
264     else
265         m_handlerURL.assign(prot, colon-prot);
266
267     // create the "host" from either the colon/slash or from the target string
268     // If prot == handler then we're in either #1 or #2, else #3.
269     // If slash == colon then we're in #2.
270     if (prot != handler || slash == colon) {
271         colon = strchr(resource, ':');
272         colon += 3;      // Get past the ://
273         slash = strchr(colon, '/');
274     }
275     string host(colon, (slash ? slash-colon : strlen(colon)));
276
277     // Build the handler URL
278     m_handlerURL += host + path;
279     return m_handlerURL.c_str();
280 }
281
282 void AbstractSPRequest::log(SPLogLevel level, const std::string& msg) const
283 {
284     reinterpret_cast<Category*>(m_log)->log(
285         (level == SPDebug ? Priority::DEBUG :
286         (level == SPInfo ? Priority::INFO :
287         (level == SPWarn ? Priority::WARN :
288         (level == SPError ? Priority::ERROR : Priority::CRIT)))),
289         msg
290         );
291 }
292
293 bool AbstractSPRequest::isPriorityEnabled(SPLogLevel level) const
294 {
295     return reinterpret_cast<Category*>(m_log)->isPriorityEnabled(
296         (level == SPDebug ? Priority::DEBUG :
297         (level == SPInfo ? Priority::INFO :
298         (level == SPWarn ? Priority::WARN :
299         (level == SPError ? Priority::ERROR : Priority::CRIT))))
300         );
301 }