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