1PERLFILTER(1)          Perl Programmers Reference Guide          PERLFILTER(1)
2
3
4

NAME

6       perlfilter - Source Filters
7

DESCRIPTION

9       This article is about a little-known feature of Perl called source fil‐
10       ters. Source filters alter the program text of a module before Perl
11       sees it, much as a C preprocessor alters the source text of a C program
12       before the compiler sees it. This article tells you more about what
13       source filters are, how they work, and how to write your own.
14
15       The original purpose of source filters was to let you encrypt your pro‐
16       gram source to prevent casual piracy. This isn't all they can do, as
17       you'll soon learn. But first, the basics.
18

CONCEPTS

20       Before the Perl interpreter can execute a Perl script, it must first
21       read it from a file into memory for parsing and compilation. If that
22       script itself includes other scripts with a "use" or "require" state‐
23       ment, then each of those scripts will have to be read from their
24       respective files as well.
25
26       Now think of each logical connection between the Perl parser and an
27       individual file as a source stream. A source stream is created when the
28       Perl parser opens a file, it continues to exist as the source code is
29       read into memory, and it is destroyed when Perl is finished parsing the
30       file. If the parser encounters a "require" or "use" statement in a
31       source stream, a new and distinct stream is created just for that file.
32
33       The diagram below represents a single source stream, with the flow of
34       source from a Perl script file on the left into the Perl parser on the
35       right. This is how Perl normally operates.
36
37           file -------> parser
38
39       There are two important points to remember:
40
41       1.   Although there can be any number of source streams in existence at
42            any given time, only one will be active.
43
44       2.   Every source stream is associated with only one file.
45
46       A source filter is a special kind of Perl module that intercepts and
47       modifies a source stream before it reaches the parser. A source filter
48       changes our diagram like this:
49
50           file ----> filter ----> parser
51
52       If that doesn't make much sense, consider the analogy of a command
53       pipeline. Say you have a shell script stored in the compressed file
54       trial.gz. The simple pipeline command below runs the script without
55       needing to create a temporary file to hold the uncompressed file.
56
57           gunzip -c trial.gz ⎪ sh
58
59       In this case, the data flow from the pipeline can be represented as
60       follows:
61
62           trial.gz ----> gunzip ----> sh
63
64       With source filters, you can store the text of your script compressed
65       and use a source filter to uncompress it for Perl's parser:
66
67            compressed           gunzip
68           Perl program ---> source filter ---> parser
69

USING FILTERS

