Massively cleaned up #include's, so they're in a consistent
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2002,2006  The FreeRADIUS server project
21  * Copyright 2002  Boian Jordanov <bjordanov@orbitel.bg>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29
30 #ifdef DEBUG
31 #undef DEBUG
32 #endif
33
34 #ifdef INADDR_ANY
35 #undef INADDR_ANY
36 #endif
37
38 #include <EXTERN.h>
39 #include <perl.h>
40 #include <XSUB.h>
41 #include <dlfcn.h>
42 #include <semaphore.h>
43
44 #ifdef __APPLE__
45 extern char **environ;
46 #endif
47
48 #ifdef USE_ITHREADS
49
50 /*
51  * Pool of Perl's clones (genetically cloned) ;)
52  *
53  */
54 typedef struct pool_handle {
55         struct pool_handle      *next;
56         struct pool_handle      *prev;
57         enum {busy, idle}       status;
58         unsigned int            request_count;
59         PerlInterpreter         *clone;
60         perl_mutex              lock;
61 } POOL_HANDLE;
62
63 typedef struct PERL_POOL {
64         POOL_HANDLE     *head;
65         POOL_HANDLE     *tail;
66
67         int             current_clones;
68         int             active_clones;
69         int             max_clones;
70         int             start_clones;
71         int             min_spare_clones;
72         int             max_spare_clones;
73         int             max_request_per_clone;
74         int             cleanup_delay;
75         enum {yes,no}   detach;
76         perl_mutex      mutex;
77         time_t          time_when_last_added;
78 } PERL_POOL;
79
80 #endif
81
82 /*
83  *      Define a structure for our module configuration.
84  *
85  *      These variables do not need to be in a structure, but it's
86  *      a lot cleaner to do so, and a pointer to the structure can
87  *      be used as the instance handle.
88  */
89 typedef struct perl_inst {
90         /* Name of the perl module */
91         char    *module;
92
93         /* Name of the functions for each module method */
94         char    *func_authorize;
95         char    *func_authenticate;
96         char    *func_accounting;
97         char    *func_start_accounting;
98         char    *func_stop_accounting;
99         char    *func_preacct;
100         char    *func_checksimul;
101         char    *func_detach;
102         char    *func_xlat;
103         char    *func_pre_proxy;
104         char    *func_post_proxy;
105         char    *func_post_auth;
106         char    *xlat_name;
107         char    *perl_flags;
108         PerlInterpreter *perl;
109 #ifdef USE_ITHREADS
110         PERL_POOL       *perl_pool;
111 #endif
112 } PERL_INST;
113 /*
114  *      A mapping of configuration file names to internal variables.
115  *
116  *      Note that the string is dynamically allocated, so it MUST
117  *      be freed.  When the configuration file parse re-reads the string,
118  *      it free's the old one, and strdup's the new one, placing the pointer
119  *      to the strdup'd string into 'config.string'.  This gets around
120  *      buffer over-flows.
121  */
122 static const CONF_PARSER module_config[] = {
123         { "module",  PW_TYPE_FILENAME,
124           offsetof(PERL_INST,module), NULL,  "module"},
125         { "func_authorize", PW_TYPE_STRING_PTR,
126           offsetof(PERL_INST,func_authorize), NULL, "authorize"},
127         { "func_authenticate", PW_TYPE_STRING_PTR,
128           offsetof(PERL_INST,func_authenticate), NULL, "authenticate"},
129         { "func_accounting", PW_TYPE_STRING_PTR,
130           offsetof(PERL_INST,func_accounting), NULL, "accounting"},
131         { "func_preacct", PW_TYPE_STRING_PTR,
132           offsetof(PERL_INST,func_preacct), NULL, "preacct"},
133         { "func_checksimul", PW_TYPE_STRING_PTR,
134           offsetof(PERL_INST,func_checksimul), NULL, "checksimul"},
135         { "func_detach", PW_TYPE_STRING_PTR,
136           offsetof(PERL_INST,func_detach), NULL, "detach"},
137         { "func_xlat", PW_TYPE_STRING_PTR,
138           offsetof(PERL_INST,func_xlat), NULL, "xlat"},
139         { "func_pre_proxy", PW_TYPE_STRING_PTR,
140           offsetof(PERL_INST,func_pre_proxy), NULL, "pre_proxy"},
141         { "func_post_proxy", PW_TYPE_STRING_PTR,
142           offsetof(PERL_INST,func_post_proxy), NULL, "post_proxy"},
143         { "func_post_auth", PW_TYPE_STRING_PTR,
144           offsetof(PERL_INST,func_post_auth), NULL, "post_auth"},
145         { "perl_flags", PW_TYPE_STRING_PTR,
146           offsetof(PERL_INST,perl_flags), NULL, NULL},
147         { "func_start_accounting", PW_TYPE_STRING_PTR,
148           offsetof(PERL_INST,func_start_accounting), NULL, NULL},
149         { "func_stop_accounting", PW_TYPE_STRING_PTR,
150           offsetof(PERL_INST,func_stop_accounting), NULL, NULL},
151
152         { NULL, -1, 0, NULL, NULL }             /* end the list */
153 };
154
155 /*
156  * man perlembed
157  */
158 EXTERN_C void boot_DynaLoader(pTHX_ CV* cv);
159
160 #ifdef USE_ITHREADS
161 /*
162  *      We use one perl to clone from it i.e. main boss
163  *      We clone it for every instance if we have perl
164  *      with -Duseithreads compiled in
165  */
166 static PerlInterpreter  *interp = NULL;
167
168 static const CONF_PARSER pool_conf[] = {
169         { "max_clones", PW_TYPE_INTEGER, offsetof(PERL_POOL, max_clones), NULL,         "32"},
170         { "start_clones",PW_TYPE_INTEGER, offsetof(PERL_POOL, start_clones), NULL,              "32"},
171         { "min_spare_clones",PW_TYPE_INTEGER, offsetof(PERL_POOL, min_spare_clones),NULL,       "0"},
172         { "max_spare_clones",PW_TYPE_INTEGER, offsetof(PERL_POOL,max_spare_clones),NULL,        "32"},
173         { "cleanup_delay",PW_TYPE_INTEGER, offsetof(PERL_POOL,cleanup_delay),NULL,              "5"},
174         { "max_request_per_clone",PW_TYPE_INTEGER, offsetof(PERL_POOL,max_request_per_clone),NULL,      "0"},
175         { NULL, -1, 0, NULL, NULL }             /* end the list */
176 };
177
178
179 #define dl_librefs "DynaLoader::dl_librefs"
180 #define dl_modules "DynaLoader::dl_modules"
181 static void rlm_perl_clear_handles(pTHX)
182 {
183         AV *librefs = get_av(dl_librefs, FALSE);
184         if (librefs) {
185                 av_clear(librefs);
186         }
187 }
188
189 static void **rlm_perl_get_handles(pTHX)
190 {
191         I32 i;
192         AV *librefs = get_av(dl_librefs, FALSE);
193         AV *modules = get_av(dl_modules, FALSE);
194         void **handles;
195
196         if (!librefs) {
197                 radlog(L_ERR,
198                    "Could not get @%s for unloading.\n",
199                    dl_librefs);
200                 return NULL;
201         }
202
203         if (!(AvFILL(librefs) >= 0)) {
204                 return NULL;
205         }
206
207         handles = (void **)rad_malloc(sizeof(void *) * (AvFILL(librefs)+2));
208
209         for (i=0; i<=AvFILL(librefs); i++) {
210                 void *handle;
211                 SV *handle_sv = *av_fetch(librefs, i, FALSE);
212
213                 if(!handle_sv) {
214                     radlog(L_ERR,
215                                "Could not fetch $%s[%d]!\n",
216                                dl_librefs, (int)i);
217                     continue;
218                 }
219                 handle = (void *)SvIV(handle_sv);
220
221                 if (handle) {
222                     handles[i] = handle;
223                 }
224         }
225
226         av_clear(modules);
227         av_clear(librefs);
228
229         handles[i] = (void *)0;
230
231         return handles;
232 }
233
234 static void rlm_perl_close_handles(void **handles)
235 {
236         int i;
237
238         if (!handles) {
239                 return;
240         }
241
242         for (i=0; handles[i]; i++) {
243                 radlog(L_DBG, "close 0x%lx\n", (unsigned long)handles[i]);
244                 dlclose(handles[i]);
245         }
246
247         free(handles);
248 }
249
250 static PerlInterpreter *rlm_perl_clone(PerlInterpreter *perl)
251 {
252         PerlInterpreter *clone;
253         UV clone_flags = 0;
254
255         PERL_SET_CONTEXT(perl);
256
257         clone = perl_clone(perl, clone_flags);
258         {
259                 dTHXa(clone);
260         }
261 #if PERL_REVISION >= 5 && PERL_VERSION <8
262         call_pv("CLONE",0);
263 #endif
264         ptr_table_free(PL_ptr_table);
265         PL_ptr_table = NULL;
266
267         PERL_SET_CONTEXT(aTHX);
268         rlm_perl_clear_handles(aTHX);
269
270         return clone;
271 }
272
273 static void rlm_perl_destruct(PerlInterpreter *perl)
274 {
275         char **orig_environ = NULL;
276         dTHXa(perl);
277
278         PERL_SET_CONTEXT(perl);
279
280         PL_perl_destruct_level = 2;
281
282         PL_origenviron = environ;
283
284         {
285                 dTHXa(perl);
286         }
287         /*
288          * FIXME: This shouldn't happen
289          *
290          */
291         while (PL_scopestack_ix > 1 ){
292                 LEAVE;
293         }
294
295         perl_destruct(perl);
296         perl_free(perl);
297
298         if (orig_environ) {
299                 environ = orig_environ;
300         }
301 }
302
303 static void rlm_destroy_perl(PerlInterpreter *perl)
304 {
305         void    **handles;
306
307         dTHXa(perl);
308         PERL_SET_CONTEXT(perl);
309
310         handles = rlm_perl_get_handles(aTHX);
311         rlm_perl_destruct(perl);
312         rlm_perl_close_handles(handles);
313 }
314
315 static void delete_pool_handle(POOL_HANDLE *handle, PERL_INST *inst)
316 {
317         POOL_HANDLE *prev;
318         POOL_HANDLE *next;
319
320         prev = handle->prev;
321         next = handle->next;
322
323         if (prev == NULL) {
324                 inst->perl_pool->head = next;
325         } else {
326                 prev->next = next;
327         }
328
329         if (next == NULL) {
330                 inst->perl_pool->tail = prev;
331         } else {
332                 next->prev = prev;
333         }
334         inst->perl_pool->current_clones--;
335         MUTEX_DESTROY(&handle->lock);
336         free(handle);
337 }
338
339 static void move2tail(POOL_HANDLE *handle, PERL_INST *inst)
340 {
341         POOL_HANDLE *prev;
342         POOL_HANDLE *next;
343
344         if (inst->perl_pool->head == NULL) {
345
346                 handle->prev = NULL;
347                 handle->next = NULL;
348                 inst->perl_pool->head = handle;
349                 inst->perl_pool->tail = handle;
350                 return;
351         }
352
353         if (inst->perl_pool->tail == handle) {
354                 return;
355         }
356
357         prev = handle->prev;
358         next = handle->next;
359
360         if ((next != NULL) ||
361                         (prev != NULL)) {
362                 if (next == NULL) {
363                         return;
364                 }
365
366                 if (prev == NULL) {
367                         inst->perl_pool->head = next;
368                         next->prev = NULL;
369
370                 } else {
371
372                         prev->next = next;
373                         next->prev = prev;
374                 }
375         }
376
377         handle->next = NULL;
378         prev = inst->perl_pool->tail;
379
380         inst->perl_pool->tail = handle;
381         handle->prev = prev;
382         prev->next = handle;
383 }
384
385
386 static POOL_HANDLE *pool_grow (PERL_INST *inst) {
387         POOL_HANDLE *handle;
388         time_t  now;
389
390         if (inst->perl_pool->max_clones == inst->perl_pool->current_clones) {
391                 return NULL;
392         }
393         if (inst->perl_pool->detach == yes ) {
394                 return NULL;
395         }
396
397         handle = (POOL_HANDLE *)rad_malloc(sizeof(POOL_HANDLE));
398
399         if (!handle) {
400                 radlog(L_ERR,"Could not find free memory for pool. Aborting");
401                 return NULL;
402         }
403
404         handle->prev = NULL;
405         handle->next = NULL;
406         handle->status = idle;
407         handle->clone = rlm_perl_clone(inst->perl);
408         handle->request_count = 0;
409         MUTEX_INIT(&handle->lock);
410         inst->perl_pool->current_clones++;
411         move2tail(handle, inst);
412
413         now = time(NULL);
414         inst->perl_pool->time_when_last_added = now;
415
416         return handle;
417 }
418
419 static POOL_HANDLE *pool_pop(PERL_INST *inst)
420 {
421         POOL_HANDLE     *handle;
422         POOL_HANDLE     *found;
423         POOL_HANDLE     *tmp;
424         /*
425          * Lock the pool and be fast other thread maybe
426          * waiting for us to finish
427          */
428         MUTEX_LOCK(&inst->perl_pool->mutex);
429
430         found = NULL;
431
432         for (handle = inst->perl_pool->head; handle ; handle = tmp) {
433                 tmp = handle->next;
434
435                 if (handle->status == idle){
436                         found = handle;
437                         break;
438                 }
439         }
440
441         if (found == NULL) {
442                 if (inst->perl_pool->current_clones < inst->perl_pool->max_clones ) {
443
444                         found = pool_grow(inst);
445
446                         if (found == NULL) {
447                                 radlog(L_ERR,"Cannot grow pool returning");
448                                 MUTEX_UNLOCK(&inst->perl_pool->mutex);
449                                 return NULL;
450                         }
451                 } else {
452                         radlog(L_ERR,"rlm_perl:: reached maximum clones %d cannot grow",
453                                         inst->perl_pool->current_clones);
454                         MUTEX_UNLOCK(&inst->perl_pool->mutex);
455                         return NULL;
456                 }
457         }
458
459         move2tail(found, inst);
460         found->status = busy;
461         MUTEX_LOCK(&found->lock);
462         inst->perl_pool->active_clones++;
463         found->request_count++;
464         /*
465          * Hurry Up
466          */
467         MUTEX_UNLOCK(&inst->perl_pool->mutex);
468         radlog(L_DBG,"perl_pool: item 0x%lx asigned new request. Handled so far: %d",
469                         (unsigned long) found->clone, found->request_count);
470         return found;
471 }
472 static int pool_release(POOL_HANDLE *handle, PERL_INST *inst) {
473
474         POOL_HANDLE *tmp, *tmp2;
475         int spare, i, t;
476         time_t  now;
477         /*
478          * Lock it
479          */
480         MUTEX_LOCK(&inst->perl_pool->mutex);
481
482         /*
483          * If detach is set then just release the mutex
484          */
485         if (inst->perl_pool->detach == yes ) {
486         handle->status = idle;
487                 MUTEX_UNLOCK(&handle->lock);
488                 MUTEX_UNLOCK(&inst->perl_pool->mutex);
489                 return 0;
490         }
491
492         MUTEX_UNLOCK(&handle->lock);
493         handle->status = idle;
494         inst->perl_pool->active_clones--;
495
496         spare = inst->perl_pool->current_clones - inst->perl_pool->active_clones;
497
498         radlog(L_DBG,"perl_pool total/active/spare [%d/%d/%d]"
499                         , inst->perl_pool->current_clones, inst->perl_pool->active_clones, spare);
500
501         if (spare < inst->perl_pool->min_spare_clones) {
502                 t = inst->perl_pool->min_spare_clones - spare;
503                 for (i=0;i<t; i++) {
504                         if ((tmp = pool_grow(inst)) == NULL) {
505                                 MUTEX_UNLOCK(&inst->perl_pool->mutex);
506                                 return -1;
507                         }
508                 }
509                 MUTEX_UNLOCK(&inst->perl_pool->mutex);
510                 return 0;
511         }
512         now = time(NULL);
513         if ((now - inst->perl_pool->time_when_last_added) < inst->perl_pool->cleanup_delay) {
514                 MUTEX_UNLOCK(&inst->perl_pool->mutex);
515                 return 0;
516         }
517         if (spare > inst->perl_pool->max_spare_clones) {
518                 spare -= inst->perl_pool->max_spare_clones;
519                 for (tmp = inst->perl_pool->head; (tmp !=NULL ) && (spare > 0) ; tmp = tmp2) {
520                         tmp2 = tmp->next;
521
522                         if(tmp->status == idle) {
523                                 rlm_destroy_perl(tmp->clone);
524                                 delete_pool_handle(tmp,inst);
525                                 spare--;
526                                 break;
527                         }
528                 }
529         }
530         /*
531          * If the clone have reached max_request_per_clone clean it.
532          */
533         if (inst->perl_pool->max_request_per_clone > 0 ) {
534                         if (handle->request_count > inst->perl_pool->max_request_per_clone) {
535                                 rlm_destroy_perl(handle->clone);
536                                 delete_pool_handle(handle,inst);
537                 }
538         }
539         /*
540          * Hurry Up :)
541          */
542         MUTEX_UNLOCK(&inst->perl_pool->mutex);
543         return 0;
544 }
545 static int init_pool (CONF_SECTION *conf, PERL_INST *inst) {
546         POOL_HANDLE     *handle;
547         int t;
548         PERL_POOL       *pool;
549
550
551         pool = rad_malloc(sizeof(PERL_POOL));
552         memset(pool,0,sizeof(PERL_POOL));
553
554         inst->perl_pool = pool;
555
556         MUTEX_INIT(&pool->mutex);
557
558         /*
559          * Read The Config
560          *
561          */
562
563         cf_section_parse(conf,pool,pool_conf);
564         inst->perl_pool = pool;
565         inst->perl_pool->detach = no;
566
567         for(t = 0;t < inst->perl_pool->start_clones ;t++){
568                 if ((handle = pool_grow(inst)) == NULL) {
569                         return -1;
570                 }
571
572         }
573
574         return 1;
575 }
576 #endif
577
578 static void xs_init(pTHX)
579 {
580         char *file = __FILE__;
581
582         /* DynaLoader is a special case */
583         newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
584
585 }
586 /*
587  *
588  * This is wrapper for radlog
589  * Now users can call radiusd::radlog(level,msg) wich is the same
590  * calling radlog from C code.
591  * Boyan
592  */
593 static XS(XS_radiusd_radlog)
594 {
595        dXSARGS;
596        if (items !=2)
597                croak("Usage: radiusd::radlog(level, message)");
598        {
599                int     level;
600                char    *msg;
601
602                level = (int) SvIV(ST(0));
603                msg   = (char *) SvPV(ST(1), PL_na);
604
605                /*
606                 *       Because 'msg' is a 'char *', we don't want '%s', etc.
607                 *       in it to give us printf-style vulnerabilities.
608                 */
609                radlog(level, "rlm_perl: %s", msg);
610         }
611        XSRETURN_NO;
612 }
613
614 /*
615  * The xlat function
616  */
617 static int perl_xlat(void *instance, REQUEST *request, char *fmt, char * out,
618                      size_t freespace, RADIUS_ESCAPE_STRING func)
619 {
620
621         PERL_INST       *inst= (PERL_INST *) instance;
622         PerlInterpreter *perl;
623         char            params[1024], *ptr, *tmp;
624         int             count, ret=0;
625         STRLEN          n_a;
626
627         /*
628          * Do an xlat on the provided string (nice recursive operation).
629         */
630         if (!radius_xlat(params, sizeof(params), fmt, request, func)) {
631                 radlog(L_ERR, "rlm_perl: xlat failed.");
632                 return 0;
633         }
634 #ifndef USE_ITHREADS
635         perl = inst->perl;
636 #endif
637 #ifdef USE_ITHREADS
638         POOL_HANDLE     *handle;
639
640         if ((handle = pool_pop(instance)) == NULL) {
641                 return 0;
642         }
643
644         perl = handle->clone;
645
646         radlog(L_DBG,"Found a interpetator 0x%lx",(unsigned long) perl);
647         {
648         dTHXa(perl);
649         }
650 #endif
651         PERL_SET_CONTEXT(perl);
652         {
653         dSP;
654         ENTER;SAVETMPS;
655
656         ptr = strtok(params, " ");
657
658         PUSHMARK(SP);
659
660         while (ptr != NULL) {
661                 XPUSHs(sv_2mortal(newSVpv(ptr,0)));
662                 ptr = strtok(NULL, " ");
663         }
664
665         PUTBACK;
666
667         count = call_pv(inst->func_xlat, G_SCALAR | G_EVAL);
668
669         SPAGAIN;
670         if (SvTRUE(ERRSV)) {
671                 radlog(L_ERR, "rlm_perl: perl_xlat exit %s\n",
672                        SvPV(ERRSV,n_a));
673                 POPs ;
674         } else if (count > 0) {
675                 tmp = POPp;
676                 strlcpy(out, tmp, freespace);
677                 ret = strlen(out);
678
679                 radlog(L_DBG,"rlm_perl: Len is %d , out is %s freespace is %d",
680                        ret, out,freespace);
681         }
682
683         PUTBACK ;
684         FREETMPS ;
685         LEAVE ;
686
687         }
688 #ifdef USE_ITHREADS
689         pool_release(handle, instance);
690 #endif
691         return ret;
692 }
693 /*
694  *      Do any per-module initialization that is separate to each
695  *      configured instance of the module.  e.g. set up connections
696  *      to external databases, read configuration files, set up
697  *      dictionary entries, etc.
698  *
699  *      If configuration information is given in the config section
700  *      that must be referenced in later calls, store a handle to it
701  *      in *instance otherwise put a null pointer there.
702  *
703  *      Boyan:
704  *      Setup a hashes wich we will use later
705  *      parse a module and give him a chance to live
706  *
707  */
708 static int perl_instantiate(CONF_SECTION *conf, void **instance)
709 {
710         PERL_INST       *inst = (PERL_INST *) instance;
711         HV              *rad_reply_hv;
712         HV              *rad_check_hv;
713         HV              *rad_config_hv;
714         HV              *rad_request_hv;
715         HV              *rad_request_proxy_hv;
716         HV              *rad_request_proxy_reply_hv;
717         AV              *end_AV;
718
719         char *embed[4];
720         const char *xlat_name;
721         int exitstatus = 0, argc=0;
722
723         /*
724          *      Set up a storage area for instance data
725          */
726         inst = rad_malloc(sizeof(PERL_INST));
727         memset(inst, 0, sizeof(PERL_INST));
728
729         /*
730          *      If the configuration parameters can't be parsed, then
731          *      fail.
732          */
733         if (cf_section_parse(conf, inst, module_config) < 0) {
734                 free(inst);
735                 return -1;
736         }
737
738
739         embed[0] = NULL;
740         if (inst->perl_flags) {
741                 embed[1] = inst->perl_flags;
742                 embed[2] = inst->module;
743                 embed[3] = "0";
744                 argc = 4;
745         } else {
746                 embed[1] = inst->module;
747                 embed[2] = "0";
748                 argc = 3;
749         }
750
751 #ifdef USE_ITHREADS
752         inst->perl = interp;
753         
754         if ((inst->perl = perl_alloc()) == NULL) {
755                 radlog(L_DBG, "rlm_perl: No memory for allocating new perl !");
756                 return (-1);
757         }
758                 
759         perl_construct(inst->perl);
760         PL_perl_destruct_level = 2;
761
762         {
763         dTHXa(inst->perl);
764         }
765         PERL_SET_CONTEXT(inst->perl);
766 #else
767         if ((inst->perl = perl_alloc()) == NULL) {
768                 radlog(L_ERR, "rlm_perl: No memory for allocating new perl !");
769                 return -1;
770         }
771
772         perl_construct(inst->perl);
773 #endif
774
775 #if PERL_REVISION >= 5 && PERL_VERSION >=8
776         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
777 #endif
778
779         exitstatus = perl_parse(inst->perl, xs_init, argc, embed, NULL);
780
781         end_AV = PL_endav;
782         PL_endav = Nullav;
783
784         if(!exitstatus) {
785                 exitstatus = perl_run(inst->perl);
786         } else {
787                 radlog(L_ERR,"rlm_perl: perl_parse failed: %s not found or has syntax errors. \n", inst->module);
788                 return (-1);
789         }
790
791         PL_endav = end_AV;
792
793         newXS("radiusd::radlog",XS_radiusd_radlog, "rlm_perl.c");
794
795         rad_reply_hv = newHV();
796         rad_check_hv = newHV();
797         rad_config_hv = newHV();
798         rad_request_hv = newHV();
799         rad_request_proxy_hv = newHV();
800         rad_request_proxy_reply_hv = newHV();
801
802         rad_reply_hv = get_hv("RAD_REPLY",1);
803         rad_check_hv = get_hv("RAD_CHECK",1);
804         rad_config_hv = get_hv("RAD_CONFIG",1);
805         rad_request_hv = get_hv("RAD_REQUEST",1);
806         rad_request_proxy_hv = get_hv("RAD_REQUEST_PROXY",1);
807         rad_request_proxy_reply_hv = get_hv("RAD_REQUEST_PROXY_REPLY",1);
808
809         xlat_name = cf_section_name2(conf);
810         if (xlat_name == NULL)
811                 xlat_name = cf_section_name1(conf);
812         if (xlat_name){
813                 inst->xlat_name = strdup(xlat_name);
814                 xlat_register(xlat_name, perl_xlat, inst);
815         }
816
817 #ifdef USE_ITHREADS
818         if ((init_pool(conf, inst)) == -1) {
819                 radlog(L_ERR,"Couldn't init a pool of perl clones. Exiting");
820                 return -1;
821         }
822
823 #endif
824         *instance = inst;
825
826         return 0;
827 }
828
829 /*
830  *      get the vps and put them in perl hash
831  *      If one VP have multiple values it is added as array_ref
832  *      Example for this is Cisco-AVPair that holds multiple values.
833  *      Which will be available as array_ref in $RAD_REQUEST{'Cisco-AVPair'}
834  */
835 static void perl_store_vps(VALUE_PAIR *vp, HV *rad_hv)
836 {
837         VALUE_PAIR      *nvp, *vpa, *vpn;
838         AV              *av;
839         char            buffer[1024];
840         int             attr, len;
841
842         hv_undef(rad_hv);
843         nvp = paircopy(vp);
844
845         while (nvp != NULL) {
846                 attr = nvp->attribute;
847                 vpa = paircopy2(nvp,attr);
848                 if (vpa->next) {
849                         av = newAV();
850                         vpn = vpa;
851                         while (vpn) {
852                                 len = vp_prints_value(buffer, sizeof(buffer),
853                                                 vpn, FALSE);
854                                 av_push(av, newSVpv(buffer, len));
855                                 vpn = vpn->next;
856                         }
857                         hv_store(rad_hv, nvp->name, strlen(nvp->name),
858                                         newRV_noinc((SV *) av), 0);
859                 } else {
860                         len = vp_prints_value(buffer, sizeof(buffer),
861                                         vpa, FALSE);
862                         hv_store(rad_hv, vpa->name, strlen(vpa->name),
863                                         newSVpv(buffer, len), 0);
864                 }
865
866                 pairfree(&vpa);
867                 vpa = nvp; while ((vpa != NULL) && (vpa->attribute == attr))
868                         vpa = vpa->next;
869                 pairdelete(&nvp, attr);
870                 nvp = vpa;
871         }
872 }
873
874 /*
875  *
876  *     Verify that a Perl SV is a string and save it in FreeRadius
877  *     Value Pair Format
878  *
879  */
880 static int pairadd_sv(VALUE_PAIR **vp, char *key, SV *sv, int operator) {
881        char            *val;
882        VALUE_PAIR      *vpp;
883
884        if (SvOK(sv)) {
885                val = SvPV_nolen(sv);
886                vpp = pairmake(key, val, operator);
887                if (vpp != NULL) {
888                        pairadd(vp, vpp);
889                        radlog(L_DBG,
890                          "rlm_perl: Added pair %s = %s", key, val);
891                        return 1;
892                } else {
893                        radlog(L_DBG,
894                          "rlm_perl: ERROR: Failed to create pair %s = %s",
895                          key, val);
896                }
897         }
898        return 0;
899 }
900
901 /*
902   *     Boyan :
903   *     Gets the content from hashes
904   */
905 static int get_hv_content(HV *my_hv, VALUE_PAIR **vp)
906 {
907        SV               *res_sv, **av_sv;
908        AV               *av;
909        char             *key;
910        I32              key_len, len, i, j;
911        int              ret=0;
912
913        *vp = NULL;
914        for (i = hv_iterinit(my_hv); i > 0; i--) {
915                res_sv = hv_iternextsv(my_hv,&key,&key_len);
916                if (SvROK(res_sv) && (SvTYPE(SvRV(res_sv)) == SVt_PVAV)) {
917                        av = (AV*)SvRV(res_sv);
918                        len = av_len(av);
919                        for (j = 0; j <= len; j++) {
920                                av_sv = av_fetch(av, j, 0);
921                                ret = pairadd_sv(vp, key, *av_sv, T_OP_ADD) + ret;
922                        }
923                } else ret = pairadd_sv(vp, key, res_sv, T_OP_EQ) + ret;
924         }
925
926         return ret;
927 }
928
929 /*
930  *      Call the function_name inside the module
931  *      Store all vps in hashes %RAD_CHECK %RAD_REPLY %RAD_REQUEST
932  *
933  */
934 static int rlmperl_call(void *instance, REQUEST *request, char *function_name)
935 {
936
937         PERL_INST       *inst = instance;
938         VALUE_PAIR      *vp;
939         int             exitstatus=0, count;
940         STRLEN          n_a;
941
942         HV              *rad_reply_hv;
943         HV              *rad_check_hv;
944         HV              *rad_config_hv;
945         HV              *rad_request_hv;
946         HV              *rad_request_proxy_hv;
947         HV              *rad_request_proxy_reply_hv;
948
949 #ifdef USE_ITHREADS
950         POOL_HANDLE     *handle;
951
952         if ((handle = pool_pop(instance)) == NULL) {
953                 return RLM_MODULE_FAIL;
954         }
955
956         radlog(L_DBG,"found interpetator at address 0x%lx",(unsigned long) handle->clone);
957         {
958         dTHXa(handle->clone);
959         PERL_SET_CONTEXT(handle->clone);
960         }
961 #else
962         PERL_SET_CONTEXT(inst->perl);
963         radlog(L_DBG,"Using perl at 0x%lx",(unsigned long) inst->perl);
964 #endif
965         {
966         dSP;
967
968         ENTER;
969         SAVETMPS;
970
971
972         /*
973          *      Radius has told us to call this function, but none
974          *      is defined.
975          */
976         if (!function_name) {
977                 return RLM_MODULE_FAIL;
978         }
979
980         rad_reply_hv = get_hv("RAD_REPLY",1);
981         rad_check_hv = get_hv("RAD_CHECK",1);
982         rad_config_hv = get_hv("RAD_CONFIG",1);
983         rad_request_hv = get_hv("RAD_REQUEST",1);
984         rad_request_proxy_hv = get_hv("RAD_REQUEST_PROXY",1);
985         rad_request_proxy_reply_hv = get_hv("RAD_REQUEST_PROXY_REPLY",1);
986
987
988         perl_store_vps(request->reply->vps, rad_reply_hv);
989         perl_store_vps(request->config_items, rad_check_hv);
990         perl_store_vps(request->packet->vps, rad_request_hv);
991         perl_store_vps(request->config_items, rad_config_hv);
992         
993         if (request->proxy != NULL) {
994                 perl_store_vps(request->proxy->vps, rad_request_proxy_hv);
995         } else {
996                 hv_undef(rad_request_proxy_hv);
997         }
998
999         if (request->proxy_reply !=NULL) {
1000                 perl_store_vps(request->proxy_reply->vps, rad_request_proxy_reply_hv);
1001         } else {
1002                 hv_undef(rad_request_proxy_reply_hv);
1003         }       
1004         
1005         PUSHMARK(SP);
1006         /*
1007         * This way %RAD_xx can be pushed onto stack as sub parameters.
1008         * XPUSHs( newRV_noinc((SV *)rad_request_hv) );
1009         * XPUSHs( newRV_noinc((SV *)rad_reply_hv) );
1010         * XPUSHs( newRV_noinc((SV *)rad_check_hv) );
1011         * PUTBACK;
1012         */
1013
1014         count = call_pv(function_name, G_SCALAR | G_EVAL | G_NOARGS);
1015
1016         SPAGAIN;
1017
1018         if (SvTRUE(ERRSV)) {
1019                 radlog(L_ERR, "rlm_perl: perl_embed:: module = %s , func = %s exit status= %s\n",
1020                        inst->module,
1021                        function_name, SvPV(ERRSV,n_a));
1022                 POPs;
1023         }
1024
1025         if (count == 1) {
1026                 exitstatus = POPi;
1027                 if (exitstatus >= 100 || exitstatus < 0) {
1028                         exitstatus = RLM_MODULE_FAIL;
1029                 }
1030         }
1031         
1032
1033         PUTBACK;
1034         FREETMPS;
1035         LEAVE;
1036         
1037         vp = NULL;
1038         if ((get_hv_content(rad_request_hv, &vp)) > 0 ) {
1039                 pairfree(&request->packet->vps);
1040                 request->packet->vps = vp;
1041                 vp = NULL;
1042
1043                 /*
1044                  *      Update cached copies
1045                  */
1046                 request->username = pairfind(request->packet->vps,
1047                                              PW_USER_NAME);
1048                 request->password = pairfind(request->packet->vps,
1049                                              PW_USER_PASSWORD);
1050                 if (!request->password)
1051                         request->password = pairfind(request->packet->vps,
1052                                                      PW_CHAP_PASSWORD);
1053         }
1054
1055         if ((get_hv_content(rad_reply_hv, &vp)) > 0 ) {
1056                 pairfree(&request->reply->vps);
1057                 request->reply->vps = vp;
1058                 vp = NULL;
1059         }
1060
1061         if ((get_hv_content(rad_check_hv, &vp)) > 0 ) {
1062                 pairfree(&request->config_items);
1063                 request->config_items = vp;
1064                 vp = NULL;
1065         }
1066         
1067         if (request->proxy &&
1068             (get_hv_content(rad_request_proxy_hv, &vp) > 0)) {
1069                 pairfree(&request->proxy->vps);
1070                 request->proxy->vps = vp;
1071                 vp = NULL;
1072         }
1073
1074         if (request->proxy_reply &&
1075             (get_hv_content(rad_request_proxy_reply_hv, &vp) > 0)) {
1076                 pairfree(&request->proxy_reply->vps);
1077                 request->proxy_reply->vps = vp;
1078                 vp = NULL;
1079         }
1080
1081         }
1082 #ifdef USE_ITHREADS
1083         pool_release(handle,instance);
1084         radlog(L_DBG,"Unreserve perl at address 0x%lx", (unsigned long) handle->clone);
1085 #endif
1086
1087         return exitstatus;
1088 }
1089
1090 /*
1091  *      Find the named user in this modules database.  Create the set
1092  *      of attribute-value pairs to check and reply with for this user
1093  *      from the database. The authentication code only needs to check
1094  *      the password, the rest is done here.
1095  */
1096 static int perl_authorize(void *instance, REQUEST *request)
1097 {
1098         return rlmperl_call(instance, request,
1099                             ((PERL_INST *)instance)->func_authorize);
1100 }
1101
1102 /*
1103  *      Authenticate the user with the given password.
1104  */
1105 static int perl_authenticate(void *instance, REQUEST *request)
1106 {
1107         return rlmperl_call(instance, request,
1108                             ((PERL_INST *)instance)->func_authenticate);
1109 }
1110 /*
1111  *      Massage the request before recording it or proxying it
1112  */
1113 static int perl_preacct(void *instance, REQUEST *request)
1114 {
1115         return rlmperl_call(instance, request,
1116                             ((PERL_INST *)instance)->func_preacct);
1117 }
1118 /*
1119  *      Write accounting information to this modules database.
1120  */
1121 static int perl_accounting(void *instance, REQUEST *request)
1122 {
1123         VALUE_PAIR      *pair;
1124         int             acctstatustype=0;
1125
1126         if ((pair = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE)) != NULL) {
1127                 acctstatustype = pair->lvalue;
1128         } else {
1129                 radlog(L_ERR, "Invalid Accounting Packet");
1130                 return RLM_MODULE_INVALID;
1131         }
1132
1133         switch (acctstatustype) {
1134
1135                 case PW_STATUS_START:
1136
1137                         if (((PERL_INST *)instance)->func_start_accounting) {
1138                                 return rlmperl_call(instance, request,
1139                                             ((PERL_INST *)instance)->func_start_accounting);
1140                         } else {
1141                                 return rlmperl_call(instance, request,
1142                                             ((PERL_INST *)instance)->func_accounting);
1143                         }
1144                         break;
1145
1146                 case PW_STATUS_STOP:
1147
1148                         if (((PERL_INST *)instance)->func_stop_accounting) {
1149                                 return rlmperl_call(instance, request,
1150                                             ((PERL_INST *)instance)->func_stop_accounting);
1151                         } else {
1152                                 return rlmperl_call(instance, request,
1153                                             ((PERL_INST *)instance)->func_accounting);
1154                         }
1155                         break;
1156                 default:
1157                         return rlmperl_call(instance, request,
1158                                             ((PERL_INST *)instance)->func_accounting);
1159
1160         }
1161 }
1162 /*
1163  *      Check for simultaneouse-use
1164  */
1165 static int perl_checksimul(void *instance, REQUEST *request)
1166 {
1167         return rlmperl_call(instance, request,
1168                         ((PERL_INST *)instance)->func_checksimul);
1169 }
1170 /*
1171  *      Pre-Proxy request
1172  */
1173 static int perl_pre_proxy(void *instance, REQUEST *request)
1174 {
1175         return rlmperl_call(instance, request,
1176                         ((PERL_INST *)instance)->func_pre_proxy);
1177 }
1178 /*
1179  *      Post-Proxy request
1180  */
1181 static int perl_post_proxy(void *instance, REQUEST *request)
1182 {
1183         return rlmperl_call(instance, request,
1184                         ((PERL_INST *)instance)->func_post_proxy);
1185 }
1186 /*
1187  *      Pre-Auth request
1188  */
1189 static int perl_post_auth(void *instance, REQUEST *request)
1190 {
1191         return rlmperl_call(instance, request,
1192                         ((PERL_INST *)instance)->func_post_auth);
1193 }
1194 /*
1195  * Detach a instance give a chance to a module to make some internal setup ...
1196  */
1197 static int perl_detach(void *instance)
1198 {
1199         PERL_INST       *inst = (PERL_INST *) instance;
1200         int             exitstatus = 0, count = 0;
1201
1202 #ifdef USE_ITHREADS
1203         POOL_HANDLE     *handle, *tmp, *tmp2;
1204
1205         MUTEX_LOCK(&inst->perl_pool->mutex);
1206         inst->perl_pool->detach = yes;
1207         MUTEX_UNLOCK(&inst->perl_pool->mutex);
1208
1209         for (handle = inst->perl_pool->head; handle != NULL; handle = handle->next) {
1210
1211                 radlog(L_DBG,"Detach perl 0x%lx", (unsigned long) handle->clone);
1212                 /*
1213                  * Wait until clone becomes idle
1214                  */
1215                 MUTEX_LOCK(&handle->lock);
1216
1217                 /*
1218                  * Give a clones chance to run detach function
1219                  */
1220                 {
1221                 dTHXa(handle->clone);
1222                 PERL_SET_CONTEXT(handle->clone);
1223                 {
1224                 dSP; ENTER; SAVETMPS; PUSHMARK(SP);
1225                 count = call_pv(inst->func_detach, G_SCALAR | G_EVAL );
1226                 SPAGAIN;
1227
1228                 if (count == 1) {
1229                         exitstatus = POPi;
1230                         /*
1231                          * FIXME: bug in perl
1232                          *
1233                          */
1234                         if (exitstatus >= 100 || exitstatus < 0) {
1235                                 exitstatus = RLM_MODULE_FAIL;
1236                         }
1237                 }
1238                 PUTBACK;
1239                 FREETMPS;
1240                 LEAVE;
1241                 radlog(L_DBG,"detach at 0x%lx returned status %d",
1242                                 (unsigned long) handle->clone, exitstatus);
1243                 }
1244                 }
1245                 MUTEX_UNLOCK(&handle->lock);
1246         }
1247         /*
1248          * Free handles
1249          */
1250
1251         for (tmp = inst->perl_pool->head; tmp !=NULL  ; tmp = tmp2) {
1252                 tmp2 = tmp->next;
1253                 radlog(L_DBG,"rlm_perl:: Destroy perl");
1254                 rlm_perl_destruct(tmp->clone);
1255                 delete_pool_handle(tmp,inst);
1256         }
1257
1258         {
1259         dTHXa(inst->perl);
1260 #endif /* USE_ITHREADS */
1261         PERL_SET_CONTEXT(inst->perl);
1262         {
1263         dSP; ENTER; SAVETMPS;
1264         PUSHMARK(SP);
1265
1266         count = call_pv(inst->func_detach, G_SCALAR | G_EVAL );
1267         SPAGAIN;
1268
1269         if (count == 1) {
1270                 exitstatus = POPi;
1271                 if (exitstatus >= 100 || exitstatus < 0) {
1272                         exitstatus = RLM_MODULE_FAIL;
1273                 }
1274         }
1275         PUTBACK;
1276         FREETMPS;
1277         LEAVE;
1278         }
1279 #ifdef USE_ITHREADS
1280         }
1281 #endif
1282
1283         xlat_unregister(inst->xlat_name, perl_xlat);
1284         free(inst->xlat_name);
1285
1286
1287 #ifdef USE_ITHREADS
1288         free(inst->perl_pool->head);
1289         free(inst->perl_pool->tail);
1290         MUTEX_DESTROY(&inst->perl_pool->mutex);
1291         free(inst->perl_pool);
1292         rlm_perl_destruct(inst->perl);
1293 #else
1294         perl_destruct(inst->perl);
1295         perl_free(inst->perl);
1296 #endif
1297
1298         free(inst);
1299         return exitstatus;
1300 }
1301 /*
1302  *      The module name should be the only globally exported symbol.
1303  *      That is, everything else should be 'static'.
1304  *
1305  *      If the module needs to temporarily modify it's instantiation
1306  *      data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
1307  *      The server will then take care of ensuring that the module
1308  *      is single-threaded.
1309  */
1310 module_t rlm_perl = {
1311         RLM_MODULE_INIT,
1312         "perl",                         /* Name */
1313 #ifdef USE_ITHREADS
1314         RLM_TYPE_THREAD_SAFE,           /* type */
1315 #else
1316         RLM_TYPE_THREAD_UNSAFE,
1317 #endif
1318         perl_instantiate,               /* instantiation */
1319         perl_detach,                    /* detach */
1320         {
1321                 perl_authenticate,      /* authenticate */
1322                 perl_authorize,         /* authorize */
1323                 perl_preacct,           /* preacct */
1324                 perl_accounting,        /* accounting */
1325                 perl_checksimul,        /* check simul */
1326                 perl_pre_proxy,         /* pre-proxy */
1327                 perl_post_proxy,        /* post-proxy */
1328                 perl_post_auth          /* post-auth */
1329         },
1330 };