Implement config_targetRegister()
[metaproxy-moved-to-github.git] / src / filter_auth_simple.cpp
1 /* $Id: filter_auth_simple.cpp,v 1.11 2006-01-18 11:22:03 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 // I feel a little bad about the duplication of code between this and
129 // config_userRegister().  But not bad enough to refactor.
130 //
131 void yp2::filter::AuthSimple::config_targetRegister(std::string filename)
132 {
133     FILE *fp = fopen(filename.c_str(), "r");
134     if (fp == 0)
135         die("can't open auth_simple target-register '" + filename + "': " +
136             strerror(errno));
137
138     char buf[1000];
139     while (fgets(buf, sizeof buf, fp)) {
140         if (*buf == '\n' || *buf == '#')
141             continue;
142         buf[strlen(buf)-1] = 0;
143         char *targetsp = strchr(buf, ':');
144         if (targetsp == 0)
145             die("auth_simple target-register '" + filename + "': " +
146                 "no targets on line: '" + buf + "'");
147         *targetsp++ = 0;
148         std::list<std::string> tmp;
149         boost::split(tmp, targetsp, boost::is_any_of(","));
150         m_p->targetsByUser[buf] = tmp;
151
152         if (0) {                // debugging
153             printf("Added user '%s' with targets:\n", buf);
154             std::list<std::string>::const_iterator i;
155             for (i = tmp.begin(); i != tmp.end(); i++) {
156                 printf("\t%s\n", (*i).c_str());
157             }
158         }
159     }
160 }
161
162
163 void yf::AuthSimple::process(yp2::Package &package) const
164 {
165     Z_GDU *gdu = package.request().get();
166
167     if (!gdu || gdu->which != Z_GDU_Z3950) {
168         // Pass on the package -- This means that authentication is
169         // waived, which may not be the correct thing for non-Z APDUs
170         // as it means that SRW sessions don't demand authentication
171         return package.move();
172     }
173
174     switch (gdu->u.z3950->which) {
175     case Z_APDU_initRequest: return process_init(package);
176     case Z_APDU_searchRequest: return process_search(package);
177     case Z_APDU_scanRequest: return process_scan(package);
178         // In theory, we should check database authorisation for
179         // extended services, too (A) the proxy currently does not
180         // implement XS and turns off its negotiation bit; (B) it
181         // would be insanely complex to do as the top-level XS request
182         // structure does not carry a database name, but it is buried
183         // down in some of the possible EXTERNALs used as
184         // taskSpecificParameters; and (C) since many extended
185         // services modify the database, we'd need to more exotic
186         // authorisation database than we want to support.
187     default: break;
188     }   
189
190     // Operations other than those listed above do not require authorisation
191     return package.move();
192 }
193
194
195 static void reject_init(yp2::Package &package, const char *addinfo);
196
197
198 void yf::AuthSimple::process_init(yp2::Package &package) const
199 {
200     Z_IdAuthentication *auth =
201         package.request().get()->u.z3950->u.initRequest->idAuthentication;
202         // This is just plain perverted.
203
204     if (!auth)
205         return reject_init(package, "no credentials supplied");
206     if (auth->which != Z_IdAuthentication_idPass)
207         return reject_init(package, "only idPass authentication is supported");
208     Z_IdPass *idPass = auth->u.idPass;
209
210     if (m_p->userRegister.count(idPass->userId)) {
211         // groupId is ignored, in accordance with ancient tradition.
212         yf::AuthSimple::Rep::PasswordAndDBs pdbs =
213             m_p->userRegister[idPass->userId];
214         if (pdbs.password == idPass->password) {
215             // Success!  Remember who the user is for future reference
216             {
217                 boost::mutex::scoped_lock lock(m_p->mutex);
218                 m_p->userBySession[package.session()] = idPass->userId;
219             }
220             return package.move();
221         }
222     }
223
224     return reject_init(package, "username/password combination rejected");
225 }
226
227
228 // I find it unutterable disappointing that I have to provide this
229 static bool contains(std::list<std::string> list, std::string thing) {
230     std::list<std::string>::const_iterator i;
231     for (i = list.begin(); i != list.end(); i++)
232         if (*i == thing)
233             return true;
234
235     return false;
236 }
237
238
239 void yf::AuthSimple::process_search(yp2::Package &package) const
240 {
241     Z_SearchRequest *req =
242         package.request().get()->u.z3950->u.searchRequest;
243
244     if (m_p->userBySession.count(package.session()) == 0) {
245         // It's a non-authenticated session, so just accept the operation
246         return package.move();
247     }
248
249     std::string user = m_p->userBySession[package.session()];
250     yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
251     for (int i = 0; i < req->num_databaseNames; i++) {
252         if (!contains(pdb.dbs, req->databaseNames[i]) &&
253             !contains(pdb.dbs, "*")) {
254             // Make an Search rejection APDU
255             yp2::odr odr;
256             Z_APDU *apdu = odr.create_searchResponse(
257                 package.request().get()->u.z3950, 
258                 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
259                 req->databaseNames[i]);
260             package.response() = apdu;
261             package.session().close();
262             return;
263         }
264     }
265
266     // All the requested databases are acceptable
267     return package.move();
268 }
269
270
271 void yf::AuthSimple::process_scan(yp2::Package &package) const
272 {
273     Z_ScanRequest *req =
274         package.request().get()->u.z3950->u.scanRequest;
275
276     if (m_p->userBySession.count(package.session()) == 0) {
277         // It's a non-authenticated session, so just accept the operation
278         return package.move();
279     }
280
281     std::string user = m_p->userBySession[package.session()];
282     yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
283     for (int i = 0; i < req->num_databaseNames; i++) {
284         if (!contains(pdb.dbs, req->databaseNames[i])) {
285             // Make an Scan rejection APDU
286             yp2::odr odr;
287             Z_APDU *apdu = odr.create_scanResponse(
288                 package.request().get()->u.z3950, 
289                 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
290                 req->databaseNames[i]);
291             package.response() = apdu;
292             package.session().close();
293             return;
294         }
295     }
296
297     // All the requested databases are acceptable
298     return package.move();
299 }
300
301
302 static void reject_init(yp2::Package &package, const char *addinfo) { 
303     // Make an Init rejection APDU
304     Z_GDU *gdu = package.request().get();
305     yp2::odr odr;
306     Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950,
307         YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR, addinfo);
308     apdu->u.initResponse->implementationName = "YP2/YAZ";
309     *apdu->u.initResponse->result = 0; // reject
310     package.response() = apdu;
311     package.session().close();
312 }
313
314
315 static yp2::filter::Base* filter_creator()
316 {
317     return new yp2::filter::AuthSimple;
318 }
319
320 extern "C" {
321     struct yp2_filter_struct yp2_filter_auth_simple = {
322         0,
323         "auth_simple",
324         filter_creator
325     };
326 }
327
328
329 /*
330  * Local variables:
331  * c-basic-offset: 4
332  * indent-tabs-mode: nil
333  * c-file-style: "stroustrup"
334  * End:
335  * vim: shiftwidth=4 tabstop=8 expandtab
336  */