Cari di Perl 
    Perl User Manual
Daftar Isi
(Sebelumnya) Preparing a new module for dis ...Perl Glossary (Berikutnya)
Language Reference

Source Filters

Daftar Isi

NAME

perlfilter - Source Filters

DESCRIPTION

This article is about a little-known feature of Perl calledsource filters. Source filters alter the program text of a modulebefore Perl sees it, much as a C preprocessor alters the source text ofa C program before the compiler sees it. This article tells you moreabout what source filters are, how they work, and how to write yourown.

The original purpose of source filters was to let you encrypt yourprogram source to prevent casual piracy. This isn't all they can do, asyou'll soon learn. But first, the basics.

CONCEPTS

Before the Perl interpreter can execute a Perl script, it must firstread it from a file into memory for parsing and compilation. If thatscript itself includes other scripts with a use or requirestatement, then each of those scripts will have to be read from theirrespective files as well.

Now think of each logical connection between the Perl parser and anindividual file as a source stream. A source stream is created whenthe Perl parser opens a file, it continues to exist as the source codeis read into memory, and it is destroyed when Perl is finished parsingthe file. If the parser encounters a require or use statement ina source stream, a new and distinct stream is created just for thatfile.

The diagram below represents a single source stream, with the flow ofsource from a Perl script file on the left into the Perl parser on theright. This is how Perl normally operates.

  1. file -------> parser

There are two important points to remember:

1.

Although there can be any number of source streams in existence at anygiven time, only one will be active.

2.

Every source stream is associated with only one file.

A source filter is a special kind of Perl module that intercepts andmodifies a source stream before it reaches the parser. A source filterchanges our diagram like this:

  1. file ----> filter ----> parser

If that doesn't make much sense, consider the analogy of a commandpipeline. Say you have a shell script stored in the compressed filetrial.gz. The simple pipeline command below runs the script withoutneeding to create a temporary file to hold the uncompressed file.

  1. gunzip -c trial.gz | sh

In this case, the data flow from the pipeline can be represented as follows:

  1. trial.gz ----> gunzip ----> sh

With source filters, you can store the text of your script compressed and use a source filter to uncompress it for Perl's parser:

  1. compressed gunzip
  2. Perl program ---> source filter ---> parser

USING FILTERS

So how do you use a source filter in a Perl script? Above, I said thata source filter is just a special kind of module. Like all Perlmodules, a source filter is invoked with a use statement.

Say you want to pass your Perl source through the C preprocessor beforeexecution. As it happens, the source filters distribution comes with a Cpreprocessor filter module called Filter::cpp.

Below is an example program, cpp_test, which makes use of this filter.Line numbers have been added to allow specific lines to be referencedeasily.

  1. 1: use Filter::cpp;
  2. 2: #define TRUE 1
  3. 3: $a = TRUE;
  4. 4: print "a = $a\n";

When you execute this script, Perl creates a source stream for thefile. Before the parser processes any of the lines from the file, thesource stream looks like this:

  1. cpp_test ---------> parser

Line 1, use Filter::cpp, includes and installs the cpp filtermodule. All source filters work this way. The use statement is compiledand executed at compile time, before any more of the file is read, andit attaches the cpp filter to the source stream behind the scenes. Nowthe data flow looks like this:

  1. cpp_test ----> cpp filter ----> parser

As the parser reads the second and subsequent lines from the sourcestream, it feeds those lines through the cpp source filter beforeprocessing them. The cpp filter simply passes each line through thereal C preprocessor. The output from the C preprocessor is theninserted back into the source stream by the filter.

  1. .-> cpp --.
  2. | |
  3. | |
  4. | <-'
  5. cpp_test ----> cpp filter ----> parser

The parser then sees the following code:

  1. use Filter::cpp;
  2. $a = 1;
  3. print "a = $a\n";

Let's consider what happens when the filtered code includes anothermodule with use:

  1. 1: use Filter::cpp;
  2. 2: #define TRUE 1
  3. 3: use Fred;
  4. 4: $a = TRUE;
  5. 5: print "a = $a\n";

The cpp filter does not apply to the text of the Fred module, onlyto the text of the file that used it (cpp_test). Although the usestatement on line 3 will pass through the cpp filter, the module thatgets included (Fred) will not. The source streams look like thisafter line 3 has been parsed and before line 4 is parsed:

  1. cpp_test ---> cpp filter ---> parser (INACTIVE)
  2. Fred.pm ----> parser

As you can see, a new stream has been created for reading the sourcefrom Fred.pm. This stream will remain active until all of Fred.pmhas been parsed. The source stream for cpp_test will still exist,but is inactive. Once the parser has finished reading Fred.pm, thesource stream associated with it will be destroyed. The source streamfor cpp_test then becomes active again and the parser reads line 4and subsequent lines from cpp_test.

