Imported Upstream version 2.2.1+dfsg
[shibboleth/sp.git] / shibsp / handler / impl / TransformSessionInitiator.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  * 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
89 #ifndef SHIBSP_LITE
90             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
91                 m_alwaysRun = getBool("alwaysRun").second;
92                 e = XMLHelper::getFirstChildElement(e);
93                 while (e) {
94                     if (e->hasChildNodes()) {
95                         const XMLCh* flag = e->getAttributeNS(NULL, force);
96                         if (!flag)
97                             flag = &chNull;
98                         if (XMLString::equals(e->getLocalName(), Subst)) {
99                             auto_ptr_char temp(e->getFirstChild()->getNodeValue());
100                             m_subst.push_back(pair<bool,string>((*flag==chDigit_1 || *flag==chLatin_t), temp.get()));
101                         }
102                         else if (XMLString::equals(e->getLocalName(), Regex) && e->hasAttributeNS(NULL, match)) {
103                             auto_ptr_char m(e->getAttributeNS(NULL, match));
104                             auto_ptr_char repl(e->getFirstChild()->getNodeValue());
105                             m_regex.push_back(make_pair((*flag==chDigit_1 || *flag==chLatin_t), pair<string,string>(m.get(), repl.get())));
106                         }
107                         else {
108                             m_log.warn("Unknown element found in Transform SessionInitiator configuration, check for errors.");
109                         }
110                     }
111                     e = XMLHelper::getNextSiblingElement(e);
112                 }
113             }
114 #endif
115         }
116
117         virtual ~TransformSessionInitiator() {}
118         
119         void setParent(const PropertySet* parent);
120         void receive(DDF& in, ostream& out);
121         pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
122
123     private:
124         void doRequest(const Application& application, string& entityID) const;
125         string m_appId;
126 #ifndef SHIBSP_LITE
127         bool m_alwaysRun;
128         vector< pair<bool, string> > m_subst;
129         vector< pair< bool, pair<string,string> > > m_regex;
130 #endif
131     };
132
133 #if defined (_MSC_VER)
134     #pragma warning( pop )
135 #endif
136
137     SessionInitiator* SHIBSP_DLLLOCAL TransformSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
138     {
139         return new TransformSessionInitiator(p.first, p.second);
140     }
141
142 };
143
144 void TransformSessionInitiator::setParent(const PropertySet* parent)
145 {
146     DOMPropertySet::setParent(parent);
147     pair<bool,const char*> loc = getString("Location");
148     if (loc.first) {
149         string address = m_appId + loc.second + "::run::TransformSI";
150         setAddress(address.c_str());
151     }
152     else {
153         m_log.warn("no Location property in Transform SessionInitiator (or parent), can't register as remoted handler");
154     }
155 }
156
157 pair<bool,long> TransformSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
158 {
159     // We have to have a candidate name to function.
160     if (entityID.empty())
161         return make_pair(false,0L);
162
163     string target;
164     const Application& app=request.getApplication();
165
166     m_log.debug("attempting to transform input (%s) into a valid entityID", entityID.c_str());
167
168     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
169         doRequest(app, entityID);
170     else {
171         // Remote the call.
172         DDF out,in = DDF(m_address.c_str()).structure();
173         DDFJanitor jin(in), jout(out);
174         in.addmember("application_id").string(app.getId());
175         in.addmember("entity_id").string(entityID.c_str());
176     
177         // Remote the processing.
178         out = request.getServiceProvider().getListenerService()->send(in);
179         if (out.isstring())
180             entityID = out.string();
181     }
182     
183     return make_pair(false,0L);
184 }
185
186 void TransformSessionInitiator::receive(DDF& in, ostream& out)
187 {
188     // Find application.
189     const char* aid=in["application_id"].string();
190     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
191     if (!app) {
192         // Something's horribly wrong.
193         m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
194         throw ConfigurationException("Unable to locate application for new session, deleted?");
195     }
196
197     const char* entityID = in["entity_id"].string();
198     if (!entityID)
199         throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
200
201     string copy(entityID);
202     doRequest(*app, copy);
203     DDF ret = DDF(NULL).string(copy.c_str());
204     DDFJanitor jout(ret);
205     out << ret;
206 }
207
208 void TransformSessionInitiator::doRequest(const Application& application, string& entityID) const
209 {
210 #ifndef SHIBSP_LITE
211     MetadataProvider* m=application.getMetadataProvider();
212     Locker locker(m);
213
214     MetadataProviderCriteria mc(application, entityID.c_str(), &IDPSSODescriptor::ELEMENT_QNAME);
215     pair<const EntityDescriptor*,const RoleDescriptor*> entity;
216     if (!m_alwaysRun) {
217         // First check the original value, it might be valid already.
218         entity = m->getEntityDescriptor(mc);
219         if (entity.first)
220             return;
221     }
222
223     m_log.debug("attempting transform of (%s)", entityID.c_str());
224
225     // Guess not, try each subst.
226     string transform;
227     for (vector< pair<bool,string> >::const_iterator t = m_subst.begin(); t != m_subst.end(); ++t) {
228         string::size_type pos = t->second.find("$entityID");
229         if (pos == string::npos)
230             continue;
231         transform = t->second;
232         transform.replace(pos, 9, entityID);
233         if (t->first) {
234             m_log.info("forcibly transformed entityID from (%s) to (%s)", entityID.c_str(), transform.c_str());
235             entityID = transform;
236         }
237
238         m_log.debug("attempting lookup with entityID (%s)", transform.c_str());
239     
240         mc.entityID_ascii = transform.c_str();
241         entity = m->getEntityDescriptor(mc);
242         if (entity.first) {
243             m_log.info("transformed entityID from (%s) to (%s)", entityID.c_str(), transform.c_str());
244             if (!t->first)
245                 entityID = transform;
246             return;
247         }
248     }
249
250     // Now try regexs.
251     for (vector< pair< bool, pair<string,string> > >::const_iterator r = m_regex.begin(); r != m_regex.end(); ++r) {
252         try {
253             RegularExpression exp(r->second.first.c_str());
254             XMLCh* temp = exp.replace(entityID.c_str(), r->second.second.c_str());
255             if (temp) {
256                 auto_ptr_char narrow(temp);
257                 XMLString::release(&temp);
258
259                 // For some reason it returns the match string if it doesn't match the expression.
260                 if (entityID == narrow.get())
261                     continue;
262
263                 if (r->first) {
264                     m_log.info("forcibly transformed entityID from (%s) to (%s)", entityID.c_str(), narrow.get());
265                     entityID = narrow.get();
266                 }
267
268                 m_log.debug("attempting lookup with entityID (%s)", narrow.get());
269
270                 mc.entityID_ascii = narrow.get();
271                 entity = m->getEntityDescriptor(mc);
272                 if (entity.first) {
273                     m_log.info("transformed entityID from (%s) to (%s)", entityID.c_str(), narrow.get());
274                     if (!r->first)
275                         entityID = narrow.get();
276                     return;
277                 }
278             }
279         }
280         catch (XMLException& ex) {
281             auto_ptr_char msg(ex.getMessage());
282             m_log.error("caught error applying regular expression: %s", msg.get());
283         }
284     }
285
286     m_log.warn("unable to find a valid entityID based on the supplied input");
287 #endif
288 }