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