This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Doc patches: assorted minor nits
[perl5.git] / pod / perlfaq9.pod
1 =head1 NAME
2
3 perlfaq9 - Networking ($Revision: 1.9 $, $Date: 2002/04/07 18:46:13 $)
4
5 =head1 DESCRIPTION
6
7 This section deals with questions related to networking, the internet,
8 and a few on the web.
9
10 =head2 What is the correct form of response from a CGI script?
11
12 (Alan Flavell <flavell+www@a5.ph.gla.ac.uk> answers...)
13
14 The Common Gateway Interface (CGI) specifies a software interface between 
15 a program ("CGI script") and a web server (HTTPD). It is not specific 
16 to Perl, and has its own FAQs and tutorials, and usenet group, 
17 comp.infosystems.www.authoring.cgi 
18
19 The original CGI specification is at: http://hoohoo.ncsa.uiuc.edu/cgi/
20
21 Current best-practice RFC draft at: http://CGI-Spec.Golux.Com/
22
23 Other relevant documentation listed in: http://www.perl.org/CGI_MetaFAQ.html
24
25 These Perl FAQs very selectively cover some CGI issues. However, Perl 
26 programmers are strongly advised to use the CGI.pm module, to take care
27 of the details for them. 
28
29 The similarity between CGI response headers (defined in the CGI
30 specification) and HTTP response headers (defined in the HTTP
31 specification, RFC2616) is intentional, but can sometimes be confusing.
32
33 The CGI specification defines two kinds of script: the "Parsed Header"
34 script, and the "Non Parsed Header" (NPH) script. Check your server
35 documentation to see what it supports. "Parsed Header" scripts are
36 simpler in various respects. The CGI specification allows any of the
37 usual newline representations in the CGI response (it's the server's
38 job to create an accurate HTTP response based on it). So "\n" written in
39 text mode is technically correct, and recommended. NPH scripts are more
40 tricky: they must put out a complete and accurate set of HTTP
41 transaction response headers; the HTTP specification calls for records
42 to be terminated with carriage-return and line-feed, i.e ASCII \015\012
43 written in binary mode.
44
45 Using CGI.pm gives excellent platform independence, including EBCDIC
46 systems. CGI.pm selects an appropriate newline representation
47 ($CGI::CRLF) and sets binmode as appropriate.
48
49 =head2 My CGI script runs from the command line but not the browser.  (500 Server Error)
50
51 Several things could be wrong.  You can go through the "Troubleshooting
52 Perl CGI scripts" guide at
53
54         http://www.perl.org/troubleshooting_CGI.html
55
56 If, after that, you can demonstrate that you've read the FAQs and that 
57 your problem isn't something simple that can be easily answered, you'll
58 probably receive a courteous and useful reply to your question if you
59 post it on comp.infosystems.www.authoring.cgi (if it's something to do
60 with HTTP or the CGI protocols).  Questions that appear to be Perl
61 questions but are really CGI ones that are posted to comp.lang.perl.misc
62 are not so well received.
63
64 The useful FAQs, related documents, and troubleshooting guides are 
65 listed in the CGI Meta FAQ:
66
67         http://www.perl.org/CGI_MetaFAQ.html
68
69
70 =head2 How can I get better error messages from a CGI program?
71
72 Use the CGI::Carp module.  It replaces C<warn> and C<die>, plus the
73 normal Carp modules C<carp>, C<croak>, and C<confess> functions with
74 more verbose and safer versions.  It still sends them to the normal
75 server error log.
76
77     use CGI::Carp;
78     warn "This is a complaint";
79     die "But this one is serious";
80
81 The following use of CGI::Carp also redirects errors to a file of your choice,
82 placed in a BEGIN block to catch compile-time warnings as well:
83
84     BEGIN {
85         use CGI::Carp qw(carpout);
86         open(LOG, ">>/var/local/cgi-logs/mycgi-log")
87             or die "Unable to append to mycgi-log: $!\n";
88         carpout(*LOG);
89     }
90
91 You can even arrange for fatal errors to go back to the client browser,
92 which is nice for your own debugging, but might confuse the end user.
93
94     use CGI::Carp qw(fatalsToBrowser);
95     die "Bad error here";
96
97 Even if the error happens before you get the HTTP header out, the module
98 will try to take care of this to avoid the dreaded server 500 errors.
99 Normal warnings still go out to the server error log (or wherever
100 you've sent them with C<carpout>) with the application name and date
101 stamp prepended.
102
103 =head2 How do I remove HTML from a string?
104
105 The most correct way (albeit not the fastest) is to use HTML::Parser
106 from CPAN.  Another mostly correct
107 way is to use HTML::FormatText which not only removes HTML but also
108 attempts to do a little simple formatting of the resulting plain text.
109
110 Many folks attempt a simple-minded regular expression approach, like
111 C<< s/<.*?>//g >>, but that fails in many cases because the tags
112 may continue over line breaks, they may contain quoted angle-brackets,
113 or HTML comment may be present.  Plus, folks forget to convert
114 entities--like C<&lt;> for example.
115
116 Here's one "simple-minded" approach, that works for most files:
117
118     #!/usr/bin/perl -p0777
119     s/<(?:[^>'"]*|(['"]).*?\1)*>//gs
120
121 If you want a more complete solution, see the 3-stage striphtml
122 program in
123 http://www.cpan.org/authors/Tom_Christiansen/scripts/striphtml.gz
124 .
125
126 Here are some tricky cases that you should think about when picking
127 a solution:
128
129     <IMG SRC = "foo.gif" ALT = "A > B">
130
131     <IMG SRC = "foo.gif"
132          ALT = "A > B">
133
134     <!-- <A comment> -->
135
136     <script>if (a<b && a>c)</script>
137
138     <# Just data #>
139
140     <![INCLUDE CDATA [ >>>>>>>>>>>> ]]>
141
142 If HTML comments include other tags, those solutions would also break
143 on text like this:
144
145     <!-- This section commented out.
146         <B>You can't see me!</B>
147     -->
148
149 =head2 How do I extract URLs?
150
151 You can easily extract all sorts of URLs from HTML with
152 C<HTML::SimpleLinkExtor> which handles anchors, images, objects,
153 frames, and many other tags that can contain a URL.  If you need 
154 anything more complex, you can create your own subclass of 
155 C<HTML::LinkExtor> or C<HTML::Parser>.  You might even use 
156 C<HTML::SimpleLinkExtor> as an example for something specifically
157 suited to your needs.
158
159 Less complete solutions involving regular expressions can save 
160 you a lot of processing time if you know that the input is simple.  One
161 solution from Tom Christiansen runs 100 times faster than most
162 module based approaches but only extracts URLs from anchors where the first
163 attribute is HREF and there are no other attributes. 
164
165         #!/usr/bin/perl -n00
166         # qxurl - tchrist@perl.com
167         print "$2\n" while m{
168             < \s*
169               A \s+ HREF \s* = \s* (["']) (.*?) \1
170             \s* >
171         }gsix;
172
173
174 =head2 How do I download a file from the user's machine?  How do I open a file on another machine?
175
176 In the context of an HTML form, you can use what's known as
177 B<multipart/form-data> encoding.  The CGI.pm module (available from
178 CPAN) supports this in the start_multipart_form() method, which isn't
179 the same as the startform() method.
180
181 =head2 How do I make a pop-up menu in HTML?
182
183 Use the B<< <SELECT> >> and B<< <OPTION> >> tags.  The CGI.pm
184 module (available from CPAN) supports this widget, as well as many
185 others, including some that it cleverly synthesizes on its own.
186
187 =head2 How do I fetch an HTML file?
188
189 One approach, if you have the lynx text-based HTML browser installed
190 on your system, is this:
191
192     $html_code = `lynx -source $url`;
193     $text_data = `lynx -dump $url`;
194
195 The libwww-perl (LWP) modules from CPAN provide a more powerful way
196 to do this.  They don't require lynx, but like lynx, can still work
197 through proxies:
198
199     # simplest version
200     use LWP::Simple;
201     $content = get($URL);
202
203     # or print HTML from a URL
204     use LWP::Simple;
205     getprint "http://www.linpro.no/lwp/";
206
207     # or print ASCII from HTML from a URL
208     # also need HTML-Tree package from CPAN
209     use LWP::Simple;
210     use HTML::Parser;
211     use HTML::FormatText;
212     my ($html, $ascii);
213     $html = get("http://www.perl.com/");
214     defined $html
215         or die "Can't fetch HTML from http://www.perl.com/";
216     $ascii = HTML::FormatText->new->format(parse_html($html));
217     print $ascii;
218
219 =head2 How do I automate an HTML form submission?
220
221 If you're submitting values using the GET method, create a URL and encode
222 the form using the C<query_form> method:
223
224     use LWP::Simple;
225     use URI::URL;
226
227     my $url = url('http://www.perl.com/cgi-bin/cpan_mod');
228     $url->query_form(module => 'DB_File', readme => 1);
229     $content = get($url);
230
231 If you're using the POST method, create your own user agent and encode
232 the content appropriately.
233
234     use HTTP::Request::Common qw(POST);
235     use LWP::UserAgent;
236
237     $ua = LWP::UserAgent->new();
238     my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod',
239                    [ module => 'DB_File', readme => 1 ];
240     $content = $ua->request($req)->as_string;
241
242 =head2 How do I decode or create those %-encodings on the web?
243
244
245 If you are writing a CGI script, you should be using the CGI.pm module
246 that comes with perl, or some other equivalent module.  The CGI module
247 automatically decodes queries for you, and provides an escape()
248 function to handle encoding.
249
250
251 The best source of detailed information on URI encoding is RFC 2396.
252 Basically, the following substitutions do it:
253
254     s/([^\w()'*~!.-])/sprintf '%%%02x', ord $1/eg;   # encode
255
256     s/%([A-Fa-f\d]{2})/chr hex $1/eg;            # decode
257
258 However, you should only apply them to individual URI components, not
259 the entire URI, otherwise you'll lose information and generally mess
260 things up.  If that didn't explain it, don't worry.  Just go read
261 section 2 of the RFC, it's probably the best explanation there is.
262
263 RFC 2396 also contains a lot of other useful information, including a
264 regexp for breaking any arbitrary URI into components (Appendix B).
265
266 =head2 How do I redirect to another page?
267
268 Specify the complete URL of the destination (even if it is on the same
269 server). This is one of the two different kinds of CGI "Location:"
270 responses which are defined in the CGI specification for a Parsed Headers
271 script. The other kind (an absolute URLpath) is resolved internally to
272 the server without any HTTP redirection. The CGI specifications do not
273 allow relative URLs in either case.
274
275 Use of CGI.pm is strongly recommended.  This example shows redirection
276 with a complete URL. This redirection is handled by the web browser.
277
278       use CGI qw/:standard/;
279
280       my $url = 'http://www.cpan.org/';
281       print redirect($url);
282
283
284 This example shows a redirection with an absolute URLpath.  This
285 redirection is handled by the local web server.
286
287       my $url = '/CPAN/index.html';
288       print redirect($url);
289
290
291 But if coded directly, it could be as follows (the final "\n" is 
292 shown separately, for clarity), using either a complete URL or
293 an absolute URLpath. 
294
295       print "Location: $url\n";   # CGI response header
296       print "\n";                 # end of headers
297
298
299 =head2 How do I put a password on my web pages?
300
301 That depends.  You'll need to read the documentation for your web
302 server, or perhaps check some of the other FAQs referenced above.
303
304 =head2 How do I edit my .htpasswd and .htgroup files with Perl?
305
306 The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide a
307 consistent OO interface to these files, regardless of how they're
308 stored.  Databases may be text, dbm, Berkeley DB or any database with
309 a DBI compatible driver.  HTTPD::UserAdmin supports files used by the
310 `Basic' and `Digest' authentication schemes.  Here's an example:
311
312     use HTTPD::UserAdmin ();
313     HTTPD::UserAdmin
314           ->new(DB => "/foo/.htpasswd")
315           ->add($username => $password);
316
317 =head2 How do I make sure users can't enter values into a form that cause my CGI script to do bad things?
318
319 See the security references listed in the CGI Meta FAQ
320
321         http://www.perl.org/CGI_MetaFAQ.html
322
323 =head2 How do I parse a mail header?
324
325 For a quick-and-dirty solution, try this solution derived
326 from L<perlfunc/split>:
327
328     $/ = '';
329     $header = <MSG>;
330     $header =~ s/\n\s+/ /g;      # merge continuation lines
331     %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header );
332
333 That solution doesn't do well if, for example, you're trying to
334 maintain all the Received lines.  A more complete approach is to use
335 the Mail::Header module from CPAN (part of the MailTools package).
336
337 =head2 How do I decode a CGI form?
338
339 You use a standard module, probably CGI.pm.  Under no circumstances
340 should you attempt to do so by hand!
341
342 You'll see a lot of CGI programs that blindly read from STDIN the number
343 of bytes equal to CONTENT_LENGTH for POSTs, or grab QUERY_STRING for
344 decoding GETs.  These programs are very poorly written.  They only work
345 sometimes.  They typically forget to check the return value of the read()
346 system call, which is a cardinal sin.  They don't handle HEAD requests.
347 They don't handle multipart forms used for file uploads.  They don't deal
348 with GET/POST combinations where query fields are in more than one place.
349 They don't deal with keywords in the query string.
350
351 In short, they're bad hacks.  Resist them at all costs.  Please do not be
352 tempted to reinvent the wheel.  Instead, use the CGI.pm or CGI_Lite.pm
353 (available from CPAN), or if you're trapped in the module-free land
354 of perl1 .. perl4, you might look into cgi-lib.pl (available from
355 http://cgi-lib.stanford.edu/cgi-lib/ ).
356
357 Make sure you know whether to use a GET or a POST in your form.
358 GETs should only be used for something that doesn't update the server.
359 Otherwise you can get mangled databases and repeated feedback mail
360 messages.  The fancy word for this is ``idempotency''.  This simply
361 means that there should be no difference between making a GET request
362 for a particular URL once or multiple times.  This is because the
363 HTTP protocol definition says that a GET request may be cached by the
364 browser, or server, or an intervening proxy.  POST requests cannot be
365 cached, because each request is independent and matters.  Typically,
366 POST requests change or depend on state on the server (query or update
367 a database, send mail, or purchase a computer).
368
369 =head2 How do I check a valid mail address?
370
371 You can't, at least, not in real time.  Bummer, eh?
372
373 Without sending mail to the address and seeing whether there's a human
374 on the other hand to answer you, you cannot determine whether a mail
375 address is valid.  Even if you apply the mail header standard, you
376 can have problems, because there are deliverable addresses that aren't
377 RFC-822 (the mail header standard) compliant, and addresses that aren't
378 deliverable which are compliant.
379
380 Many are tempted to try to eliminate many frequently-invalid
381 mail addresses with a simple regex, such as
382 C</^[\w.-]+\@(?:[\w-]+\.)+\w+$/>.  It's a very bad idea.  However,
383 this also throws out many valid ones, and says nothing about
384 potential deliverability, so it is not suggested.  Instead, see
385 http://www.cpan.org/authors/Tom_Christiansen/scripts/ckaddr.gz ,
386 which actually checks against the full RFC spec (except for nested
387 comments), looks for addresses you may not wish to accept mail to
388 (say, Bill Clinton or your postmaster), and then makes sure that the
389 hostname given can be looked up in the DNS MX records.  It's not fast,
390 but it works for what it tries to do.
391
392 Our best advice for verifying a person's mail address is to have them
393 enter their address twice, just as you normally do to change a password.
394 This usually weeds out typos.  If both versions match, send
395 mail to that address with a personal message that looks somewhat like:
396
397     Dear someuser@host.com,
398
399     Please confirm the mail address you gave us Wed May  6 09:38:41
400     MDT 1998 by replying to this message.  Include the string
401     "Rumpelstiltskin" in that reply, but spelled in reverse; that is,
402     start with "Nik...".  Once this is done, your confirmed address will
403     be entered into our records.
404
405 If you get the message back and they've followed your directions,
406 you can be reasonably assured that it's real.
407
408 A related strategy that's less open to forgery is to give them a PIN
409 (personal ID number).  Record the address and PIN (best that it be a
410 random one) for later processing.  In the mail you send, ask them to
411 include the PIN in their reply.  But if it bounces, or the message is
412 included via a ``vacation'' script, it'll be there anyway.  So it's
413 best to ask them to mail back a slight alteration of the PIN, such as
414 with the characters reversed, one added or subtracted to each digit, etc.
415
416 =head2 How do I decode a MIME/BASE64 string?
417
418 The MIME-Base64 package (available from CPAN) handles this as well as
419 the MIME/QP encoding.  Decoding BASE64 becomes as simple as:
420
421     use MIME::Base64;
422     $decoded = decode_base64($encoded);
423
424 The MIME-Tools package (available from CPAN) supports extraction with
425 decoding of BASE64 encoded attachments and content directly from email
426 messages.
427
428 If the string to decode is short (less than 84 bytes long)
429 a more direct approach is to use the unpack() function's "u"
430 format after minor transliterations:
431
432     tr#A-Za-z0-9+/##cd;                   # remove non-base64 chars
433     tr#A-Za-z0-9+/# -_#;                  # convert to uuencoded format
434     $len = pack("c", 32 + 0.75*length);   # compute length byte
435     print unpack("u", $len . $_);         # uudecode and print
436
437 =head2 How do I return the user's mail address?
438
439 On systems that support getpwuid, the $< variable, and the
440 Sys::Hostname module (which is part of the standard perl distribution),
441 you can probably try using something like this:
442
443     use Sys::Hostname;
444     $address = sprintf('%s@%s', scalar getpwuid($<), hostname);
445
446 Company policies on mail address can mean that this generates addresses
447 that the company's mail system will not accept, so you should ask for
448 users' mail addresses when this matters.  Furthermore, not all systems
449 on which Perl runs are so forthcoming with this information as is Unix.
450
451 The Mail::Util module from CPAN (part of the MailTools package) provides a
452 mailaddress() function that tries to guess the mail address of the user.
453 It makes a more intelligent guess than the code above, using information
454 given when the module was installed, but it could still be incorrect.
455 Again, the best way is often just to ask the user.
456
457 =head2 How do I send mail?
458
459 Use the C<sendmail> program directly:
460
461     open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
462                         or die "Can't fork for sendmail: $!\n";
463     print SENDMAIL <<"EOF";
464     From: User Originating Mail <me\@host>
465     To: Final Destination <you\@otherhost>
466     Subject: A relevant subject line
467
468     Body of the message goes here after the blank line
469     in as many lines as you like.
470     EOF
471     close(SENDMAIL)     or warn "sendmail didn't close nicely";
472
473 The B<-oi> option prevents sendmail from interpreting a line consisting
474 of a single dot as "end of message".  The B<-t> option says to use the
475 headers to decide who to send the message to, and B<-odq> says to put
476 the message into the queue.  This last option means your message won't
477 be immediately delivered, so leave it out if you want immediate
478 delivery.
479
480 Alternate, less convenient approaches include calling mail (sometimes
481 called mailx) directly or simply opening up port 25 have having an
482 intimate conversation between just you and the remote SMTP daemon,
483 probably sendmail.
484
485 Or you might be able use the CPAN module Mail::Mailer:
486
487     use Mail::Mailer;
488
489     $mailer = Mail::Mailer->new();
490     $mailer->open({ From    => $from_address,
491                     To      => $to_address,
492                     Subject => $subject,
493                   })
494         or die "Can't open: $!\n";
495     print $mailer $body;
496     $mailer->close();
497
498 The Mail::Internet module uses Net::SMTP which is less Unix-centric than
499 Mail::Mailer, but less reliable.  Avoid raw SMTP commands.  There
500 are many reasons to use a mail transport agent like sendmail.  These
501 include queuing, MX records, and security.
502
503 =head2 How do I use MIME to make an attachment to a mail message?
504
505 This answer is extracted directly from the MIME::Lite documentation.
506 Create a multipart message (i.e., one with attachments).
507
508     use MIME::Lite;
509
510     ### Create a new multipart message:
511     $msg = MIME::Lite->new(
512                  From    =>'me@myhost.com',
513                  To      =>'you@yourhost.com',
514                  Cc      =>'some@other.com, some@more.com',
515                  Subject =>'A message with 2 parts...',
516                  Type    =>'multipart/mixed'
517                  );
518
519     ### Add parts (each "attach" has same arguments as "new"):
520     $msg->attach(Type     =>'TEXT',
521                  Data     =>"Here's the GIF file you wanted"
522                  );
523     $msg->attach(Type     =>'image/gif',
524                  Path     =>'aaa000123.gif',
525                  Filename =>'logo.gif'
526                  );
527
528     $text = $msg->as_string;
529
530 MIME::Lite also includes a method for sending these things.
531
532     $msg->send;
533
534 This defaults to using L<sendmail(1)> but can be customized to use
535 SMTP via L<Net::SMTP>.
536
537 =head2 How do I read mail?
538
539 While you could use the Mail::Folder module from CPAN (part of the
540 MailFolder package) or the Mail::Internet module from CPAN (also part
541 of the MailTools package), often a module is overkill.  Here's a
542 mail sorter.
543
544     #!/usr/bin/perl
545     # bysub1 - simple sort by subject
546     my(@msgs, @sub);
547     my $msgno = -1;
548     $/ = '';                    # paragraph reads
549     while (<>) {
550         if (/^From/m) {
551             /^Subject:\s*(?:Re:\s*)*(.*)/mi;
552             $sub[++$msgno] = lc($1) || '';
553         }
554         $msgs[$msgno] .= $_;
555     }
556     for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) {
557         print $msgs[$i];
558     }
559
560 Or more succinctly,
561
562     #!/usr/bin/perl -n00
563     # bysub2 - awkish sort-by-subject
564     BEGIN { $msgno = -1 }
565     $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m;
566     $msg[$msgno] .= $_;
567     END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] }
568
569 =head2 How do I find out my hostname/domainname/IP address?
570
571 The normal way to find your own hostname is to call the C<`hostname`>
572 program.  While sometimes expedient, this has some problems, such as
573 not knowing whether you've got the canonical name or not.  It's one of
574 those tradeoffs of convenience versus portability.
575
576 The Sys::Hostname module (part of the standard perl distribution) will
577 give you the hostname after which you can find out the IP address
578 (assuming you have working DNS) with a gethostbyname() call.
579
580     use Socket;
581     use Sys::Hostname;
582     my $host = hostname();
583     my $addr = inet_ntoa(scalar gethostbyname($host || 'localhost'));
584
585 Probably the simplest way to learn your DNS domain name is to grok
586 it out of /etc/resolv.conf, at least under Unix.  Of course, this
587 assumes several things about your resolv.conf configuration, including
588 that it exists.
589
590 (We still need a good DNS domain name-learning method for non-Unix
591 systems.)
592
593 =head2 How do I fetch a news article or the active newsgroups?
594
595 Use the Net::NNTP or News::NNTPClient modules, both available from CPAN.
596 This can make tasks like fetching the newsgroup list as simple as
597
598     perl -MNews::NNTPClient
599       -e 'print News::NNTPClient->new->list("newsgroups")'
600
601 =head2 How do I fetch/put an FTP file?
602
603 LWP::Simple (available from CPAN) can fetch but not put.  Net::FTP (also
604 available from CPAN) is more complex but can put as well as fetch.
605
606 =head2 How can I do RPC in Perl?
607
608 A DCE::RPC module is being developed (but is not yet available) and
609 will be released as part of the DCE-Perl package (available from
610 CPAN).  The rpcgen suite, available from CPAN/authors/id/JAKE/, is
611 an RPC stub generator and includes an RPC::ONC module.
612
613 =head1 AUTHOR AND COPYRIGHT
614
615 Copyright (c) 1997-2002 Tom Christiansen and Nathan Torkington.
616 All rights reserved.
617
618 This documentation is free; you can redistribute it and/or modify it
619 under the same terms as Perl itself.
620
621 Irrespective of its distribution, all code examples in this file
622 are hereby placed into the public domain.  You are permitted and
623 encouraged to use this code in your own programs for fun
624 or for profit as you see fit.  A simple comment in the code giving
625 credit would be courteous but is not required.