1b854abfe00d636da5b52c0eaadbc5b7eec03e55
[freeradius.git] / src / modules / rlm_redis / rlm_redis.c
1 /*
2  *   This program is is free software; you can redistribute it and/or modify
3  *   it under the terms of the GNU General Public License, version 2 if the
4  *   License as published by the Free Software Foundation.
5  *
6  *   This program is distributed in the hope that it will be useful,
7  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
8  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9  *   GNU General Public License for more details.
10  *
11  *   You should have received a copy of the GNU General Public License
12  *   along with this program; if not, write to the Free Software
13  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
14  */
15  
16 /**
17  * $Id$
18  * @file rlm_redis.c
19  * @brief Driver for the REDIS noSQL key value stores.
20  *
21  * @copyright 2000,2006  The FreeRADIUS server project
22  * @copyright 2011  TekSavvy Solutions <gabe@teksavvy.com>
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 (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(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, 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(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                                        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_xlat(void *instance, REQUEST *request,
141                       const char *fmt, char *out, size_t freespace)
142 {
143         REDIS_INST *inst = instance;
144         REDISSOCK *dissocket;
145         size_t ret = 0;
146         char *buffer_ptr;
147         char buffer[21];
148
149         dissocket = fr_connection_get(inst->pool);
150         if (!dissocket) {
151                 radlog(L_ERR, "rlm_redis (%s): redis_get_socket() failed",
152                        inst->xlat_name);
153         
154                 return 0;
155         }
156
157         /* Query failed for some reason, release socket and return */
158         if (rlm_redis_query(&dissocket, inst, fmt, request) < 0) {
159                 goto release;
160         }
161
162         switch (dissocket->reply->type) {
163         case REDIS_REPLY_INTEGER:
164                 buffer_ptr = buffer;
165                 snprintf(buffer_ptr, sizeof(buffer), "%lld",
166                          dissocket->reply->integer);
167
168                 ret = strlen(buffer_ptr);
169                 break;
170
171         case REDIS_REPLY_STATUS:
172         case REDIS_REPLY_STRING:
173                 buffer_ptr = dissocket->reply->str;
174                 ret = dissocket->reply->len;
175                 break;
176
177         default:
178                 buffer_ptr = NULL;
179                 break;
180         }
181
182         if ((ret >= freespace) || (buffer_ptr == NULL)) {
183                 RDEBUG("rlm_redis (%s): Can't write result, insufficient space or unsupported result\n",
184                        inst->xlat_name);
185                 ret = 0;
186                 goto release;
187         }
188         
189         strlcpy(out, buffer_ptr, freespace);
190
191 release:
192         rlm_redis_finish_query(dissocket);
193         fr_connection_release(inst->pool, dissocket);
194         
195         return ret;
196 }
197
198 /*
199  *      Only free memory we allocated.  The strings allocated via
200  *      cf_section_parse() do not need to be freed.
201  */
202 static int redis_detach(void *instance)
203 {
204         REDIS_INST *inst = instance;
205
206         fr_connection_pool_delete(inst->pool);
207
208         if (inst->xlat_name) {
209                 xlat_unregister(inst->xlat_name, redis_xlat, instance);
210         }
211
212         return 0;
213 }
214
215 /*
216  *      Query the redis database
217  */
218 int rlm_redis_query(REDISSOCK **dissocket_p, REDIS_INST *inst,
219                     const char *query, REQUEST *request)
220 {
221         REDISSOCK *dissocket;
222         int argc;
223         const char *argv[MAX_REDIS_ARGS];
224         char argv_buf[MAX_QUERY_LEN];
225
226         if (!query || !*query || !inst || !dissocket_p) {
227                 return -1;
228         }
229
230         argc = rad_expand_xlat(request, query, MAX_REDIS_ARGS, argv, 0,
231                                 sizeof(argv_buf), argv_buf);
232         if (argc <= 0)
233                 return -1;
234
235         dissocket = *dissocket_p;
236
237         DEBUG2("executing %s ...", argv[0]);
238         dissocket->reply = redisCommandArgv(dissocket->conn, argc, argv, NULL);
239
240         if (!dissocket->reply) {
241                 radlog(L_ERR, "rlm_redis: (%s) REDIS error: %s",
242                        inst->xlat_name, dissocket->conn->errstr);
243
244                 dissocket = fr_connection_reconnect(inst->pool, dissocket);
245                 if (!dissocket) {
246                 error:
247                         *dissocket_p = NULL;
248                         return -1;
249                 }
250
251                 dissocket->reply = redisCommand(dissocket->conn, query);
252                 if (!dissocket->reply) {
253                         radlog(L_ERR, "rlm_redis (%s): failed after re-connect",
254                                inst->xlat_name);
255                         fr_connection_del(inst->pool, dissocket);
256                         goto error;
257                 }
258
259                 *dissocket_p = dissocket;
260         }
261
262         if (dissocket->reply->type == REDIS_REPLY_ERROR) {
263                 radlog(L_ERR, "rlm_redis (%s): query failed, %s",
264                        inst->xlat_name, query);
265                 return -1;
266         }
267
268         return 0;
269 }
270
271 /*
272  *      Clear the redis reply object if any
273  */
274 int rlm_redis_finish_query(REDISSOCK *dissocket)
275 {
276         if (!dissocket || !dissocket->reply) {
277                 return -1;
278         }
279
280         freeReplyObject(dissocket->reply);
281         dissocket->reply = NULL;
282         return 0;
283 }
284
285 static int redis_instantiate(CONF_SECTION *conf, void **instance)
286 {
287         REDIS_INST *inst;
288         const char *xlat_name;
289
290         /*
291          *      Set up a storage area for instance data
292          */
293         *instance = inst = talloc_zero(conf, REDIS_INST);
294         if (!inst) return -1;
295
296         /*
297          *      If the configuration parameters can't be parsed, then
298          *      fail.
299          */
300         if (cf_section_parse(conf, inst, module_config) < 0) {
301                 return -1;
302         }
303
304         xlat_name = cf_section_name2(conf);
305
306         if (!xlat_name)
307                 xlat_name = cf_section_name1(conf);
308
309         xlat_register(inst->xlat_name, redis_xlat, inst);
310
311         inst->pool = fr_connection_pool_init(conf, inst,
312                                              redis_create_conn, NULL,
313                                              redis_delete_conn);
314         if (!inst->pool) {
315                 return -1;
316         }
317
318         inst->redis_query = rlm_redis_query;
319         inst->redis_finish_query = rlm_redis_finish_query;
320
321         return 0;
322 }
323
324 module_t rlm_redis = {
325         RLM_MODULE_INIT,
326         "redis",
327         RLM_TYPE_THREAD_SAFE, /* type */
328         redis_instantiate, /* instantiation */
329         redis_detach, /* detach */
330         {
331                 NULL, /* authentication */
332                 NULL, /* authorization */
333                 NULL, /* preaccounting */
334                 NULL, /* accounting */
335                 NULL, /* checksimul */
336                 NULL, /* pre-proxy */
337                 NULL, /* post-proxy */
338                 NULL /* post-auth */
339         },
340 };