Remove debugging output (compiled user-register file)
[metaproxy-moved-to-github.git] / src / filter_auth_simple.cpp
1 /* $Id: filter_auth_simple.cpp,v 1.7 2006-01-17 17:58:46 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 (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             // Make an Search rejection APDU
207             yp2::odr odr;
208             Z_APDU *apdu = odr.create_searchResponse(
209                 package.request().get()->u.z3950, 
210                 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
211                 req->databaseNames[i]);
212             package.response() = apdu;
213             package.session().close();
214             return;
215         }
216     }
217
218     // All the requested databases are acceptable
219     return package.move();
220 }
221
222
223 void yf::AuthSimple::process_scan(yp2::Package &package) const
224 {
225     Z_ScanRequest *req =
226         package.request().get()->u.z3950->u.scanRequest;
227
228     if (m_p->userBySession.count(package.session()) == 0) {
229         // It's a non-authenticated session, so just accept the operation
230         return package.move();
231     }
232
233     std::string user = m_p->userBySession[package.session()];
234     yf::AuthSimple::Rep::PasswordAndDBs pdb = m_p->userRegister[user];
235     for (int i = 0; i < req->num_databaseNames; i++) {
236         if (!contains(pdb.dbs, req->databaseNames[i])) {
237             // Make an Scan rejection APDU
238             yp2::odr odr;
239             Z_APDU *apdu = odr.create_scanResponse(
240                 package.request().get()->u.z3950, 
241                 YAZ_BIB1_ACCESS_TO_SPECIFIED_DATABASE_DENIED,
242                 req->databaseNames[i]);
243             package.response() = apdu;
244             package.session().close();
245             return;
246         }
247     }
248
249     // All the requested databases are acceptable
250     return package.move();
251 }
252
253
254 static void reject_init(yp2::Package &package, const char *addinfo) { 
255     // Make an Init rejection APDU
256     Z_GDU *gdu = package.request().get();
257     yp2::odr odr;
258     Z_APDU *apdu = odr.create_initResponse(gdu->u.z3950,
259         YAZ_BIB1_INIT_AC_AUTHENTICATION_SYSTEM_ERROR, addinfo);
260     apdu->u.initResponse->implementationName = "YP2/YAZ";
261     *apdu->u.initResponse->result = 0; // reject
262     package.response() = apdu;
263     package.session().close();
264 }
265
266
267 static yp2::filter::Base* filter_creator()
268 {
269     return new yp2::filter::AuthSimple;
270 }
271
272 extern "C" {
273     struct yp2_filter_struct yp2_filter_auth_simple = {
274         0,
275         "auth_simple",
276         filter_creator
277     };
278 }
279
280
281 /*
282  * Local variables:
283  * c-basic-offset: 4
284  * indent-tabs-mode: nil
285  * c-file-style: "stroustrup"
286  * End:
287  * vim: shiftwidth=4 tabstop=8 expandtab
288  */