rlm_otp import from HEAD
[freeradius.git] / src / modules / rlm_perl / rlm_perl.c
1 /*
2  * rlm_perl.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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * Copyright 2002  The FreeRADIUS server project
21  * Copyright 2002  Boian Jordanov <bjordanov@orbitel.bg>
22  */
23
24 #include "autoconf.h"
25 #include "libradius.h"
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30
31 #include "radiusd.h"
32 #include "modules.h"
33 #include "conffile.h"
34
35 #ifdef DEBUG
36 #undef DEBUG
37 #endif
38
39 #ifdef INADDR_ANY
40 #undef INADDR_ANY
41 #endif
42
43 #ifdef INADDR_NONE
44 #undef INADDR_NONE
45 #endif
46
47 #include <EXTERN.h>
48 #include <perl.h>
49 #include <XSUB.h>
50 #include <dlfcn.h>
51 #include <semaphore.h>
52
53 static const char rcsid[] = "$Id$";
54
55
56 /*
57  *      Define a structure for our module configuration.
58  *
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.
62  */
63 typedef struct perl_inst {
64         /* Name of the perl module */
65         char    *module;
66
67         /* Name of the functions for each module method */
68         char    *func_authorize;
69         char    *func_authenticate;
70         char    *func_accounting;
71         char    *func_start_accounting;
72         char    *func_stop_accounting;
73         char    *func_preacct;
74         char    *func_checksimul;
75         char    *func_detach;
76         char    *func_xlat;
77         char    *xlat_name;
78         char    *perl_flags;
79 } PERL_INST;
80 /*
81  *      A mapping of configuration file names to internal variables.
82  *
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
87  *      buffer over-flows.
88  */
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},
112
113         { NULL, -1, 0, NULL, NULL }             /* end the list */
114 };
115
116 /*
117  * man perlembed
118  */
119 EXTERN_C void boot_DynaLoader(pTHX_ CV* cv);
120
121 /*
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
125  */
126 static PerlInterpreter  *interp;
127
128 #ifdef USE_ITHREADS
129
130 /*
131  * Pool of Perl's clones (genetically cloned) ;)
132  *
133  */
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;
140 } POOL_HANDLE;
141
142 typedef struct PERL_POOL {
143         POOL_HANDLE     *head;
144         POOL_HANDLE     *tail;
145
146         int             current_clones;
147         int             active_clones;
148         int             max_clones;
149         int             start_clones;
150         int             min_spare_clones;
151         int             max_spare_clones;
152         int             max_request_per_clone;
153         int             cleanup_delay;
154         perl_mutex      mutex;
155         time_t          time_when_last_added;
156 } PERL_POOL;
157
158 static PERL_POOL perl_pool;
159
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 */
168 };
169
170
171 #define dl_librefs "DynaLoader::dl_librefs"
172 #define dl_modules "DynaLoader::dl_modules"
173 static void rlm_perl_clear_handles(pTHX)
174 {
175         AV *librefs = get_av(dl_librefs, FALSE);
176         if (librefs) {
177                 av_clear(librefs);
178         }
179 }
180
181 static void **rlm_perl_get_handles(pTHX)
182 {
183         I32 i;
184         AV *librefs = get_av(dl_librefs, FALSE);
185         AV *modules = get_av(dl_modules, FALSE);
186         void **handles;
187
188         if (!librefs) {
189                 radlog(L_ERR,
190                    "Could not get @%s for unloading.\n",
191                    dl_librefs);
192                 return NULL;
193         }
194
195         if (!(AvFILL(librefs) >= 0)) {
196                 return NULL;
197         }
198
199         handles = (void **)rad_malloc(sizeof(void *) * (AvFILL(librefs)+2));
200
201         for (i=0; i<=AvFILL(librefs); i++) {
202                 void *handle;
203                 SV *handle_sv = *av_fetch(librefs, i, FALSE);
204
205                 if(!handle_sv) {
206                     radlog(L_ERR,
207                                "Could not fetch $%s[%d]!\n",
208                                dl_librefs, (int)i);
209                     continue;
210                 }
211                 handle = (void *)SvIV(handle_sv);
212
213                 if (handle) {
214                     handles[i] = handle;
215                 }
216         }
217
218         av_clear(modules);
219         av_clear(librefs);
220
221         handles[i] = (void *)0;
222
223         return handles;
224 }
225
226 static void rlm_perl_close_handles(void **handles)
227 {
228         int i;
229
230         if (!handles) {
231                 return;
232         }
233
234         for (i=0; handles[i]; i++) {
235                 radlog(L_DBG, "close 0x%lx\n", (unsigned long)handles[i]);
236                 dlclose(handles[i]);
237         }
238
239         free(handles);
240 }
241
242 static PerlInterpreter *rlm_perl_clone()
243 {
244         PerlInterpreter *clone;
245         UV      clone_flags = CLONEf_KEEP_PTR_TABLE;
246
247         PERL_SET_CONTEXT(interp);
248
249         clone = perl_clone(interp, clone_flags);
250         {
251                 dTHXa(clone);
252         }
253
254         ptr_table_free(PL_ptr_table);
255         PL_ptr_table = NULL;
256
257         PERL_SET_CONTEXT(aTHX);
258         rlm_perl_clear_handles(aTHX);
259
260         return clone;
261 }
262
263 static void rlm_perl_destruct(PerlInterpreter *perl)
264 {
265         char **orig_environ = NULL;
266         dTHXa(perl);
267
268         PERL_SET_CONTEXT(perl);
269
270         PL_perl_destruct_level = 2;
271
272         PL_origenviron = environ;
273
274         {
275                 dTHXa(perl);
276         }
277         /*
278          * FIXME: This shouldn't happen
279          *
280          */
281         while (PL_scopestack_ix > 1 ){
282                 LEAVE;
283         }
284
285         perl_destruct(perl);
286         perl_free(perl);
287
288         if (orig_environ) {
289                 environ = orig_environ;
290         }
291 }
292
293 static void rlm_destroy_perl(PerlInterpreter *perl)
294 {
295         void    **handles;
296
297         dTHXa(perl);
298         PERL_SET_CONTEXT(perl);
299
300         handles = rlm_perl_get_handles(aTHX);
301         rlm_perl_destruct(perl);
302         rlm_perl_close_handles(handles);
303 }
304
305 static void delete_pool_handle(POOL_HANDLE *handle)
306 {
307         POOL_HANDLE *prev;
308         POOL_HANDLE *next;
309
310         prev = handle->prev;
311         next = handle->next;
312
313         if (prev == NULL) {
314                 perl_pool.head = next;
315         } else {
316                 prev->next = next;
317         }
318
319         if (next == NULL) {
320                 perl_pool.tail = prev;
321         } else {
322                 next->prev = prev;
323         }
324         perl_pool.current_clones--;
325 }
326
327 static void move2tail(POOL_HANDLE *handle)
328 {
329         POOL_HANDLE *prev;
330         POOL_HANDLE *next;
331
332         if (perl_pool.head == NULL) {
333
334                 handle->prev = NULL;
335                 handle->next = NULL;
336                 perl_pool.head = handle;
337                 perl_pool.tail = handle;
338                 return;
339         }
340
341         if (perl_pool.tail == handle) {
342                 return;
343         }
344
345         prev = handle->prev;
346         next = handle->next;
347
348         if ((next != NULL) ||
349                         (prev != NULL)) {
350                 if (next == NULL) {
351                         return;
352                 }
353
354                 if (prev == NULL) {
355                         perl_pool.head = next;
356                         next->prev = NULL;
357
358                 } else {
359
360                         prev->next = next;
361                         next->prev = prev;
362                 }
363         }
364
365         handle->next = NULL;
366         prev = perl_pool.tail;
367
368         perl_pool.tail = handle;
369         handle->prev = prev;
370         prev->next = handle;
371 }
372
373
374 static POOL_HANDLE *pool_grow () {
375         POOL_HANDLE *handle;
376         time_t  now;
377
378         if (perl_pool.max_clones == perl_pool.current_clones) {
379                 return NULL;
380         }
381
382         handle = (POOL_HANDLE *)rad_malloc(sizeof(POOL_HANDLE));
383
384         if (!handle) {
385                 radlog(L_ERR,"Could not find free memory for pool. Aborting");
386                 return NULL;
387         }
388
389         handle->prev = NULL;
390         handle->next = NULL;
391         handle->status = idle;
392         handle->clone = rlm_perl_clone();
393         handle->request_count = 0;
394         perl_pool.current_clones++;
395         move2tail(handle);
396
397         now = time(NULL);
398         perl_pool.time_when_last_added = now;
399
400         return handle;
401 }
402
403 static POOL_HANDLE *pool_pop()
404 {
405         POOL_HANDLE     *handle;
406         POOL_HANDLE     *found;
407         POOL_HANDLE     *tmp;
408         /*
409          * Lock the pool and be fast other thread maybe
410          * waiting for us to finish
411          */
412         MUTEX_LOCK(&perl_pool.mutex);
413
414         found = NULL;
415
416         for (handle = perl_pool.head; handle ; handle = tmp) {
417                 tmp = handle->next;
418
419                 if (handle->status == idle){
420                         found = handle;
421                         break;
422                 }
423         }
424
425         if (found == NULL) {
426                 if (perl_pool.current_clones < perl_pool.max_clones ) {
427
428                         found = pool_grow();
429                         perl_pool.current_clones++;
430
431                         if (found == NULL) {
432                                 radlog(L_ERR,"Cannot grow pool returning");
433                                 MUTEX_UNLOCK(&perl_pool.mutex);
434                                 return NULL;
435                         }
436                 } else {
437                         radlog(L_ERR,"reached maximum clones %d cannot grow",
438                                         perl_pool.current_clones);
439                         MUTEX_UNLOCK(&perl_pool.mutex);
440                         return NULL;
441                 }
442         }
443
444         move2tail(found);
445         found->status = busy;
446         perl_pool.active_clones++;
447         found->request_count++;
448         /*
449          * Hurry Up
450          */
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);
454         return found;
455 }
456 static int pool_release(POOL_HANDLE *handle) {
457
458         POOL_HANDLE *tmp, *tmp2;
459         int spare, i, t;
460         time_t  now;
461         /*
462          * Lock it
463          */
464         MUTEX_LOCK(&perl_pool.mutex);
465         handle->status = idle;
466         perl_pool.active_clones--;
467
468         spare = perl_pool.current_clones - perl_pool.active_clones;
469
470         radlog(L_DBG,"perl_pool total/active/spare [%d/%d/%d]"
471                         , perl_pool.current_clones, perl_pool.active_clones, spare);
472
473         if (spare < perl_pool.min_spare_clones) {
474                 t = perl_pool.min_spare_clones - spare;
475                 for (i=0;i<t; i++) {
476                         if ((tmp = pool_grow()) == NULL) {
477                                 MUTEX_UNLOCK(&perl_pool.mutex);
478                                 return -1;
479                         }
480                 }
481                 MUTEX_UNLOCK(&perl_pool.mutex);
482                 return 0;
483         }
484         now = time(NULL);
485         if ((now - perl_pool.time_when_last_added) < perl_pool.cleanup_delay) {
486                 MUTEX_UNLOCK(&perl_pool.mutex);
487                 return 0;
488         }
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) {
492                         tmp2 = tmp->next;
493
494                         if(tmp->status == idle) {
495                                 rlm_destroy_perl(tmp->clone);
496                                 delete_pool_handle(tmp);
497                                 perl_pool.current_clones--;
498                                 spare--;
499                                 break;
500                         }
501                 }
502         }
503         /*
504          * Hurry Up :)
505          */
506         MUTEX_UNLOCK(&perl_pool.mutex);
507         return 0;
508 }
509 static int init_pool (CONF_SECTION *conf) {
510         POOL_HANDLE     *handle;
511         int t;
512
513         MUTEX_INIT(&perl_pool.mutex);
514
515         /*
516          * Read The Config
517          *
518          */
519
520         cf_section_parse(conf,NULL,pool_conf);
521
522         for(t = 0;t < perl_pool.start_clones ;t++){
523                 if ((handle = pool_grow()) == NULL) {
524                         return -1;
525                 }
526
527         }
528
529         return 1;
530 }
531 #endif
532 /*
533  *      Do any per-module initialization.  e.g. set up connections
534  *      to external databases, read configuration files, set up
535  *      dictionary entries, etc.
536  *
537  *      Try to avoid putting too much stuff in here - it's better to
538  *      do it in instantiate() where it is not global.
539  */
540 static int perl_init(void)
541 {
542         if ((interp = perl_alloc()) == NULL) {
543                 radlog(L_INFO, "rlm_perl: No memory for allocating new perl !");
544                 return -1;
545         }
546
547         perl_construct(interp);
548         PL_perl_destruct_level = 2;
549
550         return 0;
551
552 }
553
554 static void xs_init(pTHX)
555 {
556         char *file = __FILE__;
557
558         /* DynaLoader is a special case */
559         newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
560
561 }
562 /*
563  *
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.
567  * Boyan
568  */
569 static XS(XS_radiusd_radlog)
570 {
571        dXSARGS;
572        if (items !=2)
573                croak("Usage: radiusd::radlog(level, message)");
574        {
575                int     level;
576                char    *msg;
577
578                level = (int) SvIV(ST(0));
579                msg   = (char *) SvPV(ST(1), PL_na);
580
581                /*
582                 *       Because 'msg' is a 'char *', we don't want '%s', etc.
583                 *       in it to give us printf-style vulnerabilities.
584                 */
585                radlog(level, "rlm_perl: %s", msg);
586         }
587        XSRETURN_NO;
588 }
589
590 /*
591  * The xlat function
592  */
593 static int perl_xlat(void *instance, REQUEST *request, char *fmt, char * out,
594                      int freespace, RADIUS_ESCAPE_STRING func)
595 {
596
597         PERL_INST       *inst= (PERL_INST *) instance;
598         PerlInterpreter *perl;
599         char            params[1024], *tmp_ptr, *ptr, *tmp;
600         int             count, ret;
601         STRLEN          n_a;
602
603         perl = interp;
604
605 #ifdef USE_ITHREADS
606         POOL_HANDLE     *handle;
607
608         if ((handle = pool_pop()) == NULL) {
609                 return 0;
610         }
611
612         perl = handle->clone;
613
614         radlog(L_DBG,"Found a interpetator 0x%lx",(unsigned long) perl);
615         {
616         dTHXa(perl);
617         }
618 #endif
619         {
620         dSP;
621         ENTER;SAVETMPS;
622
623         /*
624          * Do an xlat on the provided string (nice recursive operation).
625         */
626         if (!radius_xlat(params, sizeof(params), fmt, request, func)) {
627                 radlog(L_ERR, "rlm_perl: xlat failed.");
628                 return 0;
629         }
630         ptr = strtok(params, " ");
631
632         PUSHMARK(SP);
633
634         XPUSHs(sv_2mortal(newSVpv(ptr,0)));
635
636         while ((tmp_ptr = strtok(NULL, " ")) != NULL) {
637                 XPUSHs(sv_2mortal(newSVpv(tmp_ptr,0)));
638         }
639
640         PUTBACK;
641
642         count = call_pv(inst->func_xlat, G_SCALAR | G_EVAL);
643
644         SPAGAIN;
645         if (SvTRUE(ERRSV)) {
646                 radlog(L_ERR, "rlm_perl: perl_xlat exit %s\n",
647                        SvPV(ERRSV,n_a));
648                 return 0;
649         }
650
651         if (count > 0) {
652                 tmp = POPp;
653                 ret = strlen(tmp);
654                 strncpy(out,tmp,ret);
655
656                 radlog(L_DBG,"rlm_perl: Len is %d , out is %s freespace is %d",
657                        ret, out,freespace);
658
659                 PUTBACK ;
660                 FREETMPS ;
661                 LEAVE ;
662
663                 if (ret <= freespace)
664                         return ret;
665         }
666         }
667 #ifdef USE_ITHREADS
668         pool_release(handle);
669 #endif
670         return 0;
671 }
672 /*
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.
677  *
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.
681  *
682  *      Boyan:
683  *      Setup a hashes wich we will use later
684  *      parse a module and give him a chance to live
685  *
686  */
687 static int perl_instantiate(CONF_SECTION *conf, void **instance)
688 {
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();
693
694         char *embed[4], *xlat_name;
695         int exitstatus = 0, argc=0;
696
697         /*
698          *      Set up a storage area for instance data
699          */
700         inst = rad_malloc(sizeof(PERL_INST));
701         memset(inst, 0, sizeof(PERL_INST));
702
703         /*
704          *      If the configuration parameters can't be parsed, then
705          *      fail.
706          */
707         if (cf_section_parse(conf, inst, module_config) < 0) {
708                 free(inst);
709                 return -1;
710         }
711
712
713         embed[0] = NULL;
714         if (inst->perl_flags) {
715                 embed[1] = inst->perl_flags;
716                 embed[2] = inst->module;
717                 embed[3] = "0";
718                 argc = 4;
719         } else {
720                 embed[1] = inst->module;
721                 embed[2] = "0";
722                 argc = 3;
723         }
724
725         exitstatus = perl_parse(interp, xs_init, argc, embed, NULL);
726
727 #if PERL_REVISION >= 5 && PERL_VERSION >=8
728         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
729 #endif
730
731         if(!exitstatus) {
732                 exitstatus = perl_run(interp);
733         } else {
734                 radlog(L_INFO,"rlm_perl: perl_parse failed: %s not found or has syntax errors. \n", inst->module);
735                 return (-1);
736         }
737
738         newXS("radiusd::radlog",XS_radiusd_radlog, "rlm_perl.c");
739
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);
743
744         xlat_name = cf_section_name2(conf);
745         if (xlat_name == NULL)
746                 xlat_name = cf_section_name1(conf);
747         if (xlat_name){
748                 inst->xlat_name = strdup(xlat_name);
749                 xlat_register(xlat_name, perl_xlat, inst);
750         }
751
752 #ifdef USE_ITHREADS
753
754         if ((init_pool(conf)) == -1) {
755                 radlog(L_ERR,"Couldn't init a pool of perl clones. Exiting");
756                 return -1;
757         }
758
759 #endif
760         *instance = inst;
761
762         return 0;
763 }
764
765 /*
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'}
770  */
771 static void perl_store_vps(VALUE_PAIR *vp, HV *rad_hv)
772 {
773         VALUE_PAIR      *nvp, *vpa, *vpn;
774         AV              *av;
775         char            buffer[1024];
776         int             attr, len;
777
778         hv_clear(rad_hv);
779         nvp = paircopy(vp);
780
781         while (nvp != NULL) {
782                 attr = nvp->attribute;
783                 vpa = paircopy2(nvp,attr);
784                 if (vpa->next) {
785                         av = newAV();
786                         vpn = vpa;
787                         while (vpn) {
788                                 len = vp_prints_value(buffer, sizeof(buffer),
789                                                 vpn, FALSE);
790                                 av_push(av, newSVpv(buffer, len));
791                                 vpn = vpn->next;
792                         }
793                         hv_store(rad_hv, nvp->name, strlen(nvp->name),
794                                         newRV((SV *) av), 0);
795                 } else {
796                         len = vp_prints_value(buffer, sizeof(buffer),
797                                         vpa, FALSE);
798                         hv_store(rad_hv, vpa->name, strlen(vpa->name),
799                                         newSVpv(buffer, len), 0);
800                 }
801
802                 pairfree(&vpa);
803                 vpa = nvp; while ((vpa != NULL) && (vpa->attribute == attr))
804                         vpa = vpa->next;
805                 pairdelete(&nvp, attr);
806                 nvp = vpa;
807         }
808 }
809
810 /*
811  *
812  *     Verify that a Perl SV is a string and save it in FreeRadius
813  *     Value Pair Format
814  *
815  */
816 static int pairadd_sv(VALUE_PAIR **vp, char *key, SV *sv) {
817        char            *val;
818        int             val_len;
819        VALUE_PAIR      *vpp;
820
821        if ((sv != NULL) && (SvPOK(sv))) {
822                val = SvPV(sv, val_len);
823                vpp = pairmake(key, val, T_OP_EQ);
824                if (vpp != NULL) {
825                        pairadd(vp, vpp);
826                        radlog(L_DBG,
827                          "rlm_perl: Added pair %s = %s", key, val);
828                        return 1;
829                } else {
830                        radlog(L_DBG,
831                          "rlm_perl: ERROR: Failed to create pair %s = %s",
832                          key, val);
833                }
834         }
835        return 0;
836 }
837
838 /*
839   *     Boyan :
840   *     Gets the content from hashes
841   */
842 static int get_hv_content(HV *my_hv, VALUE_PAIR **vp)
843 {
844        SV               *res_sv, **av_sv;
845        AV               *av;
846        char             *key;
847        I32              key_len, len, i, j;
848        int              ret=0;
849
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);
854                        len = av_len(av);
855                        for (j = 0; j <= len; j++) {
856                                av_sv = av_fetch(av, j, 0);
857                                ret = pairadd_sv(vp, key, *av_sv) + ret;
858                        }
859                } else ret = pairadd_sv(vp, key, res_sv) + ret;
860         }
861
862         return ret;
863 }
864
865 /*
866  *      Call the function_name inside the module
867  *      Store all vps in hashes %RAD_CHECK %RAD_REPLY %RAD_REQUEST
868  *
869  */
870 static int rlmperl_call(void *instance, REQUEST *request, char *function_name)
871 {
872
873         PERL_INST       *inst = instance;
874         VALUE_PAIR      *vp;
875         int             exitstatus=0, count;
876         STRLEN          n_a;
877
878         HV              *rad_reply_hv;
879         HV              *rad_check_hv;
880         HV              *rad_request_hv;
881
882 #ifdef USE_ITHREADS
883         POOL_HANDLE     *handle;
884
885         if ((handle = pool_pop()) == NULL) {
886                 return RLM_MODULE_FAIL;
887         }
888
889         radlog(L_DBG,"found interpetator at address 0x%lx",(unsigned long) handle->clone);
890         {
891         dTHXa(handle->clone);
892         PERL_SET_CONTEXT(handle->clone);
893         }
894 #endif
895         {
896         dSP;
897
898         ENTER;
899         SAVETMPS;
900
901
902         /*
903          *      Radius has told us to call this function, but none
904          *      is defined.
905          */
906         if (!function_name) {
907                 return RLM_MODULE_FAIL;
908         }
909
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);
913
914
915
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);
919         vp = NULL;
920
921
922         PUSHMARK(SP);
923         /*
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) );
928         * PUTBACK;
929         */
930
931         count = call_pv(function_name, G_SCALAR | G_EVAL | G_NOARGS);
932
933         SPAGAIN;
934
935         if (count == 1) {
936                 exitstatus = POPi;
937                 if (exitstatus >= 100 || exitstatus < 0) {
938                         exitstatus = RLM_MODULE_FAIL;
939                 }
940         }
941
942         PUTBACK;
943         FREETMPS;
944         LEAVE;
945
946         if (SvTRUE(ERRSV)) {
947                 radlog(L_ERR, "rlm_perl: perl_embed:: module = %s , func = %s exit status= %s\n",
948                        inst->module,
949                        function_name, SvPV(ERRSV,n_a));
950         }
951
952         if ((get_hv_content(rad_reply_hv, &vp)) > 0 ) {
953                 pairmove(&request->reply->vps, &vp);
954                 pairfree(&vp);
955         }
956
957         if ((get_hv_content(rad_check_hv, &vp)) > 0 ) {
958                 pairmove(&request->config_items, &vp);
959                 pairfree(&vp);
960         }
961
962 #if 0
963         /*
964          *      Do we want to allow this?
965          */
966         if ((get_hv_content(rad_request_hv, &vp)) > 0 ) {
967                 pairfree(&request->packet->vps);
968                 request->packet->vps = vp;
969         }
970 #endif
971
972         }
973 #ifdef USE_ITHREADS
974         pool_release(handle);
975         radlog(L_DBG,"Unreserve perl at address 0x%lx", (unsigned long) handle->clone);
976 #endif
977
978         return exitstatus;
979 }
980
981 /*
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.
986  */
987 static int perl_authorize(void *instance, REQUEST *request)
988 {
989         return rlmperl_call(instance, request,
990                             ((PERL_INST *)instance)->func_authorize);
991 }
992
993 /*
994  *      Authenticate the user with the given password.
995  */
996 static int perl_authenticate(void *instance, REQUEST *request)
997 {
998         return rlmperl_call(instance, request,
999                             ((PERL_INST *)instance)->func_authenticate);
1000 }
1001 /*
1002  *      Massage the request before recording it or proxying it
1003  */
1004 static int perl_preacct(void *instance, REQUEST *request)
1005 {
1006         return rlmperl_call(instance, request,
1007                             ((PERL_INST *)instance)->func_preacct);
1008 }
1009
1010
1011 /*
1012  *      Write accounting information to this modules database.
1013  */
1014
1015 static int perl_accounting(void *instance, REQUEST *request)
1016 {
1017         VALUE_PAIR      *pair;
1018         int             acctstatustype=0;
1019
1020         if ((pair = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE)) != NULL) {
1021                 acctstatustype = pair->lvalue;
1022         } else {
1023                 radlog(L_ERR, "Invalid Accounting Packet");
1024                 return RLM_MODULE_INVALID;
1025         }
1026
1027         switch (acctstatustype) {
1028
1029                 case PW_STATUS_START:
1030
1031                         if (((PERL_INST *)instance)->func_start_accounting) {
1032                                 return rlmperl_call(instance, request,
1033                                             ((PERL_INST *)instance)->func_start_accounting);
1034                         } else {
1035                                 return rlmperl_call(instance, request,
1036                                             ((PERL_INST *)instance)->func_accounting);
1037                         }
1038                         break;
1039
1040                 case PW_STATUS_STOP:
1041
1042                         if (((PERL_INST *)instance)->func_stop_accounting) {
1043                                 return rlmperl_call(instance, request,
1044                                             ((PERL_INST *)instance)->func_stop_accounting);
1045                         } else {
1046                                 return rlmperl_call(instance, request,
1047                                             ((PERL_INST *)instance)->func_accounting);
1048                         }
1049                         break;
1050                 default:
1051                         return rlmperl_call(instance, request,
1052                                             ((PERL_INST *)instance)->func_accounting);
1053
1054         }
1055 }
1056 /*
1057  *      Check for simultaneouse-use
1058  */
1059
1060 static int perl_checksimul(void *instance, REQUEST *request)
1061 {
1062         return rlmperl_call(instance, request,
1063                         ((PERL_INST *)instance)->func_checksimul);
1064 }
1065
1066 /*
1067  * Detach a instance give a chance to a module to make some internal setup ...
1068  */
1069 static int perl_detach(void *instance)
1070 {
1071         PERL_INST       *inst = (PERL_INST *) instance;
1072         int             exitstatus=0,count=0;
1073
1074 #ifdef USE_ITHREADS
1075         POOL_HANDLE     *handle;
1076
1077         for (handle = perl_pool.head; handle; handle = handle->next) {
1078
1079                 radlog(L_INFO,"Detach perl 0x%lx", (unsigned long) handle->clone);
1080                 /*
1081                  * Wait until clone becomes idle
1082                  *
1083                  */
1084                 while (handle->status == busy) {
1085                 }
1086
1087                 /*
1088                  * Give a clones chance to run detach function
1089                  */
1090                 {
1091                 dTHXa(handle->clone);
1092                 PERL_SET_CONTEXT(handle->clone);
1093                 {
1094                 dSP; PUSHMARK(SP);
1095                 count = call_pv(inst->func_detach, G_SCALAR | G_EVAL );
1096                 SPAGAIN;
1097
1098                 if (count == 1) {
1099                         exitstatus = POPi;
1100                         /*
1101                          * FIXME: bug in perl
1102                          *
1103                          */
1104                         if (exitstatus >= 100 || exitstatus < 0) {
1105                                 exitstatus = RLM_MODULE_FAIL;
1106                         }
1107                 }
1108                 PUTBACK;
1109                 radlog(L_INFO,"detach at 0x%lx returned status %d",
1110                                 (unsigned long) handle->clone, exitstatus);
1111                 }
1112                 }
1113
1114         }
1115         /*
1116          *
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.
1120          *
1121          */
1122         {
1123         dTHXa(interp);
1124         PERL_SET_CONTEXT(interp);
1125 #endif /* USE_ITHREADS */
1126         {
1127         dSP;
1128         PUSHMARK(SP);
1129         count = call_pv(inst->func_detach, G_SCALAR | G_EVAL );
1130         SPAGAIN;
1131
1132         if (count == 1) {
1133                 exitstatus = POPi;
1134                 if (exitstatus >= 100 || exitstatus < 0) {
1135                         exitstatus = RLM_MODULE_FAIL;
1136                 }
1137         }
1138         PUTBACK;
1139         }
1140 #ifdef USE_ITHREADS
1141         }
1142 #endif
1143
1144         xlat_unregister(inst->xlat_name, perl_xlat);
1145         free(inst->xlat_name);
1146
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);
1153
1154         free(inst);
1155         return exitstatus;
1156 }
1157
1158 /*
1159  *      The module name should be the only globally exported symbol.
1160  *      That is, everything else should be 'static'.
1161  *
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.
1166  */
1167 module_t rlm_perl = {
1168         "perl",                         /* Name */
1169 #ifdef USE_ITHREADS
1170         RLM_TYPE_THREAD_SAFE,           /* type */
1171 #else
1172         RLM_TYPE_THREAD_UNSAFE,
1173 #endif
1174         perl_init,                      /* initialization */
1175         perl_instantiate,               /* instantiation */
1176         {
1177                 perl_authenticate,
1178                 perl_authorize,
1179                 perl_preacct,
1180                 perl_accounting,
1181                 perl_checksimul,        /* check simul */
1182                 NULL,                   /* pre-proxy */
1183                 NULL,                   /* post-proxy */
1184                 NULL                    /* post-auth */
1185         },
1186         perl_detach,                    /* detach */
1187         NULL,                           /* destroy */
1188 };