File: perl.c

package info (click to toggle)
inn2 2.5.4-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 11,720 kB
  • ctags: 8,983
  • sloc: ansic: 92,499; sh: 13,509; perl: 12,921; makefile: 2,985; yacc: 842; python: 342; lex: 255
file content (558 lines) | stat: -rw-r--r-- 14,625 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
/*  $Id: perl.c 9483 2013-06-06 20:10:20Z iulius $
**
**  Perl filtering support for innd.
**
**  Originally written by Christophe Wolfhugel <wolf@pasteur.fr> (although
**  he wouldn't recognise it anymore so don't blame him) and modified,
**  expanded and tweaked since by James Brister, Jeremy Nixon, Ed Mooring,
**  Russell Vincent, and Russ Allbery.
**
**  This file should contain all innd-specific Perl linkage.  Linkage
**  applicable to both innd and nnrpd should go into lib/perl.c instead.
**
**  We are assuming Perl 5.004 or later.
**
**  Future work:
**
**   - The breakdown between this file, lib/perl.c, and nnrpd/perl.c should
**     be rethought, ideally in the light of supporting multiple filters in
**     different languages.
**
**   - Variable and key names should be standardized between this and nnrpd.
**
**   - The XS code is still calling CC* functions.  The common code between
**     the two control interfaces should be factored out into the rest of
**     innd instead.
**
**   - There's a needless perl_get_cv() call for *every message ID* offered
**     to the server right now.  We need to stash whether that filter is
**     active.
*/

#include "config.h"

/* Skip this entire file if DO_PERL (./configure --with-perl) isn't set. */
#if DO_PERL

#include "clibrary.h"
#include "inn/wire.h"
#include "innd.h"

#include <EXTERN.h>
#include <perl.h>
#include <XSUB.h>
#include "ppport.h"

#include "innperl.h"

/* Prototypes for XS functions. */
XS(XS_INN_addhist);
XS(XS_INN_article);
XS(XS_INN_cancel);
XS(XS_INN_filesfor);
XS(XS_INN_havehist);
XS(XS_INN_head);
XS(XS_INN_newsgroup);


/*
**  Run an incoming article through the Perl article filter.  Returns NULL
**  accept the article or a rejection message to reject it.
*/
char *
PLartfilter(const ARTDATA *data, char *artBody, long artLen, int lines)
{
    dSP;
    const ARTHEADER * hp;
    const HDRCONTENT *hc = data->HdrContent;
    HV *        hdr;
    CV *        filter;
    int         i, rc;
    char *      p;
    static char buf[256];
    bool        failure;

    if (!PerlFilterActive) return NULL;
    filter = perl_get_cv("filter_art", 0);
    if (!filter) return NULL;

    /* Create %hdr and stash a copy of every known header. */
    hdr = perl_get_hv("hdr", 1);
    for (i = 0 ; i < MAX_ARTHEADER ; i++) {
	if (HDR_FOUND(i)) {
	    hp = &ARTheaders[i];
            (void) hv_store(hdr, (char *) hp->Name, hp->Size, newSVpv(HDR(i), 0), 0);
	}
    }

    /* Store the article body.  We don't want to make another copy of it,
       since it could potentially be quite large.  In testing, this produced
       a 17% speed improvement over making a copy of the article body
       for a fairly heavy filter.
       Available since Perl 5.7.1, newSVpvn_share allows to avoid such
       a copy (getting round its use for older versions of Perl leads
       to unreliable SV * bodies as for regexps).  And for Perl not to
       compute a hash for artBody, we give it "42". */
    if (artBody) {
#if (PERL_REVISION == 5) && ((PERL_VERSION < 7) || ((PERL_VERSION == 7) && (PERL_SUBVERSION < 1)))
        (void) hv_store(hdr, "__BODY__", 8, newSVpv(artBody, artLen), 0);
#else
        (void) hv_store(hdr, "__BODY__", 8, newSVpvn_share(artBody, artLen, 42), 0);
#endif /* Perl < 5.7.1 */
    }

    (void) hv_store(hdr, "__LINES__", 9, newSViv(lines), 0);

    ENTER;
    SAVETMPS;
    PUSHMARK(SP);
    PUTBACK;
    rc = perl_call_sv((SV *) filter, G_EVAL|G_SCALAR|G_NOARGS);
    SPAGAIN;

    hv_undef(hdr);

    /* Check $@, which will be set if the sub died. */
    buf[0] = '\0';
    if (SvTRUE(ERRSV)) {
        failure = true;
        syslog(L_ERROR, "Perl function filter_art died on article %s: %s",
               HDR_FOUND(HDR__MESSAGE_ID) ? HDR(HDR__MESSAGE_ID) : "?",
               SvPV(ERRSV, PL_na));
        (void) POPs;
    } else {
        failure = false;
        if (rc == 1) {
            p = POPp;
            if (p && *p)
                strlcpy(buf, p, sizeof(buf));
        }
    }

    PUTBACK;
    FREETMPS;
    LEAVE;

    if (failure)
        PerlFilter(false);

    return (buf[0] != '\0') ? buf : NULL;
}


/*
**  Run an incoming message-ID from CHECK, IHAVE or TAKETHIS through
**  the Perl filter.
**  Returns NULL to accept the article or a rejection message to reject it.
*/
char *
PLmidfilter(char *messageID)
{
    dSP;
    CV          *filter;
    int         rc;
    char        *p;
    static char buf[256];
    bool        failure;

    if (!PerlFilterActive) return NULL;
    filter = perl_get_cv("filter_messageid", 0);
    if (!filter) return NULL;

    /* Pass filter_messageid() the message ID on the Perl stack. */
    ENTER;
    SAVETMPS;
    PUSHMARK(SP);
    XPUSHs(sv_2mortal(newSVpv(messageID, 0)));
    PUTBACK;
    rc = perl_call_sv((SV *) filter, G_EVAL|G_SCALAR);
    SPAGAIN;

    /* Check $@, which will be set if the sub died. */
    buf[0] = '\0';
    if (SvTRUE(ERRSV)) {
        failure = true;
        syslog(L_ERROR, "Perl function filter_messageid died on id %s: %s",
               messageID, SvPV(ERRSV, PL_na));
        (void) POPs;
    } else {
        failure = false;
        if (rc == 1) {
            p = POPp;
            if (p && *p)
                strlcpy(buf, p, sizeof(buf));
        }
    }

    PUTBACK;
    FREETMPS;
    LEAVE;

    if (failure)
        PerlFilter(false);

    return (buf[0] != '\0') ? buf : NULL;
}


/*
**  Call a Perl sub on any change in INN's mode, passing in the old and new
**  mode and the reason.
*/
void
PLmode(OPERATINGMODE Mode, OPERATINGMODE NewMode, char *reason)
{
    dSP;
    HV          *mode;
    CV          *filter;
    bool        failure;

    filter = perl_get_cv("filter_mode", 0);
    if (!filter) return;

    /* Current mode goes into $mode{Mode}, new mode in $mode{NewMode}, and
       the reason in $mode{reason}. */
    mode = perl_get_hv("mode", 1);

    if (Mode == OMrunning)
        (void) hv_store(mode, "Mode", 4, newSVpv("running", 7), 0);
    if (Mode == OMpaused)
        (void) hv_store(mode, "Mode", 4, newSVpv("paused", 6), 0);
    if (Mode == OMthrottled)
        (void) hv_store(mode, "Mode", 4, newSVpv("throttled", 9), 0);
    if (Mode == OMshutdown)
        (void) hv_store(mode, "Mode", 4, newSVpv("shutdown", 8), 0);

    if (NewMode == OMrunning)
        (void) hv_store(mode, "NewMode", 7, newSVpv("running", 7), 0);
    if (NewMode == OMpaused)
        (void) hv_store(mode, "NewMode", 7, newSVpv("paused", 6), 0);
    if (NewMode == OMthrottled)
        (void) hv_store(mode, "NewMode", 7, newSVpv("throttled", 9), 0);
    if (NewMode == OMshutdown)
        (void) hv_store(mode, "NewMode", 7, newSVpv("shutdown", 8), 0);

    (void) hv_store(mode, "reason", 6, newSVpv(reason, 0), 0);

    ENTER;
    SAVETMPS;
    PUSHMARK(SP);
    PUTBACK;

    perl_call_sv((SV *) filter, G_EVAL|G_DISCARD|G_NOARGS);

    SPAGAIN;

    /* Check $@, which will be set if the sub died. */
    if (SvTRUE(ERRSV)) {
        failure = true;
        syslog(L_ERROR, "Perl function filter_mode died: %s",
                SvPV(ERRSV, PL_na));
        (void) POPs;
    } else {
        failure = false;
    }

    hv_undef(mode);

    PUTBACK;
    FREETMPS;
    LEAVE;

    if (failure)
        PerlFilter(false);
}


/*
**  Called by CCmode, this returns the Perl filter statistics if a Perl
**  function to generate such statistics has been defined, or NULL otherwise.
**  If a string is returned, it's in newly allocated memory that must be freed
**  by the caller.
*/
char *
PLstats(void)
{
    dSP;
    char *argv[] = { NULL };

    if (perl_get_cv("filter_stats", false) == NULL)
        return NULL;
    else {
        char *stats = NULL;
        char *result;

	ENTER;
	SAVETMPS;
        /* No need for PUSHMARK(SP) with call_argv(). */
	perl_call_argv("filter_stats", G_EVAL | G_NOARGS, argv);
	SPAGAIN;
        result = POPp;
        if (result != NULL && *result)
            stats = xstrdup(result);
	PUTBACK;
	FREETMPS;
	LEAVE;

        return stats;
    }
}


/*
**  The remainder of this file are XS callbacks visible to embedded Perl
**  code to perform various innd functions.  They were originally written by
**  Ed Mooring (mooring@acm.org) on May 14, 1998, and have since been split
**  between this file and lib/perl.c (which has the ones that can also be
**  used in nnrpd).  The function that registers them at startup is at the
**  end.
*/

/*
**  Add an entry to history.  Takes message ID and optionally arrival,
**  article, and expire times and storage API token.  If the times aren't
**  given, they default to now.  If the token isn't given, that field will
**  be left empty.  Returns boolean success.
*/
XS(XS_INN_addhist)
{
    dXSARGS;
    int         i;
    char        tbuff[32];
    char*       parambuf[6];

    /* Suppress warnings for the mandatory XS argument. */
    cv = cv;

    if (items < 1 || items > 5)
        croak("Usage INN::addhist(msgid,[arrival,articletime,expire,token])");

    for (i = 0; i < items; i++)
        parambuf[i] = (char *) SvPV(ST(0), PL_na);

    /* If any of the times are missing, they should default to now. */
    if (i < 4) {
        snprintf(tbuff, sizeof(tbuff), "%ld", (long) time(NULL));
        for (; i < 4; i++)
            parambuf[i] = tbuff;
    }

    /* The token defaults to an empty string. */
    if (i == 4)
        parambuf[4] = (char *) "";

    parambuf[5] = NULL;

    /* CCaddhist returns NULL on success. */
    if (CCaddhist(parambuf))
        XSRETURN_NO;
    else
        XSRETURN_YES;
}


/*
**  Takes the message ID of an article and returns the full article as a
**  string or undef if the article wasn't found.  It will be converted from
**  wire format to native format.  Note that this call isn't particularly
**  optimized or cheap.
*/
XS(XS_INN_article)
{
    dXSARGS;
    char *      msgid;
    TOKEN       token;
    ARTHANDLE * art;
    char *      p;
    size_t      len;

    /* Suppress warnings for the mandatory XS argument. */
    cv = cv;

    if (items != 1)
	croak("Usage: INN::article(msgid)");

    /* Get the article token from the message ID and the history file. */
    msgid = (char *) SvPV(ST(0), PL_na);
    if (!HISlookup(History, msgid, NULL, NULL, NULL, &token)) XSRETURN_UNDEF;

    /* Retrieve the article and convert it from wire format. */
    art = SMretrieve(token, RETR_ALL);
    if (art == NULL) XSRETURN_UNDEF;
    p = wire_to_native(art->data, art->len, &len);
    SMfreearticle(art);

    /* Push a copy of the article onto the Perl stack, free our temporary
       memory allocation, and return the article to Perl. */
    ST(0) = sv_2mortal(newSVpv(p, len));
    free(p);
    XSRETURN(1);
}


/*
**  Cancel a message by message ID; returns boolean success.  Equivalent to
**  ctlinnd cancel <message>.
*/
XS(XS_INN_cancel)
{
    dXSARGS;
    char        *msgid;
    char        *parambuf[2];

    /* Suppress warnings for the mandatory XS argument. */
    cv = cv;

    if (items != 1)
        croak("Usage: INN::cancel(msgid)");

    msgid = (char *) SvPV(ST(0), PL_na);
    parambuf[0] = msgid;
    parambuf[1] = NULL;

    /* CCcancel returns NULL on success. */
    if (CCcancel(parambuf))
        XSRETURN_NO;
    else
        XSRETURN_YES;
}


