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