1PERLFILTER(1) Perl Programmers Reference Guide PERLFILTER(1)
2
3
4
6 perlfilter - Source Filters
7
9 This article is about a little-known feature of Perl called source
10 filters. 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
16 program source to prevent casual piracy. This isn't all they can do, as
17 you'll soon learn. But first, the basics.
18
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"
23 statement, 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
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
73 modules, 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
81 filter. Line numbers have been added to allow specific lines to be
82 referenced 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
96 module. 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
132 statement on line 3 will pass through the cpp filter, the module that
133 gets included ("Fred") will not. The source streams look like this
134 after 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
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
177 The first of the three available techniques is to write the filter
178 completely in C. The external module you create interfaces directly
179 with 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
185 reasonable knowledge of Perl guts. One of the few times it is worth
186 going to this trouble is when writing a source scrambler. The "decrypt"
187 filter (which unscrambles the source before Perl parses it) included
188 with the source filter distribution is an example of a C source filter
189 (see 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 is, anyone determined
195 enough can retrieve the original source code. The reason is quite
196 simple - once the decryption filter has decrypted the source back
197 to its original form, fragments of it will be stored in the
198 computer's memory as Perl parses it. The source might only be in
199 memory for a short period of time, but anyone possessing a
200 debugger, skill, and lots of patience can eventually reconstruct
201 your program.
202
203 That said, there are a number of steps that can be taken to make
204 life difficult for the potential cracker. The most important:
205 Write your decryption filter in C and statically link the
206 decryption module into the Perl binary. For further tips to make
207 life difficult for the potential cracker, see the file decrypt.pm
208 in the source filters module.
209
211 An alternative to writing the filter in C is to create a separate
212 executable in the language of your choice. The separate executable
213 reads from standard input, does whatever processing is necessary, and
214 writes the filtered data to standard output. "Filter::cpp" is an
215 example of a source filter implemented as a separate executable - the
216 executable is the C preprocessor bundled with your C compiler.
217
218 The source filter distribution includes two modules that simplify this
219 task: "Filter::exec" and "Filter::sh". Both allow you to run any
220 external executable. Both use a coprocess to control the flow of data
221 into and out of the external executable. (For details on coprocesses,
222 see Stephens, W.R. "Advanced Programming in the UNIX Environment."
223 Addison-Wesley, ISBN 0-210-56317-7, pages 441-445.) The difference
224 between them is that "Filter::exec" spawns the external command
225 directly, while "Filter::sh" spawns a shell to execute the external
226 command. (Unix uses the Bourne shell; NT uses the cmd shell.) Spawning
227 a shell allows you to make use of the shell metacharacters and
228 redirection facilities.
229
230 Here is an example script that uses "Filter::sh":
231
232 use Filter::sh 'tr XYZ PQR';
233 $a = 1;
234 print "XYZ a = $a\n";
235
236 The output you'll get when the script is executed:
237
238 PQR a = 1
239
240 Writing a source filter as a separate executable works fine, but a
241 small performance penalty is incurred. For example, if you execute the
242 small example above, a separate subprocess will be created to run the
243 Unix "tr" command. Each use of the filter requires its own subprocess.
244 If creating subprocesses is expensive on your system, you might want to
245 consider one of the other options for creating source filters.
246
248 The easiest and most portable option available for creating your own
249 source filter is to write it completely in Perl. To distinguish this
250 from the previous two techniques, I'll call it a Perl source filter.
251
252 To help understand how to write a Perl source filter we need an example
253 to study. Here is a complete source filter that performs rot13
254 decoding. (Rot13 is a very simple encryption scheme used in Usenet
255 postings to hide the contents of offensive posts. It moves every letter
256 forward thirteen places, so that A becomes N, B becomes O, and Z
257 becomes M.)
258
259 package Rot13;
260
261 use Filter::Util::Call;
262
263 sub import {
264 my ($type) = @_;
265 my ($ref) = [];
266 filter_add(bless $ref);
267 }
268
269 sub filter {
270 my ($self) = @_;
271 my ($status);
272
273 tr/n-za-mN-ZA-M/a-zA-Z/
274 if ($status = filter_read()) > 0;
275 $status;
276 }
277
278 1;
279
280 All Perl source filters are implemented as Perl classes and have the
281 same basic structure as the example above.
282
283 First, we include the "Filter::Util::Call" module, which exports a
284 number of functions into your filter's namespace. The filter shown
285 above uses two of these functions, "filter_add()" and "filter_read()".
286
287 Next, we create the filter object and associate it with the source
288 stream by defining the "import" function. If you know Perl well enough,
289 you know that "import" is called automatically every time a module is
290 included with a use statement. This makes "import" the ideal place to
291 both create and install a filter object.
292
293 In the example filter, the object ($ref) is blessed just like any other
294 Perl object. Our example uses an anonymous array, but this isn't a
295 requirement. Because this example doesn't need to store any context
296 information, we could have used a scalar or hash reference just as
297 well. The next section demonstrates context data.
298
299 The association between the filter object and the source stream is made
300 with the "filter_add()" function. This takes a filter object as a
301 parameter ($ref in this case) and installs it in the source stream.
302
303 Finally, there is the code that actually does the filtering. For this
304 type of Perl source filter, all the filtering is done in a method
305 called "filter()". (It is also possible to write a Perl source filter
306 using a closure. See the "Filter::Util::Call" manual page for more
307 details.) It's called every time the Perl parser needs another line of
308 source to process. The "filter()" method, in turn, reads lines from the
309 source stream using the "filter_read()" function.
310
311 If a line was available from the source stream, "filter_read()" returns
312 a status value greater than zero and appends the line to $_. A status
313 value of zero indicates end-of-file, less than zero means an error. The
314 filter function itself is expected to return its status in the same
315 way, and put the filtered line it wants written to the source stream in
316 $_. The use of $_ accounts for the brevity of most Perl source filters.
317
318 In order to make use of the rot13 filter we need some way of encoding
319 the source file in rot13 format. The script below, "mkrot13", does just
320 that.
321
322 die "usage mkrot13 filename\n" unless @ARGV;
323 my $in = $ARGV[0];
324 my $out = "$in.tmp";
325 open(IN, "<$in") or die "Cannot open file $in: $!\n";
326 open(OUT, ">$out") or die "Cannot open file $out: $!\n";
327
328 print OUT "use Rot13;\n";
329 while (<IN>) {
330 tr/a-zA-Z/n-za-mN-ZA-M/;
331 print OUT;
332 }
333
334 close IN;
335 close OUT;
336 unlink $in;
337 rename $out, $in;
338
339 If we encrypt this with "mkrot13":
340
341 print " hello fred \n";
342
343 the result will be this:
344
345 use Rot13;
346 cevag "uryyb serq\a";
347
348 Running it produces this output:
349
350 hello fred
351
353 The rot13 example was a trivial example. Here's another demonstration
354 that shows off a few more features.
355
356 Say you wanted to include a lot of debugging code in your Perl script
357 during development, but you didn't want it available in the released
358 product. Source filters offer a solution. In order to keep the example
359 simple, let's say you wanted the debugging output to be controlled by
360 an environment variable, "DEBUG". Debugging code is enabled if the
361 variable exists, otherwise it is disabled.
362
363 Two special marker lines will bracket debugging code, like this:
364
365 ## DEBUG_BEGIN
366 if ($year > 1999) {
367 warn "Debug: millennium bug in year $year\n";
368 }
369 ## DEBUG_END
370
371 When the "DEBUG" environment variable exists, the filter ensures that
372 Perl parses only the code between the "DEBUG_BEGIN" and "DEBUG_END"
373 markers. That means that when "DEBUG" does exist, the code above should
374 be passed through the filter unchanged. The marker lines can also be
375 passed through as-is, because the Perl parser will see them as comment
376 lines. When "DEBUG" isn't set, we need a way to disable the debug code.
377 A simple way to achieve that is to convert the lines between the two
378 markers into comments:
379
380 ## DEBUG_BEGIN
381 #if ($year > 1999) {
382 # warn "Debug: millennium bug in year $year\n";
383 #}
384 ## DEBUG_END
385
386 Here is the complete Debug filter:
387
388 package Debug;
389
390 use strict;
391 use warnings;
392 use Filter::Util::Call;
393
394 use constant TRUE => 1;
395 use constant FALSE => 0;
396
397 sub import {
398 my ($type) = @_;
399 my (%context) = (
400 Enabled => defined $ENV{DEBUG},
401 InTraceBlock => FALSE,
402 Filename => (caller)[1],
403 LineNo => 0,
404 LastBegin => 0,
405 );
406 filter_add(bless \%context);
407 }
408
409 sub Die {
410 my ($self) = shift;
411 my ($message) = shift;
412 my ($line_no) = shift || $self->{LastBegin};
413 die "$message at $self->{Filename} line $line_no.\n"
414 }
415
416 sub filter {
417 my ($self) = @_;
418 my ($status);
419 $status = filter_read();
420 ++ $self->{LineNo};
421
422 # deal with EOF/error first
423 if ($status <= 0) {
424 $self->Die("DEBUG_BEGIN has no DEBUG_END")
425 if $self->{InTraceBlock};
426 return $status;
427 }
428
429 if ($self->{InTraceBlock}) {
430 if (/^\s*##\s*DEBUG_BEGIN/ ) {
431 $self->Die("Nested DEBUG_BEGIN", $self->{LineNo})
432 } elsif (/^\s*##\s*DEBUG_END/) {
433 $self->{InTraceBlock} = FALSE;
434 }
435
436 # comment out the debug lines when the filter is disabled
437 s/^/#/ if ! $self->{Enabled};
438 } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
439 $self->{InTraceBlock} = TRUE;
440 $self->{LastBegin} = $self->{LineNo};
441 } elsif ( /^\s*##\s*DEBUG_END/ ) {
442 $self->Die("DEBUG_END has no DEBUG_BEGIN", $self->{LineNo});
443 }
444 return $status;
445 }
446
447 1;
448
449 The big difference between this filter and the previous example is the
450 use of context data in the filter object. The filter object is based on
451 a hash reference, and is used to keep various pieces of context
452 information between calls to the filter function. All but two of the
453 hash fields are used for error reporting. The first of those two,
454 Enabled, is used by the filter to determine whether the debugging code
455 should be given to the Perl parser. The second, InTraceBlock, is true
456 when the filter has encountered a "DEBUG_BEGIN" line, but has not yet
457 encountered the following "DEBUG_END" line.
458
459 If you ignore all the error checking that most of the code does, the
460 essence of the filter is as follows:
461
462 sub filter {
463 my ($self) = @_;
464 my ($status);
465 $status = filter_read();
466
467 # deal with EOF/error first
468 return $status if $status <= 0;
469 if ($self->{InTraceBlock}) {
470 if (/^\s*##\s*DEBUG_END/) {
471 $self->{InTraceBlock} = FALSE
472 }
473
474 # comment out debug lines when the filter is disabled
475 s/^/#/ if ! $self->{Enabled};
476 } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
477 $self->{InTraceBlock} = TRUE;
478 }
479 return $status;
480 }
481
482 Be warned: just as the C-preprocessor doesn't know C, the Debug filter
483 doesn't know Perl. It can be fooled quite easily:
484
485 print <<EOM;
486 ##DEBUG_BEGIN
487 EOM
488
489 Such things aside, you can see that a lot can be achieved with a modest
490 amount of code.
491
493 You now have better understanding of what a source filter is, and you
494 might even have a possible use for them. If you feel like playing with
495 source filters but need a bit of inspiration, here are some extra
496 features you could add to the Debug filter.
497
498 First, an easy one. Rather than having debugging code that is all-or-
499 nothing, it would be much more useful to be able to control which
500 specific blocks of debugging code get included. Try extending the
501 syntax for debug blocks to allow each to be identified. The contents of
502 the "DEBUG" environment variable can then be used to control which
503 blocks get included.
504
505 Once you can identify individual blocks, try allowing them to be
506 nested. That isn't difficult either.
507
508 Here is an interesting idea that doesn't involve the Debug filter.
509 Currently Perl subroutines have fairly limited support for formal
510 parameter lists. You can specify the number of parameters and their
511 type, but you still have to manually take them out of the @_ array
512 yourself. Write a source filter that allows you to have a named
513 parameter list. Such a filter would turn this:
514
515 sub MySub ($first, $second, @rest) { ... }
516
517 into this:
518
519 sub MySub($$@) {
520 my ($first) = shift;
521 my ($second) = shift;
522 my (@rest) = @_;
523 ...
524 }
525
526 Finally, if you feel like a real challenge, have a go at writing a
527 full-blown Perl macro preprocessor as a source filter. Borrow the
528 useful features from the C preprocessor and any other macro processors
529 you know. The tricky bit will be choosing how much knowledge of Perl's
530 syntax you want your filter to have.
531
533 Some Filters Clobber the "DATA" Handle
534 Some source filters use the "DATA" handle to read the calling
535 program. When using these source filters you cannot rely on this
536 handle, nor expect any particular kind of behavior when operating
537 on it. Filters based on Filter::Util::Call (and therefore
538 Filter::Simple) do not alter the "DATA" filehandle.
539
541 The Source Filters distribution is available on CPAN, in
542
543 CPAN/modules/by-module/Filter
544
545 Starting from Perl 5.8 Filter::Util::Call (the core part of the Source
546 Filters distribution) is part of the standard Perl distribution. Also
547 included is a friendlier interface called Filter::Simple, by Damian
548 Conway.
549
551 Paul Marquess <Paul.Marquess@btinternet.com>
552
554 This article originally appeared in The Perl Journal #11, and is
555 copyright 1998 The Perl Journal. It appears courtesy of Jon Orwant and
556 The Perl Journal. This document may be distributed under the same
557 terms as Perl itself.
558
559
560
561perl v5.10.1 2009-06-27 PERLFILTER(1)