This is Info file perl.info, produced by Makeinfo version 1.68 from the
input file bigperl.texi.

   settitle perl


File: perl.info,  Node: perlfaq9,  Next: Top,  Prev: Top,  Up: Top

Networking ($Revision: 1.26 $, $Date: 1999/05/23 16:08:30 $)
************************************************************

NAME
====

   perlfaq9 - Networking ($Revision: 1.26 $, $Date: 1999/05/23 16:08:30 $)

DESCRIPTION
===========

   This section deals with questions related to networking, the internet,
and a few on the web.

My CGI script runs from the command line but not the browser.   (500 Server Error)
----------------------------------------------------------------------------------

   If you can demonstrate that you've read the following FAQs and that
your problem isn't something simple that can be easily answered, you'll
probably receive a courteous and useful reply to your question if you post
it on comp.infosystems.www.authoring.cgi (if it's something to do with
HTTP, HTML, or the CGI protocols).  Questions that appear to be Perl
questions but are really CGI ones that are posted to comp.lang.perl.misc
may not be so well received.

   The useful FAQs and related documents are:

     CGI FAQ
         http://www.webthing.com/tutorials/cgifaq.html

     Web FAQ
         http://www.boutell.com/faq/

     WWW Security FAQ
         http://www.w3.org/Security/Faq/

     HTTP Spec
         http://www.w3.org/pub/WWW/Protocols/HTTP/

     HTML Spec
         http://www.w3.org/TR/REC-html40/
         http://www.w3.org/pub/WWW/MarkUp/

     CGI Spec
         http://www.w3.org/CGI/

     CGI Security FAQ
         http://www.go2net.com/people/paulp/cgi-security/safe-cgi.txt

How can I get better error messages from a CGI program?
-------------------------------------------------------

   Use the CGI::Carp module.  It replaces warn and die, plus the normal
Carp modules carp, croak, and `confess' functions with more verbose and
safer versions.  It still sends them to the normal server error log.

     use CGI::Carp;
     warn "This is a complaint";
     die "But this one is serious";

   The following use of CGI::Carp also redirects errors to a file of your
choice, placed in a BEGIN block to catch compile-time warnings as well:

     BEGIN {
         use CGI::Carp qw(carpout);
         open(LOG, ">>/var/local/cgi-logs/mycgi-log")
             or die "Unable to append to mycgi-log: $!\n";
         carpout(*LOG);
     }

   You can even arrange for fatal errors to go back to the client browser,
which is nice for your own debugging, but might confuse the end user.

     use CGI::Carp qw(fatalsToBrowser);
     die "Bad error here";

   Even if the error happens before you get the HTTP header out, the module
will try to take care of this to avoid the dreaded server 500 errors.
Normal warnings still go out to the server error log (or wherever you've
sent them with `carpout') with the application name and date stamp
prepended.

How do I remove HTML from a string?
-----------------------------------

   The most correct way (albeit not the fastest) is to use HTML::Parser