You can use more than one source filter on a single file. Similarly,you can reuse the same filter in as many files as you like.

For example, if you have a uuencoded and compressed source file, it ispossible to stack a uudecode filter and an uncompression filter likethis:

  1. use Filter::uudecode; use Filter::uncompress;
  2. M'XL(".H<US4''V9I;F%L')Q;>7/;1I;_>_I3=&E=%:F*I"T?22Q/
  3. M6]9*<IQCO*XFT"0[PL%%'Y+IG?WN^ZYN-$'J.[.JE$,20/?K=_[>
  4. ...

Once the first line has been processed, the flow will look like this:

  1. file ---> uudecode ---> uncompress ---> parser
  2. filter filter

Data flows through filters in the same order they appear in the sourcefile. The uudecode filter appeared before the uncompress filter, so thesource file will be uudecoded before it's uncompressed.

WRITING A SOURCE FILTER

There are three ways to write your own source filter. You can write itin C, use an external program as a filter, or write the filter in Perl.I won't cover the first two in any great detail, so I'll get them outof the way first. Writing the filter in Perl is most convenient, soI'll devote the most space to it.

WRITING A SOURCE FILTER IN C

The first of the three available techniques is to write the filtercompletely in C. The external module you create interfaces directlywith the source filter hooks provided by Perl.

The advantage of this technique is that you have complete control overthe implementation of your filter. The big disadvantage is theincreased complexity required to write the filter - not only do youneed to understand the source filter hooks, but you also need areasonable knowledge of Perl guts. One of the few times it is worthgoing to this trouble is when writing a source scrambler. Thedecrypt filter (which unscrambles the source before Perl parses it)included with the source filter distribution is an example of a Csource filter (see Decryption Filters, below).

  • Decryption Filters

    All decryption filters work on the principle of "security throughobscurity." Regardless of how well you write a decryption filter andhow strong your encryption algorithm is, anyone determined enough canretrieve the original source code. The reason is quite simple - oncethe decryption filter has decrypted the source back to its originalform, fragments of it will be stored in the computer's memory as Perlparses it. The source might only be in memory for a short period oftime, but anyone possessing a debugger, skill, and lots of patience caneventually reconstruct your program.

    That said, there are a number of steps that can be taken to make lifedifficult for the potential cracker. The most important: Write yourdecryption filter in C and statically link the decryption module intothe Perl binary. For further tips to make life difficult for thepotential cracker, see the file decrypt.pm in the source filtersdistribution.

CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE

An alternative to writing the filter in C is to create a separateexecutable in the language of your choice. The separate executablereads from standard input, does whatever processing is necessary, andwrites the filtered data to standard output. Filter::cpp is anexample of a source filter implemented as a separate executable - theexecutable is the C preprocessor bundled with your C compiler.

The source filter distribution includes two modules that simplify thistask: Filter::exec and Filter::sh. Both allow you to run anyexternal executable. Both use a coprocess to control the flow of datainto and out of the external executable. (For details on coprocesses,see Stephens, W.R., "Advanced Programming in the UNIX Environment."Addison-Wesley, ISBN 0-210-56317-7, pages 441-445.) The differencebetween them is that Filter::exec spawns the external commanddirectly, while Filter::sh spawns a shell to execute the externalcommand. (Unix uses the Bourne shell; NT uses the cmd shell.) Spawninga shell allows you to make use of the shell metacharacters andredirection facilities.

Here is an example script that uses Filter::sh:

  1. use Filter::sh 'tr XYZ PQR';
  2. $a = 1;
  3. print "XYZ a = $a\n";

The output you'll get when the script is executed:

  1. PQR a = 1

Writing a source filter as a separate executable works fine, but asmall performance penalty is incurred. For example, if you execute thesmall example above, a separate subprocess will be created to run theUnix tr command. Each use of the filter requires its own subprocess.If creating subprocesses is expensive on your system, you might want toconsider one of the other options for creating source filters.

WRITING A SOURCE FILTER IN PERL

The easiest and most portable option available for creating your ownsource filter is to write it completely in Perl. To distinguish thisfrom the previous two techniques, I'll call it a Perl source filter.

To help understand how to write a Perl source filter we need an exampleto study. Here is a complete source filter that performs rot13decoding. (Rot13 is a very simple encryption scheme used in Usenetpostings to hide the contents of offensive posts. It moves every letterforward thirteen places, so that A becomes N, B becomes O, and Zbecomes M.)

  1. package Rot13;
  2. use Filter::Util::Call;
  3. sub import {
  4. my ($type) = @_;
  5. my ($ref) = [];
  6. filter_add(bless $ref);
  7. }
  8. sub filter {
  9. my ($self) = @_;
  10. my ($status);
  11. tr/n-za-mN-ZA-M/a-zA-Z/
  12. if ($status = filter_read()) > 0;
  13. $status;
  14. }
  15. 1;

