Consolidated exception and status handling into a single class.
[shibboleth/cpp-sp.git] / shib-target / shib-target.h
1 /*
2  * The Shibboleth License, Version 1.
3  * Copyright (c) 2002
4  * University Corporation for Advanced Internet Development, Inc.
5  * All rights reserved
6  *
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * Redistributions of source code must retain the above copyright notice, this
12  * list of conditions and the following disclaimer.
13  *
14  * Redistributions in binary form must reproduce the above copyright notice,
15  * this list of conditions and the following disclaimer in the documentation
16  * and/or other materials provided with the distribution, if any, must include
17  * the following acknowledgment: "This product includes software developed by
18  * the University Corporation for Advanced Internet Development
19  * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
20  * may appear in the software itself, if and wherever such third-party
21  * acknowledgments normally appear.
22  *
23  * Neither the name of Shibboleth nor the names of its contributors, nor
24  * Internet2, nor the University Corporation for Advanced Internet Development,
25  * Inc., nor UCAID may be used to endorse or promote products derived from this
26  * software without specific prior written permission. For written permission,
27  * please contact shibboleth@shibboleth.org
28  *
29  * Products derived from this software may not be called Shibboleth, Internet2,
30  * UCAID, or the University Corporation for Advanced Internet Development, nor
31  * may Shibboleth appear in their name, without prior written permission of the
32  * University Corporation for Advanced Internet Development.
33  *
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
36  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
38  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
39  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
40  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
41  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
42  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
43  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
47  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49
50 /*
51  * shib-target.h -- top-level header file for the SHIB Common Target Library
52  *
53  * Created by:  Derek Atkins <derek@ihtfp.com>
54  *
55  * $Id$
56  */
57
58 #ifndef SHIB_TARGET_H
59 #define SHIB_TARGET_H
60
61 #include <saml/saml.h>
62 #include <shib/shib.h>
63 #include <shib/shib-threads.h>
64
65 #ifdef WIN32
66 # ifndef SHIBTARGET_EXPORTS
67 #  define SHIBTARGET_EXPORTS __declspec(dllimport)
68 # endif
69 # define SHIB_SCHEMAS "/opt/shibboleth/share/xml/shibboleth"
70 # define SHIB_CONFIG "/opt/shibboleth/etc/shibboleth/shibboleth.xml"
71 #else
72 # include <shib-target/shib-paths.h>
73 # define SHIBTARGET_EXPORTS
74 #endif
75
76 #include <shib-target/shibrpc.h>
77
78 namespace shibtarget {
79   
80     DECLARE_SAML_EXCEPTION(SHIBTARGET_EXPORTS,ListenerException,SAMLException);
81
82     // Abstract APIs for access to configuration information
83     
84     struct SHIBTARGET_EXPORTS IPropertySet
85     {
86         virtual std::pair<bool,bool> getBool(const char* name, const char* ns=NULL) const=0;
87         virtual std::pair<bool,const char*> getString(const char* name, const char* ns=NULL) const=0;
88         virtual std::pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const=0;
89         virtual std::pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const=0;
90         virtual std::pair<bool,int> getInt(const char* name, const char* ns=NULL) const=0;
91         virtual const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const=0;
92         virtual const DOMElement* getElement() const=0;
93         virtual ~IPropertySet() {}
94     };
95
96     struct SHIBTARGET_EXPORTS IListener : public virtual saml::IPlugIn
97     {
98 #ifdef WIN32
99         typedef SOCKET ShibSocket;
100 #else
101         typedef int ShibSocket;
102 #endif
103         virtual bool create(ShibSocket& s) const=0;
104         virtual bool bind(ShibSocket& s, bool force=false) const=0;
105         virtual bool connect(ShibSocket& s) const=0;
106         virtual bool close(ShibSocket& s) const=0;
107         virtual bool accept(ShibSocket& listener, ShibSocket& s) const=0;
108         virtual CLIENT* getClientHandle(ShibSocket& s, u_long program, u_long version) const=0;
109         virtual ~IListener() {}
110     };
111
112     struct SHIBTARGET_EXPORTS IAccessControl : public virtual saml::ILockable, public virtual saml::IPlugIn
113     {
114         virtual bool authorized(
115             const saml::SAMLAuthenticationStatement& authn, const saml::Iterator<saml::SAMLAssertion*>& attrs
116             ) const=0;
117         virtual ~IAccessControl() {}
118     };
119
120     struct SHIBTARGET_EXPORTS IRequestMapper : public virtual saml::ILockable, public virtual saml::IPlugIn
121     {
122         typedef std::pair<const IPropertySet*,IAccessControl*> Settings;
123         virtual Settings getSettingsFromURL(const char* url) const=0;
124         virtual Settings getSettingsFromParsedURL(
125             const char* scheme, const char* hostname, unsigned int port, const char* path=NULL
126             ) const=0;
127         virtual ~IRequestMapper() {}
128     };
129     
130     struct SHIBTARGET_EXPORTS IApplication : public virtual IPropertySet
131     {
132         virtual const char* getId() const=0;
133         virtual const char* getHash() const=0;
134         virtual saml::Iterator<saml::SAMLAttributeDesignator*> getAttributeDesignators() const=0;
135         virtual saml::Iterator<shibboleth::IAAP*> getAAPProviders() const=0;
136         virtual saml::Iterator<shibboleth::IMetadata*> getMetadataProviders() const=0;
137         virtual saml::Iterator<shibboleth::ITrust*> getTrustProviders() const=0;
138         virtual saml::Iterator<shibboleth::IRevocation*> getRevocationProviders() const=0;
139         virtual saml::Iterator<const XMLCh*> getAudiences() const=0;
140         virtual const IPropertySet* getCredentialUse(const shibboleth::IEntityDescriptor* provider) const=0;
141
142         // caller is borrowing object, must use within scope of config lock
143         virtual const saml::SAMLBrowserProfile* getBrowserProfile() const=0;
144         virtual const saml::SAMLBinding* getBinding(const XMLCh* binding) const=0;
145
146         // caller is given ownership of object, must use and delete within scope of config lock
147         virtual saml::SAMLBrowserProfile::ArtifactMapper* getArtifactMapper() const=0;
148
149         virtual ~IApplication() {}
150     };
151
152     struct SHIBTARGET_EXPORTS ISessionCacheEntry : public virtual saml::ILockable
153     {
154         virtual bool isValid(time_t lifetime, time_t timeout) const=0;
155         virtual const char* getClientAddress() const=0;
156         virtual ShibProfile getProfile() const=0;
157         virtual const char* getProviderId() const=0;
158         virtual const saml::SAMLAuthenticationStatement* getAuthnStatement() const=0;
159         struct SHIBTARGET_EXPORTS CachedResponse {
160             CachedResponse(const saml::SAMLResponse* unfiltered, const saml::SAMLResponse* filtered) {
161                 this->unfiltered=unfiltered;
162                 this->filtered=filtered;
163             }
164             bool empty() {return unfiltered==NULL;}
165             const saml::SAMLResponse* unfiltered;
166             const saml::SAMLResponse* filtered;
167         };
168         virtual CachedResponse getResponse()=0;
169         virtual ~ISessionCacheEntry() {}
170     };
171
172     struct SHIBTARGET_EXPORTS ISessionCache : public virtual saml::IPlugIn
173     {
174         virtual void thread_init()=0;
175         virtual void thread_end()=0;
176         virtual std::string generateKey() const=0;
177         virtual void insert(
178             const char* key,
179             const IApplication* application,
180             const char* client_addr,
181             ShibProfile profile,
182             const char* providerId,
183             saml::SAMLAuthenticationStatement* s,
184             saml::SAMLResponse* r=NULL,
185             const shibboleth::IRoleDescriptor* source=NULL,
186             time_t created=0,
187             time_t accessed=0
188             )=0;
189         virtual ISessionCacheEntry* find(const char* key, const IApplication* application)=0;
190         virtual void remove(const char* key)=0;
191         virtual ~ISessionCache() {}
192     };
193
194     struct SHIBTARGET_EXPORTS IConfig : public virtual saml::ILockable, public virtual IPropertySet, public virtual saml::IPlugIn
195     {
196         virtual const IListener* getListener() const=0;
197         virtual ISessionCache* getSessionCache() const=0;
198         virtual saml::IReplayCache* getReplayCache() const=0;
199         virtual IRequestMapper* getRequestMapper() const=0;
200         virtual const IApplication* getApplication(const char* applicationId) const=0;
201         virtual saml::Iterator<shibboleth::ICredentials*> getCredentialsProviders() const=0;
202         virtual ~IConfig() {}
203     };
204
205     class SHIBTARGET_EXPORTS ShibTargetConfig
206     {
207     public:
208         ShibTargetConfig() : m_ini(NULL), m_features(0) {}
209         virtual ~ShibTargetConfig() {}
210
211         virtual bool init(const char* schemadir, const char* config) = 0;
212         virtual void shutdown() = 0;
213
214         enum components_t {
215             Listener = 1,
216             Caching = 2,
217             Metadata = 4,
218             Trust = 8,
219             Credentials = 16,
220             AAP = 32,
221             RequestMapper = 64,
222             GlobalExtensions = 128,
223             LocalExtensions = 256,
224             Logging = 512
225         };
226         void setFeatures(long enabled) {m_features = enabled;}
227         bool isEnabled(components_t feature) {return (m_features & feature)>0;}
228         virtual IConfig* getINI() const {return m_ini;}
229
230         static const XMLCh SHIBTARGET_NS[];
231         static ShibTargetConfig& getConfig();
232
233     protected:
234         IConfig* m_ini;
235         
236     private:
237         unsigned long m_features;
238     };
239
240     class ShibMLPPriv;
241     class SHIBTARGET_EXPORTS ShibMLP {
242     public:
243         ShibMLP();
244         ~ShibMLP();
245
246         void insert (const std::string& key, const std::string& value);
247         void insert (const std::string& key, const char* value) {
248           std::string v = value;
249           insert (key, v);
250         }
251         void insert (const char* key, const std::string& value) {
252           std::string k = key;
253           insert (k, value);
254         }
255         void insert (const char* key, const char* value) {
256           std::string k = key, v = value;
257           insert(k,v);
258         }
259         void insert (saml::SAMLException& e);
260
261         void clear () { m_map.clear(); }
262
263         const char* run (std::istream& s, const IPropertySet* props=NULL, std::string* output=NULL);
264         const char* run (const std::string& input, const IPropertySet* props=NULL, std::string* output=NULL);
265         const char* run (const char* input, const IPropertySet* props=NULL, std::string* output=NULL) {
266             std::string i = input;
267             return run(i,props,output);
268         }
269
270     private:
271         ShibMLPPriv *m_priv;
272         std::map<std::string,std::string> m_map;
273         std::string m_generated;
274     };
275
276   class HTAccessInfo {
277   public:
278     class RequireLine {
279     public:
280       bool use_line;
281       std::vector<std::string> tokens;
282     };
283
284     HTAccessInfo() {}
285     ~HTAccessInfo() {
286       for (int k = 0; k < elements.size(); k++)
287         delete elements[k];
288       elements.resize(0);
289     }
290
291     std::vector<RequireLine*> elements;
292     bool requireAll;
293   };
294
295   class HTGroupTable {
296   public:
297     virtual ~HTGroupTable() {}
298     virtual bool lookup(const char *entry) = 0;
299   protected:
300     HTGroupTable() {}
301   };
302
303   // This usurps the existing SHIRE and RM apis into a single class.
304   class ShibTargetPriv;
305   class SHIBTARGET_EXPORTS ShibTarget {
306   public:
307     ShibTarget(const IApplication *app);
308     virtual ~ShibTarget(void);
309
310     // These are defined here so the subclass does not need to specifically
311     // depend on log4cpp.  We could use log4cpp::Priority::PriorityLevel
312     // but this is just as easy, IMHO.  It's just a case statement in the
313     // implementation to handle the event level.
314     enum ShibLogLevel {
315       LogLevelDebug,
316       LogLevelInfo,
317       LogLevelWarn,
318       LogLevelError
319     };
320
321     //
322     // Note: subclasses MUST implement ALL of these virtual methods
323     //
324
325     // Send a message to the Webserver log
326     virtual void log(ShibLogLevel level, const std::string &msg)=0;
327
328     void log(ShibLogLevel level, const char *msg) {
329       std::string s = msg;
330       log(level, s);
331     }
332
333     // Get/Set a cookie for this connection
334     virtual std::string getCookies(void)=0;    
335     virtual void setCookie(const std::string &name, const std::string &value)=0;
336     void setCookie(const char *name, const char *value) {
337       std::string ns = name;
338       std::string vs = value;
339       setCookie(ns, vs);
340     }
341     void setCookie(const char *name, const std::string &value) {
342       std::string ns = name;
343       setCookie(ns, value);
344     }
345
346
347     // Get the request's GET arguments or POST data from the server
348     virtual std::string getArgs(void)=0;
349     virtual std::string getPostData(void)=0;
350
351     // Clear a header, set a header
352     // These APIs are used for exporting the Assertions into the
353     // Headers.  It will clear some well-known headers first to make
354     // sure none remain.  Then it will process the set of assertions
355     // and export them via setHeader().
356     virtual void clearHeader(const std::string &name)=0;
357     virtual void setHeader(const std::string &name, const std::string &value)=0;
358     virtual std::string getHeader(const std::string &name)=0;
359     virtual void setRemoteUser(const std::string &user)=0;
360     virtual std::string getRemoteUser(void)=0;
361
362     void clearHeader(const char *n) {
363       std::string s = n;
364       clearHeader(s);
365     }
366     void setHeader(const char *n, const char *v) {
367       std::string ns = n;
368       std::string vs = v;
369       setHeader(ns, vs);
370     }
371     void setHeader(const std::string &n, const char *v) {
372       std::string vs = v;
373       setHeader(n, vs);
374     }
375     void setHeader(const char *n, const std::string &v) {
376       std::string ns = n;
377       setHeader(ns, v);
378     }
379     std::string getHeader(const char *n) {
380       std::string s = n;
381       return getHeader(s);
382     }
383     void setRemoteUser(const char *n) {
384       std::string s = n;
385       setRemoteUser(s);
386     }
387
388     // returns the "auth type"..  if this string is not "shibboleth" then
389     // the request will be denied.  Any kind of "override" should be handled
390     // by the subclass before returning this value.  Note that the default
391     // implementation always returns "shibboleth".
392     virtual std::string getAuthType(void);
393
394     // Note: we still need to define exactly what kind of data in contained
395     // in the HTAccessInfo -- perhaps we can stub it out so non-htaccess
396     // systems have something they can plug in?
397     virtual HTAccessInfo* getAccessInfo(void);
398     virtual HTGroupTable* getGroupTable(std::string &user);
399
400     // We're done.  Finish up.  Send either a result (error?) page or a redirect.
401     // If there are no headers supplied assume the content-type == text/html
402     typedef std::pair<std::string, std::string> header_t;
403     virtual void* sendPage(
404                            const std::string &msg,
405                            const std::string content_type = "text/html",
406                            const saml::Iterator<header_t>& headers = EMPTY(header_t),
407                            int code = 200
408                            )=0;
409     void* sendPage(const char *msg) {
410       std::string m = msg;
411       return sendPage(m);
412     }
413
414     virtual void* sendRedirect(const std::string url)=0;
415
416     // These next two APIs are used to obtain the module-specific "OK"
417     // and "Decline" results.  OK means "we believe that this request
418     // should be accepted".  Declined means "we believe that this is
419     // not a shibbolized request so we have no comment".
420
421     virtual void* returnDecline(void);
422     virtual void* returnOK(void);
423
424     //
425     // Note:  Subclasses need not implement anything below this line
426     //
427
428     // These functions implement the server-agnostic shibboleth engine
429     // The web server modules implement a subclass and then call into 
430     // these methods once they instantiate their request object.
431     // 
432     // Return value:
433     //   these APIs will always return the result of sendPage(), sendRedirect(),
434     //   returnDecline(), or returnOK() in the void* portion of the return code.
435     //   Exactly what those values are is module- (subclass-) implementation
436     //   specific.  The 'bool' part of the return value declares whether the
437     //   void* is valid or not.  If the bool is true then the void* is valid.
438     //   If the bool is false then the API did not call any callback, the void*
439     //   is not valid, and the caller should continue processing (the API Call
440     //   finished successfully).
441     //
442     //   The arguments are all overrides..  The requireSession and
443     //   exportAssertion values passed in here are only used if the
444     //   settings resource is negative.
445     //
446     //   The handleProfile argument declares whether doCheckAuthN() should
447     //   automatically call doHandlePOST() when it encounters a request for
448     //   the ShireURL;  if false it will call returnOK() instead.
449     //
450     std::pair<bool,void*> doCheckAuthN(bool requireSession = false, bool handleProfile = false);
451     std::pair<bool,void*> doHandleProfile();
452     std::pair<bool,void*> doCheckAuthZ();
453     std::pair<bool,void*> doExportAssertions(bool exportAssertion = false);
454
455     //**************************************************************************
456     // These APIs are for backwards-compatibility.  Hopefully they can
457     // eventually go away.
458
459     // SHIRE APIs
460
461     // Get the session cookie name and properties for the application
462     std::pair<std::string,const char*> getCookieNameProps(const char* prefix) const;
463
464     // Find the default assertion consumer service for the resource
465     const char* getShireURL(const char* resource) const;
466         
467     // Generate a Shib 1.x AuthnRequest redirect URL for the resource
468     std::string getAuthnRequest(const char* resource);
469         
470     // Process a lazy session setup request and turn it into an AuthnRequest
471     std::string getLazyAuthnRequest(const char* query_string);
472         
473   protected:
474     ShibTarget();
475
476     // Currently wraps remoted interface.
477     // TODO: Move this functionality behind IListener
478     void sessionNew(
479         int supported_profiles,
480         const char* packet,
481         const char* ip,
482         std::string& cookie,
483         std::string& target
484         ) const;
485
486     void sessionGet(
487         const char* cookie,
488         const char* ip,
489         ShibProfile& profile,
490         std::string& provider_id,
491         saml::SAMLAuthenticationStatement** auth_statement=NULL,
492         saml::SAMLResponse** attr_response_pre=NULL,
493         saml::SAMLResponse** attr_response_post=NULL
494         ) const;
495
496     // Initialize the request from the parsed URL
497     // protocol == http, https, etc
498     // hostname == server name
499     // port == server port
500     // uri == resource path
501     // method == GET, POST, etc.
502     void init(ShibTargetConfig *config,
503               std::string protocol, std::string hostname, int port,
504               std::string uri, std::string content_type, std::string remote_host,
505               std::string method);
506
507   private:
508     mutable ShibTargetPriv *m_priv;
509   };
510 }
511
512 #endif /* SHIB_TARGET_H */