Clean up default port handling
[shibboleth/cpp-sp.git] / shibsp / AbstractSPRequest.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * AbstractSPRequest.cpp
23  *
24  * Abstract base for SPRequest implementations.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "AbstractSPRequest.h"
30 #include "Application.h"
31 #include "GSSRequest.h"
32 #include "ServiceProvider.h"
33 #include "SessionCache.h"
34 #include "util/CGIParser.h"
35
36 #include <boost/lexical_cast.hpp>
37
38 using namespace shibsp;
39 using namespace opensaml;
40 using namespace xmltooling;
41 using namespace std;
42
43 SPRequest::SPRequest()
44 {
45 }
46
47 SPRequest::~SPRequest()
48 {
49 }
50
51 string SPRequest::getSecureHeader(const char* name) const
52 {
53     return getHeader(name);
54 }
55
56 void SPRequest::setAuthType(const char* authtype)
57 {
58 }
59
60 #ifdef SHIBSP_HAVE_GSSAPI
61 GSSRequest::GSSRequest()
62 {
63 }
64
65 GSSRequest::~GSSRequest()
66 {
67 }
68 #endif
69
70 AbstractSPRequest::AbstractSPRequest(const char* category)
71     : m_sp(SPConfig::getConfig().getServiceProvider()),
72         m_mapper(nullptr), m_app(nullptr), m_sessionTried(false), m_session(nullptr),
73         m_log(&Category::getInstance(category))
74 {
75     m_sp->lock();
76 }
77
78 AbstractSPRequest::~AbstractSPRequest()
79 {
80     if (m_session)
81         m_session->unlock();
82     if (m_mapper)
83         m_mapper->unlock();
84     if (m_sp)
85         m_sp->unlock();
86 }
87
88 const ServiceProvider& AbstractSPRequest::getServiceProvider() const
89 {
90     return *m_sp;
91 }
92
93 RequestMapper::Settings AbstractSPRequest::getRequestSettings() const
94 {
95     if (!m_mapper) {
96         // Map request to application and content settings.
97         m_mapper = m_sp->getRequestMapper();
98         m_mapper->lock();
99         m_settings = m_mapper->getSettings(*this);
100
101         if (reinterpret_cast<Category*>(m_log)->isDebugEnabled()) {
102             reinterpret_cast<Category*>(m_log)->debug(
103                 "mapped %s to %s", getRequestURL(), m_settings.first->getString("applicationId").second
104                 );
105         }
106     }
107     return m_settings;
108 }
109
110 const Application& AbstractSPRequest::getApplication() const
111 {
112     if (!m_app) {
113         // Now find the application from the URL settings
114         m_app = m_sp->getApplication(getRequestSettings().first->getString("applicationId").second);
115         if (!m_app)
116             throw ConfigurationException("Unable to map non-default applicationId to an ApplicationOverride, check configuration.");
117     }
118     return *m_app;
119 }
120
121 Session* AbstractSPRequest::getSession(bool checkTimeout, bool ignoreAddress, bool cache)
122 {
123     // Only attempt this once.
124     if (cache && m_sessionTried)
125         return m_session;
126     else if (cache)
127         m_sessionTried = true;
128
129     // Need address checking and timeout settings.
130     time_t timeout = 3600;
131     if (checkTimeout || !ignoreAddress) {
132         const PropertySet* props = getApplication().getPropertySet("Sessions");
133         if (props) {
134             if (checkTimeout) {
135                 pair<bool,unsigned int> p = props->getUnsignedInt("timeout");
136                 if (p.first)
137                     timeout = p.second;
138             }
139             pair<bool,bool> pcheck = props->getBool("consistentAddress");
140             if (pcheck.first)
141                 ignoreAddress = !pcheck.second;
142         }
143     }
144
145     // The cache will either silently pass a session or nullptr back, or throw an exception out.
146     Session* session = getServiceProvider().getSessionCache()->find(
147         getApplication(), *this, (ignoreAddress ? nullptr : getRemoteAddr().c_str()), (checkTimeout ? &timeout : nullptr)
148         );
149     if (cache)
150         m_session = session;
151     return session;
152 }
153
154 static char _x2c(const char *what)
155 {
156     register char digit;
157
158     digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
159     digit *= 16;
160     digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
161     return(digit);
162 }
163
164 void AbstractSPRequest::setRequestURI(const char* uri)
165 {
166     // Fix for bug 574, secadv 20061002
167     // Unescape URI up to query string delimiter by looking for %XX escapes.
168     // Adapted from Apache's util.c, ap_unescape_url function.
169     if (uri) {
170         while (*uri) {
171             if (*uri == '?') {
172                 m_uri += uri;
173                 break;
174             }
175             else if (*uri != '%') {
176                 m_uri += *uri;
177             }
178             else {
179                 ++uri;
180                 if (!isxdigit(*uri) || !isxdigit(*(uri+1)))
181                     throw ConfigurationException("Bad request, contained unsupported encoded characters.");
182                 m_uri += _x2c(uri);
183                 ++uri;
184             }
185             ++uri;
186         }
187     }
188 }
189
190 const char* AbstractSPRequest::getRequestURI() const
191 {
192     return m_uri.c_str();
193 }
194
195 const char* AbstractSPRequest::getRequestURL() const
196 {
197     if (m_url.empty()) {
198         // Compute the full target URL
199         int port = getPort();
200         const char* scheme = getScheme();
201         m_url = string(scheme) + "://" + getHostname();
202         if (!isDefaultPort())
203             m_url += ":" + boost::lexical_cast<string>(port);
204         m_url += m_uri;
205     }
206     return m_url.c_str();
207 }
208
209 string AbstractSPRequest::getRemoteAddr() const
210 {
211     pair<bool,const char*> addr = getRequestSettings().first->getString("REMOTE_ADDR");
212     return addr.first ? getHeader(addr.second) : "";
213 }
214
215 const char* AbstractSPRequest::getParameter(const char* name) const
216 {
217     if (!m_parser.get())
218         m_parser.reset(new CGIParser(*this));
219
220     pair<CGIParser::walker,CGIParser::walker> bounds = m_parser->getParameters(name);
221     return (bounds.first==bounds.second) ? nullptr : bounds.first->second;
222 }
223
224 vector<const char*>::size_type AbstractSPRequest::getParameters(const char* name, vector<const char*>& values) const
225 {
226     if (!m_parser.get())
227         m_parser.reset(new CGIParser(*this));
228
229     pair<CGIParser::walker,CGIParser::walker> bounds = m_parser->getParameters(name);
230     while (bounds.first != bounds.second) {
231         values.push_back(bounds.first->second);
232         ++bounds.first;
233     }
234     return values.size();
235 }
236
237 const char* AbstractSPRequest::getHandlerURL(const char* resource) const
238 {
239     if (!resource)
240         resource = getRequestURL();
241
242     if (!m_handlerURL.empty() && resource && !strcmp(getRequestURL(), resource))
243         return m_handlerURL.c_str();
244
245     // Check for relative URL.
246     string stackresource;
247     if (resource && *resource == '/') {
248         // Compute a URL to the root of the site and point resource at constructed string.
249         int port = getPort();
250         const char* scheme = getScheme();
251         stackresource = string(scheme) + "://" + getHostname();
252         if (!isDefaultPort())
253             stackresource += ":" + boost::lexical_cast<string>(port);
254         stackresource += resource;
255         resource = stackresource.c_str();
256     }
257
258 #ifdef HAVE_STRCASECMP
259     if (!resource || (strncasecmp(resource,"http://",7) && strncasecmp(resource,"https://",8)))
260 #else
261     if (!resource || (strnicmp(resource,"http://",7) && strnicmp(resource,"https://",8)))
262 #endif
263         throw ConfigurationException("Target resource was not an absolute URL.");
264
265     bool ssl_only = true;
266     const char* handler = nullptr;
267     const PropertySet* props = getApplication().getPropertySet("Sessions");
268     if (props) {
269         pair<bool,bool> p = props->getBool("handlerSSL");
270         if (p.first)
271             ssl_only = p.second;
272         pair<bool,const char*> p2 = props->getString("handlerURL");
273         if (p2.first)
274             handler = p2.second;
275     }
276
277     if (!handler) {
278         handler = "/Shibboleth.sso";
279     }
280     else if (*handler!='/' && strncmp(handler,"http:",5) && strncmp(handler,"https:",6)) {
281         throw ConfigurationException(
282             "Invalid handlerURL property ($1) in <Sessions> element for Application ($2)",
283             params(2, handler ? handler : "null", m_app->getId())
284             );
285     }
286
287     // The "handlerURL" property can be in one of three formats:
288     //
289     // 1) a full URI:       http://host/foo/bar
290     // 2) a hostless URI:   http:///foo/bar
291     // 3) a relative path:  /foo/bar
292     //
293     // #  Protocol  Host        Path
294     // 1  handler   handler     handler
295     // 2  handler   resource    handler
296     // 3  resource  resource    handler
297     //
298     // note: if ssl_only is true, make sure the protocol is https
299
300     const char* path = nullptr;
301
302     // Decide whether to use the handler or the resource for the "protocol"
303     const char* prot;
304     if (*handler != '/') {
305         prot = handler;
306     }
307     else {
308         prot = resource;
309         path = handler;
310     }
311
312     // break apart the "protocol" string into protocol, host, and "the rest"
313     const char* colon = strchr(prot, ':');
314     colon += 3;
315     const char* slash = strchr(colon, '/');
316     if (!path)
317         path = slash;
318
319     // Compute the actual protocol and store in member.
320     if (ssl_only)
321         m_handlerURL.assign("https://");
322     else
323         m_handlerURL.assign(prot, colon-prot);
324
325     // create the "host" from either the colon/slash or from the target string
326     // If prot == handler then we're in either #1 or #2, else #3.
327     // If slash == colon then we're in #2.
328     if (prot != handler || slash == colon) {
329         colon = strchr(resource, ':');
330         colon += 3;      // Get past the ://
331         slash = strchr(colon, '/');
332     }
333     string host(colon, (slash ? slash-colon : strlen(colon)));
334
335     // Build the handler URL
336     m_handlerURL += host + path;
337     return m_handlerURL.c_str();
338 }
339
340 void AbstractSPRequest::log(SPLogLevel level, const std::string& msg) const
341 {
342     reinterpret_cast<Category*>(m_log)->log(
343         (level == SPDebug ? Priority::DEBUG :
344         (level == SPInfo ? Priority::INFO :
345         (level == SPWarn ? Priority::WARN :
346         (level == SPError ? Priority::ERROR : Priority::CRIT)))),
347         msg
348         );
349 }
350
351 bool AbstractSPRequest::isPriorityEnabled(SPLogLevel level) const
352 {
353     return reinterpret_cast<Category*>(m_log)->isPriorityEnabled(
354         (level == SPDebug ? Priority::DEBUG :
355         (level == SPInfo ? Priority::INFO :
356         (level == SPWarn ? Priority::WARN :
357         (level == SPError ? Priority::ERROR : Priority::CRIT))))
358         );
359 }