Clean Solaris build.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAMLDSSessionInitiator.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  * SAMLDSSessionInitiator.cpp
19  * 
20  * SAML Discovery Service support.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "SPRequest.h"
27 #include "handler/AbstractHandler.h"
28 #include "handler/SessionInitiator.h"
29
30 #include <xmltooling/XMLToolingConfig.h>
31 #include <xmltooling/util/URLEncoder.h>
32
33 using namespace shibsp;
34 using namespace opensaml;
35 using namespace xmltooling;
36 using namespace std;
37
38 namespace shibsp {
39
40 #if defined (_MSC_VER)
41     #pragma warning( push )
42     #pragma warning( disable : 4250 )
43 #endif
44
45     class SHIBSP_DLLLOCAL SAMLDSSessionInitiator : public SessionInitiator, public AbstractHandler
46     {
47     public:
48         SAMLDSSessionInitiator(const DOMElement* e, const char* appId)
49                 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAMLDS")), m_url(NULL), m_returnParam(NULL) {
50             pair<bool,const char*> url = getString("URL");
51             if (!url.first)
52                 throw ConfigurationException("SAMLDS SessionInitiator requires a URL property.");
53             m_url = url.second;
54             url = getString("entityIDParam");
55             if (url.first)
56                 m_returnParam = url.second;
57         }
58         virtual ~SAMLDSSessionInitiator() {}
59         
60         pair<bool,long> run(SPRequest& request, const char* entityID=NULL, bool isHandler=true) const;
61
62     private:
63         const char* m_url;
64         const char* m_returnParam;
65     };
66
67 #if defined (_MSC_VER)
68     #pragma warning( pop )
69 #endif
70
71     SessionInitiator* SHIBSP_DLLLOCAL SAMLDSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
72     {
73         return new SAMLDSSessionInitiator(p.first, p.second);
74     }
75
76 };
77
78 pair<bool,long> SAMLDSSessionInitiator::run(SPRequest& request, const char* entityID, bool isHandler) const
79 {
80     // The IdP CANNOT be specified for us to run. Otherwise, we'd be redirecting to a DS
81     // anytime the IdP's metadata was wrong.
82     if (entityID && *entityID)
83         return make_pair(false,0L);
84
85     string target;
86     const char* option;
87     bool isPassive=false;
88     const Application& app=request.getApplication();
89
90     if (isHandler) {
91         option = request.getParameter("SAMLDS");
92         if (option && !strcmp(option,"1")) {
93             saml2md::MetadataException ex("No identity provider was selected by user.");
94             ex.addProperty("statusCode", "urn:oasis:names:tc:SAML:2.0:status:Requester");
95             ex.addProperty("statusCode2", "urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP");
96             ex.raise();
97         }
98         
99         option = request.getParameter("target");
100         if (option)
101             target = option;
102         recoverRelayState(request.getApplication(), request, target, false);
103
104         option = request.getParameter("isPassive");
105         if (option)
106             isPassive = !strcmp(option,"true");
107     }
108     else {
109         // We're running as a "virtual handler" from within the filter.
110         // The target resource is the current one and everything else is
111         // defaulted or set by content policy.
112         target=request.getRequestURL();
113         pair<bool,bool> passopt = getBool("isPassive");
114         isPassive = passopt.first && passopt.second;
115     }
116
117     m_log.debug("sending request to SAMLDS (%s)", m_url);
118
119     // Compute the return URL. We start with a self-referential link.
120     string returnURL=request.getHandlerURL(target.c_str());
121     pair<bool,const char*> thisloc = getString("Location");
122     if (thisloc.first) returnURL += thisloc.second;
123     returnURL += "?SAMLDS=1"; // signals us not to loop if we get no answer back
124
125     if (isHandler) {
126         // We may already have RelayState set if we looped back here,
127         // but just in case target is a resource, we reset it back.
128         option = request.getParameter("target");
129         if (option)
130             target = option;
131     }
132     preserveRelayState(request.getApplication(), request, target);
133
134     const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
135     if (isHandler) {
136         // Now the hard part. The base assumption is to append the entire query string, if any,
137         // to the self-link. But we want to replace target with the RelayState-preserved value
138         // to hide it from the DS.
139         const char* query = request.getQueryString();
140         if (query) {
141             // See if it starts with target.
142             if (!strncmp(query, "target=", 7)) {
143                 // We skip this altogether and advance the query past it to the first separator.
144                 query = strchr(query, '&');
145                 // If we still have more, just append it.
146                 if (query && *(++query))
147                     returnURL = returnURL + '&' + query;
148             }
149             else {
150                 // There's something in the query before target appears, so we have to find it.
151                 thisloc.second = strstr(query,"&target=");
152                 if (thisloc.second) {
153                     // We found it, so first append everything up to it.
154                     returnURL += '&';
155                     returnURL.append(query, thisloc.second - query);
156                     query = thisloc.second + 8; // move up just past the equals sign.
157                     thisloc.second = strchr(query, '&');
158                     if (thisloc.second)
159                         returnURL += thisloc.second;
160                 }
161                 else {
162                     // No target in the existing query, so just append it as is.
163                     returnURL = returnURL + '&' + query;
164                 }
165             }
166         }
167
168         // Now append the sanitized target as needed.
169         if (!target.empty())
170             returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
171     }
172     else if (!target.empty()) {
173         // For a virtual handler, we just append target to the return link.
174         returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());;
175     }
176
177     string req=string(m_url) + (strchr(m_url,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
178         "&return=" + urlenc->encode(returnURL.c_str());
179     if (m_returnParam)
180         req = req + "&returnIDParam=" + m_returnParam;
181     if (isPassive)
182         req += "&isPassive=true";
183
184     return make_pair(true, request.sendRedirect(req.c_str()));
185 }