Recognise <targetRegister> as well as <userRegister>
[metaproxy-moved-to-github.git] / src / filter_auth_simple.cpp
1 /* $Id: filter_auth_simple.cpp,v 1.10 2006-01-18 11:12:15 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<std::string, std::list<std::string> > targetsByUser;
39             std::map<yp2::Session, std::string> userBySession;
40         };
41     }
42 }
43
44 yf::AuthSimple::AuthSimple() : m_p(new Rep)
45 {
46     // nothing to do
47 }
48
49 yf::AuthSimple::~AuthSimple()
50 {  // must have a destructor because of boost::scoped_ptr
51 }
52
53
54 static void die(std::string s) { throw yp2::filter::FilterException(s); }
55
56
57 // Read XML config.. Put config info in m_p.
58 void yp2::filter::AuthSimple::configure(const xmlNode * ptr)
59 {
60     std::string userRegisterName;
61     bool got_userRegisterName = false;
62     std::string targetRegisterName;
63     bool got_targetRegisterName = false;
64
65     for (ptr = ptr->children; ptr != 0; ptr = ptr->next) {
66         if (ptr->type != XML_ELEMENT_NODE)
67             continue;
68         if (!strcmp((const char *) ptr->name, "userRegister")) {
69             userRegisterName = yp2::xml::get_text(ptr);
70             got_userRegisterName = true;
71         } else if (!strcmp((const char *) ptr->name, "targetRegister")) {
72             targetRegisterName = yp2::xml::get_text(ptr);
73             got_targetRegisterName = true;
74         } else {
75             die("Bad element in auth_simple: <"
76                 + std::string((const char *) ptr->name) + ">");
77         }
78     }
79
80     if (!got_userRegisterName && !got_targetRegisterName)
81         die("auth_simple: no user-register or target-register "
82             "filename specified");
83
84     if (got_userRegisterName)
85         config_userRegister(userRegisterName);
86     if (got_targetRegisterName)
87         config_targetRegister(targetRegisterName);
88 }
89
90
91 void yp2::filter::AuthSimple::config_userRegister(std::string filename)
92 {
93     FILE *fp = fopen(filename.c_str(), "r");
94     if (fp == 0)
95         die("can't open auth_simple user-register '" + filename + "': " +
96             strerror(errno));
97
98     char buf[1000];
99     while (fgets(buf, sizeof buf, fp)) {
100         if (*buf == '\n' || *buf == '#')
101             continue;
102         buf[strlen(buf)-1] = 0;
103         char *passwdp = strchr(buf, ':');
104         if (passwdp == 0)
105             die("auth_simple user-register '" + filename + "': " +
106                 "no password on line: '" + buf + "'");
107         *passwdp++ = 0;
108         char *databasesp = strchr(passwdp, ':');
109         if (databasesp == 0)
110             die("auth_simple user-register '" + filename + "': " +
111                 "no databases on line: '" + buf + ":" + passwdp + "'");
112         *databasesp++ = 0;
113         yf::AuthSimple::Rep::PasswordAndDBs tmp(passwdp);
114         boost::split(tmp.dbs, databasesp, boost::is_any_of(","));
115         m_p->userRegister[buf] = tmp;
116
117         if (0) {                // debugging
118             printf("Added user '%s' -> password '%s'\n", buf, passwdp);
119             std::list<std::string>::const_iterator i;
120             for (i = tmp.dbs.begin(); i != tmp.dbs.end(); i++) {
121                 printf("db '%s'\n", (*i).c_str());
122             }
123         }
124     }
125 }
126
127
128 void yp2::filter::AuthSimple::config_targetRegister(std::string filename)
129 {
130     // ### empty!
131 }
132
133
134 void yf::AuthSimple::process(yp2::Package &package) const
135 {
136     Z_GDU *gdu = package.request().get();
137
138     if (!gdu || gdu->which != Z_GDU_Z3950) {
139         // Pass on the package -- This means that authentication is
140         // waived, which may not be the correct thing for non-Z APDUs
141         // as it means that SRW sessions don't demand authentication
142         return package.move();
143     }
144
145     switch (gdu->u.z3950->which) {
146     case Z_APDU_initRequest: return process_init(package);
147     case Z_APDU_searchRequest: return process_search(package);
148     case Z_APDU_scanRequest: return process_scan(package);
149         // In theory, we should check database authorisation for
150         // extended services, too (A) the proxy currently does not
151         // implement XS and turns off its negotiation bit; (B) it
152         // would be insanely complex to do as the top-level XS request
153         // structure does not carry a database name, but it is buried
154         // down in some of the possible EXTERNALs used as
155         // taskSpecificParameters; and (C) since many extended
156         // services modify the database, we'd need to more exotic
157         // authorisation database than we want to support.
158     default: break;
159     }   
160
161     // Operations other than those listed above do not require authorisation
162     return package.move();
163 }
164
165
166 static void reject_init(yp2::Package &package, const char *addinfo);
167
168
169 void yf::AuthSimple::process_init(yp2::Package &package) const
170 {
171     Z_IdAuthentication *auth =
172         package.request().get()->u.z3950->u.initRequest->idAuthentication;
173         // This is just plain perverted.
174
175     if (!auth)
176         return reject_init(package, "no credentials supplied");
177     if (auth->which != Z_IdAuthentication_idPass)
178         return reject_init(package, "only idPass authentication is supported");
179     Z_IdPass *idPass = auth->u.idPass;
180
181     if (m_p->userRegister.count(idPass->userId)) {
182         // groupId is ignored, in accordance with ancient tradition.
183         yf::AuthSimple::Rep::PasswordAndDBs pdbs =
184             m_p->userRegister[idPass->userId];
185         if (pdbs.password == idPass->password) {
186             // Success!  Remember who the user is for future reference
187             {
188                 boost::mutex::scoped_lock lock(m_p->mutex);
189                 m_p->userBySession[package.session()] = idPass->userId;
190             }
191             return package.move();
192         }
193     }
194
195     return reject_init(package, "username/password combination rejected");
196 }
197
198
199 // I find it unutterable disappointing that I have to provide this
200 static bool contains(std::list<std::string> list, std::string thing) {
201     std::list<std::string>::const_iterator i;
202     for (i = list.begin(); i != list.end(); i++)
203         if (*i == thing)
204             return true;
205
206     return false;
207 }
208
209
210 void yf::AuthSimple::process_search(yp2::Package &package) const
211 {
212     Z_SearchRequest *req =
213         package.request().get()->u.z3950->u.searchRequest;
214
215     if (m_p->userBySession.count(package.session()) == 0) {
216         // It's a non-authenticated session, so just accept the operation
217         return package.move();
218     }
219
220     std::string user = m_p->userBySession[package.session()];
221     yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
222     for (int i = 0; i < req->num_databaseNames; i++) {
223         if (!contains(pdb.dbs, req->databaseNames[i]) &&
224             !contains(pdb.dbs, "*")) {
225             // Make an Search rejection APDU
226             yp2::odr odr;
227             Z_APDU *apdu = odr.create_searchResponse(
228                 package.request().get()->u.z3950, 
229                 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
230                 req->databaseNames[i]);
231             package.response() = apdu;
232             package.session().close();
233             return;
234         }
235     }
236
237     // All the requested databases are acceptable
238     return package.move();
239 }
240
241
242 void yf::AuthSimple::process_scan(yp2::Package &package) const
243 {
244     Z_ScanRequest *req =
245         package.request().get()->u.z3950->u.scanRequest;
246
247     if (m_p->userBySession.count(package.session()) == 0) {
248         // It's a non-authenticated session, so just accept the operation
249         return package.move();
250     }
251
252     std::string user = m_p->userBySession[package.session()];
253     yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
254     for (int i = 0; i < req->num_databaseNames; i++) {
255         if (!contains(pdb.dbs, req->databaseNames[i])) {
256             // Make an Scan rejection APDU
257             yp2::odr odr;
258             Z_APDU *apdu = odr.create_scanResponse(
259                 package.request().get()->u.z3950, 
260                 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
261                 req->databaseNames[i]);
262             package.response() = apdu;
263             package.session().close();
264             return;
265         }
266     }
267
268     // All the requested databases are acceptable
269     return package.move();
270 }
271
272
273 static void reject_init(yp2::Package &package, const char *addinfo) { 
274     // Make an Init rejection APDU
275     Z_GDU *gdu = package.request().get();
276     yp2::odr odr;
277     Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950,
278         YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR, addinfo);
279     apdu->u.initResponse->implementationName = "YP2/YAZ";
280     *apdu->u.initResponse->result = 0; // reject
281     package.response() = apdu;
282     package.session().close();
283 }
284
285
286 static yp2::filter::Base* filter_creator()
287 {
288     return new yp2::filter::AuthSimple;
289 }
290
291 extern "C" {
292     struct yp2_filter_struct yp2_filter_auth_simple = {
293         0,
294         "auth_simple",
295         filter_creator
296     };
297 }
298
299
300 /*
301  * Local variables:
302  * c-basic-offset: 4
303  * indent-tabs-mode: nil
304  * c-file-style: "stroustrup"
305  * End:
306  * vim: shiftwidth=4 tabstop=8 expandtab
307  */