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