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