/*
**  Return the files for a given message ID, taken from the history file.
**  This function should really be named INN::token() and probably will be
**  some day.
*/
XS(XS_INN_filesfor)
{
    dXSARGS;
    char        *msgid;
    TOKEN       token;

    /* Suppress warnings for the mandatory XS argument. */
    cv = cv;

    if (items != 1)
        croak("Usage: INN::filesfor(msgid)");

    msgid = (char *) SvPV(ST(0), PL_na);
    if (HISlookup(History, msgid, NULL, NULL, NULL, &token)) {
        XSRETURN_PV(TokenToText(token));
    } else {
        XSRETURN_UNDEF;
    }
}


/*
**  Whether message ID is in the history file; returns boolean.
*/
XS(XS_INN_havehist)
{
    dXSARGS;
    char        *msgid;

    /* Suppress warnings for the mandatory XS argument. */
    cv = cv;

    if (items != 1)
        croak("Usage: INN::havehist(msgid)");

    msgid = (char *) SvPV(ST(0), PL_na);
    if (HIScheck(History, msgid))
        XSRETURN_YES;
    else
        XSRETURN_NO;
}


/*
**  Takes the message ID of an article and returns the article headers as
**  a string or undef if the article wasn't found.  Each line of the header
**  will end with \n.
*/
XS(XS_INN_head)
{
    dXSARGS;
    char *      msgid;
    TOKEN       token;
    ARTHANDLE * art;
    char *      p;
    size_t      len;

    /* Suppress warnings for the mandatory XS argument. */
    cv = cv;

    if (items != 1)
        croak("Usage: INN::head(msgid)");

    /* Get the article token from the message ID and the history file. */
    msgid = (char *) SvPV(ST(0), PL_na);
    if (!HISlookup(History, msgid, NULL, NULL, NULL, &token)) XSRETURN_UNDEF;

    /* Retrieve the article header and convert it from wire format. */
    art = SMretrieve(token, RETR_HEAD);
    if (art == NULL) XSRETURN_UNDEF;
    p = wire_to_native(art->data, art->len, &len);
    SMfreearticle(art);

    /* Push a copy of the article header onto the Perl stack, free our
       temporary memory allocation, and return the header to Perl. */
    ST(0) = sv_2mortal(newSVpv(p, len));
    free(p);
    XSRETURN(1);
}


/*
**  Returns the active file flag for a newsgroup or undef if it isn't in the
**  active file.
*/
XS(XS_INN_newsgroup)
{
    dXSARGS;
    char *      newsgroup;
    NEWSGROUP * ngp;
    char *      end;
    int         size;

    /* Suppress warnings for the mandatory XS argument. */
    cv = cv;

    if (items != 1)
        croak("Usage: INN::newsgroup(group)");
    newsgroup = (char *) SvPV(ST(0), PL_na);

    ngp = NGfind(newsgroup);
    if (!ngp) {
        XSRETURN_UNDEF;
    } else {
        /* ngp->Rest is newline-terminated; find the end. */
        end = strchr(ngp->Rest, '\n');
        if (end == NULL) {
            size = strlen(ngp->Rest);
        } else {
            size = end - ngp->Rest;
        }
        ST(0) = sv_2mortal(newSVpv(ngp->Rest, size));
        XSRETURN(1);
    }
}


/*
**  Initialize the XS callbacks defined in this file.
*/
void
PLxsinit(void)
{
    inn_newXS("INN::addhist", XS_INN_addhist, "perl.c");
    inn_newXS("INN::article", XS_INN_article, "perl.c");
    inn_newXS("INN::cancel", XS_INN_cancel, "perl.c");
    inn_newXS("INN::havehist", XS_INN_havehist, "perl.c");
    inn_newXS("INN::head", XS_INN_head, "perl.c");
    inn_newXS("INN::newsgroup", XS_INN_newsgroup, "perl.c");
    inn_newXS("INN::filesfor", XS_INN_filesfor, "perl.c");
}

#endif /* defined(DO_PERL) */