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