3aa012c7257c02db6ced78f4e82b6b3e1af867c5
[shibboleth/sp.git] / shibsp / handler / impl / TransformSessionInitiator.cpp
1 /*
2  *  Copyright 2001-2010 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  * TransformSessionInitiator.cpp
19  * 
20  * Support for mapping input into an entityID using a transform.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SPRequest.h"
28 #include "handler/AbstractHandler.h"
29 #include "handler/RemotedHandler.h"
30 #include "handler/SessionInitiator.h"
31 #include "util/SPConstants.h"
32
33 #ifndef SHIBSP_LITE
34 # include "metadata/MetadataProviderCriteria.h"
35 # include <saml/saml2/metadata/Metadata.h>
36 #endif
37 #include <xmltooling/XMLToolingConfig.h>
38 #include <xmltooling/util/URLEncoder.h>
39 #include <xercesc/util/XMLUniDefs.hpp>
40 #include <xercesc/util/regx/RegularExpression.hpp>
41
42 using namespace shibsp;
43 using namespace opensaml::saml2md;
44 using namespace opensaml;
45 using namespace xmltooling;
46 using namespace std;
47
48 namespace shibsp {
49
50 #if defined (_MSC_VER)
51     #pragma warning( push )
52     #pragma warning( disable : 4250 )
53 #endif
54
55     class SHIBSP_DLLLOCAL TransformSINodeFilter : public DOMNodeFilter
56     {
57     public:
58 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
59         short
60 #else
61         FilterAction
62 #endif
63         acceptNode(const DOMNode* node) const {
64             return FILTER_REJECT;
65         }
66     };
67
68     static SHIBSP_DLLLOCAL TransformSINodeFilter g_TSINFilter;
69
70 #ifndef SHIBSP_LITE
71     static const XMLCh force[] =        UNICODE_LITERAL_5(f,o,r,c,e);
72     static const XMLCh match[] =        UNICODE_LITERAL_5(m,a,t,c,h);
73     static const XMLCh Regex[] =        UNICODE_LITERAL_5(R,e,g,e,x);
74     static const XMLCh Subst[] =        UNICODE_LITERAL_5(S,u,b,s,t);
75 #endif
76
77     class SHIBSP_DLLLOCAL TransformSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
78     {
79     public:
80         TransformSessionInitiator(const DOMElement* e, const char* appId)
81                 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.Transform"), &g_TSINFilter), m_appId(appId) {
82             // If Location isn't set, defer address registration until the setParent call.
83             pair<bool,const char*> loc = getString("Location");
84             if (loc.first) {
85                 string address = m_appId + loc.second + "::run::TransformSI";
86                 setAddress(address.c_str());
87             }
88             m_supportedOptions.insert("isPassive");
89
90 #ifndef SHIBSP_LITE
91             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
92                 m_alwaysRun = getBool("alwaysRun").second;
93                 e = XMLHelper::getFirstChildElement(e);
94                 while (e) {
95                     if (e->hasChildNodes()) {
96                         const XMLCh* flag = e->getAttributeNS(NULL, force);
97                         if (!flag)
98                             flag = &chNull;
99                         if (XMLString::equals(e->getLocalName(), Subst)) {
100                             auto_ptr_char temp(e->getFirstChild()->getNodeValue());
101                             if (temp.get() && *temp.get())
102                                 m_subst.push_back(pair<bool,string>((*flag==chDigit_1 || *flag==chLatin_t), temp.get()));
103                         }
104                         else if (XMLString::equals(e->getLocalName(), Regex) && e->hasAttributeNS(NULL, match)) {
105                             auto_ptr_char m(e->getAttributeNS(NULL, match));
106                             auto_ptr_char repl(e->getFirstChild()->getNodeValue());
107                             if (m.get() && *m.get() && repl.get() && *repl.get())
108                                 m_regex.push_back(make_pair((*flag==chDigit_1 || *flag==chLatin_t), pair<string,string>(m.get(), repl.get())));
109                         }
110                         else {
111                             m_log.warn("Unknown element found in Transform SessionInitiator configuration, check for errors.");
112                         }
113                     }
114                     e = XMLHelper::getNextSiblingElement(e);
115                 }
116             }
117 #endif
118         }
119
120         virtual ~TransformSessionInitiator() {}
121         
122         void setParent(const PropertySet* parent);
123         void receive(DDF& in, ostream& out);
124         pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
125
126     private:
127         void doRequest(const Application& application, string& entityID) const;
128         string m_appId;
129 #ifndef SHIBSP_LITE
130         bool m_alwaysRun;
131         vector< pair<bool, string> > m_subst;
132         vector< pair< bool, pair<string,string> > > m_regex;
133 #endif
134     };
135
136 #if defined (_MSC_VER)
137     #pragma warning( pop )
138 #endif
139
140     SessionInitiator* SHIBSP_DLLLOCAL TransformSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
141     {
142         return new TransformSessionInitiator(p.first, p.second);
143     }
144
145 };
146
147 void TransformSessionInitiator::setParent(const PropertySet* parent)
148 {
149     DOMPropertySet::setParent(parent);
150     pair<bool,const char*> loc = getString("Location");
151     if (loc.first) {
152         string address = m_appId + loc.second + "::run::TransformSI";
153         setAddress(address.c_str());
154     }
155     else {
156         m_log.warn("no Location property in Transform SessionInitiator (or parent), can't register as remoted handler");
157     }
158 }
159
160 pair<bool,long> TransformSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
161 {
162     // We have to have a candidate name to function.
163     if (entityID.empty() || !checkCompatibility(request, isHandler))
164         return make_pair(false,0L);
165
166     const Application& app=request.getApplication();
167
168     m_log.debug("attempting to transform input (%s) into a valid entityID", entityID.c_str());
169
170     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
171         doRequest(app, entityID);
172     else {
173         // Remote the call.
174         DDF out,in = DDF(m_address.c_str()).structure();
175         DDFJanitor jin(in), jout(out);
176         in.addmember("application_id").string(app.getId());
177         in.addmember("entity_id").string(entityID.c_str());
178     
179         // Remote the processing.
180         out = request.getServiceProvider().getListenerService()->send(in);
181         if (out.isstring())
182             entityID = out.string();
183     }
184     
185     return make_pair(false,0L);
186 }
187
188 void TransformSessionInitiator::receive(DDF& in, ostream& out)
189 {
190     // Find application.
191     const char* aid=in["application_id"].string();
192     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
193     if (!app) {
194         // Something's horribly wrong.
195         m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
196         throw ConfigurationException("Unable to locate application for new session, deleted?");
197     }
198
199     const char* entityID = in["entity_id"].string();
200     if (!entityID)
201         throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
202
203     string copy(entityID);
204     doRequest(*app, copy);
205     DDF ret = DDF(NULL).string(copy.c_str());
206     DDFJanitor jout(ret);
207     out << ret;
208 }
209
210 void TransformSessionInitiator::doRequest(const Application& application, string& entityID) const
211 {
212 #ifndef SHIBSP_LITE
213     MetadataProvider* m=application.getMetadataProvider();
214     Locker locker(m);
215
216     MetadataProviderCriteria mc(application, entityID.c_str(), &IDPSSODescriptor::ELEMENT_QNAME);
217     pair<const EntityDescriptor*,const RoleDescriptor*> entity;
218     if (!m_alwaysRun) {
219         // First check the original value, it might be valid already.
220         entity = m->getEntityDescriptor(mc);
221         if (entity.first)
222             return;
223     }
224
225     m_log.debug("attempting transform of (%s)", entityID.c_str());
226
227     // Guess not, try each subst.
228     string transform;
229     for (vector< pair<bool,string> >::const_iterator t = m_subst.begin(); t != m_subst.end(); ++t) {
230         string::size_type pos = t->second.find("$entityID");
231         if (pos == string::npos)
232             continue;
233         transform = t->second;
234         transform.replace(pos, 9, entityID);
235         if (t->first) {
236             m_log.info("forcibly transformed entityID from (%s) to (%s)", entityID.c_str(), transform.c_str());
237             entityID = transform;
238         }
239
240         m_log.debug("attempting lookup with entityID (%s)", transform.c_str());
241     
242         mc.entityID_ascii = transform.c_str();
243         entity = m->getEntityDescriptor(mc);
244         if (entity.first) {
245             m_log.info("transformed entityID from (%s) to (%s)", entityID.c_str(), transform.c_str());
246             if (!t->first)
247                 entityID = transform;
248             return;
249         }
250     }
251
252     // Now try regexs.
253     for (vector< pair< bool, pair<string,string> > >::const_iterator r = m_regex.begin(); r != m_regex.end(); ++r) {
254         try {
255             RegularExpression exp(r->second.first.c_str());
256             XMLCh* temp = exp.replace(entityID.c_str(), r->second.second.c_str());
257             if (temp) {
258                 auto_ptr_char narrow(temp);
259                 XMLString::release(&temp);
260
261                 // For some reason it returns the match string if it doesn't match the expression.
262                 if (entityID == narrow.get())
263                     continue;
264
265                 if (r->first) {
266                     m_log.info("forcibly transformed entityID from (%s) to (%s)", entityID.c_str(), narrow.get());
267                     entityID = narrow.get();
268                 }
269
270                 m_log.debug("attempting lookup with entityID (%s)", narrow.get());
271
272                 mc.entityID_ascii = narrow.get();
273                 entity = m->getEntityDescriptor(mc);
274                 if (entity.first) {
275                     m_log.info("transformed entityID from (%s) to (%s)", entityID.c_str(), narrow.get());
276                     if (!r->first)
277                         entityID = narrow.get();
278                     return;
279                 }
280             }
281         }
282         catch (XMLException& ex) {
283             auto_ptr_char msg(ex.getMessage());
284             m_log.error("caught error applying regular expression: %s", msg.get());
285         }
286     }
287
288     m_log.warn("unable to find a valid entityID based on the supplied input");
289 #endif
290 }