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.
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.
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
19 * @brief Translates requests between the server an a perl interpreter.
21 * @copyright 2002,2006 The FreeRADIUS server project
22 * @copyright 2002 Boian Jordanov <bjordanov@orbitel.bg>
26 #include <freeradius-devel/radiusd.h>
27 #include <freeradius-devel/modules.h>
28 #include <freeradius-devel/rad_assert.h>
37 #include <semaphore.h>
40 extern char **environ;
44 * Define a structure for our module configuration.
46 * These variables do not need to be in a structure, but it's
47 * a lot cleaner to do so, and a pointer to the structure can
48 * be used as the instance handle.
50 typedef struct rlm_perl_t {
51 /* Name of the perl module */
54 /* Name of the functions for each module method */
55 char const *func_authorize;
56 char const *func_authenticate;
57 char const *func_accounting;
58 char const *func_start_accounting;
59 char const *func_stop_accounting;
60 char const *func_preacct;
61 char const *func_checksimul;
62 char const *func_detach;
63 char const *func_xlat;
65 char const *func_pre_proxy;
66 char const *func_post_proxy;
68 char const *func_post_auth;
70 char const *func_recv_coa;
71 char const *func_send_coa;
73 char const *xlat_name;
74 char const *perl_flags;
75 PerlInterpreter *perl;
76 pthread_key_t *thread_key;
79 pthread_mutex_t clone_mutex;
82 HV *rad_perlconf_hv; //!< holds "config" items (perl %RAD_PERLCONF hash).
86 * A mapping of configuration file names to internal variables.
88 #define RLM_PERL_CONF(_x) { "func_" STRINGIFY(_x), PW_TYPE_STRING, \
89 offsetof(rlm_perl_t,func_##_x), NULL, STRINGIFY(_x)}
91 static const CONF_PARSER module_config[] = {
92 { "module", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, rlm_perl_t, module), NULL },
93 { "filename", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_REQUIRED, rlm_perl_t, module), NULL },
95 RLM_PERL_CONF(authorize),
96 RLM_PERL_CONF(authenticate),
97 RLM_PERL_CONF(post_auth),
98 RLM_PERL_CONF(accounting),
99 RLM_PERL_CONF(preacct),
100 RLM_PERL_CONF(checksimul),
101 RLM_PERL_CONF(detach),
105 RLM_PERL_CONF(pre_proxy),
106 RLM_PERL_CONF(post_proxy),
109 RLM_PERL_CONF(recv_coa),
110 RLM_PERL_CONF(send_coa),
112 { "perl_flags", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_perl_t, perl_flags), NULL },
114 { "func_start_accounting", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_perl_t, func_start_accounting), NULL },
116 { "func_stop_accounting", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_perl_t, func_stop_accounting), NULL },
118 { NULL, -1, 0, NULL, NULL } /* end the list */
124 EXTERN_C void boot_DynaLoader(pTHX_ CV* cv);
127 #define dl_librefs "DynaLoader::dl_librefs"
128 #define dl_modules "DynaLoader::dl_modules"
129 static void rlm_perl_clear_handles(pTHX)
131 AV *librefs = get_av(dl_librefs, false);
137 static void **rlm_perl_get_handles(pTHX)
140 AV *librefs = get_av(dl_librefs, false);
141 AV *modules = get_av(dl_modules, false);
144 if (!librefs) return NULL;
146 if (!(AvFILL(librefs) >= 0)) {
150 handles = (void **)rad_malloc(sizeof(void *) * (AvFILL(librefs)+2));
152 for (i=0; i<=AvFILL(librefs); i++) {
154 SV *handle_sv = *av_fetch(librefs, i, false);
157 ERROR("Could not fetch $%s[%d]!\n",
161 handle = (void *)SvIV(handle_sv);
171 handles[i] = (void *)0;
176 static void rlm_perl_close_handles(void **handles)
184 for (i=0; handles[i]; i++) {
185 DEBUG("close %p\n", handles[i]);
193 static void rlm_perl_destruct(PerlInterpreter *perl)
197 PERL_SET_CONTEXT(perl);
199 PL_perl_destruct_level = 2;
201 PL_origenviron = environ;
208 * FIXME: This shouldn't happen
211 while (PL_scopestack_ix > 1 ){
220 static void rlm_destroy_perl(PerlInterpreter *perl)
225 PERL_SET_CONTEXT(perl);
227 handles = rlm_perl_get_handles(aTHX);
228 if (handles) rlm_perl_close_handles(handles);
229 rlm_perl_destruct(perl);
233 static void rlm_perl_make_key(pthread_key_t *key)
235 pthread_key_create(key, (void*)rlm_destroy_perl);
238 static PerlInterpreter *rlm_perl_clone(PerlInterpreter *perl, pthread_key_t *key)
242 PerlInterpreter *interp;
245 PERL_SET_CONTEXT(perl);
247 interp = pthread_getspecific(*key);
248 if (interp) return interp;
250 interp = perl_clone(perl, clone_flags);
254 #if PERL_REVISION >= 5 && PERL_VERSION <8
257 ptr_table_free(PL_ptr_table);
260 PERL_SET_CONTEXT(aTHX);
261 rlm_perl_clear_handles(aTHX);
263 ret = pthread_setspecific(*key, interp);
265 DEBUG("rlm_perl: Failed associating interpretor with thread %s", fr_syserror(ret));
267 rlm_perl_destruct(interp);
276 * This is wrapper for radlog
277 * Now users can call radiusd::radlog(level,msg) wich is the same
278 * calling radlog from C code.
280 static XS(XS_radiusd_radlog)
284 croak("Usage: radiusd::radlog(level, message)");
289 level = (int) SvIV(ST(0));
290 msg = (char *) SvPV(ST(1), PL_na);
293 * Because 'msg' is a 'char *', we don't want '%s', etc.
294 * in it to give us printf-style vulnerabilities.
296 radlog(level, "rlm_perl: %s", msg);
301 static void xs_init(pTHX)
303 char const *file = __FILE__;
305 /* DynaLoader is a special case */
306 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
308 newXS("radiusd::radlog",XS_radiusd_radlog, "rlm_perl");
314 static ssize_t perl_xlat(void *instance, REQUEST *request, char const *fmt, char *out, size_t freespace)
317 rlm_perl_t *inst = (rlm_perl_t *) instance;
325 PerlInterpreter *interp;
327 pthread_mutex_lock(&inst->clone_mutex);
328 interp = rlm_perl_clone(inst->perl, inst->thread_key);
331 PERL_SET_CONTEXT(interp);
333 pthread_mutex_unlock(&inst->clone_mutex);
335 PERL_SET_CONTEXT(inst->perl);
344 while ((q = strchr(p, ' '))) {
345 XPUSHs(sv_2mortal(newSVpv(p, p - q)));
352 count = call_pv(inst->func_xlat, G_SCALAR | G_EVAL);
356 REDEBUG("Exit %s", SvPV(ERRSV,n_a));
358 } else if (count > 0) {
360 strlcpy(out, tmp, freespace);
363 RDEBUG("Len is %zu , out is %s freespace is %zu", ret, out, freespace);
376 * Parse a configuration section, and populate a HV.
377 * This function is recursively called (allows to have nested hashes.)
379 static void perl_parse_config(CONF_SECTION *cs, int lvl, HV *rad_hv)
381 if (!cs || !rad_hv) return;
383 int indent_section = (lvl + 1) * 4;
384 int indent_item = (lvl + 2) * 4;
386 DEBUG("%*s%s {", indent_section, " ", cf_section_name1(cs));
390 for (ci = cf_item_find_next(cs, NULL);
392 ci = cf_item_find_next(cs, ci)) {
395 * Create a new HV, store it as a reference in current HV,
396 * Then recursively call perl_parse_config with this section and the new HV.
398 if (cf_item_is_section(ci)) {
399 CONF_SECTION *sub_cs = cf_itemtosection(ci);
400 char const *key = cf_section_name1(sub_cs); /* hash key */
406 if (hv_exists(rad_hv, key, strlen(key))) {
407 WARN("rlm_perl: Ignoring duplicate config section '%s'", key);
412 ref = newRV_inc((SV*) sub_hv);
414 (void)hv_store(rad_hv, key, strlen(key), ref, 0);
416 perl_parse_config(sub_cs, lvl + 1, sub_hv);
417 } else if (cf_item_is_pair(ci)){
418 CONF_PAIR *cp = cf_itemtopair(ci);
419 char const *key = cf_pair_attr(cp); /* hash key */
420 char const *value = cf_pair_value(cp); /* hash value */
422 if (!key || !value) continue;
426 * Store item attr / value in current HV.
428 if (hv_exists(rad_hv, key, strlen(key))) {
429 WARN("rlm_perl: Ignoring duplicate config item '%s'", key);
433 (void)hv_store(rad_hv, key, strlen(key), newSVpv(value, strlen(value)), 0);
435 DEBUG("%*s%s = %s", indent_item, " ", key, value);
439 DEBUG("%*s}", indent_section, " ");
443 * Do any per-module initialization that is separate to each
444 * configured instance of the module. e.g. set up connections
445 * to external databases, read configuration files, set up
446 * dictionary entries, etc.
448 * If configuration information is given in the config section
449 * that must be referenced in later calls, store a handle to it
450 * in *instance otherwise put a null pointer there.
452 * Setup a hashes wich we will use later
453 * parse a module and give him a chance to live
456 static int mod_instantiate(CONF_SECTION *conf, void *instance)
458 rlm_perl_t *inst = instance;
461 char const **embed_c; /* Stupid Perl and lack of const consistency */
464 char const *xlat_name;
465 int exitstatus = 0, argc=0;
467 MEM(embed_c = talloc_zero_array(inst, char const *, 4));
468 memcpy(&embed, &embed_c, sizeof(embed));
470 * Create pthread key. This key will be stored in instance
474 pthread_mutex_init(&inst->clone_mutex, NULL);
476 inst->thread_key = rad_malloc(sizeof(*inst->thread_key));
477 memset(inst->thread_key,0,sizeof(*inst->thread_key));
479 rlm_perl_make_key(inst->thread_key);
485 if (inst->perl_flags) {
486 embed_c[1] = inst->perl_flags;
487 embed_c[2] = inst->module;
491 embed_c[1] = inst->module;
496 PERL_SYS_INIT3(&argc, &embed, &envp);
498 if ((inst->perl = perl_alloc()) == NULL) {
499 ERROR("rlm_perl: No memory for allocating new perl !");
503 perl_construct(inst->perl);
506 PL_perl_destruct_level = 2;
511 PERL_SET_CONTEXT(inst->perl);
514 #if PERL_REVISION >= 5 && PERL_VERSION >=8
515 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
518 exitstatus = perl_parse(inst->perl, xs_init, argc, embed, NULL);
524 perl_run(inst->perl);
526 ERROR("rlm_perl: perl_parse failed: %s not found or has syntax errors. \n", inst->module);
532 xlat_name = cf_section_name2(conf);
534 xlat_name = cf_section_name1(conf);
536 xlat_register(xlat_name, perl_xlat, NULL, inst);
539 /* parse perl configuration sub-section */
541 cs = cf_section_sub_find(conf, "config");
543 DEBUG("rlm_perl (%s): parsing 'config' section...", xlat_name);
545 inst->rad_perlconf_hv = get_hv("RAD_PERLCONF",1);
546 perl_parse_config(cs, 0, inst->rad_perlconf_hv);
548 DEBUG("rlm_perl (%s): done parsing 'config'.", xlat_name);
555 * get the vps and put them in perl hash
556 * If one VP have multiple values it is added as array_ref
557 * Example for this is Cisco-AVPair that holds multiple values.
558 * Which will be available as array_ref in $RAD_REQUEST{'Cisco-AVPair'}
560 static void perl_store_vps(UNUSED TALLOC_CTX *ctx, REQUEST *request, VALUE_PAIR *vps, HV *rad_hv)
568 pairsort(&vps, attrtagcmp);
569 for (vp = fr_cursor_init(&cursor, &vps);
571 vp = fr_cursor_next(&cursor)) {
581 * Tagged attributes are added to the hash with name
582 * <attribute>:<tag>, others just use the normal attribute
585 if (vp->da->flags.has_tag && (vp->tag != TAG_ANY)) {
586 snprintf(namebuf, sizeof(namebuf), "%s:%d", vp->da->name, vp->tag);
593 * We've sorted by type, then tag, so attributes of the
594 * same type/tag should follow on from each other.
596 if ((next = fr_cursor_next_peek(&cursor)) && ATTRIBUTE_EQ(vp, next)) {
600 for (next = fr_cursor_first(&cursor);
602 next = fr_cursor_next_by_da(&cursor, vp->da, vp->tag)) {
603 switch (vp->da->type) {
605 av_push(av, newSVpv(next->vp_strvalue, next->length));
606 RDEBUG("<-- %s = %s", next->da->name, next->vp_strvalue);
610 len = vp_prints_value(buffer, sizeof(buffer), next, 0);
611 RDEBUG("<-- %s = %s", next->da->name, buffer);
612 av_push(av, newSVpv(buffer, truncate_len(len, sizeof(buffer))));
616 (void)hv_store(rad_hv, name, strlen(name), newRV_noinc((SV *)av), 0);
622 * It's a normal single valued attribute
624 switch (vp->da->type) {
626 RDEBUG("<-- %s = %s", next->da->name, next->vp_strvalue);
627 (void)hv_store(rad_hv, name, strlen(name), newSVpv(vp->vp_strvalue, vp->length), 0);
631 len = vp_prints_value(buffer, sizeof(buffer), next, 0);
632 RDEBUG("<-- %s = %s", next->da->name, buffer);
633 (void)hv_store(rad_hv, name, strlen(name), newSVpv(buffer, truncate_len(len, sizeof(buffer))), 0);
641 * Verify that a Perl SV is a string and save it in FreeRadius
645 static int pairadd_sv(TALLOC_CTX *ctx, REQUEST *request, VALUE_PAIR **vps, char *key, SV *sv, FR_TOKEN op)
653 vp = pairmake(ctx, vps, key, NULL, op);
656 REDEBUG("Failed to create pair %s = %s", key, val);
660 if (vp->da->type != PW_TYPE_STRING) {
661 if (pairparsevalue(vp, val, 0) < 0) goto fail;
663 pairstrncpy(vp, val, len);
666 RDEBUG("--> %s = %s", key, val);
673 * Gets the content from hashes
675 static int get_hv_content(TALLOC_CTX *ctx, REQUEST *request, HV *my_hv, VALUE_PAIR **vps)
680 I32 key_len, len, i, j;
684 for (i = hv_iterinit(my_hv); i > 0; i--) {
685 res_sv = hv_iternextsv(my_hv,&key,&key_len);
686 if (SvROK(res_sv) && (SvTYPE(SvRV(res_sv)) == SVt_PVAV)) {
687 av = (AV*)SvRV(res_sv);
689 for (j = 0; j <= len; j++) {
690 av_sv = av_fetch(av, j, 0);
691 ret = pairadd_sv(ctx, request, vps, key, *av_sv, T_OP_ADD) + ret;
693 } else ret = pairadd_sv(ctx, request, vps, key, res_sv, T_OP_EQ) + ret;
700 * Call the function_name inside the module
701 * Store all vps in hashes %RAD_CHECK %RAD_REPLY %RAD_REQUEST
704 static int do_perl(void *instance, REQUEST *request, char const *function_name)
707 rlm_perl_t *inst = instance;
709 int exitstatus=0, count;
717 HV *rad_request_proxy_hv;
718 HV *rad_request_proxy_reply_hv;
722 * Radius has told us to call this function, but none
725 if (!function_name) return RLM_MODULE_FAIL;
728 pthread_mutex_lock(&inst->clone_mutex);
730 PerlInterpreter *interp;
732 interp = rlm_perl_clone(inst->perl,inst->thread_key);
735 PERL_SET_CONTEXT(interp);
738 pthread_mutex_unlock(&inst->clone_mutex);
740 PERL_SET_CONTEXT(inst->perl);
749 rad_reply_hv = get_hv("RAD_REPLY",1);
750 rad_check_hv = get_hv("RAD_CHECK",1);
751 rad_config_hv = get_hv("RAD_CONFIG",1);
752 rad_request_hv = get_hv("RAD_REQUEST",1);
754 perl_store_vps(request->reply, request, request->reply->vps, rad_reply_hv);
755 perl_store_vps(request, request, request->config_items, rad_check_hv);
756 perl_store_vps(request->packet, request, request->packet->vps, rad_request_hv);
757 perl_store_vps(request, request, request->config_items, rad_config_hv);
760 rad_request_proxy_hv = get_hv("RAD_REQUEST_PROXY",1);
761 rad_request_proxy_reply_hv = get_hv("RAD_REQUEST_PROXY_REPLY",1);
763 if (request->proxy != NULL) {
764 perl_store_vps(request->proxy, request, request->proxy->vps, rad_request_proxy_hv);
766 hv_undef(rad_request_proxy_hv);
769 if (request->proxy_reply !=NULL) {
770 perl_store_vps(request->proxy_reply, request, request->proxy_reply->vps, rad_request_proxy_reply_hv);
772 hv_undef(rad_request_proxy_reply_hv);
778 * This way %RAD_xx can be pushed onto stack as sub parameters.
779 * XPUSHs( newRV_noinc((SV *)rad_request_hv) );
780 * XPUSHs( newRV_noinc((SV *)rad_reply_hv) );
781 * XPUSHs( newRV_noinc((SV *)rad_check_hv) );
785 count = call_pv(function_name, G_SCALAR | G_EVAL | G_NOARGS);
790 ERROR("rlm_perl: perl_embed:: module = %s , func = %s exit status= %s\n",
792 function_name, SvPV(ERRSV,n_a));
798 if (exitstatus >= 100 || exitstatus < 0) {
799 exitstatus = RLM_MODULE_FAIL;
809 if ((get_hv_content(request->packet, request, rad_request_hv, &vp)) > 0 ) {
810 pairfree(&request->packet->vps);
811 request->packet->vps = vp;
815 * Update cached copies
817 request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
818 request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
819 if (!request->password)
820 request->password = pairfind(request->packet->vps, PW_CHAP_PASSWORD, 0, TAG_ANY);
823 if ((get_hv_content(request->reply, request, rad_reply_hv, &vp)) > 0 ) {
824 pairfree(&request->reply->vps);
825 request->reply->vps = vp;
829 if ((get_hv_content(request, request, rad_check_hv, &vp)) > 0 ) {
830 pairfree(&request->config_items);
831 request->config_items = vp;
836 if (request->proxy &&
837 (get_hv_content(request->proxy, request, rad_request_proxy_hv, &vp) > 0)) {
838 pairfree(&request->proxy->vps);
839 request->proxy->vps = vp;
843 if (request->proxy_reply &&
844 (get_hv_content(request->proxy_reply, request, rad_request_proxy_reply_hv, &vp) > 0)) {
845 pairfree(&request->proxy_reply->vps);
846 request->proxy_reply->vps = vp;
855 #define RLM_PERL_FUNC(_x) static rlm_rcode_t CC_HINT(nonnull) mod_##_x(void *instance, REQUEST *request) \
857 return do_perl(instance, request, \
858 ((rlm_perl_t *)instance)->func_##_x); \
861 RLM_PERL_FUNC(authorize)
862 RLM_PERL_FUNC(authenticate)
863 RLM_PERL_FUNC(post_auth)
865 RLM_PERL_FUNC(checksimul)
868 RLM_PERL_FUNC(pre_proxy)
869 RLM_PERL_FUNC(post_proxy)
873 RLM_PERL_FUNC(recv_coa)
874 RLM_PERL_FUNC(send_coa)
877 RLM_PERL_FUNC(preacct)
880 * Write accounting information to this modules database.
882 static rlm_rcode_t CC_HINT(nonnull) mod_accounting(void *instance, REQUEST *request)
885 int acctstatustype=0;
887 if ((pair = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE, 0, TAG_ANY)) != NULL) {
888 acctstatustype = pair->vp_integer;
890 ERROR("Invalid Accounting Packet");
891 return RLM_MODULE_INVALID;
894 switch (acctstatustype) {
896 case PW_STATUS_START:
898 if (((rlm_perl_t *)instance)->func_start_accounting) {
899 return do_perl(instance, request,
900 ((rlm_perl_t *)instance)->func_start_accounting);
902 return do_perl(instance, request,
903 ((rlm_perl_t *)instance)->func_accounting);
909 if (((rlm_perl_t *)instance)->func_stop_accounting) {
910 return do_perl(instance, request,
911 ((rlm_perl_t *)instance)->func_stop_accounting);
913 return do_perl(instance, request,
914 ((rlm_perl_t *)instance)->func_accounting);
918 return do_perl(instance, request,
919 ((rlm_perl_t *)instance)->func_accounting);
926 * Detach a instance give a chance to a module to make some internal setup ...
928 DIAG_OFF(nested-externs)
929 static int mod_detach(void *instance)
931 rlm_perl_t *inst = (rlm_perl_t *) instance;
932 int exitstatus = 0, count = 0;
934 hv_undef(inst->rad_perlconf_hv);
938 * FIXME: Call this in the destruct function?
941 dTHXa(handle->clone);
942 PERL_SET_CONTEXT(handle->clone);
944 dSP; ENTER; SAVETMPS; PUSHMARK(SP);
945 count = call_pv(inst->func_detach, G_SCALAR | G_EVAL );
954 if (exitstatus >= 100 || exitstatus < 0) {
955 exitstatus = RLM_MODULE_FAIL;
965 if (inst->func_detach) {
967 PERL_SET_CONTEXT(inst->perl);
969 dSP; ENTER; SAVETMPS;
972 count = call_pv(inst->func_detach, G_SCALAR | G_EVAL );
977 if (exitstatus >= 100 || exitstatus < 0) {
978 exitstatus = RLM_MODULE_FAIL;
988 rlm_perl_destruct(inst->perl);
989 pthread_mutex_destroy(&inst->clone_mutex);
991 perl_destruct(inst->perl);
992 perl_free(inst->perl);
998 DIAG_ON(nested-externs)
1001 * The module name should be the only globally exported symbol.
1002 * That is, everything else should be 'static'.
1004 * If the module needs to temporarily modify it's instantiation
1005 * data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
1006 * The server will then take care of ensuring that the module
1007 * is single-threaded.
1009 module_t rlm_perl = {
1013 RLM_TYPE_THREAD_SAFE, /* type */
1015 RLM_TYPE_THREAD_UNSAFE,
1019 mod_instantiate, /* instantiation */
1020 mod_detach, /* detach */
1022 mod_authenticate, /* authenticate */
1023 mod_authorize, /* authorize */
1024 mod_preacct, /* preacct */
1025 mod_accounting, /* accounting */
1026 mod_checksimul, /* check simul */
1028 mod_pre_proxy, /* pre-proxy */
1029 mod_post_proxy, /* post-proxy */
1033 mod_post_auth /* post-auth */