Recognise special database name "*" in user-register file, indicating
[metaproxy-moved-to-github.git] / src / filter_auth_simple.cpp
1 /* $Id: filter_auth_simple.cpp,v 1.9 2006-01-18 10:50:13 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 userRegisterName;
57     bool got_userRegisterName = 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, "userRegister")) {
63             userRegisterName = yp2::xml::get_text(ptr);
64             got_userRegisterName = 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_userRegisterName)
73         throw yp2::filter::FilterException("auth_simple: no user-register "
74                                            "filename specified");
75
76     FILE *fp = fopen(userRegisterName.c_str(), "r");
77     if (fp == 0)
78         throw yp2::filter::FilterException("can't open auth_simple " 
79                                            "user-register '" + userRegisterName
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                                                userRegisterName + "': " +
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                                                userRegisterName + "': " +
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 (0) {                // 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     case Z_APDU_scanRequest: return process_scan(package);
131         // In theory, we should check database authorisation for
132         // extended services, too (A) the proxy currently does not
133         // implement XS and turns off its negotiation bit; (B) it
134         // would be insanely complex to do as the top-level XS request
135         // structure does not carry a database name, but it is buried
136         // down in some of the possible EXTERNALs used as
137         // taskSpecificParameters; and (C) since many extended
138         // services modify the database, we'd need to more exotic
139         // authorisation database than we want to support.
140     default: break;
141     }   
142
143     // Operations other than those listed above do not require authorisation
144     return package.move();
145 }
146
147
148 static void reject_init(yp2::Package &package, const char *addinfo);
149
150
151 void yf::AuthSimple::process_init(yp2::Package &package) const
152 {
153     Z_IdAuthentication *auth =
154         package.request().get()->u.z3950->u.initRequest->idAuthentication;
155         // This is just plain perverted.
156
157     if (!auth)
158         return reject_init(package, "no credentials supplied");
159     if (auth->which != Z_IdAuthentication_idPass)
160         return reject_init(package, "only idPass authentication is supported");
161     Z_IdPass *idPass = auth->u.idPass;
162
163     if (m_p->userRegister.count(idPass->userId)) {
164         // groupId is ignored, in accordance with ancient tradition.
165         yf::AuthSimple::Rep::PasswordAndDBs pdbs =
166             m_p->userRegister[idPass->userId];
167         if (pdbs.password == idPass->password) {
168             // Success!  Remember who the user is for future reference
169             {
170                 boost::mutex::scoped_lock lock(m_p->mutex);
171                 m_p->userBySession[package.session()] = idPass->userId;
172             }
173             return package.move();
174         }
175     }
176
177     return reject_init(package, "username/password combination rejected");
178 }
179
180
181 // I find it unutterable disappointing that I have to provide this
182 static bool contains(std::list<std::string> list, std::string thing) {
183     std::list<std::string>::const_iterator i;
184     for (i = list.begin(); i != list.end(); i++)
185         if (*i == thing)
186             return true;
187
188     return false;
189 }
190
191
192 void yf::AuthSimple::process_search(yp2::Package &package) const
193 {
194     Z_SearchRequest *req =
195         package.request().get()->u.z3950->u.searchRequest;
196
197     if (m_p->userBySession.count(package.session()) == 0) {
198         // It's a non-authenticated session, so just accept the operation
199         return package.move();
200     }
201
202     std::string user = m_p->userBySession[package.session()];
203     yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
204     for (int i = 0; i < req->num_databaseNames; i++) {
205         if (!contains(pdb.dbs, req->databaseNames[i]) &&
206             !contains(pdb.dbs, "*")) {
207             // Make an Search rejection APDU
208             yp2::odr odr;
209             Z_APDU *apdu = odr.create_searchResponse(
210                 package.request().get()->u.z3950, 
211                 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
212                 req->databaseNames[i]);
213             package.response() = apdu;
214             package.session().close();
215             return;
216         }
217     }
218
219     // All the requested databases are acceptable
220     return package.move();
221 }
222
223
224 void yf::AuthSimple::process_scan(yp2::Package &package) const
225 {
226     Z_ScanRequest *req =
227         package.request().get()->u.z3950->u.scanRequest;
228
229     if (m_p->userBySession.count(package.session()) == 0) {
230         // It's a non-authenticated session, so just accept the operation
231         return package.move();
232     }
233
234     std::string user = m_p->userBySession[package.session()];
235     yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
236     for (int i = 0; i < req->num_databaseNames; i++) {
237         if (!contains(pdb.dbs, req->databaseNames[i])) {
238             // Make an Scan rejection APDU
239             yp2::odr odr;
240             Z_APDU *apdu = odr.create_scanResponse(
241                 package.request().get()->u.z3950, 
242                 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
243                 req->databaseNames[i]);
244             package.response() = apdu;
245             package.session().close();
246             return;
247         }
248     }
249
250     // All the requested databases are acceptable
251     return package.move();
252 }
253
254
255 static void reject_init(yp2::Package &package, const char *addinfo) { 
256     // Make an Init rejection APDU
257     Z_GDU *gdu = package.request().get();
258     yp2::odr odr;
259     Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950,
260         YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR, addinfo);
261     apdu->u.initResponse->implementationName = "YP2/YAZ";
262     *apdu->u.initResponse->result = 0; // reject
263     package.response() = apdu;
264     package.session().close();
265 }
266
267
268 static yp2::filter::Base* filter_creator()
269 {
270     return new yp2::filter::AuthSimple;
271 }
272
273 extern "C" {
274     struct yp2_filter_struct yp2_filter_auth_simple = {
275         0,
276         "auth_simple",
277         filter_creator
278     };
279 }
280
281
282 /*
283  * Local variables:
284  * c-basic-offset: 4
285  * indent-tabs-mode: nil
286  * c-file-style: "stroustrup"
287  * End:
288  * vim: shiftwidth=4 tabstop=8 expandtab
289  */