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