71       So how do you use a source filter in a Perl script? Above, I said that
72       a source filter is just a special kind of module. Like all Perl mod‐
73       ules, a source filter is invoked with a use statement.
74
75       Say you want to pass your Perl source through the C preprocessor before
76       execution. You could use the existing "-P" command line option to do
77       this, but as it happens, the source filters distribution comes with a C
78       preprocessor filter module called Filter::cpp. Let's use that instead.
79
80       Below is an example program, "cpp_test", which makes use of this fil‐
81       ter.  Line numbers have been added to allow specific lines to be refer‐
82       enced easily.
83
84           1: use Filter::cpp;
85           2: #define TRUE 1
86           3: $a = TRUE;
87           4: print "a = $a\n";
88
89       When you execute this script, Perl creates a source stream for the
90       file. Before the parser processes any of the lines from the file, the
91       source stream looks like this:
92
93           cpp_test ---------> parser
94
95       Line 1, "use Filter::cpp", includes and installs the "cpp" filter mod‐
96       ule. All source filters work this way. The use statement is compiled
97       and executed at compile time, before any more of the file is read, and
98       it attaches the cpp filter to the source stream behind the scenes. Now
99       the data flow looks like this:
100
101           cpp_test ----> cpp filter ----> parser
102
103       As the parser reads the second and subsequent lines from the source
104       stream, it feeds those lines through the "cpp" source filter before
105       processing them. The "cpp" filter simply passes each line through the
106       real C preprocessor. The output from the C preprocessor is then
107       inserted back into the source stream by the filter.
108
109                         .-> cpp --.
110                         ⎪         ⎪
111                         ⎪         ⎪
112                         ⎪       <-'
113          cpp_test ----> cpp filter ----> parser
114
115       The parser then sees the following code:
116
117           use Filter::cpp;
118           $a = 1;
119           print "a = $a\n";
120
121       Let's consider what happens when the filtered code includes another
122       module with use:
123
124           1: use Filter::cpp;
125           2: #define TRUE 1
126           3: use Fred;
127           4: $a = TRUE;
128           5: print "a = $a\n";
129
130       The "cpp" filter does not apply to the text of the Fred module, only to
131       the text of the file that used it ("cpp_test"). Although the use state‐
132       ment on line 3 will pass through the cpp filter, the module that gets
133       included ("Fred") will not. The source streams look like this after
134       line 3 has been parsed and before line 4 is parsed:
135
136           cpp_test ---> cpp filter ---> parser (INACTIVE)
137
138           Fred.pm ----> parser
139
140       As you can see, a new stream has been created for reading the source
141       from "Fred.pm". This stream will remain active until all of "Fred.pm"
142       has been parsed. The source stream for "cpp_test" will still exist, but
143       is inactive. Once the parser has finished reading Fred.pm, the source
144       stream associated with it will be destroyed. The source stream for
145       "cpp_test" then becomes active again and the parser reads line 4 and
146       subsequent lines from "cpp_test".
147
148       You can use more than one source filter on a single file. Similarly,
149       you can reuse the same filter in as many files as you like.
150
151       For example, if you have a uuencoded and compressed source file, it is
152       possible to stack a uudecode filter and an uncompression filter like
153       this:
154
155           use Filter::uudecode; use Filter::uncompress;
156           M'XL(".H<US4''V9I;F%L')Q;>7/;1I;_>_I3=&E=%:F*I"T?22Q/
157           M6]9*<IQCO*XFT"0[PL%%'Y+IG?WN^ZYN-$'J.[.JE$,20/?K=_[>
158           ...
159
160       Once the first line has been processed, the flow will look like this:
161
162           file ---> uudecode ---> uncompress ---> parser
163                      filter         filter
164
165       Data flows through filters in the same order they appear in the source
166       file. The uudecode filter appeared before the uncompress filter, so the
167       source file will be uudecoded before it's uncompressed.
168

WRITING A SOURCE FILTER

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

WRITING A SOURCE FILTER IN C

177       The first of the three available techniques is to write the filter com‐
178       pletely in C. The external module you create interfaces directly with
179       the source filter hooks provided by Perl.
180
181       The advantage of this technique is that you have complete control over
182       the implementation of your filter. The big disadvantage is the
183       increased complexity required to write the filter - not only do you
184       need to understand the source filter hooks, but you also need a reason‐
185       able knowledge of Perl guts. One of the few times it is worth going to
186       this trouble is when writing a source scrambler. The "decrypt" filter
187       (which unscrambles the source before Perl parses it) included with the
188       source filter distribution is an example of a C source filter (see
189       Decryption Filters, below).
190
191       Decryption Filters
192            All decryption filters work on the principle of "security through
193            obscurity." Regardless of how well you write a decryption filter
194            and how strong your encryption algorithm, anyone determined enough
195            can retrieve the original source code. The reason is quite simple
196            - once the decryption filter has decrypted the source back to its
197            original form, fragments of it will be stored in the computer's
198            memory as Perl parses it. The source might only be in memory for a
199            short period of time, but anyone possessing a debugger, skill, and
200            lots of patience can eventually reconstruct your program.
201
202            That said, there are a number of steps that can be taken to make
203            life difficult for the potential cracker. The most important:
204            Write your decryption filter in C and statically link the decryp‐
205            tion module into the Perl binary. For further tips to make life
206            difficult for the potential cracker, see the file decrypt.pm in
207            the source filters module.
208

CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE

210       An alternative to writing the filter in C is to create a separate exe‐
211       cutable in the language of your choice. The separate executable reads
212       from standard input, does whatever processing is necessary, and writes
213       the filtered data to standard output. "Filter:cpp" is an example of a
214       source filter implemented as a separate executable - the executable is
215       the C preprocessor bundled with your C compiler.
216
217       The source filter distribution includes two modules that simplify this
218       task: "Filter::exec" and "Filter::sh". Both allow you to run any exter‐
219       nal executable. Both use a coprocess to control the flow of data into
220       and out of the external executable. (For details on coprocesses, see
221       Stephens, W.R. "Advanced Programming in the UNIX Environment."  Addi‐
222       son-Wesley, ISBN 0-210-56317-7, pages 441-445.) The difference between
223       them is that "Filter::exec" spawns the external command directly, while
224       "Filter::sh" spawns a shell to execute the external command. (Unix uses
225       the Bourne shell; NT uses the cmd shell.) Spawning a shell allows you
226       to make use of the shell metacharacters and redirection facilities.
227
228       Here is an example script that uses "Filter::sh":
229
230           use Filter::sh 'tr XYZ PQR';
231           $a = 1;
232           print "XYZ a = $a\n";
233
234       The output you'll get when the script is executed:
235
236           PQR a = 1
237
238       Writing a source filter as a separate executable works fine, but a
239       small performance penalty is incurred. For example, if you execute the
240       small example above, a separate subprocess will be created to run the
241       Unix "tr" command. Each use of the filter requires its own subprocess.
242       If creating subprocesses is expensive on your system, you might want to
243       consider one of the other options for creating source filters.
244

WRITING A SOURCE FILTER IN PERL

246       The easiest and most portable option available for creating your own
247       source filter is to write it completely in Perl. To distinguish this
248       from the previous two techniques, I'll call it a Perl source filter.
249
250       To help understand how to write a Perl source filter we need an example
251       to study. Here is a complete source filter that performs rot13 decod‐
252       ing. (Rot13 is a very simple encryption scheme used in Usenet postings
253       to hide the contents of offensive posts. It moves every letter forward
254       thirteen places, so that A becomes N, B becomes O, and Z becomes M.)
255
256          package Rot13;
257
258          use Filter::Util::Call;
259
260          sub import {
261             my ($type) = @_;
262             my ($ref) = [];
263             filter_add(bless $ref);
264          }
265
266          sub filter {
267             my ($self) = @_;
268             my ($status);
269
270             tr/n-za-mN-ZA-M/a-zA-Z/
271                if ($status = filter_read()) > 0;
272             $status;
273          }
274
275          1;
276
277       All Perl source filters are implemented as Perl classes and have the
278       same basic structure as the example above.
279
280       First, we include the "Filter::Util::Call" module, which exports a num‐
281       ber of functions into your filter's namespace. The filter shown above
282       uses two of these functions, "filter_add()" and "filter_read()".
283
284       Next, we create the filter object and associate it with the source
285       stream by defining the "import" function. If you know Perl well enough,
286       you know that "import" is called automatically every time a module is
287       included with a use statement. This makes "import" the ideal place to
288       both create and install a filter object.
289
290       In the example filter, the object ($ref) is blessed just like any other
291       Perl object. Our example uses an anonymous array, but this isn't a
292       requirement. Because this example doesn't need to store any context
293       information, we could have used a scalar or hash reference just as
294       well. The next section demonstrates context data.
295
296       The association between the filter object and the source stream is made
297       with the "filter_add()" function. This takes a filter object as a
298       parameter ($ref in this case) and installs it in the source stream.
299
300       Finally, there is the code that actually does the filtering. For this
301       type of Perl source filter, all the filtering is done in a method
302       called "filter()". (It is also possible to write a Perl source filter
303       using a closure. See the "Filter::Util::Call" manual page for more
304       details.) It's called every time the Perl parser needs another line of
305       source to process. The "filter()" method, in turn, reads lines from the
306       source stream using the "filter_read()" function.
307
308       If a line was available from the source stream, "filter_read()" returns
309       a status value greater than zero and appends the line to $_.  A status
310       value of zero indicates end-of-file, less than zero means an error. The
311       filter function itself is expected to return its status in the same
312       way, and put the filtered line it wants written to the source stream in
313       $_. The use of $_ accounts for the brevity of most Perl source filters.
314
315       In order to make use of the rot13 filter we need some way of encoding
316       the source file in rot13 format. The script below, "mkrot13", does just
317       that.
318
319           die "usage mkrot13 filename\n" unless @ARGV;
320           my $in = $ARGV[0];
321           my $out = "$in.tmp";
322           open(IN, "<$in") or die "Cannot open file $in: $!\n";
323           open(OUT, ">$out") or die "Cannot open file $out: $!\n";
324
325           print OUT "use Rot13;\n";
326           while (<IN>) {
327              tr/a-zA-Z/n-za-mN-ZA-M/;
328              print OUT;
329           }
330
331           close IN;
332           close OUT;
333           unlink $in;
334           rename $out, $in;
335
336       If we encrypt this with "mkrot13":
337
338           print " hello fred \n";
339
340       the result will be this:
341
342           use Rot13;
343           cevag "uryyb serq\a";
344
345       Running it produces this output:
346
347           hello fred
348