from CPAN.  Another mostly correct way is to use HTML::FormatText which
not only removes HTML but also attempts to do a little simple formatting
of the resulting plain text.

   Many folks attempt a simple-minded regular expression approach, like `<
s/<.*?'//g >>, but that fails in many cases because the tags may continue
over line breaks, they may contain quoted angle-brackets, or HTML comment
may be present.  Plus folks forget to convert entities, like `&lt;' for
example.

   Here's one "simple-minded" approach, that works for most files:

     #!/usr/bin/perl -p0777
     s/<(?:[^>'"]*|(['"]).*?\1)*>//gs

   If you want a more complete solution, see the 3-stage striphtml program
in http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/striphtml.gz .

   Here are some tricky cases that you should think about when picking a
solution:

     <IMG SRC = "foo.gif" ALT = "A > B">

     <IMG SRC = "foo.gif"
     	 ALT = "A > B">

     <!-- <A comment> -->

     <script>if (a<b && a>c)</script>

     <# Just data #>

     <![INCLUDE CDATA [ >>>>>>>>>>>> ]]>

   If HTML comments include other tags, those solutions would also break
on text like this:

     <!-- This section commented out.
         <B>You can't see me!</B>
     -->

How do I extract URLs?
----------------------

   A quick but imperfect approach is

     #!/usr/bin/perl -n00
     # qxurl - tchrist@perl.com
     print "$2\n" while m{
     	< \s*
     	  A \s+ HREF \s* = \s* (["']) (.*?) \1
     	\s* >
     }gsix;

   This version does not adjust relative URLs, understand alternate bases,
deal with HTML comments, deal with HREF and NAME attributes in the same
tag, understand extra qualifiers like TARGET, or accept URLs themselves as
arguments.  It also runs about 100x faster than a more "complete" solution
using the LWP suite of modules, such as the
http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/xurl.gz program.

How do I download a file from the user's machine?  How do I open a file on another machine?
-------------------------------------------------------------------------------------------

   In the context of an HTML form, you can use what's known as
*multipart/form-data* encoding.  The CGI.pm module (available from CPAN)
supports this in the start_multipart_form() method, which isn't the same
as the startform() method.

How do I make a pop-up menu in HTML?
------------------------------------

   Use the *< <SELECT* >> and *< <OPTION* >> tags.  The CGI.pm module
(available from CPAN) supports this widget, as well as many others,
including some that it cleverly synthesizes on its own.

How do I fetch an HTML file?
----------------------------

   One approach, if you have the lynx text-based HTML browser installed on
your system, is this:

     $html_code = `lynx -source $url`;
     $text_data = `lynx -dump $url`;

   The libwww-perl (LWP) modules from CPAN provide a more powerful way to
do this.  They don't require lynx, but like lynx, can still work through
proxies:

     # simplest version
     use LWP::Simple;
     $content = get($URL);

     # or print HTML from a URL
     use LWP::Simple;
     getprint "http://www.linpro.no/lwp/";

     # or print ASCII from HTML from a URL
     # also need HTML-Tree package from CPAN
     use LWP::Simple;
     use HTML::Parser;
     use HTML::FormatText;
     my ($html, $ascii);
     $html = get("http://www.perl.com/");
     defined $html
         or die "Can't fetch HTML from http://www.perl.com/";
     $ascii = HTML::FormatText->new->format(parse_html($html));
     print $ascii;

How do I automate an HTML form submission?
------------------------------------------

   If you're submitting values using the GET method, create a URL and
encode the form using the `query_form' method:

     use LWP::Simple;
     use URI::URL;

     my $url = url('http://www.perl.com/cgi-bin/cpan_mod');
     $url->query_form(module => 'DB_File', readme => 1);
     $content = get($url);

   If you're using the POST method, create your own user agent and encode
the content appropriately.

     use HTTP::Request::Common qw(POST);
     use LWP::UserAgent;

     $ua = LWP::UserAgent->new();
     my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod',
                    [ module => 'DB_File', readme => 1 ];
     $content = $ua->request($req)->as_string;

How do I decode or create those %-encodings on the web?
-------------------------------------------------------

   Here's an example of decoding:

     $string = "http://altavista.digital.com/cgi-bin/query?pg=q&what=news&fmt=.&q=%2Bcgi-bin+%2Bperl.exe";
     $string =~ s/%([a-fA-F0-9]{2})/chr(hex($1))/ge;

   Encoding is a bit harder, because you can't just blindly change all the
non-alphanumunder character (`\W') into their hex escapes.  It's important
that characters with special meaning like / and ?  not be translated.
Probably the easiest way to get this right is to avoid reinventing the
wheel and just use the URI::Escape module, available from CPAN.

How do I redirect to another page?
----------------------------------

   Instead of sending back a `Content-Type' as the headers of your reply,
send back a `Location:' header.  Officially this should be a `URI:'
header, so the CGI.pm module (available from CPAN) sends back both:

     Location: http://www.domain.com/newpage
     URI: http://www.domain.com/newpage

   Note that relative URLs in these headers can cause strange effects
because of "optimizations" that servers do.

     $url = "http://www.perl.com/CPAN/";
     print "Location: $url\n\n";
     exit;

   To target a particular frame in a frameset, include the "Window-target:"
in the header.

     print <<EOF;
     Location: http://www.domain.com/newpage
     Window-target: <FrameName>

     EOF

   To be correct to the spec, each of those virtual newlines should really
be physical `"\015\012"' sequences by the time you hit the client browser.
Except for NPH scripts, though, that local newline should get translated
by your server into standard form, so you shouldn't have a problem here,
even if you are stuck on MacOS.  Everybody else probably won't even notice.

How do I put a password on my web pages?
----------------------------------------

   That depends.  You'll need to read the documentation for your web
server, or perhaps check some of the other FAQs referenced above.

How do I edit my .htpasswd and .htgroup files with Perl?
--------------------------------------------------------

   The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide a consistent
OO interface to these files, regardless of how they're stored.  Databases
may be text, dbm, Berkley DB or any database with a DBI compatible driver.
HTTPD::UserAdmin supports files used by the `Basic' and `Digest'
authentication schemes.  Here's an example:

     use HTTPD::UserAdmin ();
     HTTPD::UserAdmin
     	  ->new(DB => "/foo/.htpasswd")
     	  ->add($username => $password);

How do I make sure users can't enter values into a form that cause my CGI script to do bad things?
--------------------------------------------------------------------------------------------------

   Read the CGI security FAQ, at
http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html, and the
Perl/CGI FAQ at http://www.perl.com/CPAN/doc/FAQs/cgi/perl-cgi-faq.html.

   In brief: use tainting (see *Note Perlsec: perlsec,), which makes sure
that data from outside your script (eg, CGI parameters) are never used in
eval or system calls.  In addition to tainting, never use the
single-argument form of system() or exec().  Instead, supply the command
and arguments as a list, which prevents shell globbing.

How do I parse a mail header?
-----------------------------

   For a quick-and-dirty solution, try this solution derived from page 222
of the 2nd edition of "Programming Perl":

     $/ = '';
     $header = <MSG>;
     $header =~ s/\n\s+/ /g;	 # merge continuation lines
     %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header );

   That solution doesn't do well if, for example, you're trying to
maintain all the Received lines.  A more complete approach is to use the
Mail::Header module from CPAN (part of the MailTools package).

How do I decode a CGI form?
---------------------------

   You use a standard module, probably CGI.pm.  Under no circumstances
should you attempt to do so by hand!

   You'll see a lot of CGI programs that blindly read from STDIN the number
of bytes equal to CONTENT_LENGTH for POSTs, or grab QUERY_STRING for
decoding GETs.  These programs are very poorly written.  They only work
sometimes.  They typically forget to check the return value of the read()
system call, which is a cardinal sin.  They don't handle HEAD requests.
They don't handle multipart forms used for file uploads.  They don't deal
with GET/POST combinations where query fields are in more than one place.
They don't deal with keywords in the query string.

   In short, they're bad hacks.  Resist them at all costs.  Please do not
be tempted to reinvent the wheel.  Instead, use the CGI.pm or CGI_Lite.pm
(available from CPAN), or if you're trapped in the module-free land of
perl1 .. perl4, you might look into cgi-lib.pl (available from
http://cgi-lib.stanford.edu/cgi-lib/ ).

   Make sure you know whether to use a GET or a POST in your form.  GETs
should only be used for something that doesn't update the server.
Otherwise you can get mangled databases and repeated feedback mail
messages.  The fancy word for this is "idempotency".  This simply means
that there should be no difference between making a GET request for a
particular URL once or multiple times.  This is because the HTTP protocol
definition says that a GET request may be cached by the browser, or
server, or an intervening proxy.  POST requests cannot be cached, because
each request is independent and matters.  Typically, POST requests change
or depend on state on the server (query or update a database, send mail,
or purchase a computer).

How do I check a valid mail address?
------------------------------------

   You can't, at least, not in real time.  Bummer, eh?

   Without sending mail to the address and seeing whether there's a human
on the other hand to answer you, you cannot determine whether a mail
address is valid.  Even if you apply the mail header standard, you can
have problems, because there are deliverable addresses that aren't RFC-822
(the mail header standard) compliant, and addresses that aren't
deliverable which are compliant.

   Many are tempted to try to eliminate many frequently-invalid mail
addresses with a simple regex, such as `/^[\w.-]+\@([\w.-]\.)+\w+$/'.
It's a very bad idea.  However, this also throws out many valid ones, and
says nothing about potential deliverability, so is not suggested.
Instead, see
http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/ckaddr.gz ,
which actually checks against the full RFC spec (except for nested
comments), looks for addresses you may not wish to accept mail to (say,
Bill Clinton or your postmaster), and then makes sure that the hostname
given can be looked up in the DNS MX records.  It's not fast, but it works
for what it tries to do.

   Our best advice for verifying a person's mail address is to have them
enter their address twice, just as you normally do to change a password.
This usually weeds out typos.  If both versions match, send mail to that
address with a personal message that looks somewhat like:

     Dear someuser@host.com,

     Please confirm the mail address you gave us Wed May  6 09:38:41
     MDT 1998 by replying to this message.  Include the string
     "Rumpelstiltskin" in that reply, but spelled in reverse; that is,
     start with "Nik...".  Once this is done, your confirmed address will
     be entered into our records.

   If you get the message back and they've followed your directions, you
can be reasonably assured that it's real.

   A related strategy that's less open to forgery is to give them a PIN
(personal ID number).  Record the address and PIN (best that it be a
random one) for later processing.  In the mail you send, ask them to
include the PIN in their reply.  But if it bounces, or the message is
included via a "vacation" script, it'll be there anyway.  So it's best to
ask them to mail back a slight alteration of the PIN, such as with the
characters reversed, one added or subtracted to each digit, etc.

How do I decode a MIME/BASE64 string?
-------------------------------------

   The MIME-tools package (available from CPAN) handles this and a lot
more.  Decoding BASE64 becomes as simple as:

     use MIME::base64;
     $decoded = decode_base64($encoded);

   A more direct approach is to use the unpack() function's "u" format
after minor transliterations:

     tr#A-Za-z0-9+/##cd;                   # remove non-base64 chars
     tr#A-Za-z0-9+/# -_#;                  # convert to uuencoded format
     $len = pack("c", 32 + 0.75*length);   # compute length byte
     print unpack("u", $len . $_);         # uudecode and print

How do I return the user's mail address?
----------------------------------------

   On systems that support getpwuid, the $< variable and the Sys::Hostname
module (which is part of the standard perl distribution), you can probably
try using something like this:

     use Sys::Hostname;
     $address = sprintf('%s@%s', scalar getpwuid($<), hostname);

   Company policies on mail address can mean that this generates addresses
that the company's mail system will not accept, so you should ask for
users' mail addresses when this matters.  Furthermore, not all systems on
which Perl runs are so forthcoming with this information as is Unix.

   The Mail::Util module from CPAN (part of the MailTools package)
provides a mailaddress() function that tries to guess the mail address of
the user.  It makes a more intelligent guess than the code above, using
information given when the module was installed, but it could still be
incorrect.  Again, the best way is often just to ask the user.

How do I send mail?
-------------------

   Use the sendmail program directly:

     open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
                         or die "Can't fork for sendmail: $!\n";
     print SENDMAIL <<"EOF";
     From: User Originating Mail <me\@host>
     To: Final Destination <you\@otherhost>
     Subject: A relevant subject line

     Body of the message goes here after the blank line
     in as many lines as you like.
     EOF
     close(SENDMAIL)     or warn "sendmail didn't close nicely";

   The *-oi* option prevents sendmail from interpreting a line consisting
of a single dot as "end of message".  The -t option says to use the
headers to decide who to send the message to, and *-odq* says to put the
message into the queue.  This last option means your message won't be
immediately delivered, so leave it out if you want immediate delivery.

   Alternate, less convenient approaches include calling mail (sometimes
called mailx) directly or simply opening up port 25 have having an
intimate conversation between just you and the remote SMTP daemon,
probably sendmail.

   Or you might be able use the CPAN module Mail::Mailer:

     use Mail::Mailer;

     $mailer = Mail::Mailer->new();
     $mailer->open({ From    => $from_address,
                     To      => $to_address,
                     Subject => $subject,
                   })
         or die "Can't open: $!\n";
     print $mailer $body;
     $mailer->close();

   The Mail::Internet module uses Net::SMTP which is less Unix-centric than
Mail::Mailer, but less reliable.  Avoid raw SMTP commands.  There are many
reasons to use a mail transport agent like sendmail.  These include
queueing, MX records, and security.

How do I read mail?
-------------------

   While you could use the Mail::Folder module from CPAN (part of the
MailFolder package) or the Mail::Internet module from CPAN (also part of
the MailTools package), often a module is overkill, though.  Here's a mail
sorter.

     #!/usr/bin/perl
     # bysub1 - simple sort by subject
     my(@msgs, @sub);
     my $msgno = -1;
     $/ = '';                    # paragraph reads
     while (<>) {
         if (/^From/m) {
             /^Subject:\s*(?:Re:\s*)*(.*)/mi;
             $sub[++$msgno] = lc($1) || '';
         }
         $msgs[$msgno] .= $_;
     }
     for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) {
         print $msgs[$i];
     }

   Or more succinctly,

     #!/usr/bin/perl -n00
     # bysub2 - awkish sort-by-subject
     BEGIN { $msgno = -1 }
     $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m;
     $msg[$msgno] .= $_;
     END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] }

How do I find out my hostname/domainname/IP address?
----------------------------------------------------

   The normal way to find your own hostname is to call the ``hostname`'
program.  While sometimes expedient, this has some problems, such as not
knowing whether you've got the canonical name or not.  It's one of those
tradeoffs of convenience versus portability.

   The Sys::Hostname module (part of the standard perl distribution) will
give you the hostname after which you can find out the IP address
(assuming you have working DNS) with a gethostbyname() call.

     use Socket;
     use Sys::Hostname;
     my $host = hostname();
     my $addr = inet_ntoa(scalar gethostbyname($host || 'localhost'));

   Probably the simplest way to learn your DNS domain name is to grok it
out of /etc/resolv.conf, at least under Unix.  Of course, this assumes
several things about your resolv.conf configuration, including that it
exists.

   (We still need a good DNS domain name-learning method for non-Unix
systems.)

How do I fetch a news article or the active newsgroups?
-------------------------------------------------------

   Use the Net::NNTP or News::NNTPClient modules, both available from CPAN.
This can make tasks like fetching the newsgroup list as simple as:

     perl -MNews::NNTPClient
       -e 'print News::NNTPClient->new->list("newsgroups")'

How do I fetch/put an FTP file?
-------------------------------

   LWP::Simple (available from CPAN) can fetch but not put.  Net::FTP (also
available from CPAN) is more complex but can put as well as fetch.

How can I do RPC in Perl?
-------------------------

   A DCE::RPC module is being developed (but is not yet available), and
will be released as part of the DCE-Perl package (available from CPAN).
The rpcgen suite, available from CPAN/authors/id/JAKE/, is an RPC stub
generator and includes an RPC::ONC module.

AUTHOR AND COPYRIGHT
====================

   Copyright (c) 1997-1999 Tom Christiansen and Nathan Torkington.  All
rights reserved.

   When included as part of the Standard Version of Perl, or as part of
its complete documentation whether printed or otherwise, this work may be
distributed only under the terms of Perl's Artistic License.  Any
distribution of this file or derivatives thereof *outside* of that package
require that special arrangements be made with copyright holder.

   Irrespective of its distribution, all code examples in this file are
hereby placed into the public domain.  You are permitted and encouraged to
use this code in your own programs for fun or for profit as you see fit.
A simple comment in the code giving credit would be courteous but is not
required.


File: perl.info,  Node: perlfilter,  Next: perldbmfilter,  Prev: perllexwarn,  Up: Top

Source Filters
**************

NAME
====

   perlfilter - Source Filters

DESCRIPTION
===========

   This article is about a little-known feature of Perl called *source
filters*. Source filters alter the program text of a module before Perl
sees it, much as a C preprocessor alters the source text of a C program
before the compiler sees it. This article tells you more about what source
filters are, how they work, and how to write your own.

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

CONCEPTS
========

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

   Now think of each logical connection between the Perl parser and an
individual file as a *source stream*. A source stream is created when the
Perl parser opens a file, it continues to exist as the source code is read
into memory, and it is destroyed when Perl is finished parsing the file.
If the parser encounters a require or use statement in a source stream, a
new and distinct stream is created just for that file.

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

     file -------> parser

   There are two important points to remember:

  1. Although there can be any number of source streams in existence at any
     given 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
and modifies a source stream before it reaches the parser. A source filter
changes our diagram like this:

     file ----> filter ----> parser

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

     gunzip -c trial.gz | sh

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

     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:

     compressed           gunzip
         Perl program ---> source filter ---> parser

USING FILTERS
=============

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

   Say you want to pass your Perl source through the C preprocessor before
execution. You could use the existing -P command line option to do this,
but as it happens, the source filters distribution comes with a C
preprocessor filter module called Filter::cpp. Let's use that instead.

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

     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 the
file. Before the parser processes any of the lines from the file, the
source stream looks like this:

     cpp_test ---------> parser

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

     cpp_test ----> cpp filter ----> parser

   As the parser reads the second and subsequent lines from the source
stream, it feeds those lines through the `cpp' source filter before
processing them. The `cpp' filter simply passes each line through the real
C preprocessor. The output from the C preprocessor is then inserted back
into the source stream by the filter.

     .-> cpp --.
     |         |
     |         |
     |       <-'
        cpp_test ----> cpp filter ----> parser

   The 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 another
module with use:

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

   The `cpp' filter does not apply to the text of the Fred module, only to
the text of the file that used it (`cpp_test'). Although the use statement
on line 3 will pass through the cpp filter, the module that gets included
(`Fred') will not. The source streams look like this after line 3 has been
parsed and before line 4 is parsed:

     cpp_test ---> cpp filter ---> parser (INACTIVE)

     Fred.pm ----> parser

   As you can see, a new stream has been created for reading the source
from `Fred.pm'. This stream will remain active until all of `Fred.pm' has
been parsed. The source stream for `cpp_test' will still exist, but is
inactive. Once the parser has finished reading Fred.pm, the source stream
associated with it will be destroyed. The source stream for `cpp_test'
then becomes active again and the parser reads line 4 and 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 is
possible to stack a uudecode filter and an uncompression filter like this:

     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         filter

   Data flows through filters in the same order they appear in the source
file. The uudecode filter appeared before the uncompress filter, so the
source 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 it
in 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 out of the
way first. Writing the filter in Perl is most convenient, so I'll devote
the most space to it.

WRITING A SOURCE FILTER IN C
============================

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

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

*Decryption Filters*
     All decryption filters work on the principle of "security through
     obscurity." Regardless of how well you write a decryption filter and
     how strong your encryption algorithm, anyone determined enough can
     retrieve the original source code. The reason is quite simple - once
     the decryption filter has decrypted the source back to its original
     form, fragments of it will be stored in the computer's memory as Perl
     parses it. The source might only be in memory for a short period of
     time, but anyone possessing a debugger, skill, and lots of patience
     can eventually reconstruct your program.

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

CREATING A SOURCE FILTER AS A SEPARATE EXECUTABLE
=================================================

   An alternative to writing the filter in C is to create a separate
executable in the language of your choice. The separate executable reads
from standard input, does whatever processing is necessary, and writes the
filtered data to standard output. `Filter:cpp' is an example of a source
filter implemented as a separate executable - the executable is the C
preprocessor bundled with your C compiler.

   The source filter distribution includes two modules that simplify this
task: `Filter::exec' and `Filter::sh'. Both allow you to run any external
executable. Both use a coprocess to control the flow of data into 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 difference between them is that
`Filter::exec' spawns the external command directly, while `Filter::sh'
spawns a shell to execute the external command. (Unix uses the Bourne
shell; NT uses the cmd shell.) Spawning a shell allows you to make use of
the shell metacharacters and redirection facilities.

   Here is an example script that uses `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 = 1

   Writing a source filter as a separate executable works fine, but a
small performance penalty is incurred. For example, if you execute the
small example above, a separate subprocess will be created to run the Unix
tr command. Each use of the filter requires its own subprocess.  If
creating subprocesses is expensive on your system, you might want to
consider 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 own
source filter is to write it completely in Perl. To distinguish this from
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 example
to study. Here is a complete source filter that performs rot13 decoding.
(Rot13 is a very simple encryption scheme used in Usenet postings to hide
the contents of offensive posts. It moves every letter forward thirteen
places, so that A becomes N, B becomes O, and Z becomes 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 ;
        }

     1;

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

   First, we include the `Filter::Util::Call' module, which exports a
number of functions into your filter's namespace. The filter shown above
uses two of these functions, `filter_add()' and `filter_read()'.

   Next, we create the filter object and associate it with the source
stream by defining the import function. If you know Perl well enough, you
know that import is called automatically every time a module is included
with a use statement. This makes import the ideal place to both create and
install a filter object.

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

   The association between the filter object and the source stream is made
with the `filter_add()' function. This takes a filter object as a
parameter ($ref in this case) and installs it in the source stream.

   Finally, there is the code that actually does the filtering. For this
type of Perl source filter, all the filtering is done in a method called
`filter()'. (It is also possible to write a Perl source filter using a
closure. See the `Filter::Util::Call' manual page for more details.) It's
called every time the Perl parser needs another line of source to process.
The `filter()' method, in turn, reads lines from the 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 an error. The
filter function itself is expected to return its status in the same way,
and put the filtered line it wants written to the source stream in $_. The
use of $_ accounts for the brevity of most Perl source filters.

   In order to make use of the rot13 filter we need some way of encoding
the source file in rot13 format. The script below, `mkrot13', does just
that.

     die "usage mkrot13 filename\n" unless @ARGV ;
     my $in = $ARGV[0] ;
     my $out = "$in.tmp" ;
     open(IN, "<$in") or die "Cannot open file $in: $!\n";
     open(OUT, ">$out") or die "Cannot open file $out: $!\n";

     print OUT "use Rot13;\n" ;
     while (<IN>) {
        tr/a-zA-Z/n-za-mN-ZA-M/ ;
        print OUT ;
     }

     close IN;
     close OUT;
     unlink $in;
     rename $out, $in;

   If we encrypt this with `mkrot13':

     print " hello fred \n" ;

   the result will be this:

     use Rot13;
     cevag "uryyb serq\a" ;

   Running it produces this output:

     hello fred

USING CONTEXT: THE DEBUG FILTER
===============================

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

   Say you wanted to include a lot of debugging code in your Perl script
during development, but you didn't want it available in the released
product. Source filters offer a solution. In order to keep the example
simple, let's say you wanted the debugging output to be controlled by an
environment variable, DEBUG. Debugging code is enabled if the variable
exists, otherwise it is disabled.

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

     ## DEBUG_BEGIN
     if ($year > 1999) {
        warn "Debug: millennium bug in year $year\n" ;
     }
     ## DEBUG_END

   When the DEBUG environment variable exists, the filter ensures that
Perl parses only the code between the `DEBUG_BEGIN' and `DEBUG_END'
markers. That means that when DEBUG does exist, the code above should be
passed through the filter unchanged. The marker lines can also be passed
through as-is, because the Perl parser will see them as comment lines.
When DEBUG isn't set, we need a way to disable the debug code. A simple
way to achieve that is to convert the lines between the two markers into
comments:

     ## DEBUG_BEGIN
     #if ($year > 1999) {
     #     warn "Debug: millennium bug in year $year\n" ;
     #}
     ## DEBUG_END

   Here is the complete Debug filter:

     package Debug;

     use strict;
     use warnings;
     use Filter::Util::Call ;

     use constant TRUE => 1 ;
     use constant FALSE => 0 ;

     sub import {
        my ($type) = @_ ;
        my (%context) = (
          Enabled => defined $ENV{DEBUG},
          InTraceBlock => FALSE,
          Filename => (caller)[1],
          LineNo => 0,
          LastBegin => 0,
        ) ;
        filter_add(bless \%context) ;
     }

     sub Die {
        my ($self) = shift ;
        my ($message) = shift ;
        my ($line_no) = shift || $self->{LastBegin} ;
        die "$message at $self->{Filename} line $line_no.\n"
     }

     sub filter {
        my ($self) = @_ ;
        my ($status) ;
        $status = filter_read() ;
        ++ $self->{LineNo} ;

     # deal with EOF/error first
     if ($status <= 0) {
         $self->Die("DEBUG_BEGIN has no DEBUG_END")
             if $self->{InTraceBlock} ;
         return $status ;
     }

     if ($self->{InTraceBlock}) {
        if (/^\s*##\s*DEBUG_BEGIN/ ) {
            $self->Die("Nested DEBUG_BEGIN", $self->{LineNo})
        } elsif (/^\s*##\s*DEBUG_END/) {
            $self->{InTraceBlock} = FALSE ;
        }

     # comment out the debug lines when the filter is disabled
     s/^/#/ if ! $self->{Enabled} ;
            } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
     $self->{InTraceBlock} = TRUE ;
     $self->{LastBegin} = $self->{LineNo} ;
            } elsif ( /^\s*##\s*DEBUG_END/ ) {
     $self->Die("DEBUG_END has no DEBUG_BEGIN", $self->{LineNo});
            }
            return $status ;
         }

     1 ;

   The big difference between this filter and the previous example is the
use of context data in the filter object. The filter object is based on a
hash reference, and is used to keep various pieces of context information
between calls to the filter function. All but two of the hash fields are
used for error reporting. The first of those two, Enabled, is used by the
filter to determine whether the debugging code should be given to the Perl
parser. The second, InTraceBlock, is true when the filter has encountered
a `DEBUG_BEGIN' line, but has not yet encountered the following
`DEBUG_END' line.

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

     sub filter {
        my ($self) = @_ ;
        my ($status) ;
        $status = filter_read() ;

     # deal with EOF/error first
     return $status if $status <= 0 ;
     if ($self->{InTraceBlock}) {
        if (/^\s*##\s*DEBUG_END/) {
           $self->{InTraceBlock} = FALSE
        }

     # comment out debug lines when the filter is disabled
     s/^/#/ if ! $self->{Enabled} ;
            } elsif ( /^\s*##\s*DEBUG_BEGIN/ ) {
     $self->{InTraceBlock} = TRUE ;
            }
            return $status ;
         }

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

     print <<EOM;
     ##DEBUG_BEGIN
     EOM

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

CONCLUSION
==========

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

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

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

   Here is a interesting idea that doesn't involve the Debug filter.
Currently Perl subroutines have fairly limited support for formal
parameter lists. You can specify the number of parameters and their type,
but you still have to manually take them out of the `@_' array yourself.
Write a source filter that allows you to have a named parameter list. Such
a filter would turn this:

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

   into this:

     sub MySub($$@) {
        my ($first) = shift ;
        my ($second) = shift ;
        my (@rest) = @_ ;
        ...
     }

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

REQUIREMENTS
============

   The Source Filters distribution is available on CPAN, in

     CPAN/modules/by-module/Filter

AUTHOR
======

   Paul Marquess <Paul.Marquess@btinternet.com>

Copyrights
==========

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


File: perl.info,  Node: perlfork,  Next: perlthrtut,  Prev: perlipc,  Up: Top

Perl's fork() emulation
***********************

NAME
====

   perlfork - Perl's fork() emulation

SYNOPSIS
========

   Perl provides a fork() keyword that corresponds to the Unix system call
of the same name.  On most Unix-like platforms where the fork() system
call is available, Perl's fork() simply calls it.

   On some platforms such as Windows where the fork() system call is not
available, Perl can be built to emulate fork() at the interpreter level.
While the emulation is designed to be as compatible as possible with the
real fork() at the the level of the Perl program, there are certain
important differences that stem from the fact that all the pseudo child
"processes" created this way live in the same real process as far as the
operating system is concerned.

   This document provides a general overview of the capabilities and
limitations of the fork() emulation.  Note that the issues discussed here
are not applicable to platforms where a real fork() is available and Perl
has been configured to use it.

DESCRIPTION
===========

   The fork() emulation is implemented at the level of the Perl
interpreter.  What this means in general is that running fork() will
actually clone the running interpreter and all its state, and run the
cloned interpreter in a separate thread, beginning execution in the new
thread just after the point where the fork() was called in the parent.  We
will refer to the thread that implements this child "process" as the
pseudo-process.

   To the Perl program that called fork(), all this is designed to be
transparent.  The parent returns from the fork() with a pseudo-process ID
that can be subsequently used in any process manipulation functions; the
child returns from the fork() with a value of 0 to signify that it is the
child pseudo-process.

Behavior of other Perl features in forked pseudo-processes
----------------------------------------------------------

   Most Perl features behave in a natural way within pseudo-processes.

$$ or $PROCESS_ID
     This special variable is correctly set to the pseudo-process ID.  It
     can be used to identify pseudo-processes within a particular session.
     Note that this value is subject to recycling if any pseudo-processes
     are launched after others have been wait()-ed on.

%ENV
     Each pseudo-process maintains its own virtual enviroment.
     Modifications to %ENV affect the virtual environment, and are only
     visible within that pseudo-process, and in any processes (or
     pseudo-processes) launched from it.

chdir() and all other builtins that accept filenames
     Each pseudo-process maintains its own virtual idea of the current
     directory.  Modifications to the current directory using chdir() are
     only visible within that pseudo-process, and in any processes (or
     pseudo-processes) launched from it.  All file and directory accesses
     from the pseudo-process will correctly map the virtual working
     directory to the real working directory appropriately.

wait() and waitpid()
     wait() and waitpid() can be passed a pseudo-process ID returned by
     fork().  These calls will properly wait for the termination of the
     pseudo-process and return its status.

kill()
     kill() can be used to terminate a pseudo-process by passing it the ID
     returned by fork().  This should not be used except under dire
     circumstances, because the operating system may not guarantee
     integrity of the process resources when a running thread is
     terminated.  Note that using kill() on a pseudo-process() may
     typically cause memory leaks, because the thread that implements the
     pseudo-process does not get a chance to clean up its resources.

exec()
     Calling exec() within a pseudo-process actually spawns the requested
     executable in a separate process and waits for it to complete before
     exiting with the same exit status as that process.  This means that
     the process ID reported within the running executable will be
     different from what the earlier Perl fork() might have returned.
     Similarly, any process manipulation functions applied to the ID
     returned by fork() will affect the waiting pseudo-process that called
     exec(), not the real process it is waiting for after the exec().

exit()
     exit() always exits just the executing pseudo-process, after
     automatically wait()-ing for any outstanding child pseudo-processes.
     Note that this means that the process as a whole will not exit unless
     all running pseudo-processes have exited.

Open handles to files, directories and network sockets
     All open handles are dup()-ed in pseudo-processes, so that closing
     any handles in one process does not affect the others.  See below for
     some limitations.

Resource limits
---------------

   In the eyes of the operating system, pseudo-processes created via the
fork() emulation are simply threads in the same process.  This means that
any process-level limits imposed by the operating system apply to all
pseudo-processes taken together.  This includes any limits imposed by the
operating system on the number of open file, directory and socket handles,
limits on disk space usage, limits on memory size, limits on CPU
utilization etc.

Killing the parent process
--------------------------

   If the parent process is killed (either using Perl's kill() builtin, or
using some external means) all the pseudo-processes are killed as well,
and the whole process exits.

Lifetime of the parent process and pseudo-processes
---------------------------------------------------

   During the normal course of events, the parent process and every
pseudo-process started by it will wait for their respective pseudo-children
to complete before they exit.  This means that the parent and every
pseudo-child created by it that is also a pseudo-parent will only exit
after their pseudo-children have exited.

   A way to mark a pseudo-processes as running detached from their parent
(so that the parent would not have to wait() for them if it doesn't want
to) will be provided in future.

CAVEATS AND LIMITATIONS
-----------------------

BEGIN blocks
     The fork() emulation will not work entirely correctly when called from
     within a BEGIN block.  The forked copy will run the contents of the
     BEGIN block, but will not continue parsing the source stream after the
     BEGIN block.  For example, consider the following code:

          BEGIN {
              fork and exit;		# fork child and exit the parent
          	print "inner\n";
          }
          print "outer\n";

     This will print:

          inner

     rather than the expected:

          inner
          outer

     This limitation arises from fundamental technical difficulties in
     cloning and restarting the stacks used by the Perl parser in the
     middle of a parse.

Open filehandles
     Any filehandles open at the time of the fork() will be dup()-ed.
     Thus, the files can be closed independently in the parent and child,
     but beware that the dup()-ed handles will still share the same seek
     pointer.  Changing the seek position in the parent will change it in
     the child and vice-versa.  One can avoid this by opening files that
     need distinct seek pointers separately in the child.

Forking pipe open() not yet implemented
     The `open(FOO, "|-")' and `open(BAR, "-|")' constructs are not yet
     implemented.  This limitation can be easily worked around in new code
     by creating a pipe explicitly.  The following example shows how to
     write to a forked child:

          # simulate open(FOO, "|-")
          sub pipe_to_fork ($) {
          	my $parent = shift;
          	pipe my $child, $parent or die;
          	my $pid = fork();
          	die "fork() failed: $!" unless defined $pid;
          	if ($pid) {
          	    close $child;
          	}
          	else {
          	    close $parent;
          	    open(STDIN, "<&=" . fileno($child)) or die;
          	}
          	$pid;
          }

          if (pipe_to_fork('FOO')) {
          	# parent
          	print FOO "pipe_to_fork\n";
          	close FOO;
          }
          else {
          	# child
          	while (<STDIN>) { print; }
          	close STDIN;
          	exit(0);
          }

     And this one reads from the child:

          # simulate open(FOO, "-|")
          sub pipe_from_fork ($) {
          	my $parent = shift;
          	pipe $parent, my $child or die;
          	my $pid = fork();
          	die "fork() failed: $!" unless defined $pid;
          	if ($pid) {
          	    close $child;
          	}
          	else {
          	    close $parent;
          	    open(STDOUT, ">&=" . fileno($child)) or die;
          	}
          	$pid;
          }

          if (pipe_from_fork('BAR')) {
          	# parent
          	while (<BAR>) { print; }
          	close BAR;
          }
          else {
          	# child
          	print "pipe_from_fork\n";
          	close STDOUT;
          	exit(0);
          }

     Forking pipe open() constructs will be supported in future.

Global state maintained by XSUBs
     External subroutines (XSUBs) that maintain their own global state may
     not work correctly.  Such XSUBs will either need to maintain locks to
     protect simultaneous access to global data from different
     pseudo-processes, or maintain all their state on the Perl symbol
     table, which is copied naturally when fork() is called.  A callback
     mechanism that provides extensions an opportunity to clone their
     state will be provided in the near future.

Interpreter embedded in larger application
     The fork() emulation may not behave as expected when it is executed
     in an application which embeds a Perl interpreter and calls Perl APIs
     that can evaluate bits of Perl code.  This stems from the fact that
     the emulation only has knowledge about the Perl interpreter's own
     data structures and knows nothing about the containing application's
     state.  For example, any state carried on the application's own call
     stack is out of reach.

Thread-safety of extensions
     Since the fork() emulation runs code in multiple threads, extensions
     calling into non-thread-safe libraries may not work reliably when
     calling fork().  As Perl's threading support gradually becomes more
     widely adopted even on platforms with a native fork(), such extensions
     are expected to be fixed for thread-safety.

BUGS
====

   * Having pseudo-process IDs be negative integers breaks down for the
     integer `-1' because the wait() and waitpid() functions treat this
     number as being special.  The tacit assumption in the current
     implementation is that the system never allocates a thread ID of 1
     for user threads.  A better representation for pseudo-process IDs
     will be implemented in future.

   * This document may be incomplete in some respects.

AUTHOR
======

   Support for concurrent interpreters and the fork() emulation was
implemented by ActiveState, with funding from Microsoft Corporation.

   This document is authored and maintained by Gurusamy Sarathy
<gsar@activestate.com>.

SEE ALSO
========

   `"fork"', *Note Perlfunc: perlfunc,, `"fork"', *Note Perlipc: perlipc,


