better documentation for goto &NAME (from M. J. T. Guy)
[p5sagit/p5-mst-13.2.git] / pod / perlfaq9.pod
CommitLineData
68dc0745 1=head1 NAME
2
d92eb7b0 3perlfaq9 - Networking ($Revision: 1.26 $, $Date: 1999/05/23 16:08:30 $)
68dc0745 4
5=head1 DESCRIPTION
6
7This section deals with questions related to networking, the internet,
8and a few on the web.
9
c8db1d39 10=head2 My CGI script runs from the command line but not the browser. (500 Server Error)
68dc0745 11
c8db1d39 12If you can demonstrate that you've read the following FAQs and that
13your problem isn't something simple that can be easily answered, you'll
14probably receive a courteous and useful reply to your question if you
15post it on comp.infosystems.www.authoring.cgi (if it's something to do
16with HTTP, HTML, or the CGI protocols). Questions that appear to be Perl
17questions but are really CGI ones that are posted to comp.lang.perl.misc
18may not be so well received.
68dc0745 19
c8db1d39 20The useful FAQs and related documents are:
68dc0745 21
c8db1d39 22 CGI FAQ
d92eb7b0 23 http://www.webthing.com/page.cgi/cgifaq
68dc0745 24
c8db1d39 25 Web FAQ
92c2ed05 26 http://www.boutell.com/faq/
68dc0745 27
c8db1d39 28 WWW Security FAQ
29 http://www.w3.org/Security/Faq/
30
31 HTTP Spec
32 http://www.w3.org/pub/WWW/Protocols/HTTP/
33
34 HTML Spec
35 http://www.w3.org/TR/REC-html40/
36 http://www.w3.org/pub/WWW/MarkUp/
37
38 CGI Spec
39 http://www.w3.org/CGI/
40
41 CGI Security FAQ
42 http://www.go2net.com/people/paulp/cgi-security/safe-cgi.txt
43
44=head2 How can I get better error messages from a CGI program?
45
46Use the CGI::Carp module. It replaces C<warn> and C<die>, plus the
47normal Carp modules C<carp>, C<croak>, and C<confess> functions with
48more verbose and safer versions. It still sends them to the normal
49server error log.
50
51 use CGI::Carp;
52 warn "This is a complaint";
53 die "But this one is serious";
54
55The following use of CGI::Carp also redirects errors to a file of your choice,
56placed in a BEGIN block to catch compile-time warnings as well:
57
58 BEGIN {
59 use CGI::Carp qw(carpout);
60 open(LOG, ">>/var/local/cgi-logs/mycgi-log")
61 or die "Unable to append to mycgi-log: $!\n";
62 carpout(*LOG);
63 }
64
65You can even arrange for fatal errors to go back to the client browser,
66which is nice for your own debugging, but might confuse the end user.
67
68 use CGI::Carp qw(fatalsToBrowser);
69 die "Bad error here";
70
71Even if the error happens before you get the HTTP header out, the module
72will try to take care of this to avoid the dreaded server 500 errors.
73Normal warnings still go out to the server error log (or wherever
74you've sent them with C<carpout>) with the application name and date
75stamp prepended.
76
68dc0745 77=head2 How do I remove HTML from a string?
78
f29c64d6 79The most correct way (albeit not the fastest) is to use HTML::Parser
7d7e76cf 80from CPAN (part of the HTML-Tree package on CPAN). Another correct
81way is to use HTML::FormatText which not only removes HTML but also
82attempts to do a little simple formatting of the resulting plain text.
68dc0745 83
84Many folks attempt a simple-minded regular expression approach, like
85C<s/E<lt>.*?E<gt>//g>, but that fails in many cases because the tags
86may continue over line breaks, they may contain quoted angle-brackets,
87or HTML comment may be present. Plus folks forget to convert
88entities, like C<&lt;> for example.
89
90Here's one "simple-minded" approach, that works for most files:
91
92 #!/usr/bin/perl -p0777
93 s/<(?:[^>'"]*|(['"]).*?\1)*>//gs
94
95If you want a more complete solution, see the 3-stage striphtml
96program in
97http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/striphtml.gz
98.
99
c8db1d39 100Here are some tricky cases that you should think about when picking
101a solution:
102
103 <IMG SRC = "foo.gif" ALT = "A > B">
104
d92eb7b0 105 <IMG SRC = "foo.gif"
c8db1d39 106 ALT = "A > B">
107
108 <!-- <A comment> -->
109
110 <script>if (a<b && a>c)</script>
111
112 <# Just data #>
113
114 <![INCLUDE CDATA [ >>>>>>>>>>>> ]]>
115
116If HTML comments include other tags, those solutions would also break
117on text like this:
118
119 <!-- This section commented out.
120 <B>You can't see me!</B>
121 -->
122
68dc0745 123=head2 How do I extract URLs?
124
54310121 125A quick but imperfect approach is
68dc0745 126
127 #!/usr/bin/perl -n00
128 # qxurl - tchrist@perl.com
129 print "$2\n" while m{
130 < \s*
131 A \s+ HREF \s* = \s* (["']) (.*?) \1
132 \s* >
133 }gsix;
134
135This version does not adjust relative URLs, understand alternate
d92eb7b0 136bases, deal with HTML comments, deal with HREF and NAME attributes
137in the same tag, understand extra qualifiers like TARGET, or accept
138URLs themselves as arguments. It also runs about 100x faster than a
139more "complete" solution using the LWP suite of modules, such as the
140http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/xurl.gz program.
68dc0745 141
142=head2 How do I download a file from the user's machine? How do I open a file on another machine?
143
144In the context of an HTML form, you can use what's known as
145B<multipart/form-data> encoding. The CGI.pm module (available from
146CPAN) supports this in the start_multipart_form() method, which isn't
147the same as the startform() method.
148
149=head2 How do I make a pop-up menu in HTML?
150
151Use the B<E<lt>SELECTE<gt>> and B<E<lt>OPTIONE<gt>> tags. The CGI.pm
152module (available from CPAN) supports this widget, as well as many
153others, including some that it cleverly synthesizes on its own.
154
155=head2 How do I fetch an HTML file?
156
46fc3d4c 157One approach, if you have the lynx text-based HTML browser installed
158on your system, is this:
68dc0745 159
160 $html_code = `lynx -source $url`;
161 $text_data = `lynx -dump $url`;
162
d92eb7b0 163The libwww-perl (LWP) modules from CPAN provide a more powerful way
164to do this. They don't require lynx, but like lynx, can still work
165through proxies:
46fc3d4c 166
c8db1d39 167 # simplest version
168 use LWP::Simple;
169 $content = get($URL);
170
171 # or print HTML from a URL
46fc3d4c 172 use LWP::Simple;
173 getprint "http://www.sn.no/libwww-perl/";
174
c8db1d39 175 # or print ASCII from HTML from a URL
65acb1b1 176 # also need HTML-Tree package from CPAN
46fc3d4c 177 use LWP::Simple;
f29c64d6 178 use HTML::Parser;
46fc3d4c 179 use HTML::FormatText;
180 my ($html, $ascii);
181 $html = get("http://www.perl.com/");
182 defined $html
183 or die "Can't fetch HTML from http://www.perl.com/";
184 $ascii = HTML::FormatText->new->format(parse_html($html));
185 print $ascii;
186
c8db1d39 187=head2 How do I automate an HTML form submission?
188
189If you're submitting values using the GET method, create a URL and encode
190the form using the C<query_form> method:
191
192 use LWP::Simple;
193 use URI::URL;
194
195 my $url = url('http://www.perl.com/cgi-bin/cpan_mod');
196 $url->query_form(module => 'DB_File', readme => 1);
197 $content = get($url);
198
199If you're using the POST method, create your own user agent and encode
200the content appropriately.
201
202 use HTTP::Request::Common qw(POST);
203 use LWP::UserAgent;
204
205 $ua = LWP::UserAgent->new();
206 my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod',
207 [ module => 'DB_File', readme => 1 ];
208 $content = $ua->request($req)->as_string;
209
210=head2 How do I decode or create those %-encodings on the web?
68dc0745 211
212Here's an example of decoding:
213
214 $string = "http://altavista.digital.com/cgi-bin/query?pg=q&what=news&fmt=.&q=%2Bcgi-bin+%2Bperl.exe";
215 $string =~ s/%([a-fA-F0-9]{2})/chr(hex($1))/ge;
216
217Encoding is a bit harder, because you can't just blindly change
d92eb7b0 218all the non-alphanumunder character (C<\W>) into their hex escapes.
68dc0745 219It's important that characters with special meaning like C</> and C<?>
220I<not> be translated. Probably the easiest way to get this right is
221to avoid reinventing the wheel and just use the URI::Escape module,
222which is part of the libwww-perl package (LWP) available from CPAN.
223
224=head2 How do I redirect to another page?
225
226Instead of sending back a C<Content-Type> as the headers of your
227reply, send back a C<Location:> header. Officially this should be a
228C<URI:> header, so the CGI.pm module (available from CPAN) sends back
229both:
230
231 Location: http://www.domain.com/newpage
232 URI: http://www.domain.com/newpage
233
234Note that relative URLs in these headers can cause strange effects
235because of "optimizations" that servers do.
236
c8db1d39 237 $url = "http://www.perl.com/CPAN/";
238 print "Location: $url\n\n";
239 exit;
240
d92eb7b0 241To target a particular frame in a frameset, include the "Window-target:"
242in the header.
243
244 print <<EOF;
245 Location: http://www.domain.com/newpage
246 Window-target: <FrameName>
247
248 EOF
249
250To be correct to the spec, each of those virtual newlines should really be
251physical C<"\015\012"> sequences by the time you hit the client browser.
252Except for NPH scripts, though, that local newline should get translated
253by your server into standard form, so you shouldn't have a problem
254here, even if you are stuck on MacOS. Everybody else probably won't
255even notice.
c8db1d39 256
68dc0745 257=head2 How do I put a password on my web pages?
258
259That depends. You'll need to read the documentation for your web
260server, or perhaps check some of the other FAQs referenced above.
261
262=head2 How do I edit my .htpasswd and .htgroup files with Perl?
263
264The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide a
265consistent OO interface to these files, regardless of how they're
46fc3d4c 266stored. Databases may be text, dbm, Berkley DB or any database with a
68dc0745 267DBI compatible driver. HTTPD::UserAdmin supports files used by the
268`Basic' and `Digest' authentication schemes. Here's an example:
269
270 use HTTPD::UserAdmin ();
271 HTTPD::UserAdmin
272 ->new(DB => "/foo/.htpasswd")
273 ->add($username => $password);
274
46fc3d4c 275=head2 How do I make sure users can't enter values into a form that cause my CGI script to do bad things?
276
277Read the CGI security FAQ, at
278http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html, and the
279Perl/CGI FAQ at
280http://www.perl.com/CPAN/doc/FAQs/cgi/perl-cgi-faq.html.
281
282In brief: use tainting (see L<perlsec>), which makes sure that data
283from outside your script (eg, CGI parameters) are never used in
284C<eval> or C<system> calls. In addition to tainting, never use the
285single-argument form of system() or exec(). Instead, supply the
286command and arguments as a list, which prevents shell globbing.
287
5a964f20 288=head2 How do I parse a mail header?
68dc0745 289
290For a quick-and-dirty solution, try this solution derived
291from page 222 of the 2nd edition of "Programming Perl":
292
293 $/ = '';
294 $header = <MSG>;
295 $header =~ s/\n\s+/ /g; # merge continuation lines
296 %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header );
297
298That solution doesn't do well if, for example, you're trying to
299maintain all the Received lines. A more complete approach is to use
300the Mail::Header module from CPAN (part of the MailTools package).
301
302=head2 How do I decode a CGI form?
303
c8db1d39 304You use a standard module, probably CGI.pm. Under no circumstances
305should you attempt to do so by hand!
306
307You'll see a lot of CGI programs that blindly read from STDIN the number
308of bytes equal to CONTENT_LENGTH for POSTs, or grab QUERY_STRING for
309decoding GETs. These programs are very poorly written. They only work
310sometimes. They typically forget to check the return value of the read()
311system call, which is a cardinal sin. They don't handle HEAD requests.
312They don't handle multipart forms used for file uploads. They don't deal
313with GET/POST combinations where query fields are in more than one place.
314They don't deal with keywords in the query string.
315
316In short, they're bad hacks. Resist them at all costs. Please do not be
317tempted to reinvent the wheel. Instead, use the CGI.pm or CGI_Lite.pm
318(available from CPAN), or if you're trapped in the module-free land
319of perl1 .. perl4, you might look into cgi-lib.pl (available from
65acb1b1 320http://cgi-lib.stanford.edu/cgi-lib/ ).
c8db1d39 321
322Make sure you know whether to use a GET or a POST in your form.
323GETs should only be used for something that doesn't update the server.
324Otherwise you can get mangled databases and repeated feedback mail
325messages. The fancy word for this is ``idempotency''. This simply
326means that there should be no difference between making a GET request
327for a particular URL once or multiple times. This is because the
328HTTP protocol definition says that a GET request may be cached by the
329browser, or server, or an intervening proxy. POST requests cannot be
330cached, because each request is independent and matters. Typically,
331POST requests change or depend on state on the server (query or update
332a database, send mail, or purchase a computer).
68dc0745 333
5a964f20 334=head2 How do I check a valid mail address?
68dc0745 335
c8db1d39 336You can't, at least, not in real time. Bummer, eh?
68dc0745 337
c8db1d39 338Without sending mail to the address and seeing whether there's a human
339on the other hand to answer you, you cannot determine whether a mail
340address is valid. Even if you apply the mail header standard, you
341can have problems, because there are deliverable addresses that aren't
342RFC-822 (the mail header standard) compliant, and addresses that aren't
343deliverable which are compliant.
68dc0745 344
c8db1d39 345Many are tempted to try to eliminate many frequently-invalid
d92eb7b0 346mail addresses with a simple regex, such as
c8db1d39 347C</^[\w.-]+\@([\w.-]\.)+\w+$/>. It's a very bad idea. However,
348this also throws out many valid ones, and says nothing about
349potential deliverability, so is not suggested. Instead, see
68dc0745 350http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/ckaddr.gz ,
351which actually checks against the full RFC spec (except for nested
5a964f20 352comments), looks for addresses you may not wish to accept mail to
68dc0745 353(say, Bill Clinton or your postmaster), and then makes sure that the
c8db1d39 354hostname given can be looked up in the DNS MX records. It's not fast,
355but it works for what it tries to do.
356
357Our best advice for verifying a person's mail address is to have them
358enter their address twice, just as you normally do to change a password.
359This usually weeds out typos. If both versions match, send
360mail to that address with a personal message that looks somewhat like:
361
362 Dear someuser@host.com,
363
364 Please confirm the mail address you gave us Wed May 6 09:38:41
365 MDT 1998 by replying to this message. Include the string
366 "Rumpelstiltskin" in that reply, but spelled in reverse; that is,
367 start with "Nik...". Once this is done, your confirmed address will
368 be entered into our records.
369
370If you get the message back and they've followed your directions,
371you can be reasonably assured that it's real.
68dc0745 372
c8db1d39 373A related strategy that's less open to forgery is to give them a PIN
374(personal ID number). Record the address and PIN (best that it be a
375random one) for later processing. In the mail you send, ask them to
376include the PIN in their reply. But if it bounces, or the message is
377included via a ``vacation'' script, it'll be there anyway. So it's
378best to ask them to mail back a slight alteration of the PIN, such as
379with the characters reversed, one added or subtracted to each digit, etc.
46fc3d4c 380
68dc0745 381=head2 How do I decode a MIME/BASE64 string?
382
383The MIME-tools package (available from CPAN) handles this and a lot
384more. Decoding BASE64 becomes as simple as:
385
386 use MIME::base64;
387 $decoded = decode_base64($encoded);
388
389A more direct approach is to use the unpack() function's "u"
390format after minor transliterations:
391
392 tr#A-Za-z0-9+/##cd; # remove non-base64 chars
393 tr#A-Za-z0-9+/# -_#; # convert to uuencoded format
394 $len = pack("c", 32 + 0.75*length); # compute length byte
395 print unpack("u", $len . $_); # uudecode and print
396
5a964f20 397=head2 How do I return the user's mail address?
68dc0745 398
399On systems that support getpwuid, the $E<lt> variable and the
400Sys::Hostname module (which is part of the standard perl distribution),
401you can probably try using something like this:
402
403 use Sys::Hostname;
231ab6d1 404 $address = sprintf('%s@%s', scalar getpwuid($<), hostname);
68dc0745 405
5a964f20 406Company policies on mail address can mean that this generates addresses
407that the company's mail system will not accept, so you should ask for
408users' mail addresses when this matters. Furthermore, not all systems
68dc0745 409on which Perl runs are so forthcoming with this information as is Unix.
410
411The Mail::Util module from CPAN (part of the MailTools package) provides a
412mailaddress() function that tries to guess the mail address of the user.
413It makes a more intelligent guess than the code above, using information
414given when the module was installed, but it could still be incorrect.
415Again, the best way is often just to ask the user.
416
c8db1d39 417=head2 How do I send mail?
68dc0745 418
c8db1d39 419Use the C<sendmail> program directly:
420
421 open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
422 or die "Can't fork for sendmail: $!\n";
423 print SENDMAIL <<"EOF";
424 From: User Originating Mail <me\@host>
425 To: Final Destination <you\@otherhost>
426 Subject: A relevant subject line
427
65acb1b1 428 Body of the message goes here after the blank line
429 in as many lines as you like.
c8db1d39 430 EOF
431 close(SENDMAIL) or warn "sendmail didn't close nicely";
432
433The B<-oi> option prevents sendmail from interpreting a line consisting
434of a single dot as "end of message". The B<-t> option says to use the
435headers to decide who to send the message to, and B<-odq> says to put
436the message into the queue. This last option means your message won't
437be immediately delivered, so leave it out if you want immediate
438delivery.
439
d92eb7b0 440Alternate, less convenient approaches include calling mail (sometimes
441called mailx) directly or simply opening up port 25 have having an
442intimate conversation between just you and the remote SMTP daemon,
443probably sendmail.
444
445Or you might be able use the CPAN module Mail::Mailer:
c8db1d39 446
447 use Mail::Mailer;
448
449 $mailer = Mail::Mailer->new();
450 $mailer->open({ From => $from_address,
451 To => $to_address,
452 Subject => $subject,
453 })
454 or die "Can't open: $!\n";
455 print $mailer $body;
456 $mailer->close();
457
458The Mail::Internet module uses Net::SMTP which is less Unix-centric than
459Mail::Mailer, but less reliable. Avoid raw SMTP commands. There
d92eb7b0 460are many reasons to use a mail transport agent like sendmail. These
c8db1d39 461include queueing, MX records, and security.
462
463=head2 How do I read mail?
464
d92eb7b0 465While you could use the Mail::Folder module from CPAN (part of the
466MailFolder package) or the Mail::Internet module from CPAN (also part
467of the MailTools package), often a module is overkill, though. Here's a
468mail sorter.
469
470 #!/usr/bin/perl
c8db1d39 471 # bysub1 - simple sort by subject
472 my(@msgs, @sub);
473 my $msgno = -1;
474 $/ = ''; # paragraph reads
475 while (<>) {
476 if (/^From/m) {
477 /^Subject:\s*(?:Re:\s*)*(.*)/mi;
478 $sub[++$msgno] = lc($1) || '';
479 }
480 $msgs[$msgno] .= $_;
d92eb7b0 481 }
c8db1d39 482 for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) {
483 print $msgs[$i];
484 }
485
d92eb7b0 486Or more succinctly,
c8db1d39 487
488 #!/usr/bin/perl -n00
489 # bysub2 - awkish sort-by-subject
490 BEGIN { $msgno = -1 }
491 $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m;
492 $msg[$msgno] .= $_;
493 END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] }
494
68dc0745 495=head2 How do I find out my hostname/domainname/IP address?
496
c8db1d39 497The normal way to find your own hostname is to call the C<`hostname`>
498program. While sometimes expedient, this has some problems, such as
499not knowing whether you've got the canonical name or not. It's one of
500those tradeoffs of convenience versus portability.
68dc0745 501
502The Sys::Hostname module (part of the standard perl distribution) will
503give you the hostname after which you can find out the IP address
504(assuming you have working DNS) with a gethostbyname() call.
505
506 use Socket;
507 use Sys::Hostname;
508 my $host = hostname();
65acb1b1 509 my $addr = inet_ntoa(scalar gethostbyname($host || 'localhost'));
68dc0745 510
511Probably the simplest way to learn your DNS domain name is to grok
512it out of /etc/resolv.conf, at least under Unix. Of course, this
513assumes several things about your resolv.conf configuration, including
514that it exists.
515
516(We still need a good DNS domain name-learning method for non-Unix
517systems.)
518
519=head2 How do I fetch a news article or the active newsgroups?
520
521Use the Net::NNTP or News::NNTPClient modules, both available from CPAN.
522This can make tasks like fetching the newsgroup list as simple as:
523
524 perl -MNews::NNTPClient
525 -e 'print News::NNTPClient->new->list("newsgroups")'
526
527=head2 How do I fetch/put an FTP file?
528
529LWP::Simple (available from CPAN) can fetch but not put. Net::FTP (also
530available from CPAN) is more complex but can put as well as fetch.
531
532=head2 How can I do RPC in Perl?
533
534A DCE::RPC module is being developed (but is not yet available), and
535will be released as part of the DCE-Perl package (available from
65acb1b1 536CPAN). The rpcgen suite, available from CPAN/authors/id/JAKE/, is
537an RPC stub generator and includes an RPC::ONC module.
68dc0745 538
539=head1 AUTHOR AND COPYRIGHT
540
65acb1b1 541Copyright (c) 1997-1999 Tom Christiansen and Nathan Torkington.
5a964f20 542All rights reserved.
543
544When included as part of the Standard Version of Perl, or as part of
545its complete documentation whether printed or otherwise, this work
d92eb7b0 546may be distributed only under the terms of Perl's Artistic License.
5a964f20 547Any distribution of this file or derivatives thereof I<outside>
548of that package require that special arrangements be made with
549copyright holder.
550
551Irrespective of its distribution, all code examples in this file
552are hereby placed into the public domain. You are permitted and
553encouraged to use this code in your own programs for fun
554or for profit as you see fit. A simple comment in the code giving
555credit would be courteous but is not required.