Per-database authorisation done at search time.
[metaproxy-moved-to-github.git] / src / filter_auth_simple.cpp
1 /* $Id: filter_auth_simple.cpp,v 1.4 2006-01-17 17:13:31 mike Exp $
2    Copyright (c) 2005, Index Data.
3
4 %LICENSE%
5  */
6
7 #include "config.hpp"
8
9 #include "filter.hpp"
10 #include "package.hpp"
11
12 #include <boost/thread/mutex.hpp>
13 #include <boost/algorithm/string.hpp>
14
15 #include "util.hpp"
16 #include "filter_auth_simple.hpp"
17
18 #include <yaz/zgdu.h>
19 #include <yaz/diagbib1.h>
20 #include <stdio.h>
21 #include <errno.h>
22
23 namespace yf = yp2::filter;
24
25 namespace yp2 {
26     namespace filter {
27         class AuthSimple::Rep {
28             friend class AuthSimple;
29             struct PasswordAndDBs {
30                 std::string password;
31                 std::list<std::string> dbs;
32                 PasswordAndDBs() {};
33                 PasswordAndDBs(std::string pw) : password(pw) {};
34                 void addDB(std::string db) { dbs.push_back(db); }
35             };
36             boost::mutex mutex;
37             std::map<std::string, PasswordAndDBs> userRegister;
38             std::map<yp2::Session, std::string> userBySession;
39         };
40     }
41 }
42
43 yf::AuthSimple::AuthSimple() : m_p(new Rep)
44 {
45     // nothing to do
46 }
47
48 yf::AuthSimple::~AuthSimple()
49 {  // must have a destructor because of boost::scoped_ptr
50 }
51
52
53 // Read XML config.. Put config info in m_p.
54 void yp2::filter::AuthSimple::configure(const xmlNode * ptr)
55 {
56     std::string filename;
57     bool got_filename = false;
58
59     for (ptr = ptr->children; ptr != 0; ptr = ptr->next) {
60         if (ptr->type != XML_ELEMENT_NODE)
61             continue;
62         if (!strcmp((const char *) ptr->name, "filename")) {
63             filename = yp2::xml::get_text(ptr);
64             got_filename = true;
65         } else {
66             throw yp2::filter::FilterException("Bad element in auth_simple: <"
67                                                + std::string((const char *)
68                                                              ptr->name) + ">");
69         }
70     }
71
72     if (!got_filename)
73         throw yp2::filter::FilterException("auth_simple: no user-register "
74                                            "filename specified");
75
76     FILE *fp = fopen(filename.c_str(), "r");
77     if (fp == 0)
78         throw yp2::filter::FilterException("can't open auth_simple " 
79                                            "user-register '" + filename +
80                                            "': " + strerror(errno));
81
82     char buf[1000];
83     while (fgets(buf, sizeof buf, fp)) {
84         if (*buf == '\n' || *buf == '#')
85             continue;
86         buf[strlen(buf)-1] = 0;
87         char *passwdp = strchr(buf, ':');
88         if (passwdp == 0)
89             throw yp2::filter::FilterException("auth_simple user-register '" +
90                                                filename + "': " +
91                                                "no password on line: '"
92                                                + buf + "'");
93         *passwdp++ = 0;
94         char *databasesp = strchr(passwdp, ':');
95         if (databasesp == 0)
96             throw yp2::filter::FilterException("auth_simple user-register '" +
97                                                filename + "': " +
98                                                "no databases on line: '" +
99                                                buf + ":" + passwdp + "'");
100         *databasesp++ = 0;
101         yf::AuthSimple::Rep::PasswordAndDBs tmp(passwdp);
102         boost::split(tmp.dbs, databasesp, boost::is_any_of(","));
103         m_p->userRegister[buf] = tmp;
104
105         if (1) {                // debugging
106             printf("Added user '%s' -> password '%s'\n", buf, passwdp);
107             std::list<std::string>::const_iterator i;
108             for (i = tmp.dbs.begin(); i != tmp.dbs.end(); i++) {
109                 printf("db '%s'\n", (*i).c_str());
110             }
111         }
112     }
113 }
114
115
116 void yf::AuthSimple::process(yp2::Package &package) const
117 {
118     Z_GDU *gdu = package.request().get();
119
120     if (!gdu || gdu->which != Z_GDU_Z3950) {
121         // Pass on the package -- This means that authentication is
122         // waived, which may not be the correct thing for non-Z APDUs
123         // as it means that SRW sessions don't demand authentication
124         return package.move();
125     }
126
127     switch (gdu->u.z3950->which) {
128     case Z_APDU_initRequest: return process_init(package);
129     case Z_APDU_searchRequest: return process_search(package);
130     default: break;
131     }   
132
133     // Operations other than those listed above do not require authorisation
134     return package.move();
135 }
136
137
138 static void reject_init(yp2::Package &package, const char *addinfo);
139
140
141 void yf::AuthSimple::process_init(yp2::Package &package) const
142 {
143     Z_IdAuthentication *auth =
144         package.request().get()->u.z3950->u.initRequest->idAuthentication;
145         // This is just plain perverted.
146
147     if (!auth)
148         return reject_init(package, "no credentials supplied");
149     if (auth->which != Z_IdAuthentication_idPass)
150         return reject_init(package, "only idPass authentication is supported");
151     Z_IdPass *idPass = auth->u.idPass;
152
153     if (m_p->userRegister.count(idPass->userId)) {
154         // groupId is ignored, in accordance with ancient tradition.
155         yf::AuthSimple::Rep::PasswordAndDBs pdbs =
156             m_p->userRegister[idPass->userId];
157         if (pdbs.password == idPass->password) {
158             // Success!  Remember who the user is for future reference
159             {
160                 boost::mutex::scoped_lock lock(m_p->mutex);
161                 m_p->userBySession[package.session()] = idPass->userId;
162             }
163             return package.move();
164         }
165     }
166
167     return reject_init(package, "username/password combination rejected");
168 }
169
170
171 // I find it unutterable disappointing that I have to provide this
172 static bool contains(std::list<std::string> list, std::string thing) {
173     std::list<std::string>::const_iterator i;
174     for (i = list.begin(); i != list.end(); i++)
175         if (*i == thing)
176             return true;
177
178     return false;
179 }
180
181
182 void yf::AuthSimple::process_search(yp2::Package &package) const
183 {
184     Z_SearchRequest *req =
185         package.request().get()->u.z3950->u.searchRequest;
186
187     if (m_p->userBySession.count(package.session()) == 0) {
188         // It's a non-authenticated session, so just accept the operation
189         return package.move();
190     }
191
192     std::string user = m_p->userBySession[package.session()];
193     yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
194     for (int i = 0; i < req->num_databaseNames; i++) {
195         if (!contains(pdb.dbs, req->databaseNames[i])) {
196             // Make an Search rejection APDU
197             yp2::odr odr;
198             Z_APDU *apdu = odr.create_searchResponse(
199                 package.request().get()->u.z3950, 
200                 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
201                 req->databaseNames[i]);
202             package.response() = apdu;
203             package.session().close();
204             return;
205         }
206     }
207
208     // All the requested databases are acceptable
209     return package.move();
210 }
211
212
213 static void reject_init(yp2::Package &package, const char *addinfo) { 
214     // Make an Init rejection APDU
215     Z_GDU *gdu = package.request().get();
216     yp2::odr odr;
217     Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950,
218         YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR, addinfo);
219     apdu->u.initResponse->implementationName = "YP2/YAZ";
220     *apdu->u.initResponse->result = 0; // reject
221     package.response() = apdu;
222     package.session().close();
223 }
224
225
226 static yp2::filter::Base* filter_creator()
227 {
228     return new yp2::filter::AuthSimple;
229 }
230
231 extern "C" {
232     struct yp2_filter_struct yp2_filter_auth_simple = {
233         0,
234         "auth_simple",
235         filter_creator
236     };
237 }
238
239
240 /*
241  * Local variables:
242  * c-basic-offset: 4
243  * indent-tabs-mode: nil
244  * c-file-style: "stroustrup"
245  * End:
246  * vim: shiftwidth=4 tabstop=8 expandtab
247  */