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.
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.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * Copyright 2002 The FreeRADIUS server project
21 * Copyright 2002 Boian Jordanov <bjordanov@orbitel.bg>
25 #include "libradius.h"
51 #include <semaphore.h>
53 static const char rcsid[] = "$Id$";
57 * Define a structure for our module configuration.
59 * These variables do not need to be in a structure, but it's
60 * a lot cleaner to do so, and a pointer to the structure can
61 * be used as the instance handle.
63 typedef struct perl_inst {
64 /* Name of the perl module */
67 /* Name of the functions for each module method */
69 char *func_authenticate;
70 char *func_accounting;
71 char *func_start_accounting;
72 char *func_stop_accounting;
74 char *func_checksimul;
81 * A mapping of configuration file names to internal variables.
83 * Note that the string is dynamically allocated, so it MUST
84 * be freed. When the configuration file parse re-reads the string,
85 * it free's the old one, and strdup's the new one, placing the pointer
86 * to the strdup'd string into 'config.string'. This gets around
89 static CONF_PARSER module_config[] = {
90 { "module", PW_TYPE_STRING_PTR,
91 offsetof(PERL_INST,module), NULL, "module"},
92 { "func_authorize", PW_TYPE_STRING_PTR,
93 offsetof(PERL_INST,func_authorize), NULL, "authorize"},
94 { "func_authenticate", PW_TYPE_STRING_PTR,
95 offsetof(PERL_INST,func_authenticate), NULL, "authenticate"},
96 { "func_accounting", PW_TYPE_STRING_PTR,
97 offsetof(PERL_INST,func_accounting), NULL, "accounting"},
98 { "func_preacct", PW_TYPE_STRING_PTR,
99 offsetof(PERL_INST,func_preacct), NULL, "preacct"},
100 { "func_checksimul", PW_TYPE_STRING_PTR,
101 offsetof(PERL_INST,func_checksimul), NULL, "checksimul"},
102 { "func_detach", PW_TYPE_STRING_PTR,
103 offsetof(PERL_INST,func_detach), NULL, "detach"},
104 { "func_xlat", PW_TYPE_STRING_PTR,
105 offsetof(PERL_INST,func_xlat), NULL, "xlat"},
106 { "perl_flags", PW_TYPE_STRING_PTR,
107 offsetof(PERL_INST,perl_flags), NULL, NULL},
108 { "func_start_accounting", PW_TYPE_STRING_PTR,
109 offsetof(PERL_INST,func_start_accounting), NULL, NULL},
110 { "func_stop_accounting", PW_TYPE_STRING_PTR,
111 offsetof(PERL_INST,func_stop_accounting), NULL, NULL},
113 { NULL, -1, 0, NULL, NULL } /* end the list */
119 EXTERN_C void boot_DynaLoader(pTHX_ CV* cv);
122 * We share one perl interpreter among all of the instances
123 * of this module. And clone it for every thread if we have perl
124 * with -Duseithreads compiled in
126 static PerlInterpreter *interp;
131 * Pool of Perl's clones (genetically cloned) ;)
134 typedef struct pool_handle {
135 struct pool_handle *next;
136 struct pool_handle *prev;
137 enum {busy, idle} status;
138 unsigned int request_count;
139 PerlInterpreter *clone;
142 typedef struct PERL_POOL {
150 int min_spare_clones;
151 int max_spare_clones;
152 int max_request_per_clone;
155 time_t time_when_last_added;
158 static PERL_POOL perl_pool;
160 static const CONF_PARSER pool_conf[] = {
161 { "max_clones", PW_TYPE_INTEGER, 0, &perl_pool.max_clones, "32"},
162 { "start_clones",PW_TYPE_INTEGER, 0, &perl_pool.start_clones, "5"},
163 { "min_spare_clones",PW_TYPE_INTEGER, 0, &perl_pool.min_spare_clones, "3"},
164 { "max_spare_clones",PW_TYPE_INTEGER, 0, &perl_pool.max_spare_clones, "3"},
165 { "cleanup_delay",PW_TYPE_INTEGER, 0, &perl_pool.cleanup_delay, "5"},
166 { "max_request_per_clone",PW_TYPE_INTEGER, 0, &perl_pool.max_request_per_clone, "0"},
167 { NULL, -1, 0, NULL, NULL } /* end the list */
171 #define dl_librefs "DynaLoader::dl_librefs"
172 #define dl_modules "DynaLoader::dl_modules"
173 static void rlm_perl_clear_handles(pTHX)
175 AV *librefs = get_av(dl_librefs, FALSE);
181 static void **rlm_perl_get_handles(pTHX)
184 AV *librefs = get_av(dl_librefs, FALSE);
185 AV *modules = get_av(dl_modules, FALSE);
190 "Could not get @%s for unloading.\n",
195 if (!(AvFILL(librefs) >= 0)) {
199 handles = (void **)rad_malloc(sizeof(void *) * (AvFILL(librefs)+2));
201 for (i=0; i<=AvFILL(librefs); i++) {
203 SV *handle_sv = *av_fetch(librefs, i, FALSE);
207 "Could not fetch $%s[%d]!\n",
211 handle = (void *)SvIV(handle_sv);
221 handles[i] = (void *)0;
226 static void rlm_perl_close_handles(void **handles)
234 for (i=0; handles[i]; i++) {
235 radlog(L_DBG, "close 0x%lx\n", (unsigned long)handles[i]);
242 static PerlInterpreter *rlm_perl_clone()
244 PerlInterpreter *clone;
245 UV clone_flags = CLONEf_KEEP_PTR_TABLE;
247 PERL_SET_CONTEXT(interp);
249 clone = perl_clone(interp, clone_flags);
254 ptr_table_free(PL_ptr_table);
257 PERL_SET_CONTEXT(aTHX);
258 rlm_perl_clear_handles(aTHX);
263 static void rlm_perl_destruct(PerlInterpreter *perl)
265 char **orig_environ = NULL;
268 PERL_SET_CONTEXT(perl);
270 PL_perl_destruct_level = 2;
272 PL_origenviron = environ;
278 * FIXME: This shouldn't happen
281 while (PL_scopestack_ix > 1 ){
289 environ = orig_environ;
293 static void rlm_destroy_perl(PerlInterpreter *perl)
298 PERL_SET_CONTEXT(perl);
300 handles = rlm_perl_get_handles(aTHX);
301 rlm_perl_destruct(perl);
302 rlm_perl_close_handles(handles);
305 static void delete_pool_handle(POOL_HANDLE *handle)
314 perl_pool.head = next;
320 perl_pool.tail = prev;
324 perl_pool.current_clones--;
327 static void move2tail(POOL_HANDLE *handle)
332 if (perl_pool.head == NULL) {
336 perl_pool.head = handle;
337 perl_pool.tail = handle;
341 if (perl_pool.tail == handle) {
348 if ((next != NULL) ||
355 perl_pool.head = next;
366 prev = perl_pool.tail;
368 perl_pool.tail = handle;
374 static POOL_HANDLE *pool_grow () {
378 if (perl_pool.max_clones == perl_pool.current_clones) {
382 handle = (POOL_HANDLE *)rad_malloc(sizeof(POOL_HANDLE));
385 radlog(L_ERR,"Could not find free memory for pool. Aborting");
391 handle->status = idle;
392 handle->clone = rlm_perl_clone();
393 handle->request_count = 0;
394 perl_pool.current_clones++;
398 perl_pool.time_when_last_added = now;
403 static POOL_HANDLE *pool_pop()
409 * Lock the pool and be fast other thread maybe
410 * waiting for us to finish
412 MUTEX_LOCK(&perl_pool.mutex);
416 for (handle = perl_pool.head; handle ; handle = tmp) {
419 if (handle->status == idle){
426 if (perl_pool.current_clones < perl_pool.max_clones ) {
429 perl_pool.current_clones++;
432 radlog(L_ERR,"Cannot grow pool returning");
433 MUTEX_UNLOCK(&perl_pool.mutex);
437 radlog(L_ERR,"reached maximum clones %d cannot grow",
438 perl_pool.current_clones);
439 MUTEX_UNLOCK(&perl_pool.mutex);
445 found->status = busy;
446 perl_pool.active_clones++;
447 found->request_count++;
451 MUTEX_UNLOCK(&perl_pool.mutex);
452 radlog(L_DBG,"perl_pool: item 0x%lx asigned new request. Handled so far: %d",
453 (unsigned long) found->clone, found->request_count);
456 static int pool_release(POOL_HANDLE *handle) {
458 POOL_HANDLE *tmp, *tmp2;
464 MUTEX_LOCK(&perl_pool.mutex);
465 handle->status = idle;
466 perl_pool.active_clones--;
468 spare = perl_pool.current_clones - perl_pool.active_clones;
470 radlog(L_DBG,"perl_pool total/active/spare [%d/%d/%d]"
471 , perl_pool.current_clones, perl_pool.active_clones, spare);
473 if (spare < perl_pool.min_spare_clones) {
474 t = perl_pool.min_spare_clones - spare;
476 if ((tmp = pool_grow()) == NULL) {
477 MUTEX_UNLOCK(&perl_pool.mutex);
481 MUTEX_UNLOCK(&perl_pool.mutex);
485 if ((now - perl_pool.time_when_last_added) < perl_pool.cleanup_delay) {
486 MUTEX_UNLOCK(&perl_pool.mutex);
489 if (spare > perl_pool.max_spare_clones) {
490 spare -= perl_pool.max_spare_clones;
491 for (tmp = perl_pool.head; (tmp !=NULL ) && (spare > 0) ; tmp = tmp2) {
494 if(tmp->status == idle) {
495 rlm_destroy_perl(tmp->clone);
496 delete_pool_handle(tmp);
497 perl_pool.current_clones--;
506 MUTEX_UNLOCK(&perl_pool.mutex);
509 static int init_pool (CONF_SECTION *conf) {
513 MUTEX_INIT(&perl_pool.mutex);
520 cf_section_parse(conf,NULL,pool_conf);
522 for(t = 0;t < perl_pool.start_clones ;t++){
523 if ((handle = pool_grow()) == NULL) {
533 * Do any per-module initialization. e.g. set up connections
534 * to external databases, read configuration files, set up
535 * dictionary entries, etc.
537 * Try to avoid putting too much stuff in here - it's better to
538 * do it in instantiate() where it is not global.
540 static int perl_init(void)
542 if ((interp = perl_alloc()) == NULL) {
543 radlog(L_INFO, "rlm_perl: No memory for allocating new perl !");
547 perl_construct(interp);
548 PL_perl_destruct_level = 2;
554 static void xs_init(pTHX)
556 char *file = __FILE__;
558 /* DynaLoader is a special case */
559 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
564 * This is wrapper for radlog
565 * Now users can call radiusd::radlog(level,msg) wich is the same
566 * calling radlog from C code.
569 static XS(XS_radiusd_radlog)
573 croak("Usage: radiusd::radlog(level, message)");
578 level = (int) SvIV(ST(0));
579 msg = (char *) SvPV(ST(1), PL_na);
582 * Because 'msg' is a 'char *', we don't want '%s', etc.
583 * in it to give us printf-style vulnerabilities.
585 radlog(level, "rlm_perl: %s", msg);
593 static int perl_xlat(void *instance, REQUEST *request, char *fmt, char * out,
594 int freespace, RADIUS_ESCAPE_STRING func)
597 PERL_INST *inst= (PERL_INST *) instance;
598 PerlInterpreter *perl;
599 char params[1024], *tmp_ptr, *ptr, *tmp;
608 if ((handle = pool_pop()) == NULL) {
612 perl = handle->clone;
614 radlog(L_DBG,"Found a interpetator 0x%lx",(unsigned long) perl);
624 * Do an xlat on the provided string (nice recursive operation).
626 if (!radius_xlat(params, sizeof(params), fmt, request, func)) {
627 radlog(L_ERR, "rlm_perl: xlat failed.");
630 ptr = strtok(params, " ");
634 XPUSHs(sv_2mortal(newSVpv(ptr,0)));
636 while ((tmp_ptr = strtok(NULL, " ")) != NULL) {
637 XPUSHs(sv_2mortal(newSVpv(tmp_ptr,0)));
642 count = call_pv(inst->func_xlat, G_SCALAR | G_EVAL);
646 radlog(L_ERR, "rlm_perl: perl_xlat exit %s\n",
654 strncpy(out,tmp,ret);
656 radlog(L_DBG,"rlm_perl: Len is %d , out is %s freespace is %d",
663 if (ret <= freespace)
668 pool_release(handle);
673 * Do any per-module initialization that is separate to each
674 * configured instance of the module. e.g. set up connections
675 * to external databases, read configuration files, set up
676 * dictionary entries, etc.
678 * If configuration information is given in the config section
679 * that must be referenced in later calls, store a handle to it
680 * in *instance otherwise put a null pointer there.
683 * Setup a hashes wich we will use later
684 * parse a module and give him a chance to live
687 static int perl_instantiate(CONF_SECTION *conf, void **instance)
689 PERL_INST *inst = (PERL_INST *) instance;
690 HV *rad_reply_hv = newHV();
691 HV *rad_check_hv = newHV();
692 HV *rad_request_hv = newHV();
694 char *embed[4], *xlat_name;
695 int exitstatus = 0, argc=0;
698 * Set up a storage area for instance data
700 inst = rad_malloc(sizeof(PERL_INST));
701 memset(inst, 0, sizeof(PERL_INST));
704 * If the configuration parameters can't be parsed, then
707 if (cf_section_parse(conf, inst, module_config) < 0) {
714 if (inst->perl_flags) {
715 embed[1] = inst->perl_flags;
716 embed[2] = inst->module;
720 embed[1] = inst->module;
725 exitstatus = perl_parse(interp, xs_init, argc, embed, NULL);
727 #if PERL_REVISION >= 5 && PERL_VERSION >=8
728 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
732 exitstatus = perl_run(interp);
734 radlog(L_INFO,"rlm_perl: perl_parse failed: %s not found or has syntax errors. \n", inst->module);
738 newXS("radiusd::radlog",XS_radiusd_radlog, "rlm_perl.c");
740 rad_reply_hv = get_hv("RAD_REPLY",1);
741 rad_check_hv = get_hv("RAD_CHECK",1);
742 rad_request_hv = get_hv("RAD_REQUEST",1);
744 xlat_name = cf_section_name2(conf);
745 if (xlat_name == NULL)
746 xlat_name = cf_section_name1(conf);
748 inst->xlat_name = strdup(xlat_name);
749 xlat_register(xlat_name, perl_xlat, inst);
754 if ((init_pool(conf)) == -1) {
755 radlog(L_ERR,"Couldn't init a pool of perl clones. Exiting");
766 * get the vps and put them in perl hash
767 * If one VP have multiple values it is added as array_ref
768 * Example for this is Cisco-AVPair that holds multiple values.
769 * Which will be available as array_ref in $RAD_REQUEST{'Cisco-AVPair'}
771 static void perl_store_vps(VALUE_PAIR *vp, HV *rad_hv)
773 VALUE_PAIR *nvp, *vpa, *vpn;
781 while (nvp != NULL) {
782 attr = nvp->attribute;
783 vpa = paircopy2(nvp,attr);
788 len = vp_prints_value(buffer, sizeof(buffer),
790 av_push(av, newSVpv(buffer, len));
793 hv_store(rad_hv, nvp->name, strlen(nvp->name),
794 newRV((SV *) av), 0);
796 len = vp_prints_value(buffer, sizeof(buffer),
798 hv_store(rad_hv, vpa->name, strlen(vpa->name),
799 newSVpv(buffer, len), 0);
803 vpa = nvp; while ((vpa != NULL) && (vpa->attribute == attr))
805 pairdelete(&nvp, attr);
812 * Verify that a Perl SV is a string and save it in FreeRadius
816 static int pairadd_sv(VALUE_PAIR **vp, char *key, SV *sv) {
821 if ((sv != NULL) && (SvPOK(sv))) {
822 val = SvPV(sv, val_len);
823 vpp = pairmake(key, val, T_OP_EQ);
827 "rlm_perl: Added pair %s = %s", key, val);
831 "rlm_perl: ERROR: Failed to create pair %s = %s",
840 * Gets the content from hashes
842 static int get_hv_content(HV *my_hv, VALUE_PAIR **vp)
847 I32 key_len, len, i, j;
850 for (i = hv_iterinit(my_hv); i > 0; i--) {
851 res_sv = hv_iternextsv(my_hv,&key,&key_len);
852 if (SvROK(res_sv) && (SvTYPE(SvRV(res_sv)) == SVt_PVAV)) {
853 av = (AV*)SvRV(res_sv);
855 for (j = 0; j <= len; j++) {
856 av_sv = av_fetch(av, j, 0);
857 ret = pairadd_sv(vp, key, *av_sv) + ret;
859 } else ret = pairadd_sv(vp, key, res_sv) + ret;
866 * Call the function_name inside the module
867 * Store all vps in hashes %RAD_CHECK %RAD_REPLY %RAD_REQUEST
870 static int rlmperl_call(void *instance, REQUEST *request, char *function_name)
873 PERL_INST *inst = instance;
875 int exitstatus=0, count;
885 if ((handle = pool_pop()) == NULL) {
886 return RLM_MODULE_FAIL;
889 radlog(L_DBG,"found interpetator at address 0x%lx",(unsigned long) handle->clone);
891 dTHXa(handle->clone);
892 PERL_SET_CONTEXT(handle->clone);
903 * Radius has told us to call this function, but none
906 if (!function_name) {
907 return RLM_MODULE_FAIL;
910 rad_reply_hv = get_hv("RAD_REPLY",1);
911 rad_check_hv = get_hv("RAD_CHECK",1);
912 rad_request_hv = get_hv("RAD_REQUEST",1);
916 perl_store_vps(request->reply->vps, rad_reply_hv);
917 perl_store_vps(request->config_items, rad_check_hv);
918 perl_store_vps(request->packet->vps, rad_request_hv);
924 * This way %RAD_xx can be pushed onto stack as sub parameters.
925 * XPUSHs( newRV_noinc((SV *)rad_request_hv) );
926 * XPUSHs( newRV_noinc((SV *)rad_reply_hv) );
927 * XPUSHs( newRV_noinc((SV *)rad_check_hv) );
931 count = call_pv(function_name, G_SCALAR | G_EVAL | G_NOARGS);
937 if (exitstatus >= 100 || exitstatus < 0) {
938 exitstatus = RLM_MODULE_FAIL;
947 radlog(L_ERR, "rlm_perl: perl_embed:: module = %s , func = %s exit status= %s\n",
949 function_name, SvPV(ERRSV,n_a));
952 if ((get_hv_content(rad_reply_hv, &vp)) > 0 ) {
953 pairmove(&request->reply->vps, &vp);
957 if ((get_hv_content(rad_check_hv, &vp)) > 0 ) {
958 pairmove(&request->config_items, &vp);
964 * Do we want to allow this?
966 if ((get_hv_content(rad_request_hv, &vp)) > 0 ) {
967 pairfree(&request->packet->vps);
968 request->packet->vps = vp;
974 pool_release(handle);
975 radlog(L_DBG,"Unreserve perl at address 0x%lx", (unsigned long) handle->clone);
982 * Find the named user in this modules database. Create the set
983 * of attribute-value pairs to check and reply with for this user
984 * from the database. The authentication code only needs to check
985 * the password, the rest is done here.
987 static int perl_authorize(void *instance, REQUEST *request)
989 return rlmperl_call(instance, request,
990 ((PERL_INST *)instance)->func_authorize);
994 * Authenticate the user with the given password.
996 static int perl_authenticate(void *instance, REQUEST *request)
998 return rlmperl_call(instance, request,
999 ((PERL_INST *)instance)->func_authenticate);
1002 * Massage the request before recording it or proxying it
1004 static int perl_preacct(void *instance, REQUEST *request)
1006 return rlmperl_call(instance, request,
1007 ((PERL_INST *)instance)->func_preacct);
1012 * Write accounting information to this modules database.
1015 static int perl_accounting(void *instance, REQUEST *request)
1018 int acctstatustype=0;
1020 if ((pair = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE)) != NULL) {
1021 acctstatustype = pair->lvalue;
1023 radlog(L_ERR, "Invalid Accounting Packet");
1024 return RLM_MODULE_INVALID;
1027 switch (acctstatustype) {
1029 case PW_STATUS_START:
1031 if (((PERL_INST *)instance)->func_start_accounting) {
1032 return rlmperl_call(instance, request,
1033 ((PERL_INST *)instance)->func_start_accounting);
1035 return rlmperl_call(instance, request,
1036 ((PERL_INST *)instance)->func_accounting);
1040 case PW_STATUS_STOP:
1042 if (((PERL_INST *)instance)->func_stop_accounting) {
1043 return rlmperl_call(instance, request,
1044 ((PERL_INST *)instance)->func_stop_accounting);
1046 return rlmperl_call(instance, request,
1047 ((PERL_INST *)instance)->func_accounting);
1051 return rlmperl_call(instance, request,
1052 ((PERL_INST *)instance)->func_accounting);
1057 * Check for simultaneouse-use
1060 static int perl_checksimul(void *instance, REQUEST *request)
1062 return rlmperl_call(instance, request,
1063 ((PERL_INST *)instance)->func_checksimul);
1067 * Detach a instance give a chance to a module to make some internal setup ...
1069 static int perl_detach(void *instance)
1071 PERL_INST *inst = (PERL_INST *) instance;
1072 int exitstatus=0,count=0;
1075 POOL_HANDLE *handle;
1077 for (handle = perl_pool.head; handle; handle = handle->next) {
1079 radlog(L_INFO,"Detach perl 0x%lx", (unsigned long) handle->clone);
1081 * Wait until clone becomes idle
1084 while (handle->status == busy) {
1088 * Give a clones chance to run detach function
1091 dTHXa(handle->clone);
1092 PERL_SET_CONTEXT(handle->clone);
1095 count = call_pv(inst->func_detach, G_SCALAR | G_EVAL );
1101 * FIXME: bug in perl
1104 if (exitstatus >= 100 || exitstatus < 0) {
1105 exitstatus = RLM_MODULE_FAIL;
1109 radlog(L_INFO,"detach at 0x%lx returned status %d",
1110 (unsigned long) handle->clone, exitstatus);
1117 * FIXME: For more efficienty we don't
1118 * free entire pool. We only reread config flags thus way
1119 * we can extend pool_size.
1124 PERL_SET_CONTEXT(interp);
1125 #endif /* USE_ITHREADS */
1129 count = call_pv(inst->func_detach, G_SCALAR | G_EVAL );
1134 if (exitstatus >= 100 || exitstatus < 0) {
1135 exitstatus = RLM_MODULE_FAIL;
1144 xlat_unregister(inst->xlat_name, perl_xlat);
1145 free(inst->xlat_name);
1147 if (inst->func_authorize) free(inst->func_authorize);
1148 if (inst->func_authenticate) free(inst->func_authenticate);
1149 if (inst->func_accounting) free(inst->func_accounting);
1150 if (inst->func_preacct) free(inst->func_preacct);
1151 if (inst->func_checksimul) free(inst->func_checksimul);
1152 if (inst->func_detach) free(inst->func_detach);
1159 * The module name should be the only globally exported symbol.
1160 * That is, everything else should be 'static'.
1162 * If the module needs to temporarily modify it's instantiation
1163 * data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
1164 * The server will then take care of ensuring that the module
1165 * is single-threaded.
1167 module_t rlm_perl = {
1170 RLM_TYPE_THREAD_SAFE, /* type */
1172 RLM_TYPE_THREAD_UNSAFE,
1174 perl_init, /* initialization */
1175 perl_instantiate, /* instantiation */
1181 perl_checksimul, /* check simul */
1182 NULL, /* pre-proxy */
1183 NULL, /* post-proxy */
1184 NULL /* post-auth */
1186 perl_detach, /* detach */