Leaked source code of windows server 2003
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.

602 lines
23 KiB

  1. =head1 NAME
  2. perlfaq9 - Networking ($Revision: 1.26 $, $Date: 1999/05/23 16:08:30 $)
  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::Parser
  57. from CPAN. Another mostly correct
  58. way is to use HTML::FormatText which not only removes HTML but also
  59. attempts to do a little simple formatting of the resulting plain text.
  60. Many folks attempt a simple-minded regular expression approach, like
  61. C<< s/<.*?>//g >>, but that fails in many cases because the tags
  62. may continue over line breaks, they may contain quoted angle-brackets,
  63. or HTML comment may be present. Plus, folks forget to convert
  64. entities--like C<&lt;> for example.
  65. Here's one "simple-minded" approach, that works for most files:
  66. #!/usr/bin/perl -p0777
  67. s/<(?:[^>'"]*|(['"]).*?\1)*>//gs
  68. If you want a more complete solution, see the 3-stage striphtml
  69. program in
  70. http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/striphtml.gz
  71. .
  72. Here are some tricky cases that you should think about when picking
  73. a solution:
  74. <IMG SRC = "foo.gif" ALT = "A > B">
  75. <IMG SRC = "foo.gif"
  76. ALT = "A > B">
  77. <!-- <A comment> -->
  78. <script>if (a<b && a>c)</script>
  79. <# Just data #>
  80. <![INCLUDE CDATA [ >>>>>>>>>>>> ]]>
  81. If HTML comments include other tags, those solutions would also break
  82. on text like this:
  83. <!-- This section commented out.
  84. <B>You can't see me!</B>
  85. -->
  86. =head2 How do I extract URLs?
  87. A quick but imperfect approach is
  88. #!/usr/bin/perl -n00
  89. # qxurl - [email protected]
  90. print "$2\n" while m{
  91. < \s*
  92. A \s+ HREF \s* = \s* (["']) (.*?) \1
  93. \s* >
  94. }gsix;
  95. This version does not adjust relative URLs, understand alternate
  96. bases, deal with HTML comments, deal with HREF and NAME attributes
  97. in the same tag, understand extra qualifiers like TARGET, or accept
  98. URLs themselves as arguments. It also runs about 100x faster than a
  99. more "complete" solution using the LWP suite of modules, such as the
  100. http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/xurl.gz program.
  101. =head2 How do I download a file from the user's machine? How do I open a file on another machine?
  102. In the context of an HTML form, you can use what's known as
  103. B<multipart/form-data> encoding. The CGI.pm module (available from
  104. CPAN) supports this in the start_multipart_form() method, which isn't
  105. the same as the startform() method.
  106. =head2 How do I make a pop-up menu in HTML?
  107. Use the B<< <SELECT> >> and B<< <OPTION> >> tags. The CGI.pm
  108. module (available from CPAN) supports this widget, as well as many
  109. others, including some that it cleverly synthesizes on its own.
  110. =head2 How do I fetch an HTML file?
  111. One approach, if you have the lynx text-based HTML browser installed
  112. on your system, is this:
  113. $html_code = `lynx -source $url`;
  114. $text_data = `lynx -dump $url`;
  115. The libwww-perl (LWP) modules from CPAN provide a more powerful way
  116. to do this. They don't require lynx, but like lynx, can still work
  117. through proxies:
  118. # simplest version
  119. use LWP::Simple;
  120. $content = get($URL);
  121. # or print HTML from a URL
  122. use LWP::Simple;
  123. getprint "http://www.linpro.no/lwp/";
  124. # or print ASCII from HTML from a URL
  125. # also need HTML-Tree package from CPAN
  126. use LWP::Simple;
  127. use HTML::Parser;
  128. use HTML::FormatText;
  129. my ($html, $ascii);
  130. $html = get("http://www.perl.com/");
  131. defined $html
  132. or die "Can't fetch HTML from http://www.perl.com/";
  133. $ascii = HTML::FormatText->new->format(parse_html($html));
  134. print $ascii;
  135. =head2 How do I automate an HTML form submission?
  136. If you're submitting values using the GET method, create a URL and encode
  137. the form using the C<query_form> method:
  138. use LWP::Simple;
  139. use URI::URL;
  140. my $url = url('http://www.perl.com/cgi-bin/cpan_mod');
  141. $url->query_form(module => 'DB_File', readme => 1);
  142. $content = get($url);
  143. If you're using the POST method, create your own user agent and encode
  144. the content appropriately.
  145. use HTTP::Request::Common qw(POST);
  146. use LWP::UserAgent;
  147. $ua = LWP::UserAgent->new();
  148. my $req = POST 'http://www.perl.com/cgi-bin/cpan_mod',
  149. [ module => 'DB_File', readme => 1 ];
  150. $content = $ua->request($req)->as_string;
  151. =head2 How do I decode or create those %-encodings on the web?
  152. If you are writing a CGI script, you should be using the CGI.pm module
  153. that comes with perl, or some other equivalent module. The CGI module
  154. automatically decodes queries for you, and provides an escape()
  155. function to handle encoding.
  156. The best source of detailed information on URI encoding is RFC 2396.
  157. Basically, the following substitutions do it:
  158. s/([^\w()'*~!.-])/sprintf '%%%02x', $1/eg; # encode
  159. s/%([A-Fa-f\d]{2})/chr hex $1/eg; # decode
  160. However, you should only apply them to individual URI components, not
  161. the entire URI, otherwise you'll lose information and generally mess
  162. things up. If that didn't explain it, don't worry. Just go read
  163. section 2 of the RFC, it's probably the best explanation there is.
  164. RFC 2396 also contains a lot of other useful information, including a
  165. regexp for breaking any arbitrary URI into components (Appendix B).
  166. =head2 How do I redirect to another page?
  167. According to RFC 2616, "Hypertext Transfer Protocol -- HTTP/1.1", the
  168. preferred method is to send a C<Location:> header instead of a
  169. C<Content-Type:> header:
  170. Location: http://www.domain.com/newpage
  171. Note that relative URLs in these headers can cause strange effects
  172. because of "optimizations" that servers do.
  173. $url = "http://www.perl.com/CPAN/";
  174. print "Location: $url\n\n";
  175. exit;
  176. To target a particular frame in a frameset, include the "Window-target:"
  177. in the header.
  178. print <<EOF;
  179. Location: http://www.domain.com/newpage
  180. Window-target: <FrameName>
  181. EOF
  182. To be correct to the spec, each of those virtual newlines should
  183. really be physical C<"\015\012"> sequences by the time your message is
  184. received by the client browser. Except for NPH scripts, though, that
  185. local newline should get translated by your server into standard form,
  186. so you shouldn't have a problem here, even if you are stuck on MacOS.
  187. Everybody else probably won't even notice.
  188. =head2 How do I put a password on my web pages?
  189. That depends. You'll need to read the documentation for your web
  190. server, or perhaps check some of the other FAQs referenced above.
  191. =head2 How do I edit my .htpasswd and .htgroup files with Perl?
  192. The HTTPD::UserAdmin and HTTPD::GroupAdmin modules provide a
  193. consistent OO interface to these files, regardless of how they're
  194. stored. Databases may be text, dbm, Berkley DB or any database with a
  195. DBI compatible driver. HTTPD::UserAdmin supports files used by the
  196. `Basic' and `Digest' authentication schemes. Here's an example:
  197. use HTTPD::UserAdmin ();
  198. HTTPD::UserAdmin
  199. ->new(DB => "/foo/.htpasswd")
  200. ->add($username => $password);
  201. =head2 How do I make sure users can't enter values into a form that cause my CGI script to do bad things?
  202. Read the CGI security FAQ, at
  203. http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html , and the
  204. Perl/CGI FAQ at
  205. http://www.perl.com/CPAN/doc/FAQs/cgi/perl-cgi-faq.html .
  206. In brief: use tainting (see L<perlsec>), which makes sure that data
  207. from outside your script (eg, CGI parameters) are never used in
  208. C<eval> or C<system> calls. In addition to tainting, never use the
  209. single-argument form of system() or exec(). Instead, supply the
  210. command and arguments as a list, which prevents shell globbing.
  211. =head2 How do I parse a mail header?
  212. For a quick-and-dirty solution, try this solution derived
  213. from L<perlfunc/split>:
  214. $/ = '';
  215. $header = <MSG>;
  216. $header =~ s/\n\s+/ /g; # merge continuation lines
  217. %head = ( UNIX_FROM_LINE, split /^([-\w]+):\s*/m, $header );
  218. That solution doesn't do well if, for example, you're trying to
  219. maintain all the Received lines. A more complete approach is to use
  220. the Mail::Header module from CPAN (part of the MailTools package).
  221. =head2 How do I decode a CGI form?
  222. You use a standard module, probably CGI.pm. Under no circumstances
  223. should you attempt to do so by hand!
  224. You'll see a lot of CGI programs that blindly read from STDIN the number
  225. of bytes equal to CONTENT_LENGTH for POSTs, or grab QUERY_STRING for
  226. decoding GETs. These programs are very poorly written. They only work
  227. sometimes. They typically forget to check the return value of the read()
  228. system call, which is a cardinal sin. They don't handle HEAD requests.
  229. They don't handle multipart forms used for file uploads. They don't deal
  230. with GET/POST combinations where query fields are in more than one place.
  231. They don't deal with keywords in the query string.
  232. In short, they're bad hacks. Resist them at all costs. Please do not be
  233. tempted to reinvent the wheel. Instead, use the CGI.pm or CGI_Lite.pm
  234. (available from CPAN), or if you're trapped in the module-free land
  235. of perl1 .. perl4, you might look into cgi-lib.pl (available from
  236. http://cgi-lib.stanford.edu/cgi-lib/ ).
  237. Make sure you know whether to use a GET or a POST in your form.
  238. GETs should only be used for something that doesn't update the server.
  239. Otherwise you can get mangled databases and repeated feedback mail
  240. messages. The fancy word for this is ``idempotency''. This simply
  241. means that there should be no difference between making a GET request
  242. for a particular URL once or multiple times. This is because the
  243. HTTP protocol definition says that a GET request may be cached by the
  244. browser, or server, or an intervening proxy. POST requests cannot be
  245. cached, because each request is independent and matters. Typically,
  246. POST requests change or depend on state on the server (query or update
  247. a database, send mail, or purchase a computer).
  248. =head2 How do I check a valid mail address?
  249. You can't, at least, not in real time. Bummer, eh?
  250. Without sending mail to the address and seeing whether there's a human
  251. on the other hand to answer you, you cannot determine whether a mail
  252. address is valid. Even if you apply the mail header standard, you
  253. can have problems, because there are deliverable addresses that aren't
  254. RFC-822 (the mail header standard) compliant, and addresses that aren't
  255. deliverable which are compliant.
  256. Many are tempted to try to eliminate many frequently-invalid
  257. mail addresses with a simple regex, such as
  258. C</^[\w.-]+\@(?:[\w-]+\.)+\w+$/>. It's a very bad idea. However,
  259. this also throws out many valid ones, and says nothing about
  260. potential deliverability, so it is not suggested. Instead, see
  261. http://www.perl.com/CPAN/authors/Tom_Christiansen/scripts/ckaddr.gz,
  262. which actually checks against the full RFC spec (except for nested
  263. comments), looks for addresses you may not wish to accept mail to
  264. (say, Bill Clinton or your postmaster), and then makes sure that the
  265. hostname given can be looked up in the DNS MX records. It's not fast,
  266. but it works for what it tries to do.
  267. Our best advice for verifying a person's mail address is to have them
  268. enter their address twice, just as you normally do to change a password.
  269. This usually weeds out typos. If both versions match, send
  270. mail to that address with a personal message that looks somewhat like:
  271. Dear [email protected],
  272. Please confirm the mail address you gave us Wed May 6 09:38:41
  273. MDT 1998 by replying to this message. Include the string
  274. "Rumpelstiltskin" in that reply, but spelled in reverse; that is,
  275. start with "Nik...". Once this is done, your confirmed address will
  276. be entered into our records.
  277. If you get the message back and they've followed your directions,
  278. you can be reasonably assured that it's real.
  279. A related strategy that's less open to forgery is to give them a PIN
  280. (personal ID number). Record the address and PIN (best that it be a
  281. random one) for later processing. In the mail you send, ask them to
  282. include the PIN in their reply. But if it bounces, or the message is
  283. included via a ``vacation'' script, it'll be there anyway. So it's
  284. best to ask them to mail back a slight alteration of the PIN, such as
  285. with the characters reversed, one added or subtracted to each digit, etc.
  286. =head2 How do I decode a MIME/BASE64 string?
  287. The MIME-Base64 package (available from CPAN) handles this as well as
  288. the MIME/QP encoding. Decoding BASE64 becomes as simple as:
  289. use MIME::Base64;
  290. $decoded = decode_base64($encoded);
  291. The MIME-Tools package (available from CPAN) supports extraction with
  292. decoding of BASE64 encoded attachments and content directly from email
  293. messages.
  294. If the string to decode is short (less than 84 bytes long)
  295. a more direct approach is to use the unpack() function's "u"
  296. format after minor transliterations:
  297. tr#A-Za-z0-9+/##cd; # remove non-base64 chars
  298. tr#A-Za-z0-9+/# -_#; # convert to uuencoded format
  299. $len = pack("c", 32 + 0.75*length); # compute length byte
  300. print unpack("u", $len . $_); # uudecode and print
  301. =head2 How do I return the user's mail address?
  302. On systems that support getpwuid, the $< variable, and the
  303. Sys::Hostname module (which is part of the standard perl distribution),
  304. you can probably try using something like this:
  305. use Sys::Hostname;
  306. $address = sprintf('%s@%s', scalar getpwuid($<), hostname);
  307. Company policies on mail address can mean that this generates addresses
  308. that the company's mail system will not accept, so you should ask for
  309. users' mail addresses when this matters. Furthermore, not all systems
  310. on which Perl runs are so forthcoming with this information as is Unix.
  311. The Mail::Util module from CPAN (part of the MailTools package) provides a
  312. mailaddress() function that tries to guess the mail address of the user.
  313. It makes a more intelligent guess than the code above, using information
  314. given when the module was installed, but it could still be incorrect.
  315. Again, the best way is often just to ask the user.
  316. =head2 How do I send mail?
  317. Use the C<sendmail> program directly:
  318. open(SENDMAIL, "|/usr/lib/sendmail -oi -t -odq")
  319. or die "Can't fork for sendmail: $!\n";
  320. print SENDMAIL <<"EOF";
  321. From: User Originating Mail <me\@host>
  322. To: Final Destination <you\@otherhost>
  323. Subject: A relevant subject line
  324. Body of the message goes here after the blank line
  325. in as many lines as you like.
  326. EOF
  327. close(SENDMAIL) or warn "sendmail didn't close nicely";
  328. The B<-oi> option prevents sendmail from interpreting a line consisting
  329. of a single dot as "end of message". The B<-t> option says to use the
  330. headers to decide who to send the message to, and B<-odq> says to put
  331. the message into the queue. This last option means your message won't
  332. be immediately delivered, so leave it out if you want immediate
  333. delivery.
  334. Alternate, less convenient approaches include calling mail (sometimes
  335. called mailx) directly or simply opening up port 25 have having an
  336. intimate conversation between just you and the remote SMTP daemon,
  337. probably sendmail.
  338. Or you might be able use the CPAN module Mail::Mailer:
  339. use Mail::Mailer;
  340. $mailer = Mail::Mailer->new();
  341. $mailer->open({ From => $from_address,
  342. To => $to_address,
  343. Subject => $subject,
  344. })
  345. or die "Can't open: $!\n";
  346. print $mailer $body;
  347. $mailer->close();
  348. The Mail::Internet module uses Net::SMTP which is less Unix-centric than
  349. Mail::Mailer, but less reliable. Avoid raw SMTP commands. There
  350. are many reasons to use a mail transport agent like sendmail. These
  351. include queueing, MX records, and security.
  352. =head2 How do I use MIME to make an attachment to a mail message?
  353. This answer is extracted directly from the MIME::Lite documentation.
  354. Create a multipart message (i.e., one with attachments).
  355. use MIME::Lite;
  356. ### Create a new multipart message:
  357. $msg = MIME::Lite->new(
  358. From =>'[email protected]',
  359. To =>'[email protected]',
  360. Cc =>'[email protected], [email protected]',
  361. Subject =>'A message with 2 parts...',
  362. Type =>'multipart/mixed'
  363. );
  364. ### Add parts (each "attach" has same arguments as "new"):
  365. $msg->attach(Type =>'TEXT',
  366. Data =>"Here's the GIF file you wanted"
  367. );
  368. $msg->attach(Type =>'image/gif',
  369. Path =>'aaa000123.gif',
  370. Filename =>'logo.gif'
  371. );
  372. $text = $msg->as_string;
  373. MIME::Lite also includes a method for sending these things.
  374. $msg->send;
  375. This defaults to using L<sendmail(1)> but can be customized to use
  376. SMTP via L<Net::SMTP>.
  377. =head2 How do I read mail?
  378. While you could use the Mail::Folder module from CPAN (part of the
  379. MailFolder package) or the Mail::Internet module from CPAN (also part
  380. of the MailTools package), often a module is overkill. Here's a
  381. mail sorter.
  382. #!/usr/bin/perl
  383. # bysub1 - simple sort by subject
  384. my(@msgs, @sub);
  385. my $msgno = -1;
  386. $/ = ''; # paragraph reads
  387. while (<>) {
  388. if (/^From/m) {
  389. /^Subject:\s*(?:Re:\s*)*(.*)/mi;
  390. $sub[++$msgno] = lc($1) || '';
  391. }
  392. $msgs[$msgno] .= $_;
  393. }
  394. for my $i (sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msgs)) {
  395. print $msgs[$i];
  396. }
  397. Or more succinctly,
  398. #!/usr/bin/perl -n00
  399. # bysub2 - awkish sort-by-subject
  400. BEGIN { $msgno = -1 }
  401. $sub[++$msgno] = (/^Subject:\s*(?:Re:\s*)*(.*)/mi)[0] if /^From/m;
  402. $msg[$msgno] .= $_;
  403. END { print @msg[ sort { $sub[$a] cmp $sub[$b] || $a <=> $b } (0 .. $#msg) ] }
  404. =head2 How do I find out my hostname/domainname/IP address?
  405. The normal way to find your own hostname is to call the C<`hostname`>
  406. program. While sometimes expedient, this has some problems, such as
  407. not knowing whether you've got the canonical name or not. It's one of
  408. those tradeoffs of convenience versus portability.
  409. The Sys::Hostname module (part of the standard perl distribution) will
  410. give you the hostname after which you can find out the IP address
  411. (assuming you have working DNS) with a gethostbyname() call.
  412. use Socket;
  413. use Sys::Hostname;
  414. my $host = hostname();
  415. my $addr = inet_ntoa(scalar gethostbyname($host || 'localhost'));
  416. Probably the simplest way to learn your DNS domain name is to grok
  417. it out of /etc/resolv.conf, at least under Unix. Of course, this
  418. assumes several things about your resolv.conf configuration, including
  419. that it exists.
  420. (We still need a good DNS domain name-learning method for non-Unix
  421. systems.)
  422. =head2 How do I fetch a news article or the active newsgroups?
  423. Use the Net::NNTP or News::NNTPClient modules, both available from CPAN.
  424. This can make tasks like fetching the newsgroup list as simple as
  425. perl -MNews::NNTPClient
  426. -e 'print News::NNTPClient->new->list("newsgroups")'
  427. =head2 How do I fetch/put an FTP file?
  428. LWP::Simple (available from CPAN) can fetch but not put. Net::FTP (also
  429. available from CPAN) is more complex but can put as well as fetch.
  430. =head2 How can I do RPC in Perl?
  431. A DCE::RPC module is being developed (but is not yet available) and
  432. will be released as part of the DCE-Perl package (available from
  433. CPAN). The rpcgen suite, available from CPAN/authors/id/JAKE/, is
  434. an RPC stub generator and includes an RPC::ONC module.
  435. =head1 AUTHOR AND COPYRIGHT
  436. Copyright (c) 1997-1999 Tom Christiansen and Nathan Torkington.
  437. All rights reserved.
  438. When included as part of the Standard Version of Perl, or as part of
  439. its complete documentation whether printed or otherwise, this work
  440. may be distributed only under the terms of Perl's Artistic License.
  441. Any distribution of this file or derivatives thereof I<outside>
  442. of that package require that special arrangements be made with
  443. copyright holder.
  444. Irrespective of its distribution, all code examples in this file
  445. are hereby placed into the public domain. You are permitted and
  446. encouraged to use this code in your own programs for fun
  447. or for profit as you see fit. A simple comment in the code giving
  448. credit would be courteous but is not required.