USING CONTEXT: THE DEBUG FILTER

350       The rot13 example was a trivial example. Here's another demonstration
351       that shows off a few more features.
352
353       Say you wanted to include a lot of debugging code in your Perl script
354       during development, but you didn't want it available in the released
355       product. Source filters offer a solution. In order to keep the example
356       simple, let's say you wanted the debugging output to be controlled by
357       an environment variable, "DEBUG". Debugging code is enabled if the
358       variable exists, otherwise it is disabled.
359
360       Two special marker lines will bracket debugging code, like this:
361
362           ## DEBUG_BEGIN
363           if ($year > 1999) {
364              warn "Debug: millennium bug in year $year\n";
365           }
366           ## DEBUG_END
367
368       When the "DEBUG" environment variable exists, the filter ensures that
369       Perl parses only the code between the "DEBUG_BEGIN" and "DEBUG_END"
370       markers. That means that when "DEBUG" does exist, the code above should
371       be passed through the filter unchanged. The marker lines can also be
372       passed through as-is, because the Perl parser will see them as comment
373       lines. When "DEBUG" isn't set, we need a way to disable the debug code.
374       A simple way to achieve that is to convert the lines between the two
375       markers into comments:
376
377           ## DEBUG_BEGIN
378           #if ($year > 1999) {
379           #     warn "Debug: millennium bug in year $year\n";
380           #}
381           ## DEBUG_END
382
383       Here is the complete Debug filter:
384
385           package Debug;
386
387           use strict;
388           use warnings;
389           use Filter::Util::Call;
390
391           use constant TRUE => 1;
392           use constant FALSE => 0;
393
394           sub import {
395              my ($type) = @_;
396              my (%context) = (
397                Enabled => defined $ENV{DEBUG},
398                InTraceBlock => FALSE,
399                Filename => (caller)[1],
400                LineNo => 0,
401                LastBegin => 0,
402              );
403              filter_add(bless \%context);
404           }
405
406           sub Die {
407              my ($self) = shift;
408              my ($message) = shift;
409              my ($line_no) = shift ⎪⎪ $self->{LastBegin};
410              die "$message at $self->{Filename} line $line_no.\n"
411           }
412
413           sub filter {
414              my ($self) = @_;
415              my ($status);
416              $status = filter_read();
417              ++ $self->{LineNo};
418
419              # deal with EOF/error first
420              if ($status <= 0) {
421                  $self->Die("DEBUG_BEGIN has no DEBUG_END")
422                      if $self->{InTraceBlock};
423                  return $status;
424              }
425
426              if ($self->{InTraceBlock}) {
427                 if (/^\s*##\s*DEBUG_BEGIN/ ) {
428                     $self->Die("Nested DEBUG_BEGIN", $self->{LineNo})
429                 } elsif (/^\s*##\s*DEBUG_END/) {
430                     $self->{InTraceBlock} = FALSE;
431                 }
432
433                 # comment out the debug lines when the filter is disabled
434                 s/^/#/ if ! $self->{Enabled};
435              } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
436                 $self->{InTraceBlock} = TRUE;
437                 $self->{LastBegin} = $self->{LineNo};
438              } elsif ( /^\s*##\s*DEBUG_END/ ) {
439                 $self->Die("DEBUG_END has no DEBUG_BEGIN", $self->{LineNo});
440              }
441              return $status;
442           }
443
444           1;
445
446       The big difference between this filter and the previous example is the
447       use of context data in the filter object. The filter object is based on
448       a hash reference, and is used to keep various pieces of context infor‐
449       mation between calls to the filter function. All but two of the hash
450       fields are used for error reporting. The first of those two, Enabled,
451       is used by the filter to determine whether the debugging code should be
452       given to the Perl parser. The second, InTraceBlock, is true when the
453       filter has encountered a "DEBUG_BEGIN" line, but has not yet encoun‐
454       tered the following "DEBUG_END" line.
455
456       If you ignore all the error checking that most of the code does, the
457       essence of the filter is as follows:
458
459           sub filter {
460              my ($self) = @_;
461              my ($status);
462              $status = filter_read();
463
464              # deal with EOF/error first
465              return $status if $status <= 0;
466              if ($self->{InTraceBlock}) {
467                 if (/^\s*##\s*DEBUG_END/) {
468                    $self->{InTraceBlock} = FALSE
469                 }
470
471                 # comment out debug lines when the filter is disabled
472                 s/^/#/ if ! $self->{Enabled};
473              } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
474                 $self->{InTraceBlock} = TRUE;
475              }
476              return $status;
477           }
478
479       Be warned: just as the C-preprocessor doesn't know C, the Debug filter
480       doesn't know Perl. It can be fooled quite easily:
481
482           print <<EOM;
483           ##DEBUG_BEGIN
484           EOM
485
486       Such things aside, you can see that a lot can be achieved with a modest
487       amount of code.
488

