Fix error in attribute copying to rlm_perl
[freeradius.git] / src / modules / rlm_perl / rlm_perl.c
1 /*
2  *   This program is is free software; you can redistribute it and/or modify
3  *   it under the terms of the GNU General Public License, version 2 if the
4  *   License as published by the Free Software Foundation.
5  *
6  *   This program is distributed in the hope that it will be useful,
7  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
8  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9  *   GNU General Public License for more details.
10  *
11  *   You should have received a copy of the GNU General Public License
12  *   along with this program; if not, write to the Free Software
13  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
14  */
15
16 /**
17  * $Id$
18  * @file rlm_perl.c
19  * @brief Translates requests between the server an a perl interpreter.
20  *
21  * @copyright 2002,2006  The FreeRADIUS server project
22  * @copyright 2002  Boian Jordanov <bjordanov@orbitel.bg>
23  */
24 RCSID("$Id$")
25
26 #include <freeradius-devel/radiusd.h>
27 #include <freeradius-devel/modules.h>
28 #include <freeradius-devel/rad_assert.h>
29
30 #ifdef INADDR_ANY
31 #undef INADDR_ANY
32 #endif
33 #include <EXTERN.h>
34 #include <perl.h>
35 #include <XSUB.h>
36 #include <dlfcn.h>
37 #include <semaphore.h>
38
39 #ifdef __APPLE__
40 extern char **environ;
41 #endif
42
43 /*
44  *      Define a structure for our module configuration.
45  *
46  *      These variables do not need to be in a structure, but it's
47  *      a lot cleaner to do so, and a pointer to the structure can
48  *      be used as the instance handle.
49  */
50 typedef struct rlm_perl_t {
51         /* Name of the perl module */
52         char const      *module;
53
54         /* Name of the functions for each module method */
55         char const      *func_authorize;
56         char const      *func_authenticate;
57         char const      *func_accounting;
58         char const      *func_start_accounting;
59         char const      *func_stop_accounting;
60         char const      *func_preacct;
61         char const      *func_checksimul;
62         char const      *func_detach;
63         char const      *func_xlat;
64 #ifdef WITH_PROXY
65         char const      *func_pre_proxy;
66         char const      *func_post_proxy;
67 #endif
68         char const      *func_post_auth;
69 #ifdef WITH_COA
70         char const      *func_recv_coa;
71         char const      *func_send_coa;
72 #endif
73         char const      *xlat_name;
74         char const      *perl_flags;
75         PerlInterpreter *perl;
76         pthread_key_t   *thread_key;
77
78 #ifdef USE_ITHREADS
79         pthread_mutex_t clone_mutex;
80 #endif
81
82         HV              *rad_perlconf_hv;       //!< holds "config" items (perl %RAD_PERLCONF hash).
83
84 } rlm_perl_t;
85 /*
86  *      A mapping of configuration file names to internal variables.
87  */
88 #define RLM_PERL_CONF(_x) { "func_" STRINGIFY(_x), PW_TYPE_STRING, \
89                         offsetof(rlm_perl_t,func_##_x), NULL, STRINGIFY(_x)}
90
91 static const CONF_PARSER module_config[] = {
92         { "module", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, rlm_perl_t, module), NULL },
93         { "filename", FR_CONF_OFFSET(PW_TYPE_FILE_INPUT | PW_TYPE_REQUIRED, rlm_perl_t, module), NULL },
94
95         RLM_PERL_CONF(authorize),
96         RLM_PERL_CONF(authenticate),
97         RLM_PERL_CONF(post_auth),
98         RLM_PERL_CONF(accounting),
99         RLM_PERL_CONF(preacct),
100         RLM_PERL_CONF(checksimul),
101         RLM_PERL_CONF(detach),
102         RLM_PERL_CONF(xlat),
103
104 #ifdef WITH_PROXY
105         RLM_PERL_CONF(pre_proxy),
106         RLM_PERL_CONF(post_proxy),
107 #endif
108 #ifdef WITH_COA
109         RLM_PERL_CONF(recv_coa),
110         RLM_PERL_CONF(send_coa),
111 #endif
112         { "perl_flags", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_perl_t, perl_flags), NULL },
113
114         { "func_start_accounting", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_perl_t, func_start_accounting), NULL },
115
116         { "func_stop_accounting", FR_CONF_OFFSET(PW_TYPE_STRING, rlm_perl_t, func_stop_accounting), NULL },
117
118         { NULL, -1, 0, NULL, NULL }             /* end the list */
119 };
120
121 /*
122  * man perlembed
123  */
124 EXTERN_C void boot_DynaLoader(pTHX_ CV* cv);
125
126 #ifdef USE_ITHREADS
127 #define dl_librefs "DynaLoader::dl_librefs"
128 #define dl_modules "DynaLoader::dl_modules"
129 static void rlm_perl_clear_handles(pTHX)
130 {
131         AV *librefs = get_av(dl_librefs, false);
132         if (librefs) {
133                 av_clear(librefs);
134         }
135 }
136
137 static void **rlm_perl_get_handles(pTHX)
138 {
139         I32 i;
140         AV *librefs = get_av(dl_librefs, false);
141         AV *modules = get_av(dl_modules, false);
142         void **handles;
143
144         if (!librefs) return NULL;
145
146         if (!(AvFILL(librefs) >= 0)) {
147                 return NULL;
148         }
149
150         handles = (void **)rad_malloc(sizeof(void *) * (AvFILL(librefs)+2));
151
152         for (i=0; i<=AvFILL(librefs); i++) {
153                 void *handle;
154                 SV *handle_sv = *av_fetch(librefs, i, false);
155
156                 if(!handle_sv) {
157                         ERROR("Could not fetch $%s[%d]!\n",
158                                dl_librefs, (int)i);
159                         continue;
160                 }
161                 handle = (void *)SvIV(handle_sv);
162
163                 if (handle) {
164                         handles[i] = handle;
165                 }
166         }
167
168         av_clear(modules);
169         av_clear(librefs);
170
171         handles[i] = (void *)0;
172
173         return handles;
174 }
175
176 static void rlm_perl_close_handles(void **handles)
177 {
178         int i;
179
180         if (!handles) {
181                 return;
182         }
183
184         for (i=0; handles[i]; i++) {
185                 DEBUG("close %p\n", handles[i]);
186                 dlclose(handles[i]);
187         }
188
189         free(handles);
190 }
191
192 DIAG_OFF(shadow)
193 static void rlm_perl_destruct(PerlInterpreter *perl)
194 {
195         dTHXa(perl);
196
197         PERL_SET_CONTEXT(perl);
198
199         PL_perl_destruct_level = 2;
200
201         PL_origenviron = environ;
202
203
204         {
205                 dTHXa(perl);
206         }
207         /*
208          * FIXME: This shouldn't happen
209          *
210          */
211         while (PL_scopestack_ix > 1 ){
212                 LEAVE;
213         }
214
215         perl_destruct(perl);
216         perl_free(perl);
217 }
218 DIAG_ON(shadow)
219
220 static void rlm_destroy_perl(PerlInterpreter *perl)
221 {
222         void    **handles;
223
224         dTHXa(perl);
225         PERL_SET_CONTEXT(perl);
226
227         handles = rlm_perl_get_handles(aTHX);
228         if (handles) rlm_perl_close_handles(handles);
229         rlm_perl_destruct(perl);
230 }
231
232 /* Create Key */
233 static void rlm_perl_make_key(pthread_key_t *key)
234 {
235         pthread_key_create(key, (void*)rlm_destroy_perl);
236 }
237
238 static PerlInterpreter *rlm_perl_clone(PerlInterpreter *perl, pthread_key_t *key)
239 {
240         int ret;
241
242         PerlInterpreter *interp;
243         UV clone_flags = 0;
244
245         PERL_SET_CONTEXT(perl);
246
247         interp = pthread_getspecific(*key);
248         if (interp) return interp;
249
250         interp = perl_clone(perl, clone_flags);
251         {
252                 dTHXa(interp);
253         }
254 #if PERL_REVISION >= 5 && PERL_VERSION <8
255         call_pv("CLONE",0);
256 #endif
257         ptr_table_free(PL_ptr_table);
258         PL_ptr_table = NULL;
259
260         PERL_SET_CONTEXT(aTHX);
261         rlm_perl_clear_handles(aTHX);
262
263         ret = pthread_setspecific(*key, interp);
264         if (ret != 0) {
265                 DEBUG("rlm_perl: Failed associating interpretor with thread %s", fr_syserror(ret));
266
267                 rlm_perl_destruct(interp);
268                 return NULL;
269         }
270
271         return interp;
272 }
273 #endif
274
275 /*
276  * This is wrapper for radlog
277  * Now users can call radiusd::radlog(level,msg) wich is the same
278  * calling radlog from C code.
279  */
280 static XS(XS_radiusd_radlog)
281 {
282         dXSARGS;
283         if (items !=2)
284                 croak("Usage: radiusd::radlog(level, message)");
285         {
286                 int     level;
287                 char    *msg;
288
289                 level = (int) SvIV(ST(0));
290                 msg   = (char *) SvPV(ST(1), PL_na);
291
292                 /*
293                  *      Because 'msg' is a 'char *', we don't want '%s', etc.
294                  *      in it to give us printf-style vulnerabilities.
295                  */
296                 radlog(level, "rlm_perl: %s", msg);
297         }
298         XSRETURN_NO;
299 }
300
301 static void xs_init(pTHX)
302 {
303         char const *file = __FILE__;
304
305         /* DynaLoader is a special case */
306         newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
307
308         newXS("radiusd::radlog",XS_radiusd_radlog, "rlm_perl");
309 }
310
311 /*
312  * The xlat function
313  */
314 static ssize_t perl_xlat(void *instance, REQUEST *request, char const *fmt, char *out, size_t freespace)
315 {
316
317         rlm_perl_t      *inst = (rlm_perl_t *) instance;
318         char            *tmp;
319         char const      *p, *q;
320         int             count;
321         size_t          ret = 0;
322         STRLEN          n_a;
323
324 #ifdef USE_ITHREADS
325         PerlInterpreter *interp;
326
327         pthread_mutex_lock(&inst->clone_mutex);
328         interp = rlm_perl_clone(inst->perl, inst->thread_key);
329         {
330                 dTHXa(interp);
331                 PERL_SET_CONTEXT(interp);
332         }
333         pthread_mutex_unlock(&inst->clone_mutex);
334 #else
335         PERL_SET_CONTEXT(inst->perl);
336 #endif
337         {
338                 dSP;
339                 ENTER;SAVETMPS;
340
341                 PUSHMARK(SP);
342
343                 p = fmt;
344                 while ((q = strchr(p, ' '))) {
345                         XPUSHs(sv_2mortal(newSVpvn(p, p - q)));
346
347                         p = q + 1;
348                 }
349
350                 PUTBACK;
351
352                 count = call_pv(inst->func_xlat, G_SCALAR | G_EVAL);
353
354                 SPAGAIN;
355                 if (SvTRUE(ERRSV)) {
356                         REDEBUG("Exit %s", SvPV(ERRSV,n_a));
357                         (void)POPs;
358                 } else if (count > 0) {
359                         tmp = POPp;
360                         strlcpy(out, tmp, freespace);
361                         ret = strlen(out);
362
363                         RDEBUG("Len is %zu , out is %s freespace is %zu", ret, out, freespace);
364                 }
365
366                 PUTBACK ;
367                 FREETMPS ;
368                 LEAVE ;
369
370         }
371
372         return ret;
373 }
374
375 /*
376  *      Parse a configuration section, and populate a HV.
377  *      This function is recursively called (allows to have nested hashes.)
378  */
379 static void perl_parse_config(CONF_SECTION *cs, int lvl, HV *rad_hv)
380 {
381         if (!cs || !rad_hv) return;
382
383         int indent_section = (lvl + 1) * 4;
384         int indent_item = (lvl + 2) * 4;
385
386         DEBUG("%*s%s {", indent_section, " ", cf_section_name1(cs));
387
388         CONF_ITEM *ci;
389
390         for (ci = cf_item_find_next(cs, NULL);
391              ci;
392              ci = cf_item_find_next(cs, ci)) {
393                 /*
394                  *  This is a section.
395                  *  Create a new HV, store it as a reference in current HV,
396                  *  Then recursively call perl_parse_config with this section and the new HV.
397                  */
398                 if (cf_item_is_section(ci)) {
399                         CONF_SECTION    *sub_cs = cf_itemtosection(ci);
400                         char const      *key = cf_section_name1(sub_cs); /* hash key */
401                         HV              *sub_hv;
402                         SV              *ref;
403
404                         if (!key) continue;
405
406                         if (hv_exists(rad_hv, key, strlen(key))) {
407                                 WARN("rlm_perl: Ignoring duplicate config section '%s'", key);
408                                 continue;
409                         }
410
411                         sub_hv = newHV();
412                         ref = newRV_inc((SV*) sub_hv);
413
414                         (void)hv_store(rad_hv, key, strlen(key), ref, 0);
415
416                         perl_parse_config(sub_cs, lvl + 1, sub_hv);
417                 } else if (cf_item_is_pair(ci)){
418                         CONF_PAIR       *cp = cf_itemtopair(ci);
419                         char const      *key = cf_pair_attr(cp);        /* hash key */
420                         char const      *value = cf_pair_value(cp);     /* hash value */
421
422                         if (!key || !value) continue;
423
424                         /*
425                          *  This is an item.
426                          *  Store item attr / value in current HV.
427                          */
428                         if (hv_exists(rad_hv, key, strlen(key))) {
429                                 WARN("rlm_perl: Ignoring duplicate config item '%s'", key);
430                                 continue;
431                         }
432
433                         (void)hv_store(rad_hv, key, strlen(key), newSVpvn(value, strlen(value)), 0);
434
435                         DEBUG("%*s%s = %s", indent_item, " ", key, value);
436                 }
437         }
438
439         DEBUG("%*s}", indent_section, " ");
440 }
441
442 /*
443  *      Do any per-module initialization that is separate to each
444  *      configured instance of the module.  e.g. set up connections
445  *      to external databases, read configuration files, set up
446  *      dictionary entries, etc.
447  *
448  *      If configuration information is given in the config section
449  *      that must be referenced in later calls, store a handle to it
450  *      in *instance otherwise put a null pointer there.
451  *
452  *      Setup a hashes wich we will use later
453  *      parse a module and give him a chance to live
454  *
455  */
456 static int mod_instantiate(CONF_SECTION *conf, void *instance)
457 {
458         rlm_perl_t       *inst = instance;
459         AV              *end_AV;
460
461         char const **embed_c;   /* Stupid Perl and lack of const consistency */
462         char **embed;
463         char **envp = NULL;
464         char const *xlat_name;
465         int exitstatus = 0, argc=0;
466
467         MEM(embed_c = talloc_zero_array(inst, char const *, 4));
468         memcpy(&embed, &embed_c, sizeof(embed));
469         /*
470          *      Create pthread key. This key will be stored in instance
471          */
472
473 #ifdef USE_ITHREADS
474         pthread_mutex_init(&inst->clone_mutex, NULL);
475
476         inst->thread_key = rad_malloc(sizeof(*inst->thread_key));
477         memset(inst->thread_key,0,sizeof(*inst->thread_key));
478
479         rlm_perl_make_key(inst->thread_key);
480 #endif
481
482         char arg[] = "0";
483
484         embed_c[0] = NULL;
485         if (inst->perl_flags) {
486                 embed_c[1] = inst->perl_flags;
487                 embed_c[2] = inst->module;
488                 embed_c[3] = arg;
489                 argc = 4;
490         } else {
491                 embed_c[1] = inst->module;
492                 embed_c[2] = arg;
493                 argc = 3;
494         }
495
496         PERL_SYS_INIT3(&argc, &embed, &envp);
497
498         if ((inst->perl = perl_alloc()) == NULL) {
499                 ERROR("rlm_perl: No memory for allocating new perl !");
500                 return (-1);
501         }
502
503         perl_construct(inst->perl);
504
505 #ifdef USE_ITHREADS
506         PL_perl_destruct_level = 2;
507
508         {
509                 dTHXa(inst->perl);
510         }
511         PERL_SET_CONTEXT(inst->perl);
512 #endif
513
514 #if PERL_REVISION >= 5 && PERL_VERSION >=8
515         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
516 #endif
517
518         exitstatus = perl_parse(inst->perl, xs_init, argc, embed, NULL);
519
520         end_AV = PL_endav;
521         PL_endav = Nullav;
522
523         if(!exitstatus) {
524                 perl_run(inst->perl);
525         } else {
526                 ERROR("rlm_perl: perl_parse failed: %s not found or has syntax errors. \n", inst->module);
527                 return (-1);
528         }
529
530         PL_endav = end_AV;
531
532         xlat_name = cf_section_name2(conf);
533         if (!xlat_name)
534                 xlat_name = cf_section_name1(conf);
535         if (xlat_name) {
536                 xlat_register(xlat_name, perl_xlat, NULL, inst);
537         }
538
539         /* parse perl configuration sub-section */
540         CONF_SECTION *cs;
541         cs = cf_section_sub_find(conf, "config");
542         if (cs) {
543                 DEBUG("rlm_perl (%s): parsing 'config' section...", xlat_name);
544
545                 inst->rad_perlconf_hv = get_hv("RAD_PERLCONF",1);
546                 perl_parse_config(cs, 0, inst->rad_perlconf_hv);
547
548                 DEBUG("rlm_perl (%s): done parsing 'config'.", xlat_name);
549         }
550
551         return 0;
552 }
553
554 static void perl_vp_to_svpvn_element(REQUEST *request, AV *av, VALUE_PAIR const *vp,
555                                      int *i, const char *hash_name, const char *list_name)
556 {
557         size_t len;
558
559         char buffer[1024];
560
561         switch (vp->da->type) {
562         case PW_TYPE_STRING:
563                 RDEBUG("$%s{'%s'}[%i] = &%s:%s -> '%s'", hash_name, vp->da->name, *i,
564                        list_name, vp->da->name, vp->vp_strvalue);
565                 av_push(av, newSVpvn(vp->vp_strvalue, vp->length));
566                 break;
567
568         default:
569                 len = vp_prints_value(buffer, sizeof(buffer), vp, 0);
570                 RDEBUG("$%s{'%s'}[%i] = &%s:%s -> '%s'", hash_name, vp->da->name, *i,
571                        list_name, vp->da->name, buffer);
572                 av_push(av, newSVpvn(buffer, truncate_len(len, sizeof(buffer))));
573                 break;
574         }
575         (*i)++;
576 }
577
578 /*
579  *      get the vps and put them in perl hash
580  *      If one VP have multiple values it is added as array_ref
581  *      Example for this is Cisco-AVPair that holds multiple values.
582  *      Which will be available as array_ref in $RAD_REQUEST{'Cisco-AVPair'}
583  */
584 static void perl_store_vps(UNUSED TALLOC_CTX *ctx, REQUEST *request, VALUE_PAIR *vps, HV *rad_hv,
585                            const char *hash_name, const char *list_name)
586 {
587         VALUE_PAIR *vp;
588
589         hv_undef(rad_hv);
590
591         vp_cursor_t cursor;
592
593         RINDENT();
594         pairsort(&vps, attrtagcmp);
595         for (vp = fr_cursor_init(&cursor, &vps);
596              vp;
597              vp = fr_cursor_next(&cursor)) {
598                 VALUE_PAIR *next;
599
600                 char const *name;
601                 char namebuf[256];
602                 char buffer[1024];
603
604                 size_t len;
605
606                 /*
607                  *      Tagged attributes are added to the hash with name
608                  *      <attribute>:<tag>, others just use the normal attribute
609                  *      name as the key.
610                  */
611                 if (vp->da->flags.has_tag && (vp->tag != TAG_ANY)) {
612                         snprintf(namebuf, sizeof(namebuf), "%s:%d", vp->da->name, vp->tag);
613                         name = namebuf;
614                 } else {
615                         name = vp->da->name;
616                 }
617
618                 /*
619                  *      We've sorted by type, then tag, so attributes of the
620                  *      same type/tag should follow on from each other.
621                  */
622                 if ((next = fr_cursor_next_peek(&cursor)) && ATTRIBUTE_EQ(vp, next)) {
623                         int i = 0;
624                         AV *av;
625
626                         av = newAV();
627
628                         perl_vp_to_svpvn_element(request, av, vp, &i, hash_name, list_name);
629                         do {
630                                 perl_vp_to_svpvn_element(request, av, next, &i, hash_name, list_name);
631                                 fr_cursor_next(&cursor);
632                         } while ((next = fr_cursor_next_peek(&cursor)) && ATTRIBUTE_EQ(vp, next));
633                         (void)hv_store(rad_hv, name, strlen(name), newRV_noinc((SV *)av), 0);
634
635                         continue;
636                 }
637
638                 /*
639                  *      It's a normal single valued attribute
640                  */
641                 switch (vp->da->type) {
642                 case PW_TYPE_STRING:
643                         RDEBUG("$%s{'%s'} = &%s:%s -> '%s'", hash_name, vp->da->name, list_name,
644                                vp->da->name, vp->vp_strvalue);
645                         (void)hv_store(rad_hv, name, strlen(name), newSVpvn(vp->vp_strvalue, vp->length), 0);
646                         break;
647
648                 default:
649                         len = vp_prints_value(buffer, sizeof(buffer), vp, 0);
650                         RDEBUG("$%s{'%s'} = &%s:%s -> '%s'", hash_name, vp->da->name,
651                                list_name, vp->da->name, buffer);
652                         (void)hv_store(rad_hv, name, strlen(name),
653                                        newSVpvn(buffer, truncate_len(len, sizeof(buffer))), 0);
654                         break;
655                 }
656         }
657         REXDENT();
658 }
659
660 /*
661  *
662  *     Verify that a Perl SV is a string and save it in FreeRadius
663  *     Value Pair Format
664  *
665  */
666 static int pairadd_sv(TALLOC_CTX *ctx, REQUEST *request, VALUE_PAIR **vps, char *key, SV *sv, FR_TOKEN op,
667                       const char *hash_name, const char *list_name)
668 {
669         char        *val;
670         VALUE_PAIR      *vp;
671
672         if (SvOK(sv)) {
673                 STRLEN len;
674                 val = SvPV(sv, len);
675                 vp = pairmake(ctx, vps, key, NULL, op);
676                 if (!vp) {
677                 fail:
678                         REDEBUG("Failed to create pair %s:%s %s %s", list_name, key,
679                                 fr_int2str(fr_tokens, op, "<INVALID>"), val);
680                         return -1;
681                 }
682
683                 switch (vp->da->type) {
684                 case PW_TYPE_STRING:
685                         pairstrncpy(vp, val, len);
686                         break;
687
688                 default:
689                         if (pairparsevalue(vp, val, len) < 0) goto fail;
690                 }
691
692                 RDEBUG("&%s:%s %s $%s{'%s'} -> '%s'", list_name, key, fr_int2str(fr_tokens, op, "<INVALID>"),
693                        hash_name, key, val);
694                 return 0;
695         }
696         return -1;
697 }
698
699 /*
700  *     Gets the content from hashes
701  */
702 static int get_hv_content(TALLOC_CTX *ctx, REQUEST *request, HV *my_hv, VALUE_PAIR **vps,
703                           const char *hash_name, const char *list_name)
704 {
705         SV              *res_sv, **av_sv;
706         AV              *av;
707         char            *key;
708         I32             key_len, len, i, j;
709         int             ret = 0;
710
711         *vps = NULL;
712         for (i = hv_iterinit(my_hv); i > 0; i--) {
713                 res_sv = hv_iternextsv(my_hv,&key,&key_len);
714                 if (SvROK(res_sv) && (SvTYPE(SvRV(res_sv)) == SVt_PVAV)) {
715                         av = (AV*)SvRV(res_sv);
716                         len = av_len(av);
717                         for (j = 0; j <= len; j++) {
718                                 av_sv = av_fetch(av, j, 0);
719                                 ret = pairadd_sv(ctx, request, vps, key, *av_sv, T_OP_ADD, hash_name, list_name) + ret;
720                         }
721                 } else ret = pairadd_sv(ctx, request, vps, key, res_sv, T_OP_EQ, hash_name, list_name) + ret;
722         }
723
724         return ret;
725 }
726
727 /*
728  *      Call the function_name inside the module
729  *      Store all vps in hashes %RAD_CHECK %RAD_REPLY %RAD_REQUEST
730  *
731  */
732 static int do_perl(void *instance, REQUEST *request, char const *function_name)
733 {
734
735         rlm_perl_t      *inst = instance;
736         VALUE_PAIR      *vp;
737         int             exitstatus=0, count;
738         STRLEN          n_a;
739
740         HV              *rad_reply_hv;
741         HV              *rad_check_hv;
742         HV              *rad_config_hv;
743         HV              *rad_request_hv;
744 #ifdef WITH_PROXY
745         HV              *rad_request_proxy_hv;
746         HV              *rad_request_proxy_reply_hv;
747 #endif
748
749         /*
750          *      Radius has told us to call this function, but none
751          *      is defined.
752          */
753         if (!function_name) return RLM_MODULE_FAIL;
754
755 #ifdef USE_ITHREADS
756         pthread_mutex_lock(&inst->clone_mutex);
757
758         PerlInterpreter *interp;
759
760         interp = rlm_perl_clone(inst->perl,inst->thread_key);
761         {
762                 dTHXa(interp);
763                 PERL_SET_CONTEXT(interp);
764         }
765
766         pthread_mutex_unlock(&inst->clone_mutex);
767 #else
768         PERL_SET_CONTEXT(inst->perl);
769 #endif
770
771         {
772                 dSP;
773
774                 ENTER;
775                 SAVETMPS;
776
777                 rad_reply_hv = get_hv("RAD_REPLY", 1);
778                 rad_check_hv = get_hv("RAD_CHECK", 1);
779                 rad_config_hv = get_hv("RAD_CONFIG", 1);
780                 rad_request_hv = get_hv("RAD_REQUEST", 1);
781
782                 perl_store_vps(request->packet, request, request->packet->vps, rad_request_hv, "RAD_REQUEST", "request");
783                 perl_store_vps(request->reply, request, request->reply->vps, rad_reply_hv, "RAD_REPLY", "reply");
784                 perl_store_vps(request, request, request->config_items, rad_check_hv, "RAD_CHECK", "control");
785                 perl_store_vps(request, request, request->config_items, rad_config_hv, "RAD_CONFIG", "control");
786
787 #ifdef WITH_PROXY
788                 rad_request_proxy_hv = get_hv("RAD_REQUEST_PROXY",1);
789                 rad_request_proxy_reply_hv = get_hv("RAD_REQUEST_PROXY_REPLY",1);
790
791                 if (request->proxy != NULL) {
792                         perl_store_vps(request->proxy, request, request->proxy->vps, rad_request_proxy_hv,
793                                        "RAD_REQUEST_PROXY", "proxy-request");
794                 } else {
795                         hv_undef(rad_request_proxy_hv);
796                 }
797
798                 if (request->proxy_reply != NULL) {
799                         perl_store_vps(request->proxy_reply, request, request->proxy_reply->vps,
800                                        rad_request_proxy_reply_hv, "RAD_REQUEST_PROXY_REPLY", "proxy-reply");
801                 } else {
802                         hv_undef(rad_request_proxy_reply_hv);
803                 }
804 #endif
805
806                 PUSHMARK(SP);
807                 /*
808                  * This way %RAD_xx can be pushed onto stack as sub parameters.
809                  * XPUSHs( newRV_noinc((SV *)rad_request_hv) );
810                  * XPUSHs( newRV_noinc((SV *)rad_reply_hv) );
811                  * XPUSHs( newRV_noinc((SV *)rad_check_hv) );
812                  * PUTBACK;
813                  */
814
815                 count = call_pv(function_name, G_SCALAR | G_EVAL | G_NOARGS);
816
817                 SPAGAIN;
818
819                 if (SvTRUE(ERRSV)) {
820                         ERROR("rlm_perl: perl_embed:: module = %s , func = %s exit status= %s\n",
821                                inst->module,
822                                function_name, SvPV(ERRSV,n_a));
823                         (void)POPs;
824                 }
825
826                 if (count == 1) {
827                         exitstatus = POPi;
828                         if (exitstatus >= 100 || exitstatus < 0) {
829                                 exitstatus = RLM_MODULE_FAIL;
830                         }
831                 }
832
833
834                 PUTBACK;
835                 FREETMPS;
836                 LEAVE;
837
838                 vp = NULL;
839                 if ((get_hv_content(request->packet, request, rad_request_hv, &vp, "RAD_REQUEST", "request")) == 0) {
840                         pairfree(&request->packet->vps);
841                         request->packet->vps = vp;
842                         vp = NULL;
843
844                         /*
845                          *      Update cached copies
846                          */
847                         request->username = pairfind(request->packet->vps, PW_USER_NAME, 0, TAG_ANY);
848                         request->password = pairfind(request->packet->vps, PW_USER_PASSWORD, 0, TAG_ANY);
849                         if (!request->password)
850                                 request->password = pairfind(request->packet->vps, PW_CHAP_PASSWORD, 0, TAG_ANY);
851                 }
852
853                 if ((get_hv_content(request->reply, request, rad_reply_hv, &vp, "RAD_REPLY", "reply")) == 0) {
854                         pairfree(&request->reply->vps);
855                         request->reply->vps = vp;
856                         vp = NULL;
857                 }
858
859                 if ((get_hv_content(request, request, rad_check_hv, &vp, "RAD_CHECK", "control")) == 0) {
860                         pairfree(&request->config_items);
861                         request->config_items = vp;
862                         vp = NULL;
863                 }
864
865 #ifdef WITH_PROXY
866                 if (request->proxy &&
867                     (get_hv_content(request->proxy, request, rad_request_proxy_hv, &vp,
868                                     "RAD_REQUEST_PROXY", "proxy-request") == 0)) {
869                         pairfree(&request->proxy->vps);
870                         request->proxy->vps = vp;
871                         vp = NULL;
872                 }
873
874                 if (request->proxy_reply &&
875                     (get_hv_content(request->proxy_reply, request, rad_request_proxy_reply_hv, &vp,
876                                     "RAD_REQUEST_PROXY_REPLY", "proxy-reply") == 0)) {
877                         pairfree(&request->proxy_reply->vps);
878                         request->proxy_reply->vps = vp;
879                         vp = NULL;
880                 }
881 #endif
882
883         }
884         return exitstatus;
885 }
886
887 #define RLM_PERL_FUNC(_x) static rlm_rcode_t CC_HINT(nonnull) mod_##_x(void *instance, REQUEST *request) \
888         {                                                               \
889                 return do_perl(instance, request,                       \
890                                ((rlm_perl_t *)instance)->func_##_x); \
891         }
892
893 RLM_PERL_FUNC(authorize)
894 RLM_PERL_FUNC(authenticate)
895 RLM_PERL_FUNC(post_auth)
896
897 RLM_PERL_FUNC(checksimul)
898
899 #ifdef WITH_PROXY
900 RLM_PERL_FUNC(pre_proxy)
901 RLM_PERL_FUNC(post_proxy)
902 #endif
903
904 #ifdef WITH_COA
905 RLM_PERL_FUNC(recv_coa)
906 RLM_PERL_FUNC(send_coa)
907 #endif
908
909 RLM_PERL_FUNC(preacct)
910
911 /*
912  *      Write accounting information to this modules database.
913  */
914 static rlm_rcode_t CC_HINT(nonnull) mod_accounting(void *instance, REQUEST *request)
915 {
916         VALUE_PAIR      *pair;
917         int             acctstatustype=0;
918
919         if ((pair = pairfind(request->packet->vps, PW_ACCT_STATUS_TYPE, 0, TAG_ANY)) != NULL) {
920                 acctstatustype = pair->vp_integer;
921         } else {
922                 ERROR("Invalid Accounting Packet");
923                 return RLM_MODULE_INVALID;
924         }
925
926         switch (acctstatustype) {
927
928         case PW_STATUS_START:
929
930                 if (((rlm_perl_t *)instance)->func_start_accounting) {
931                         return do_perl(instance, request,
932                                        ((rlm_perl_t *)instance)->func_start_accounting);
933                 } else {
934                         return do_perl(instance, request,
935                                        ((rlm_perl_t *)instance)->func_accounting);
936                 }
937                 break;
938
939         case PW_STATUS_STOP:
940
941                 if (((rlm_perl_t *)instance)->func_stop_accounting) {
942                         return do_perl(instance, request,
943                                        ((rlm_perl_t *)instance)->func_stop_accounting);
944                 } else {
945                         return do_perl(instance, request,
946                                        ((rlm_perl_t *)instance)->func_accounting);
947                 }
948                 break;
949         default:
950                 return do_perl(instance, request,
951                                ((rlm_perl_t *)instance)->func_accounting);
952
953         }
954 }
955
956
957 /*
958  * Detach a instance give a chance to a module to make some internal setup ...
959  */
960 DIAG_OFF(nested-externs)
961 static int mod_detach(void *instance)
962 {
963         rlm_perl_t      *inst = (rlm_perl_t *) instance;
964         int             exitstatus = 0, count = 0;
965
966         if (inst->rad_perlconf_hv != NULL) {
967                 hv_undef(inst->rad_perlconf_hv);
968         }
969
970 #if 0
971         /*
972          *      FIXME: Call this in the destruct function?
973          */
974         {
975                 dTHXa(handle->clone);
976                 PERL_SET_CONTEXT(handle->clone);
977                 {
978                         dSP; ENTER; SAVETMPS; PUSHMARK(SP);
979                         count = call_pv(inst->func_detach, G_SCALAR | G_EVAL );
980                         SPAGAIN;
981
982                         if (count == 1) {
983                                 exitstatus = POPi;
984                                 /*
985                                  * FIXME: bug in perl
986                                  *
987                                  */
988                                 if (exitstatus >= 100 || exitstatus < 0) {
989                                         exitstatus = RLM_MODULE_FAIL;
990                                 }
991                         }
992                         PUTBACK;
993                         FREETMPS;
994                         LEAVE;
995                 }
996         }
997 #endif
998
999         if (inst->func_detach) {
1000                 dTHXa(inst->perl);
1001                 PERL_SET_CONTEXT(inst->perl);
1002                 {
1003                         dSP; ENTER; SAVETMPS;
1004                         PUSHMARK(SP);
1005
1006                         count = call_pv(inst->func_detach, G_SCALAR | G_EVAL );
1007                         SPAGAIN;
1008
1009                         if (count == 1) {
1010                                 exitstatus = POPi;
1011                                 if (exitstatus >= 100 || exitstatus < 0) {
1012                                         exitstatus = RLM_MODULE_FAIL;
1013                                 }
1014                         }
1015                         PUTBACK;
1016                         FREETMPS;
1017                         LEAVE;
1018                 }
1019         }
1020
1021 #ifdef USE_ITHREADS
1022         rlm_perl_destruct(inst->perl);
1023         pthread_mutex_destroy(&inst->clone_mutex);
1024 #else
1025         perl_destruct(inst->perl);
1026         perl_free(inst->perl);
1027 #endif
1028
1029         PERL_SYS_TERM();
1030         return exitstatus;
1031 }
1032 DIAG_ON(nested-externs)
1033
1034 /*
1035  *      The module name should be the only globally exported symbol.
1036  *      That is, everything else should be 'static'.
1037  *
1038  *      If the module needs to temporarily modify it's instantiation
1039  *      data, the type should be changed to RLM_TYPE_THREAD_UNSAFE.
1040  *      The server will then take care of ensuring that the module
1041  *      is single-threaded.
1042  */
1043 module_t rlm_perl = {
1044         RLM_MODULE_INIT,
1045         "perl",                         /* Name */
1046 #ifdef USE_ITHREADS
1047         RLM_TYPE_THREAD_SAFE,           /* type */
1048 #else
1049         RLM_TYPE_THREAD_UNSAFE,
1050 #endif
1051         sizeof(rlm_perl_t),
1052         module_config,
1053         mod_instantiate,                /* instantiation */
1054         mod_detach,                     /* detach */
1055         {
1056                 mod_authenticate,       /* authenticate */
1057                 mod_authorize,          /* authorize */
1058                 mod_preacct,            /* preacct */
1059                 mod_accounting, /* accounting */
1060                 mod_checksimul,         /* check simul */
1061 #ifdef WITH_PROXY
1062                 mod_pre_proxy,          /* pre-proxy */
1063                 mod_post_proxy, /* post-proxy */
1064 #else
1065                 NULL, NULL,
1066 #endif
1067                 mod_post_auth           /* post-auth */
1068 #ifdef WITH_COA
1069                 , mod_recv_coa,
1070                 mod_send_coa
1071 #endif
1072         },
1073 };