Use macro for terminating CONF_PARSER arrays
[freeradius.git] / src / modules / rlm_ruby / rlm_ruby.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 as published by
4  *   the Free Software Foundation; either version 2 of the License, or (at
5  *   your option) any later version.
6  *
7  *   This program is distributed in the hope that it will be useful,
8  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *   GNU General Public License for more details.
11  *
12  *   You should have received a copy of the GNU General Public License
13  *   along with this program; if not, write to the Free Software
14  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15  */
16
17 /**
18  * $Id$
19  * @file rlm_ruby.c
20  * @brief Translates requests between the server an a ruby interpreter.
21  *
22  * @note Maintainers note
23  * @note Please don't use this module, Matz ruby was never designed for embedding.
24  * @note This module leaks memory, and the ruby code installs signal handlers
25  * @note which interfere with normal operation of the server. It's all bad...
26  * @note mruby shows some promise, feel free to rewrite the module to use that.
27  * @note https://github.com/mruby/mruby
28  *
29  * @copyright 2008 Andriy Dmytrenko aka Antti, BuzhNET
30  */
31
32
33 RCSID("$Id$")
34
35 #include <freeradius-devel/radiusd.h>
36 #include <freeradius-devel/modules.h>
37
38 /*
39  *      Undefine any HAVE_* flags which may conflict
40  *      ruby.h *REALLY* shouldn't #include its config.h file,
41  *      but it does *sigh*.
42  */
43 #undef HAVE_CRYPT
44
45 DIAG_OFF(disabled-macro-expansion)
46 #include <ruby.h>
47
48 /*
49  *      Define a structure for our module configuration.
50  *
51  *      These variables do not need to be in a structure, but it's
52  *      a lot cleaner to do so, and a pointer to the structure can
53  *      be used as the instance handle.
54  */
55 typedef struct rlm_ruby_t {
56 #define RLM_RUBY_STRUCT(foo) unsigned long func_##foo
57
58         RLM_RUBY_STRUCT(instantiate);
59         RLM_RUBY_STRUCT(authorize);
60         RLM_RUBY_STRUCT(authenticate);
61         RLM_RUBY_STRUCT(preacct);
62         RLM_RUBY_STRUCT(accounting);
63         RLM_RUBY_STRUCT(checksimul);
64         RLM_RUBY_STRUCT(pre_proxy);
65         RLM_RUBY_STRUCT(post_proxy);
66         RLM_RUBY_STRUCT(post_auth);
67 #ifdef WITH_COA
68         RLM_RUBY_STRUCT(recv_coa);
69         RLM_RUBY_STRUCT(send_coa);
70 #endif
71         RLM_RUBY_STRUCT(detach);
72
73         char const *filename;
74         char const *module_name;
75         VALUE module;
76
77 } rlm_ruby_t;
78
79 /*
80  *      A mapping of configuration file names to internal variables.
81  *
82  *      Note that the string is dynamically allocated, so it MUST
83  *      be freed.  When the configuration file parse re-reads the string,
84  *      it free's the old one, and strdup's the new one, placing the pointer
85  *      to the strdup'd string into 'config.string'.  This gets around
86  *      buffer over-flows.
87  */
88 static const CONF_PARSER module_config[] = {
89         { "filename", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_REQUIRED, struct rlm_ruby_t, filename), NULL },
90         { "module", FR_CONF_OFFSET(PW_TYPE_STRING, struct rlm_ruby_t, module_name), "Radiusd" },
91         CONF_PARSER_TERMINATOR
92 };
93
94
95 /*
96  * radiusd Ruby functions
97  */
98
99 /* radlog wrapper */
100
101 static VALUE radlog_rb(UNUSED VALUE self, VALUE msg_type, VALUE rb_msg) {
102         int status;
103         char *msg;
104         status = FIX2INT(msg_type);
105         msg = StringValuePtr(rb_msg);
106         radlog(status, "%s", msg);
107         return Qnil;
108 }
109
110 /* Tuple to value pair conversion */
111
112 static void add_vp_tuple(TALLOC_CTX *ctx, REQUEST *request, VALUE_PAIR **vpp, VALUE rb_value,
113                          char const *function_name) {
114         int i;
115         long outertuplesize;
116         VALUE_PAIR *vp;
117
118         /* If the Ruby function gave us nil for the tuple, then just return. */
119         if (NIL_P(rb_value)) {
120                 return;
121         }
122
123         if (TYPE(rb_value) != T_ARRAY) {
124                 REDEBUG("add_vp_tuple, %s: non-array passed", function_name);
125                 return;
126         }
127
128         /* Get the array size. */
129         outertuplesize = RARRAY_LEN(rb_value);
130
131         for (i = 0; i < outertuplesize; i++) {
132                 VALUE pTupleElement = rb_ary_entry(rb_value, i);
133
134                 if ((pTupleElement != 0) &&
135                     (TYPE(pTupleElement) == T_ARRAY)) {
136
137                         /* Check if it's a pair */
138                         long tuplesize;
139
140                         if ((tuplesize = RARRAY_LEN(pTupleElement)) != 2) {
141                                 REDEBUG("%s: tuple element %i is a tuple "
142                                         " of size %li. must be 2\n", function_name,
143                                         i, tuplesize);
144                         } else {
145                                 VALUE pString1, pString2;
146
147                                 pString1 = rb_ary_entry(pTupleElement, 0);
148                                 pString2 = rb_ary_entry(pTupleElement, 1);
149
150                                 if ((TYPE(pString1) == T_STRING) &&
151                                     (TYPE(pString2) == T_STRING)) {
152
153
154                                         char const *s1, *s2;
155
156                                         /* fr_pair_make() will convert and find any
157                                          * errors in the pair.
158                                          */
159
160                                         s1 = StringValuePtr(pString1);
161                                         s2 = StringValuePtr(pString2);
162
163                                         if ((s1 != NULL) && (s2 != NULL)) {
164                                                 DEBUG("%s: %s = %s ",
165                                                        function_name, s1, s2);
166
167                                                 /* xxx Might need to support other T_OP */
168                                                 vp = fr_pair_make(ctx, vpp, s1, s2, T_OP_EQ);
169                                                 if (vp != NULL) {
170                                                         DEBUG("%s: s1, s2 OK", function_name);
171                                                 } else {
172                                                         DEBUG("%s: s1, s2 FAILED", function_name);
173                                                 }
174                                         } else {
175                                                 REDEBUG("%s: string conv failed", function_name);
176                                         }
177
178                                 } else {
179                                         REDEBUG("%s: tuple element %d must be "
180                                                 "(string, string)", function_name, i);
181                                 }
182                         }
183                 } else {
184                         REDEBUG("%s: tuple element %d is not a tuple\n",
185                                 function_name, i);
186                 }
187         }
188
189 }
190
191 /* This is the core Ruby function that the others wrap around.
192  * Pass the value-pair print strings in a tuple.
193  * xxx We're not checking the errors. If we have errors, what do we do?
194  */
195
196 #define BUF_SIZE 1024
197 static rlm_rcode_t CC_HINT(nonnull (4)) do_ruby(REQUEST *request, unsigned long func,
198                                                 VALUE module, char const *function_name)
199 {
200         rlm_rcode_t rcode = RLM_MODULE_OK;
201         vp_cursor_t cursor;
202
203         char buf[BUF_SIZE]; /* same size as vp_print buffer */
204
205         VALUE_PAIR *vp;
206         VALUE rb_request, rb_result, rb_reply_items, rb_config, rbString1, rbString2;
207
208         int n_tuple;
209         DEBUG("Calling ruby function %s which has id: %lu\n", function_name, func);
210
211         /* Return with "OK, continue" if the function is not defined.
212          * TODO: Should check with rb_respond_to each time, just because ruby can define function dynamicly?
213          */
214         if (func == 0) {
215                 return rcode;
216         }
217
218         n_tuple = 0;
219         if (request) {
220                 for (vp = fr_cursor_init(&cursor, &request->packet->vps);
221                      vp;
222                      vp = fr_cursor_next(&cursor)) {
223                          n_tuple++;
224                 }
225         }
226
227         /*
228           Creating ruby array, that contains arrays of [name,value]
229           Maybe we should use hash instead? Can this names repeat?
230         */
231         rb_request = rb_ary_new2(n_tuple);
232
233         if (request) {
234                 for (vp = fr_cursor_init(&cursor, &request->packet->vps);
235                      vp;
236                      vp = fr_cursor_next(&cursor)) {
237                         VALUE tmp = rb_ary_new2(2);
238
239                         /* The name. logic from vp_prints, lib/print.c */
240                         if (vp->da->flags.has_tag) {
241                                 snprintf(buf, BUF_SIZE, "%s:%d", vp->da->name, vp->tag);
242                         } else {
243                                 strlcpy(buf, vp->da->name, sizeof(buf));
244                         }
245                         rbString1 = rb_str_new2(buf);
246                         vp_prints_value(buf, sizeof (buf), vp, '"');
247                         rbString2 = rb_str_new2(buf);
248
249                         rb_ary_push(tmp, rbString1);
250                         rb_ary_push(tmp, rbString2);
251                         rb_ary_push(rb_request, tmp);
252                 }
253         }
254
255         /* Calling corresponding ruby function, passing request and catching result */
256         rb_result = rb_funcall(module, func, 1, rb_request);
257
258         /*
259          *      Checking result, it can be array of type [result,
260          *      [array of reply pairs],[array of config pairs]],
261          *      It can also be just a fixnum, which is a result itself.
262          */
263         if (TYPE(rb_result) == T_ARRAY) {
264                 if (!FIXNUM_P(rb_ary_entry(rb_result, 0))) {
265                         ERROR("First element of an array was not a FIXNUM (Which has to be a return_value)");
266
267                         rcode = RLM_MODULE_FAIL;
268                         goto finish;
269                 }
270
271                 rcode = FIX2INT(rb_ary_entry(rb_result, 0));
272
273                 /*
274                  *      Only process the results if we were passed a request.
275                  */
276                 if (request) {
277                         rb_reply_items = rb_ary_entry(rb_result, 1);
278                         rb_config = rb_ary_entry(rb_result, 2);
279
280                         add_vp_tuple(request->reply, request, &request->reply->vps,
281                                      rb_reply_items, function_name);
282                         add_vp_tuple(request, request, &request->config,
283                                      rb_config, function_name);
284                 }
285         } else if (FIXNUM_P(rb_result)) {
286                 rcode = FIX2INT(rb_result);
287         }
288
289 finish:
290         return rcode;
291 }
292
293 static struct varlookup {
294         char const* name;
295         int value;
296 } constants[] = {
297         { "L_DBG", L_DBG},
298         { "L_AUTH", L_AUTH},
299         { "L_INFO", L_INFO},
300         { "L_ERR", L_ERR},
301         { "L_PROXY", L_PROXY},
302         { "RLM_MODULE_REJECT", RLM_MODULE_REJECT},
303         { "RLM_MODULE_FAIL", RLM_MODULE_FAIL},
304         { "RLM_MODULE_OK", RLM_MODULE_OK},
305         { "RLM_MODULE_HANDLED", RLM_MODULE_HANDLED},
306         { "RLM_MODULE_INVALID", RLM_MODULE_INVALID},
307         { "RLM_MODULE_USERLOCK", RLM_MODULE_USERLOCK},
308         { "RLM_MODULE_NOTFOUND", RLM_MODULE_NOTFOUND},
309         { "RLM_MODULE_NOOP", RLM_MODULE_NOOP},
310         { "RLM_MODULE_UPDATED", RLM_MODULE_UPDATED},
311         { "RLM_MODULE_NUMCODES", RLM_MODULE_NUMCODES},
312         { NULL, 0},
313 };
314
315 /*
316  * Import a user module and load a function from it
317  */
318 static int load_function(char const *f_name, unsigned long *func, VALUE module) {
319         if (!f_name) {
320                 *func = 0;
321         } else {
322                 *func = rb_intern(f_name);
323                 /* rb_intern returns a symbol of a function, not a function itself
324                    it can be aplied to any recipient,
325                    so we should check it for our module recipient
326                 */
327                 if (!rb_respond_to(module, *func))
328                         *func = 0;
329         }
330         DEBUG("load_function %s, result: %lu", f_name, *func);
331         return 0;
332 }
333
334 /*
335  *      Do any per-module initialization that is separate to each
336  *      configured instance of the module.  e.g. set up connections
337  *      to external databases, read configuration files, set up
338  *      dictionary entries, etc.
339  *
340  *      If configuration information is given in the config section
341  *      that must be referenced in later calls, store a handle to it
342  *      in *instance otherwise put a null pointer there.
343  */
344 static int mod_instantiate(UNUSED CONF_SECTION *conf, void *instance)
345 {
346         rlm_ruby_t *inst = instance;
347         VALUE module;
348
349         int idx;
350         int status;
351
352         /*
353          *      Initialize Ruby interpreter. Fatal error if this fails.
354          */
355         ruby_init();
356         ruby_init_loadpath();
357         ruby_script("radiusd");
358
359         /* disabling GC, it will eat your memory, but at least it will be stable. */
360         rb_gc_disable();
361
362         /*
363          *      Setup our 'radiusd' module.
364          */
365         module = inst->module = rb_define_module(inst->module_name);
366         if (!module) {
367                 ERROR("Ruby rb_define_module failed");
368
369                 return -1;
370         }
371
372         /*
373          *      Load constants into module
374          */
375         for (idx = 0; constants[idx].name; idx++) {
376                 rb_define_const(module, constants[idx].name, INT2NUM(constants[idx].value));
377         }
378
379         /*
380          *      Expose some FreeRADIUS API functions as ruby functions
381          */
382         rb_define_module_function(module, "radlog", radlog_rb, 2);
383
384         DEBUG("Loading file %s...", inst->filename);
385         rb_load_protect(rb_str_new2(inst->filename), 0, &status);
386         if (status) {
387                 ERROR("Error loading file %s status: %d", inst->filename, status);
388
389                 return -1;
390         }
391         DEBUG("Loaded file %s", inst->filename);
392
393         /*
394          *      Import user modules.
395          */
396 #define RLM_RUBY_LOAD(foo) if (load_function(#foo, &inst->func_##foo, inst->module)==-1) { \
397                 return -1; \
398         }
399
400         RLM_RUBY_LOAD(instantiate);
401         RLM_RUBY_LOAD(authenticate);
402         RLM_RUBY_LOAD(authorize);
403         RLM_RUBY_LOAD(preacct);
404         RLM_RUBY_LOAD(accounting);
405         RLM_RUBY_LOAD(checksimul);
406         RLM_RUBY_LOAD(pre_proxy);
407         RLM_RUBY_LOAD(post_proxy);
408         RLM_RUBY_LOAD(post_auth);
409 #ifdef WITH_COA
410         RLM_RUBY_LOAD(recv_coa);
411         RLM_RUBY_LOAD(send_coa);
412 #endif
413         RLM_RUBY_LOAD(detach);
414
415         /* Call the instantiate function.  No request.  Use the return value. */
416         return do_ruby(NULL, inst->func_instantiate, inst->module, "instantiate");
417 }
418
419 #define RLM_RUBY_FUNC(foo) static rlm_rcode_t CC_HINT(nonnull) mod_##foo(void *instance, REQUEST *request) \
420         { \
421                 return do_ruby(request, \
422                                ((struct rlm_ruby_t *)instance)->func_##foo,((struct rlm_ruby_t *)instance)->module, \
423                                #foo); \
424         }
425
426 RLM_RUBY_FUNC(authorize)
427 RLM_RUBY_FUNC(authenticate)
428 RLM_RUBY_FUNC(preacct)
429 RLM_RUBY_FUNC(accounting)
430 RLM_RUBY_FUNC(checksimul)
431 RLM_RUBY_FUNC(pre_proxy)
432 RLM_RUBY_FUNC(post_proxy)
433 RLM_RUBY_FUNC(post_auth)
434 #ifdef WITH_COA
435 RLM_RUBY_FUNC(recv_coa)
436 RLM_RUBY_FUNC(send_coa)
437 #endif
438
439 static int mod_detach(UNUSED void *instance)
440 {
441         ruby_finalize();
442         ruby_cleanup(0);
443
444         return 0;
445 }
446
447 /*
448  *      The module name should be the only globally exported symbol.
449  *      That is, everything else should be 'static'.
450  *
451  *      If the module needs to temporarily modify it's instantiation
452  *      data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
453  *      The server will then take care of ensuring that the module
454  *      is single-threaded.
455  */
456 extern module_t rlm_ruby;
457 module_t rlm_ruby = {
458         .magic          = RLM_MODULE_INIT,
459         .name           = "ruby",
460         .type           = RLM_TYPE_THREAD_UNSAFE, /* type, ok, let's be honest, MRI is not yet treadsafe */
461         .inst_size      = sizeof(rlm_ruby_t),
462         .config         = module_config,
463         .instantiate    = mod_instantiate,
464         .detach         = mod_detach,
465         .methods = {
466                 [MOD_AUTHENTICATE]      = mod_authenticate,
467                 [MOD_AUTHORIZE]         = mod_authorize,
468                 [MOD_PREACCT]           = mod_preacct,
469                 [MOD_ACCOUNTING]        = mod_accounting,
470                 [MOD_SESSION]           = mod_checksimul,
471                 [MOD_PRE_PROXY]         = mod_pre_proxy,
472                 [MOD_POST_PROXY]        = mod_post_proxy,
473                 [MOD_POST_AUTH]         = mod_post_auth,
474 #ifdef WITH_COA
475                 [MOD_RECV_COA]          = mod_recv_coa,
476                 [MOD_SEND_COA]          = mod_send_coa
477 #endif
478         },
479 };