6b377ac4bf963b5a600445cafef8df348112ef20
[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/signature/KeyInfo.h>
38 #include <xmltooling/util/URLEncoder.h>
39
40 using namespace shibsp;
41 using namespace opensaml::saml2md;
42 using namespace opensaml;
43 using namespace xmltooling;
44 using namespace std;
45
46 namespace shibsp {
47
48 #if defined (_MSC_VER)
49     #pragma warning( push )
50     #pragma warning( disable : 4250 )
51 #endif
52
53     class SHIBSP_DLLLOCAL TransformSINodeFilter : public DOMNodeFilter
54     {
55     public:
56         short acceptNode(const DOMNode* node) const {
57             if (XMLString::equals(node->getLocalName(), xmlsignature::Transform::LOCAL_NAME))
58                 return FILTER_REJECT;
59             return FILTER_ACCEPT;
60         }
61     };
62
63     static SHIBSP_DLLLOCAL TransformSINodeFilter g_TSINFilter;
64
65     class SHIBSP_DLLLOCAL TransformSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
66     {
67     public:
68         TransformSessionInitiator(const DOMElement* e, const char* appId)
69                 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.Transform"), &g_TSINFilter), m_appId(appId) {
70             // If Location isn't set, defer address registration until the setParent call.
71             pair<bool,const char*> loc = getString("Location");
72             if (loc.first) {
73                 string address = m_appId + loc.second + "::run::TransformSI";
74                 setAddress(address.c_str());
75             }
76
77 #ifndef SHIBSP_LITE
78             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
79                 e = XMLHelper::getFirstChildElement(e, xmlsignature::Transform::LOCAL_NAME);
80                 while (e) {
81                     if (e->hasChildNodes()) {
82                         auto_ptr_char temp(e->getFirstChild()->getNodeValue());
83                         m_transforms.push_back(temp.get());
84                     }
85                     e = XMLHelper::getNextSiblingElement(e, xmlsignature::Transform::LOCAL_NAME);
86                 }
87             }
88 #endif
89         }
90
91         virtual ~TransformSessionInitiator() {}
92         
93         void setParent(const PropertySet* parent);
94         void receive(DDF& in, ostream& out);
95         pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
96
97     private:
98         void doRequest(const Application& application, string& entityID) const;
99         string m_appId;
100 #ifndef SHIBSP_LITE
101         vector<string> m_transforms;
102 #endif
103     };
104
105 #if defined (_MSC_VER)
106     #pragma warning( pop )
107 #endif
108
109     SessionInitiator* SHIBSP_DLLLOCAL TransformSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
110     {
111         return new TransformSessionInitiator(p.first, p.second);
112     }
113
114 };
115
116 void TransformSessionInitiator::setParent(const PropertySet* parent)
117 {
118     DOMPropertySet::setParent(parent);
119     pair<bool,const char*> loc = getString("Location");
120     if (loc.first) {
121         string address = m_appId + loc.second + "::run::TransformSI";
122         setAddress(address.c_str());
123     }
124     else {
125         m_log.warn("no Location property in Transform SessionInitiator (or parent), can't register as remoted handler");
126     }
127 }
128
129 pair<bool,long> TransformSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
130 {
131     // We have to have a candidate name to function.
132     if (entityID.empty())
133         return make_pair(false,0L);
134
135     string target;
136     const Application& app=request.getApplication();
137
138     m_log.debug("attempting to transform input (%s) into a valid entityID", entityID.c_str());
139
140     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
141         doRequest(app, entityID);
142     else {
143         // Remote the call.
144         DDF out,in = DDF(m_address.c_str()).structure();
145         DDFJanitor jin(in), jout(out);
146         in.addmember("application_id").string(app.getId());
147         in.addmember("entity_id").string(entityID.c_str());
148     
149         // Remote the processing.
150         out = request.getServiceProvider().getListenerService()->send(in);
151         if (out.isstring())
152             entityID = out.string();
153     }
154     
155     return make_pair(false,0L);
156 }
157
158 void TransformSessionInitiator::receive(DDF& in, ostream& out)
159 {
160     // Find application.
161     const char* aid=in["application_id"].string();
162     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
163     if (!app) {
164         // Something's horribly wrong.
165         m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
166         throw ConfigurationException("Unable to locate application for new session, deleted?");
167     }
168
169     const char* entityID = in["entity_id"].string();
170     if (!entityID)
171         throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
172
173     string copy(entityID);
174     doRequest(*app, copy);
175     DDF ret = DDF(NULL).string(copy.c_str());
176     DDFJanitor jout(ret);
177     out << ret;
178 }
179
180 void TransformSessionInitiator::doRequest(const Application& application, string& entityID) const
181 {
182 #ifndef SHIBSP_LITE
183     MetadataProvider* m=application.getMetadataProvider();
184     Locker locker(m);
185
186     // First check the original value, it might be valid already.
187     MetadataProvider::Criteria mc(entityID.c_str(), &IDPSSODescriptor::ELEMENT_QNAME);
188     pair<const EntityDescriptor*,const RoleDescriptor*> entity = m->getEntityDescriptor(mc);
189     if (entity.first)
190         return;
191
192     // Guess not, try each transform.
193     string transform;
194     for (vector<string>::const_iterator t = m_transforms.begin(); t != m_transforms.end(); ++t) {
195         transform = *t;
196         string::size_type pos = transform.find("$entityID");
197         if (pos == string::npos)
198             continue;
199         transform.replace(pos, 9, entityID);
200         m_log.debug("attempting lookup with entityID (%s)", transform.c_str());
201     
202         mc.entityID_ascii = transform.c_str();
203         entity = m->getEntityDescriptor(mc);
204         if (entity.first) {
205             m_log.info("transformed entityID from (%s) to (%s)", entityID.c_str(), transform.c_str());
206             entityID = transform;
207             return;
208         }
209     }
210
211     m_log.warn("unable to find a valid entityID based on the supplied input");
212 #endif
213 }