All Perl source filters are implemented as Perl classes and have thesame basic structure as the example above.

First, we include the Filter::Util::Call module, which exports anumber of functions into your filter's namespace. The filter shownabove uses two of these functions, filter_add() andfilter_read().

Next, we create the filter object and associate it with the sourcestream by defining the import function. If you know Perl wellenough, you know that import is called automatically every time amodule is included with a use statement. This makes import the idealplace to both create and install a filter object.

In the example filter, the object ($ref) is blessed just like anyother Perl object. Our example uses an anonymous array, but this isn'ta requirement. Because this example doesn't need to store any contextinformation, we could have used a scalar or hash reference just aswell. The next section demonstrates context data.

The association between the filter object and the source stream is madewith the filter_add() function. This takes a filter object as aparameter ($ref in this case) and installs it in the source stream.

Finally, there is the code that actually does the filtering. For thistype of Perl source filter, all the filtering is done in a methodcalled filter(). (It is also possible to write a Perl source filterusing a closure. See the Filter::Util::Call manual page for moredetails.) It's called every time the Perl parser needs another line ofsource to process. The filter() method, in turn, reads lines fromthe source stream using the filter_read() function.

If a line was available from the source stream, filter_read()returns a status value greater than zero and appends the line to $_.A status value of zero indicates end-of-file, less than zero means anerror. The filter function itself is expected to return its status inthe same way, and put the filtered line it wants written to the sourcestream in $_. The use of $_ accounts for the brevity of most Perlsource filters.

In order to make use of the rot13 filter we need some way of encodingthe source file in rot13 format. The script below, mkrot13, doesjust that.

  1. die "usage mkrot13 filename\n" unless @ARGV;
  2. my $in = $ARGV[0];
  3. my $out = "$in.tmp";
  4. open(IN, "<$in") or die "Cannot open file $in: $!\n";
  5. open(OUT, ">$out") or die "Cannot open file $out: $!\n";
  6. print OUT "use Rot13;\n";
  7. while (<IN>) {
  8. tr/a-zA-Z/n-za-mN-ZA-M/;
  9. print OUT;
  10. }
  11. close IN;
  12. close OUT;
  13. unlink $in;
  14. rename $out, $in;

If we encrypt this with mkrot13:

  1. print " hello fred \n";

the result will be this:

  1. use Rot13;
  2. cevag "uryyb serq\a";

Running it produces this output:

  1. hello fred

USING CONTEXT: THE DEBUG FILTER

The rot13 example was a trivial example. Here's another demonstrationthat shows off a few more features.

Say you wanted to include a lot of debugging code in your Perl scriptduring development, but you didn't want it available in the releasedproduct. Source filters offer a solution. In order to keep the examplesimple, let's say you wanted the debugging output to be controlled byan environment variable, DEBUG. Debugging code is enabled if thevariable exists, otherwise it is disabled.

Two special marker lines will bracket debugging code, like this:

  1. ## DEBUG_BEGIN
  2. if ($year > 1999) {
  3. warn "Debug: millennium bug in year $year\n";
  4. }
  5. ## DEBUG_END

The filter ensures that Perl parses the code between the <DEBUG_BEGIN>and DEBUG_END markers only when the DEBUG environment variableexists. That means that when DEBUG does exist, the code aboveshould be passed through the filter unchanged. The marker lines canalso be passed through as-is, because the Perl parser will see them ascomment lines. When DEBUG isn't set, we need a way to disable thedebug code. A simple way to achieve that is to convert the linesbetween the two markers into comments:

  1. ## DEBUG_BEGIN
  2. #if ($year > 1999) {
  3. # warn "Debug: millennium bug in year $year\n"
  4. #}
  5. ## DEBUG_END

