Merge branch 'master' of github.com:FreeRADIUS/freeradius-server
[freeradius.git] / src / modules / rlm_redis / rlm_redis.c
1 /*
2  * rlm_redis.c
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2000,2006  The FreeRADIUS server project
21  * Copyright 2011  TekSavvy Solutions <gabe@teksavvy.com>
22  */
23
24 #include <freeradius-devel/ident.h>
25
26 RCSID("$Id$")
27
28 #include <freeradius-devel/radiusd.h>
29 #include <freeradius-devel/modules.h>
30
31 #include "rlm_redis.h"
32
33 static const CONF_PARSER module_config[] = {
34         { "hostname", PW_TYPE_STRING_PTR,
35           offsetof(REDIS_INST, hostname), NULL, "127.0.0.1"},
36         { "port", PW_TYPE_INTEGER,
37           offsetof(REDIS_INST, port), NULL, "6379"},
38         { "database", PW_TYPE_INTEGER,
39           offsetof(REDIS_INST, database), NULL, "0"},
40         { "password", PW_TYPE_STRING_PTR,
41           offsetof(REDIS_INST, password), NULL, NULL},
42
43         { NULL, -1, 0, NULL, NULL} /* end the list */
44 };
45
46 static int redis_delete_conn(UNUSED void *ctx, void *conn)
47 {
48         REDISSOCK *dissocket = conn;
49
50         redisFree(dissocket->conn);
51
52         if (dissocket->reply) {
53                 freeReplyObject(dissocket->reply);
54                 dissocket->reply = NULL;
55         }
56
57         free(dissocket);
58         return 1;
59 }
60
61 static void *redis_create_conn(void *ctx)
62 {
63         REDIS_INST *inst = ctx;
64         REDISSOCK *dissocket = NULL;
65         redisContext *conn;
66         char buffer[1024];
67
68         conn = redisConnect(inst->hostname, inst->port);
69         if (dissocket->conn->err) return NULL;
70
71         if (inst->password) {
72                 redisReply *reply = NULL;
73
74                 snprintf(buffer, sizeof(buffer), "AUTH %s", inst->password);
75
76                 reply = redisCommand(dissocket->conn, buffer);
77                 if (!reply) {
78                         radlog(L_ERR, "rlm_redis (%s): Failed to run AUTH",
79                                inst->xlat_name);
80                 do_close:
81                         if (reply) freeReplyObject(reply);
82                         redisFree(conn);
83                         return NULL;
84                 }
85
86
87                 switch (reply->type) {
88                 case REDIS_REPLY_STATUS:
89                         if (strcmp(reply->str, "OK") != 0) {
90                                 radlog(L_ERR, "rlm_redis (%s): Failed authentication: reply %s",
91                                        inst->xlat_name, dissocket->reply->str);
92                                 goto do_close;
93                         }
94                         break;  /* else it's OK */
95
96                 default:
97                         radlog(L_ERR, "rlm_redis (%s): Unexpected reply to AUTH",
98                                inst->xlat_name);
99                         goto do_close;
100                 }
101         }
102
103         if (inst->database) {
104                 redisReply *reply = NULL;
105
106                 snprintf(buffer, sizeof(buffer), "SELECT %d", inst->database);
107
108                 reply = redisCommand(dissocket->conn, buffer);
109                 if (!reply) {
110                         radlog(L_ERR, "rlm_redis (%s): Failed to run SELECT",
111                                inst->xlat_name);
112                         goto do_close;
113                 }
114
115
116                 switch (reply->type) {
117                 case REDIS_REPLY_STATUS:
118                         if (strcmp(reply->str, "OK") != 0) {
119                                 radlog(L_ERR, "rlm_redis (%s): Failed SELECT %d: reply %s",
120                                        inst->xlat_name, inst->database,
121                                        dissocket->reply->str);
122                                 goto do_close;
123                         }
124                         break;  /* else it's OK */
125
126                 default:
127                         radlog(L_ERR, "rlm_redis (%s): Unexpected reply to SELECT",
128                                inst->xlat_name);
129                         goto do_close;
130                 }
131         }
132
133         dissocket = rad_malloc(sizeof(*dissocket));
134         memset(dissocket, 0, sizeof(*dissocket));
135         dissocket->conn = conn;
136
137         return dissocket;
138 }
139
140 static size_t redis_escape_func(UNUSED REQUEST *request,
141         char *out, size_t outlen, const char *in, UNUSED void *arg)
142 {
143
144         size_t len = 0;
145
146         while (*in) {
147                 /*
148                  *      Non-printable characters get replaced with their
149                  *      mime-encoded equivalents.
150                  */
151                 if ((*in <= 32) || (*in == '\\')) {
152                         /*
153                          *      Only 3 or less bytes available.
154                          */
155                         if (outlen <= 3) {
156                                 break;
157                         }
158
159                         snprintf(out, outlen, "=%02X", (unsigned char) in[0]);
160                         in++;
161                         out += 3;
162                         outlen -= 3;
163                         len += 3;
164                         continue;
165                 }
166
167                 /*
168                  *      Only one byte left.
169                  */
170                 if (outlen <= 1) {
171                         break;
172                 }
173
174                 /*
175                  *      Allowed character.
176                  */
177                 *out = *in;
178                 out++;
179                 in++;
180                 outlen--;
181                 len++;
182         }
183         *out = '\0';
184         return len;
185
186 }
187
188 static size_t redis_xlat(void *instance, REQUEST *request,
189                       const char *fmt, char *out, size_t freespace)
190 {
191         REDIS_INST *inst = instance;
192         REDISSOCK *dissocket;
193         size_t ret = 0;
194         char *buffer_ptr;
195         char buffer[21];
196         char querystr[MAX_QUERY_LEN];
197
198         if (!radius_xlat(querystr, sizeof(querystr), fmt, request,
199                     redis_escape_func, inst)) {
200                 radlog(L_ERR, "rlm_redis (%s): xlat failed.",
201                        inst->xlat_name);
202
203                 return 0;
204         }
205
206         dissocket = fr_connection_get(inst->pool);
207         if (!dissocket) {
208                 radlog(L_ERR, "rlm_redis (%s): redis_get_socket() failed",
209                        inst->xlat_name);
210         
211                 return 0;
212         }
213
214         /* Query failed for some reason, release socket and return */
215         if (rlm_redis_query(&dissocket, inst, querystr) < 0) {
216                 goto release;
217         }
218
219         switch (dissocket->reply->type) {
220         case REDIS_REPLY_INTEGER:
221                 buffer_ptr = buffer;
222                 snprintf(buffer_ptr, sizeof(buffer), "%lld",
223                          dissocket->reply->integer);
224
225                 ret = strlen(buffer_ptr);
226                 break;
227
228         case REDIS_REPLY_STATUS:
229         case REDIS_REPLY_STRING:
230                 buffer_ptr = dissocket->reply->str;
231                 ret = dissocket->reply->len;
232                 break;
233
234         default:
235                 buffer_ptr = NULL;
236                 break;
237         }
238
239         if ((ret >= freespace) || (buffer_ptr == NULL)) {
240                 RDEBUG("rlm_redis (%s): Can't write result, insufficient space or unsupported result\n",
241                        inst->xlat_name);
242                 ret = 0;
243                 goto release;
244         }
245         
246         strlcpy(out, buffer_ptr, freespace);
247
248 release:
249         rlm_redis_finish_query(dissocket);
250         fr_connection_release(inst->pool, dissocket);
251         
252         return ret;
253 }
254
255 /*
256  *      Only free memory we allocated.  The strings allocated via
257  *      cf_section_parse() do not need to be freed.
258  */
259 static int redis_detach(void *instance)
260 {
261         REDIS_INST *inst = instance;
262
263         fr_connection_pool_delete(inst->pool);
264
265         if (inst->xlat_name) {
266                 xlat_unregister(inst->xlat_name, redis_xlat, instance);
267                 free(inst->xlat_name);
268         }
269         free(inst->xlat_name);
270         free(inst);
271
272         return 0;
273 }
274
275 /*
276  *      Query the redis database
277  */
278 int rlm_redis_query(REDISSOCK **dissocket_p, REDIS_INST *inst, char *query)
279 {
280         REDISSOCK *dissocket;
281
282         if (!query || !*query || !inst || !dissocket_p) {
283                 return -1;
284         }
285
286         dissocket = *dissocket_p;
287
288         DEBUG2("executing query %s", query);
289         dissocket->reply = redisCommand(dissocket->conn, query);
290
291         if (!dissocket->reply) {
292                 radlog(L_ERR, "rlm_redis: (%s) REDIS error: %s",
293                        inst->xlat_name, dissocket->conn->errstr);
294
295                 dissocket = fr_connection_reconnect(inst->pool, dissocket);
296                 if (!dissocket) {
297                 error:
298                         *dissocket_p = NULL;
299                         return -1;
300                 }
301
302                 dissocket->reply = redisCommand(dissocket->conn, query);
303                 if (!dissocket->reply) {
304                         radlog(L_ERR, "rlm_redis (%s): failed after re-connect",
305                                inst->xlat_name);
306                         fr_connection_del(inst->pool, dissocket);
307                         goto error;
308                 }
309
310                 *dissocket_p = dissocket;
311         }
312
313         if (dissocket->reply->type == REDIS_REPLY_ERROR) {
314                 radlog(L_ERR, "rlm_redis (%s): query failed, %s",
315                        inst->xlat_name, query);
316
317                 /* Free the reply just in case */
318                 rlm_redis_finish_query(dissocket);
319
320                 return -1;
321         }
322
323         return 0;
324 }
325
326 /*
327  *      Clear the redis reply object if any
328  */
329 int rlm_redis_finish_query(REDISSOCK *dissocket)
330 {
331         if (!dissocket || !dissocket->reply) {
332                 return -1;
333         }
334
335         freeReplyObject(dissocket->reply);
336         dissocket->reply = NULL;
337         return 0;
338 }
339
340 static int redis_instantiate(CONF_SECTION *conf, void **instance)
341 {
342         REDIS_INST *inst;
343         const char *xlat_name;
344
345         /*
346          *      Set up a storage area for instance data
347          */
348         inst = rad_malloc(sizeof (REDIS_INST));
349         if (!inst) {
350                 return -1;
351         }
352         memset(inst, 0, sizeof (*inst));
353
354         /*
355          *      If the configuration parameters can't be parsed, then
356          *      fail.
357          */
358         if (cf_section_parse(conf, inst, module_config) < 0) {
359                 free(inst);
360                 return -1;
361         }
362
363         xlat_name = cf_section_name2(conf);
364
365         if (!xlat_name)
366                 xlat_name = cf_section_name1(conf);
367
368         inst->xlat_name = strdup(xlat_name);
369         xlat_register(inst->xlat_name, redis_xlat, inst);
370
371         inst->pool = fr_connection_pool_init(conf, inst,
372                                              redis_create_conn, NULL,
373                                              redis_delete_conn);
374         if (!inst->pool) {
375                 redis_detach(inst);
376                 return -1;
377         }
378
379         inst->redis_query = rlm_redis_query;
380         inst->redis_finish_query = rlm_redis_finish_query;
381         inst->redis_escape_func = redis_escape_func;
382
383         *instance = inst;
384
385         return 0;
386 }
387
388 module_t rlm_redis = {
389         RLM_MODULE_INIT,
390         "redis",
391         RLM_TYPE_THREAD_SAFE, /* type */
392         redis_instantiate, /* instantiation */
393         redis_detach, /* detach */
394         {
395                 NULL, /* authentication */
396                 NULL, /* authorization */
397                 NULL, /* preaccounting */
398                 NULL, /* accounting */
399                 NULL, /* checksimul */
400                 NULL, /* pre-proxy */
401                 NULL, /* post-proxy */
402                 NULL /* post-auth */
403         },
404 };