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