Here is the complete Debug filter:

  1. package Debug;
  2. use strict;
  3. use warnings;
  4. use Filter::Util::Call;
  5. use constant TRUE => 1;
  6. use constant FALSE => 0;
  7. sub import {
  8. my ($type) = @_;
  9. my (%context) = (
  10. Enabled => defined $ENV{DEBUG},
  11. InTraceBlock => FALSE,
  12. Filename => (caller)[1],
  13. LineNo => 0,
  14. LastBegin => 0,
  15. );
  16. filter_add(bless \%context);
  17. }
  18. sub Die {
  19. my ($self) = shift;
  20. my ($message) = shift;
  21. my ($line_no) = shift || $self->{LastBegin};
  22. die "$message at $self->{Filename} line $line_no.\n"
  23. }
  24. sub filter {
  25. my ($self) = @_;
  26. my ($status);
  27. $status = filter_read();
  28. ++ $self->{LineNo};
  29. # deal with EOF/error first
  30. if ($status <= 0) {
  31. $self->Die("DEBUG_BEGIN has no DEBUG_END")
  32. if $self->{InTraceBlock};
  33. return $status;
  34. }
  35. if ($self->{InTraceBlock}) {
  36. if (/^\s*##\s*DEBUG_BEGIN/ ) {
  37. $self->Die("Nested DEBUG_BEGIN", $self->{LineNo})
  38. } elsif (/^\s*##\s*DEBUG_END/) {
  39. $self->{InTraceBlock} = FALSE;
  40. }
  41. # comment out the debug lines when the filter is disabled
  42. s/^/#/ if ! $self->{Enabled};
  43. } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
  44. $self->{InTraceBlock} = TRUE;
  45. $self->{LastBegin} = $self->{LineNo};
  46. } elsif ( /^\s*##\s*DEBUG_END/ ) {
  47. $self->Die("DEBUG_END has no DEBUG_BEGIN", $self->{LineNo});
  48. }
  49. return $status;
  50. }
  51. 1;

The big difference between this filter and the previous example is theuse of context data in the filter object. The filter object is based ona hash reference, and is used to keep various pieces of contextinformation between calls to the filter function. All but two of thehash fields are used for error reporting. The first of those two,Enabled, is used by the filter to determine whether the debugging codeshould be given to the Perl parser. The second, InTraceBlock, is truewhen the filter has encountered a DEBUG_BEGIN line, but has not yetencountered the following DEBUG_END line.

If you ignore all the error checking that most of the code does, theessence of the filter is as follows:

  1. sub filter {
  2. my ($self) = @_;
  3. my ($status);
  4. $status = filter_read();
  5. # deal with EOF/error first
  6. return $status if $status <= 0;
  7. if ($self->{InTraceBlock}) {
  8. if (/^\s*##\s*DEBUG_END/) {
  9. $self->{InTraceBlock} = FALSE
  10. }
  11. # comment out debug lines when the filter is disabled
  12. s/^/#/ if ! $self->{Enabled};
  13. } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
  14. $self->{InTraceBlock} = TRUE;
  15. }
  16. return $status;
  17. }

Be warned: just as the C-preprocessor doesn't know C, the Debug filterdoesn't know Perl. It can be fooled quite easily:

  1. print <<EOM;
  2. ##DEBUG_BEGIN
  3. EOM

Such things aside, you can see that a lot can be achieved with a modestamount of code.

CONCLUSION

You now have better understanding of what a source filter is, and youmight even have a possible use for them. If you feel like playing withsource filters but need a bit of inspiration, here are some extrafeatures you could add to the Debug filter.

First, an easy one. Rather than having debugging code that isall-or-nothing, it would be much more useful to be able to controlwhich specific blocks of debugging code get included. Try extending thesyntax for debug blocks to allow each to be identified. The contents ofthe DEBUG environment variable can then be used to control whichblocks get included.

Once you can identify individual blocks, try allowing them to benested. That isn't difficult either.

Here is an interesting idea that doesn't involve the Debug filter.Currently Perl subroutines have fairly limited support for formalparameter lists. You can specify the number of parameters and theirtype, but you still have to manually take them out of the @_ arrayyourself. Write a source filter that allows you to have a namedparameter list. Such a filter would turn this:

  1. sub MySub ($first, $second, @rest) { ... }

into this:

  1. sub MySub($$@) {
  2. my ($first) = shift;
  3. my ($second) = shift;
  4. my (@rest) = @_;
  5. ...
  6. }

Finally, if you feel like a real challenge, have a go at writing afull-blown Perl macro preprocessor as a source filter. Borrow theuseful features from the C preprocessor and any other macro processorsyou know. The tricky bit will be choosing how much knowledge of Perl'ssyntax you want your filter to have.

THINGS TO LOOK OUT FOR

  • Some Filters Clobber the DATA Handle

    Some source filters use the DATA handle to read the calling program.When using these source filters you cannot rely on this handle, nor expectany particular kind of behavior when operating on it. Filters based onFilter::Util::Call (and therefore Filter::Simple) do not alter the DATAfilehandle.

REQUIREMENTS

The Source Filters distribution is available on CPAN, in

  1. CPAN/modules/by-module/Filter

Starting from Perl 5.8 Filter::Util::Call (the core part of theSource Filters distribution) is part of the standard Perl distribution.Also included is a friendlier interface called Filter::Simple, byDamian Conway.

AUTHOR

Paul Marquess <[email protected]>

Copyrights

This article originally appeared in The Perl Journal #11, and iscopyright 1998 The Perl Journal. It appears courtesy of Jon Orwant andThe Perl Journal. This document may be distributed under the same termsas Perl itself.

 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) Preparing a new module for dis ...Perl Glossary (Berikutnya)