CONCLUSION

490       You now have better understanding of what a source filter is, and you
491       might even have a possible use for them. If you feel like playing with
492       source filters but need a bit of inspiration, here are some extra fea‐
493       tures you could add to the Debug filter.
494
495       First, an easy one. Rather than having debugging code that is
496       all-or-nothing, it would be much more useful to be able to control
497       which specific blocks of debugging code get included. Try extending the
498       syntax for debug blocks to allow each to be identified. The contents of
499       the "DEBUG" environment variable can then be used to control which
500       blocks get included.
501
502       Once you can identify individual blocks, try allowing them to be
503       nested. That isn't difficult either.
504
505       Here is an interesting idea that doesn't involve the Debug filter.
506       Currently Perl subroutines have fairly limited support for formal
507       parameter lists. You can specify the number of parameters and their
508       type, but you still have to manually take them out of the @_ array
509       yourself. Write a source filter that allows you to have a named parame‐
510       ter list. Such a filter would turn this:
511
512           sub MySub ($first, $second, @rest) { ... }
513
514       into this:
515
516           sub MySub($$@) {
517              my ($first) = shift;
518              my ($second) = shift;
519              my (@rest) = @_;
520              ...
521           }
522
523       Finally, if you feel like a real challenge, have a go at writing a
524       full-blown Perl macro preprocessor as a source filter. Borrow the use‐
525       ful features from the C preprocessor and any other macro processors you
526       know. The tricky bit will be choosing how much knowledge of Perl's syn‐
527       tax you want your filter to have.
528

THINGS TO LOOK OUT FOR

530       Some Filters Clobber the "DATA" Handle
531            Some source filters use the "DATA" handle to read the calling pro‐
532            gram.  When using these source filters you cannot rely on this
533            handle, nor expect any particular kind of behavior when operating
534            on it.  Filters based on Filter::Util::Call (and therefore Fil‐
535            ter::Simple) do not alter the "DATA" filehandle.
536

REQUIREMENTS

538       The Source Filters distribution is available on CPAN, in
539
540           CPAN/modules/by-module/Filter
541
542       Starting from Perl 5.8 Filter::Util::Call (the core part of the Source
543       Filters distribution) is part of the standard Perl distribution.  Also
544       included is a friendlier interface called Filter::Simple, by Damian
545       Conway.
546

AUTHOR

548       Paul Marquess <Paul.Marquess@btinternet.com>
549

Copyrights

551       This article originally appeared in The Perl Journal #11, and is copy‐
552       right 1998 The Perl Journal. It appears courtesy of Jon Orwant and The
553       Perl Journal.  This document may be distributed under the same terms as
554       Perl itself.
555
556
557
558perl v5.8.8                       2006-01-07                     PERLFILTER(1)
Impressum