Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

554 lines
20 KiB

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