📄 perlfilter.pod
字号:
=head1 NAMEperlfilter - Source Filters=head1 DESCRIPTIONThis article is about a little-known feature of Perl calledI<source 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.=head1 CONCEPTSBefore 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 C<use> or C<require>statement, 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 I<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 C<require> or C<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. file -------> parserThere are two important points to remember:=over 5=item 1.Although there can be any number of source streams in existence at anygiven time, only one will be active.=item 2.Every source stream is associated with only one file.=backA 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: file ----> filter ----> parserIf that doesn't make much sense, consider the analogy of a commandpipeline. Say you have a shell script stored in the compressed fileI<trial.gz>. The simple pipeline command below runs the script withoutneeding to create a temporary file to hold the uncompressed file. gunzip -c trial.gz | shIn this case, the data flow from the pipeline can be represented as follows: trial.gz ----> gunzip ----> shWith source filters, you can store the text of your script compressed and use a source filter to uncompress it for Perl's parser: compressed gunzip Perl program ---> source filter ---> parser=head1 USING FILTERSSo 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. You could use the existing C<-P> command line option to dothis, but as it happens, the source filters distribution comes with a Cpreprocessor filter module called Filter::cpp. Let's use that instead.Below is an example program, C<cpp_test>, which makes use of this filter.Line numbers have been added to allow specific lines to be referencedeasily. 1: use Filter::cpp; 2: #define TRUE 1 3: $a = TRUE; 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: cpp_test ---------> parserLine 1, C<use Filter::cpp>, includes and installs the C<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: cpp_test ----> cpp filter ----> parserAs the parser reads the second and subsequent lines from the sourcestream, it feeds those lines through the C<cpp> source filter beforeprocessing them. The C<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. .-> cpp --. | | | | | <-' cpp_test ----> cpp filter ----> parserThe parser then sees the following code: use Filter::cpp; $a = 1; print "a = $a\n";Let's consider what happens when the filtered code includes anothermodule with use: 1: use Filter::cpp; 2: #define TRUE 1 3: use Fred; 4: $a = TRUE; 5: print "a = $a\n";The C<cpp> filter does not apply to the text of the Fred module, onlyto the text of the file that used it (C<cpp_test>). Although the usestatement on line 3 will pass through the cpp filter, the module thatgets included (C<Fred>) will not. The source streams look like thisafter line 3 has been parsed and before line 4 is parsed: cpp_test ---> cpp filter ---> parser (INACTIVE) Fred.pm ----> parserAs you can see, a new stream has been created for reading the sourcefrom C<Fred.pm>. This stream will remain active until all of C<Fred.pm>has been parsed. The source stream for C<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 C<cpp_test> then becomes active again and the parser reads line 4and subsequent lines from C<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: use Filter::uudecode; use Filter::uncompress; M'XL(".H<US4''V9I;F%L')Q;>7/;1I;_>_I3=&E=%:F*I"T?22Q/ M6]9*<IQCO*XFT"0[PL%%'Y+IG?WN^ZYN-$'J.[.JE$,20/?K=_[> ...Once the first line has been processed, the flow will look like this: file ---> uudecode ---> uncompress ---> parser filter filterData 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.=head1 WRITING A SOURCE FILTERThere 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.=head1 WRITING A SOURCE FILTER IN CThe 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. TheC<decrypt> 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).=over 5=item B<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, 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 I<decrypt.pm> in the source filtersmodule.=back=head1 CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLEAn 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. C<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: C<Filter::exec> and C<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 C<Filter::exec> spawns the external commanddirectly, while C<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 C<Filter::sh>: use Filter::sh 'tr XYZ PQR'; $a = 1; print "XYZ a = $a\n";The output you'll get when the script is executed: PQR a = 1Writing 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 C<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.=head1 WRITING A SOURCE FILTER IN PERLThe 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.) package Rot13; use Filter::Util::Call; sub import { my ($type) = @_; my ($ref) = []; filter_add(bless $ref); } sub filter { my ($self) = @_; my ($status); tr/n-za-mN-ZA-M/a-zA-Z/ if ($status = filter_read()) > 0; $status; }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -