Debian Codegraph @

bin/server

raw
1 #!/usr/bin/env perl
2 use strict;
3 use warnings;
4 use Getopt::Long;
5
6 ########################
7 # Command Line Options
8 ########################
9 my %opts = ( port => 8080, host => 'localhost', bg => 0 );
10 GetOptions(
11 "port|p=s" => \$opts{port},
12 "host|H=s" => \$opts{host},
13 "background|b" => \$opts{bg},
14 "help|h" => \$opts{help},
15 "include|I=s" => \$opts{include},
16 ) || ( $opts{help} = 1 );
17 die_with_usage() if $opts{help};
18 $opts{ra_class} = shift || die_with_usage("No class given");
19
20 #########################
21 # Setup the Environment
22 #########################
23 extend_INC( $opts{include} );
24 load_class( $opts{ra_class} );
25
26 ######################
27 # Run the Web Server
28 ######################
29 my $server = WebServer->new( $opts{port} );
30 $server->host( $opts{host} );
31 my $run_method = $opts{bg} ? "background" : "run";
32 $server->{ra_class} = $opts{ra_class};
33 $server->$run_method();
34 exit;
35
36 ###########
37 # Helpers
38 ###########
39
40 sub extend_INC {
41 my $include = shift || "";
42 my @dirs = split /,/, $include;
43 unshift @INC, reverse(@dirs);
44 }
45
46 sub load_class {
47 my $klass = shift;
48 eval "require $klass;";
49 die "Unable to load $klass: $@\n" if $@;
50 }
51
52 sub die_with_usage {
53 my $msg = shift || "";
54 warn "$msg\n\n" if $msg;
55 die <<USAGE
56 Usage: $0 [options] Some::RA::Class
57
58 Runs a server dedicated to serving up Some::RA::Class, which should subclass
59 REST::Application or REST::Application::Routes.
60
61 Options:
62
63 --include
64 -I
65 Use this to add directories to Perl's \@INC. Directories should be
66 comma seperated.
67
68 --port port_num
69 -p port_num
70 Set the port number for the server to run on.
71
72 --host hostname
73 -H hostname
74 Set the hostname the server binds to.
75
76 --background
77 -b
78 Use this to background the webserver, otherwise it runs in the
79 foreground.
80
81 USAGE
82 }
83
84 package WebServer;
85 use strict;
86 use warnings;
87 use REST::Application;
88 use base qw(HTTP::Server::Simple::CGI);
89
90 sub handle_request {
91 my ( $self, $cgi ) = @_;
92 my $klass = $self->{ra_class};
93 my $ra = $klass->new();
94 $ra->run();
95 }
96
97 sub print_banner {
98 my $self = shift;
99 print "Server is serving class "
100 . $self->{ra_class}
101 . " at http://"
102 . $self->host . ":"
103 . $self->port . "/\n\n";
104 }
105
106 1;
107
108 package HTTP::Server::Simple;
109 use strict;
110 use warnings;
111 use FileHandle;
112 use Socket;
113 use Carp;
114 use URI::Escape;
115
116 no warnings 'redefine';
117
118 use vars qw($VERSION $bad_request_doc);
119 $VERSION = '0.26';
120
121
122 =head1 NAME
123
124 HTTP::Server::Simple - Lightweight HTTP server
125
126
127 =head1 SYNOPSIS
128
129 use warnings;
130 use strict;
131
132 use HTTP::Server::Simple;
133
134 my $server = HTTP::Server::Simple->new();
135 $server->run();
136
137 However, normally you will sub-class the HTTP::Server::Simple::CGI
138 module (see L<HTTP::Server::Simple::CGI>);
139
140 package Your::Web::Server;
141 use base qw(HTTP::Server::Simple::CGI);
142
143 sub handle_request {
144 my ($self, $cgi) = @_;
145
146 #... do something, print output to default
147 # selected filehandle...
148
149 }
150
151 1;
152
153 =head1 DESCRIPTION
154
155 This is a simple standalone HTTP server. By default, it doesn't thread
156 or fork.
157
158 It does, however, act as a simple frontend which can be used
159 to build a standalone web-based application or turn a CGI into one.
160
161 (It's possible to use Net::Server to get threading, forking,
162 preforking and so on. Autrijus Tang wrote the functionality and owes docs for that ;)
163
164 By default, the server traps a few signals:
165
166 =over
167
168 =item HUP
169
170 When you C<kill -HUP> the server, it does its best to rexec
171 itself. Please note that in order to provide restart-on-SIGHUP,
172 HTTP::Server::Simple sets a SIGHUP handler during initialisation. If
173 your request handling code forks you need to make sure you reset this
174 or unexpected things will happen if somebody sends a HUP to all running
175 processes spawned by your app (e.g. by "kill -HUP <script>")
176
177
178 =item PIPE
179
180 If the server detects a broken pipe while writing output to the client,
181 it ignores the signal. Otherwise, a client closing the connection early
182 could kill the server
183
184 =back
185
186 =head2 HTTP::Server::Simple->new($port)
187
188 API call to start a new server. Does not actually start listening
189 until you call C<-E<gt>run()>.
190
191 =cut
192
193 sub new {
194 my ( $proto, $port ) = @_;
195 my $class = ref($proto) || $proto;
196
197 if ( $class eq __PACKAGE__ ) {
198 require HTTP::Server::Simple::CGI;
199 return HTTP::Server::Simple::CGI->new( @_[ 1 .. $#_ ] );
200 }
201
202 my $self = {};
203 bless( $self, $class );
204 $self->port( $port || '8080' );
205
206
207
208 return $self;
209 }
210
211
212 =head2 lookup_localhost
213
214 Looks up the local host's hostname and IP address.
215
216 Stuffs them into
217
218 $self->{'localname'} and $self->{'localaddr'}
219
220 =cut
221
222 sub lookup_localhost {
223 my $self = shift;
224
225 my $local_sockaddr = getsockname( $self->stdio_handle );
226 my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
227 $self->host( gethostbyaddr( $localiaddr, AF_INET ) || "localhost");
228 $self->{'local_addr'} = inet_ntoa($localiaddr) || "127.0.0.1";
229 }
230
231
232
233
234 =head2 port [NUMBER]
235
236 Takes an optional port number for this server to listen on.
237
238 Returns this server's port. (Defaults to 8080)
239
240 =cut
241
242 sub port {
243 my $self = shift;
244 $self->{'port'} = shift if (@_);
245 return ( $self->{'port'} );
246
247 }
248
249 =head2 host [address]
250
251 Takes an optional host address for this server to bind to.
252
253 Returns this server's bound address (if any). Defaults to C<undef>
254 (bind to all interfaces).
255
256 =cut
257
258 sub host {
259 my $self = shift;
260 $self->{'host'} = shift if (@_);
261 return ( $self->{'host'} );
262
263 }
264
265 =head2 background
266
267 Run the server in the background. returns pid.
268
269 =cut
270
271 sub background {
272 my $self = shift;
273 my $child = fork;
274 die "Can't fork: $!" unless defined($child);
275 return $child if $child;
276
277 if ( $^O !~ /MSWin32/ ) {
278 require POSIX;
279 POSIX::setsid()
280 or die "Can't start a new session: $!";
281 }
282 $self->run();
283 }
284
285 =head2 run
286
287 Run the server. If all goes well, this won't ever return, but it will
288 start listening for http requests.
289
290 =cut
291
292 my $server_class_id = 0;
293
294 sub run {
295 my $self = shift;
296 my $server = $self->net_server;
297
298 # Handle SIGHUP
299
300 local $SIG{CHLD} = 'IGNORE'; # reap child processes
301 local $SIG{HUP} = sub {
302
303 # XXX TODO: Autrijus says this code was incorrect when he wrote
304 # it and we should move to the sample code from perldoc perlipc
305 close HTTPDaemon;
306
307 # and then, on systems implementing fork(), we make sure
308 # we are running with a new pid, so another -HUP will still
309 # work on the new process.
310 require Config;
311 if ( $Config::Config{d_fork} and my $pid = fork() ) {
312
313 # finally, allow ^C on the parent process to terminate
314 # the children.
315 waitpid( $pid, 0 );
316 exit;
317 }
318
319 # do the exec. if $0 is not executable, try running it with $^X.
320 exec {$0}( ( ( -x $0 ) ? () : ($^X) ), $0, @ARGV );
321 } if exists $SIG{'HUP'};
322
323 # $pkg is generated anew for each invocation to "run"
324 # Just so we can use different net_server() implementations
325 # in different runs.
326 my $pkg = join '::', ref($self), "NetServer" . $server_class_id++;
327
328 no strict 'refs';
329 *{"$pkg\::process_request"} = $self->_process_request;
330
331 if ($server) {
332 require join( '/', split /::/, $server ) . '.pm';
333 *{"$pkg\::ISA"} = [$server];
334 $self->print_banner;
335 }
336 else {
337 $self->setup_listener;
338 $self->after_setup_listener();
339 *{"$pkg\::run"} = $self->_default_run;
340 }
341
342 $pkg->run( port => $self->port );
343 }
344
345 =head2 net_server
346
347 User-overridable method. If you set it to a C<Net::Server> subclass,
348 that subclass is used for the C<run> method. Otherwise, a minimal
349 implementation is used as default.
350
351 =cut
352
353 sub net_server {undef}
354
355 sub _default_run {
356 my $self = shift;
357
358 # Default "run" closure method for a stub, minimal Net::Server instance.
359 return sub {
360 my $pkg = shift;
361
362 $self->print_banner;
363
364 while (1) {
365 local $SIG{PIPE} = 'IGNORE'; # If we don't ignore SIGPIPE, a
366 # client closing the connection before we
367 # finish sending will cause the server to exit
368 while ( accept( my $remote = new FileHandle, HTTPDaemon ) ) {
369 $self->stdio_handle($remote);
370 $self->lookup_localhost() unless ($self->host);
371 $self->accept_hook if $self->can("accept_hook");
372
373
374 *STDIN = $self->stdin_handle();
375 *STDOUT = $self->stdout_handle();
376 select STDOUT; # required for HTTP::Server::Simple::Recorder
377 # XXX TODO glasser: why?
378 $pkg->process_request;
379 close $remote;
380 }
381 }
382 };
383 }
384
385 sub _process_request {
386 my $self = shift;
387
388 # Create a callback closure that is invoked for each incoming request;
389 # the $self above is bound into the closure.
390 sub {
391
392 $self->stdio_handle(*STDIN) unless $self->stdio_handle;
393
394 # Default to unencoded, raw data out.
395 # if you're sending utf8 and latin1 data mixed, you may need to override this
396 binmode STDIN, ':raw';
397 binmode STDOUT, ':raw';
398
399 # The ternary operator below is to protect against a crash caused by IE
400 # Ported from Catalyst::Engine::HTTP (Originally by Jasper Krogh and Peter Edwards)
401 # ( http://dev.catalyst.perl.org/changeset/5195, 5221 )
402
403 my $remote_sockaddr = getpeername( $self->stdio_handle );
404 my ( undef, $iaddr ) = $remote_sockaddr ? sockaddr_in($remote_sockaddr) : (undef,undef);
405 my $peeraddr = $iaddr ? ( inet_ntoa($iaddr) || "127.0.0.1" ) : '127.0.0.1';
406
407 my ( $method, $request_uri, $proto ) = $self->parse_request;
408
409 unless ($self->valid_http_method($method) ) {
410 $self->bad_request;
411 return;
412 }
413
414 $proto ||= "HTTP/0.9";
415
416 my ( $file, $query_string )
417 = ( $request_uri =~ /([^?]*)(?:\?(.*))?/ ); # split at ?
418
419 $self->setup(
420 method => $method,
421 protocol => $proto,
422 query_string => ( defined($query_string) ? $query_string : '' ),
423 request_uri => $request_uri,
424 path => $file,
425 localname => $self->host,
426 localport => $self->port,
427 peername => $peeraddr,
428 peeraddr => $peeraddr,
429 );
430
431 # HTTP/0.9 didn't have any headers (I think)
432 if ( $proto =~ m{HTTP/(\d(\.\d)?)$} and $1 >= 1 ) {
433
434 my $headers = $self->parse_headers
435 or do { $self->bad_request; return };
436
437 $self->headers($headers);
438
439 }
440
441 $self->post_setup_hook if $self->can("post_setup_hook");
442
443 $self->handler;
444 }
445 }
446
447
448
449
450
451 =head2 stdio_handle [FILEHANDLE]
452
453 When called with an argument, sets the socket to the server to that arg.
454
455 Returns the socket to the server; you should only use this for actual socket-related
456 calls like C<getsockname>. If all you want is to read or write to the socket,
457 you should use C<stdin_handle> and C<stdout_handle> to get the in and out filehandles
458 explicitly.
459
460 =cut
461
462 sub stdio_handle {
463 my $self = shift;
464 $self->{'_stdio_handle'} = shift if (@_);
465 return $self->{'_stdio_handle'};
466 }
467
468 =head2 stdin_handle
469
470 Returns a filehandle used for input from the client. By default,
471 returns whatever was set with C<stdio_handle>, but a subclass
472 could do something interesting here (see L<HTTP::Server::Simple::Logger>).
473
474 =cut
475
476 sub stdin_handle {
477 my $self = shift;
478 return $self->stdio_handle;
479 }
480
481 =head2 stdout_handle
482
483 Returns a filehandle used for output to the client. By default,
484 returns whatever was set with C<stdio_handle>, but a subclass
485 could do something interesting here (see L<HTTP::Server::Simple::Logger>).
486
487 =cut
488
489 sub stdout_handle {
490 my $self = shift;
491 return $self->stdio_handle;
492 }
493
494 =head1 IMPORTANT SUB-CLASS METHODS
495
496 A selection of these methods should be provided by sub-classes of this
497 module.
498
499 =head2 handler
500
501 This method is called after setup, with no parameters. It should
502 print a valid, I<full> HTTP response to the default selected
503 filehandle.
504
505 =cut
506
507 sub handler {
508 my ($self) = @_;
509 if ( ref($self) ne __PACKAGE__ ) {
510 croak "do not call " . ref($self) . "::SUPER->handler";
511 }
512 else {
513 die "handler called out of context";
514 }
515 }
516
517 =head2 setup(name =E<gt> $value, ...)
518
519 This method is called with a name =E<gt> value list of various things
520 to do with the request. This list is given below.
521
522 The default setup handler simply tries to call methods with the names
523 of keys of this list.
524
525 ITEM/METHOD Set to Example
526 ----------- ------------------ ------------------------
527 method Request Method "GET", "POST", "HEAD"
528 protocol HTTP version "HTTP/1.1"
529 request_uri Complete Request URI "/foobar/baz?foo=bar"
530 path Path part of URI "/foobar/baz"
531 query_string Query String undef, "foo=bar"
532 port Received Port 80, 8080
533 peername Remote name "200.2.4.5", "foo.com"
534 peeraddr Remote address "200.2.4.5", "::1"
535 localname Local interface "localhost", "myhost.com"
536
537 =cut
538
539 sub setup {
540 my $self = shift;
541 while ( my ( $item, $value ) = splice @_, 0, 2 ) {
542 $self->$item($value) if $self->can($item);
543 }
544 }
545
546 =head2 headers([Header =E<gt> $value, ...])
547
548 Receives HTTP headers and does something useful with them. This is
549 called by the default C<setup()> method.
550
551 You have lots of options when it comes to how you receive headers.
552
553 You can, if you really want, define C<parse_headers()> and parse them
554 raw yourself.
555
556 Secondly, you can intercept them very slightly cooked via the
557 C<setup()> method, above.
558
559 Thirdly, you can leave the C<setup()> header as-is (or calling the
560 superclass C<setup()> for unknown request items). Then you can define
561 C<headers()> in your sub-class and receive them all at once.
562
563 Finally, you can define handlers to receive individual HTTP headers.
564 This can be useful for very simple SOAP servers (to name a
565 crack-fueled standard that defines its own special HTTP headers).
566
567 To do so, you'll want to define the C<header()> method in your subclass.
568 That method will be handed a (key,value) pair of the header name and the value.
569
570
571 =cut
572
573 sub headers {
574 my $self = shift;
575 my $headers = shift;
576
577 my $can_header = $self->can("header");
578 while ( my ( $header, $value ) = splice @$headers, 0, 2 ) {
579 if ($can_header) {
580 $self->header( $header => $value );
581 }
582 }
583 }
584
585 =head2 accept_hook
586
587 If defined by a sub-class, this method is called directly after an
588 accept happens.
589
590 =head2 post_setup_hook
591
592 If defined by a sub-class, this method is called after all setup has
593 finished, before the handler method.
594
595 =head2 print_banner
596
597 This routine prints a banner before the server request-handling loop
598 starts.
599
600 Methods below this point are probably not terribly useful to define
601 yourself in subclasses.
602
603 =cut
604
605 sub print_banner {
606 my $self = shift;
607
608 print( __PACKAGE__
609 . ": You can connect to your server at "
610 . "http://localhost:"
611 . $self->port
612 . "/\n" );
613
614 }
615
616 =head2 parse_request
617
618 Parse the HTTP request line.
619
620 Returns three values, the request method, request URI and the protocol
621 Sub-classed versions of this should return three values - request
622 method, request URI and proto
623
624 =cut
625
626 sub parse_request {
627 my $self = shift;
628 my $chunk;
629 while ( sysread( STDIN, my $buff, 1 ) ) {
630 last if $buff eq "\n";
631 $chunk .= $buff;
632 }
633 defined($chunk) or return undef;
634 $_ = $chunk;
635
636 m/^(\w+)\s+(\S+)(?:\s+(\S+))?\r?$/;
637 my $method = $1 || '';
638 my $uri = $2 || '';
639 my $protocol = $3 || '';
640
641 return ( $method, uri_unescape( $uri ), $protocol );
642 }
643
644 =head2 parse_headers
645
646 Parse incoming HTTP headers from STDIN.
647
648 Remember, this is a B<simple> HTTP server, so nothing intelligent is
649 done with them C<:-)>.
650
651 This should return an ARRAY ref of C<(header =E<gt> value)> pairs
652 inside the array.
653
654 =cut
655
656 sub parse_headers {
657 my $self = shift;
658
659 my @headers;
660
661 my $chunk = '';
662 while ( sysread( STDIN, my $buff, 1 ) ) {
663 if ( $buff eq "\n" ) {
664 $chunk =~ s/[\r\l\n\s]+$//;
665 if ( $chunk =~ /^([\w\-]+): (.+)/i ) {
666 push @headers, $1 => $2;
667 }
668 last if ( $chunk =~ /^$/ );
669 $chunk = '';
670 }
671 else { $chunk .= $buff }
672 }
673
674 return ( \@headers );
675 }
676
677 =head2 setup_listener
678
679 This routine binds the server to a port and interface.
680
681 =cut
682
683 sub setup_listener {
684 my $self = shift;
685
686 my $tcp = getprotobyname('tcp');
687
688 socket( HTTPDaemon, PF_INET, SOCK_STREAM, $tcp ) or die "socket: $!";
689 setsockopt( HTTPDaemon, SOL_SOCKET, SO_REUSEADDR, pack( "l", 1 ) )
690 or warn "setsockopt: $!";
691 bind( HTTPDaemon,
692 sockaddr_in(
693 $self->port(),
694 ( $self->host
695 ? inet_aton( $self->host )
696 : INADDR_ANY
697 )
698 )
699 )
700 or die "bind: $!";
701 listen( HTTPDaemon, SOMAXCONN ) or die "listen: $!";
702
703 }
704
705
706 =head2 after_setup_listener
707
708 This method is called immediately after setup_listener. It's here just for you to override.
709
710 =cut
711
712 sub after_setup_listener {
713 }
714
715 =head2 bad_request
716
717 This method should print a valid HTTP response that says that the
718 request was invalid.
719
720 =cut
721
722 $bad_request_doc = join "", <DATA>;
723
724 sub bad_request {
725 my $self = shift;
726
727 print "HTTP/1.0 400 Bad request\r\n"; # probably OK by now
728 print "Content-Type: text/html\r\nContent-Length: ",
729 length($bad_request_doc), "\r\n\r\n", $bad_request_doc;
730 }
731
732 =head2 valid_http_method($method)
733
734 Given a candidate HTTP method in $method, determine if it is valid.
735 Override if, for example, you'd like to do some WebDAV.
736
737 =cut
738
739 sub valid_http_method {
740 my $self = shift;
741 my $method = shift or return 0;
742 return $method =~ /^(?:GET|POST|HEAD|PUT|DELETE)$/;
743 }
744
745 =head1 AUTHOR
746
747 Copyright (c) 2004-2006 Jesse Vincent, <[email protected]>.
748 All rights reserved.
749
750 Marcus Ramberg <[email protected]> contributed tests, cleanup, etc
751
752 Sam Vilain, <[email protected]> contributed the CGI.pm split-out and
753 header/setup API.
754
755 =head1 BUGS
756
757 There certainly are some. Please report them via rt.cpan.org
758
759 =head1 LICENSE
760
761 This library is free software; you can redistribute it and/or modify
762 it under the same terms as Perl itself.
763
764 =cut
765
766 1;
767
768 __DATA__
769 <html>
770 <head>
771 <title>Bad Request</title>
772 </head>
773 <body>
774 <h1>Bad Request</h1>
775
776 <p>Your browser sent a request which this web server could not
777 grok.</p>
778 </body>
779 </html>
780
781 package HTTP::Server::Simple::CGI;
782
783 use base qw(HTTP::Server::Simple HTTP::Server::Simple::CGI::Environment);
784 use strict;
785 use warnings;
786
787 use CGI ();
788
789 use vars qw($VERSION $default_doc);
790 $VERSION = $HTTP::Server::Simple::VERSION;
791
792 =head1 NAME
793
794 HTTP::Server::Simple::CGI - CGI.pm-style version of HTTP::Server::Simple
795
796 =head1 DESCRIPTION
797
798 HTTP::Server::Simple was already simple, but some smart-ass pointed
799 out that there is no CGI in HTTP, and so this module was born to
800 isolate the CGI.pm-related parts of this handler.
801
802
803 =head2 accept_hook
804
805 The accept_hook in this sub-class clears the environment to the
806 start-up state.
807
808 =cut
809
810 sub accept_hook {
811 my $self = shift;
812 $self->setup_environment(@_);
813 }
814
815 =head2 post_setup_hook
816
817
818
819 =cut
820
821 sub post_setup_hook {
822 my $self = shift;
823 $self->setup_server_url;
824 CGI::initialize_globals();
825 }
826
827 =head2 setup
828
829 This method sets up CGI environment variables based on various
830 meta-headers, like the protocol, remote host name, request path, etc.
831
832 See the docs in L<HTTP::Server::Simple> for more detail.
833
834 =cut
835
836 sub setup {
837 my $self = shift;
838 $self->setup_environment_from_metadata(@_);
839 }
840
841 =head2 handle_request CGI
842
843 This routine is called whenever your server gets a request it can
844 handle.
845
846 It's called with a CGI object that's been pre-initialized.
847 You want to override this method in your subclass
848
849
850 =cut
851
852 $default_doc = ( join "", <DATA> );
853
854 sub handle_request {
855 my ( $self, $cgi ) = @_;
856
857 print "HTTP/1.0 200 OK\r\n"; # probably OK by now
858 print "Content-Type: text/html\r\nContent-Length: ", length($default_doc),
859 "\r\n\r\n", $default_doc;
860 }
861
862 =head2 handler
863
864 Handler implemented as part of HTTP::Server::Simple API
865
866 =cut
867
868 sub handler {
869 my $self = shift;
870 my $cgi = new CGI();
871 eval { $self->handle_request($cgi) };
872 if ($@) {
873 my $error = $@;
874 warn $error;
875 }
876 }
877
878 1;
879
880 __DATA__
881 <html>
882 <head>
883 <title>Hello!</title>
884 </head>
885 <body>
886 <h1>Congratulations!</h1>
887
888 <p>You now have a functional HTTP::Server::Simple::CGI running.
889 </p>
890
891 <p><i>(If you're seeing this page, it means you haven't subclassed
892 HTTP::Server::Simple::CGI, which you'll need to do to make it
893 useful.)</i>
894 </p>
895 </body>
896 </html>
897
898 package HTTP::Server::Simple::CGI::Environment;
899
900 use strict;
901 use warnings;
902 use HTTP::Server::Simple;
903
904 use vars qw($VERSION %ENV_MAPPING);
905 $VERSION = $HTTP::Server::Simple::VERSION;
906
907 my %clean_env = %ENV;
908
909 =head1 NAME
910
911 HTTP::Server::Simple::CGI::Environment - a HTTP::Server::Simple mixin to provide the CGI protocol
912
913 =head1 DESCRIPTION
914
915 This mixin abstracts the CGI protocol out from HTTP::Server::Simple::CGI so that
916 it's easier to provide your own CGI handlers with HTTP::Server::Simple which
917 B<don't> use CGI.pm
918
919 =head2 setup_environment
920
921 C<setup_environemnt> is usually called in the superclass's accept_hook
922
923 This routine in this sub-class clears the environment to the
924 start-up state.
925
926 =cut
927
928 sub setup_environment {
929 %ENV = (
930 %clean_env,
931 SERVER_SOFTWARE => "HTTP::Server::Simple/$VERSION",
932 GATEWAY_INTERFACE => 'CGI/1.1'
933 );
934 }
935
936 =head2 setup_server_url
937
938 Sets up the SERVER_URL environment variable
939
940 =cut
941
942 sub setup_server_url {
943 $ENV{SERVER_URL}
944 ||= ( "http://" . ($ENV{SERVER_NAME} || 'localhost') . ":" . ( $ENV{SERVER_PORT}||80) . "/" );
945 }
946
947 =head2 setup_environment_from_metadata
948
949 This method sets up CGI environment variables based on various
950 meta-headers, like the protocol, remote host name, request path, etc.
951
952 See the docs in L<HTTP::Server::Simple> for more detail.
953
954 =cut
955
956 %ENV_MAPPING = (
957 protocol => "SERVER_PROTOCOL",
958 localport => "SERVER_PORT",
959 localname => "SERVER_NAME",
960 path => "PATH_INFO",
961 request_uri => "REQUEST_URI",
962 method => "REQUEST_METHOD",
963 peeraddr => "REMOTE_ADDR",
964 peername => "REMOTE_HOST",
965 query_string => "QUERY_STRING",
966 );
967
968 sub setup_environment_from_metadata {
969 no warnings 'uninitialized';
970 my $self = shift;
971
972 # XXX TODO: rather than clone functionality from the base class,
973 # we should call super
974 #
975 while ( my ( $item, $value ) = splice @_, 0, 2 ) {
976 if ( my $k = $ENV_MAPPING{$item} ) {
977 $ENV{$k} = $value;
978 }
979 }
980
981 }
982
983 =head2 header
984
985 C<header> turns a single HTTP headers into CGI environment variables.
986
987 =cut
988
989 sub header {
990 my $self = shift;
991 my $tag = shift;
992 my $value = shift;
993
994 $tag = uc($tag);
995 $tag =~ s/^COOKIES$/COOKIE/;
996 $tag =~ s/-/_/g;
997 $tag = "HTTP_" . $tag
998 unless $tag =~ m/^(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)$/;
999
1000 if ( exists $ENV{$tag} ) {
1001 $ENV{$tag} .= "; $value";
1002 }
1003 else {
1004 $ENV{$tag} = $value;
1005 }
1006 }
1007
1008 1;
1009
1010 #
1011 # $Id: server,v 1.2 2007/01/18 04:57:14 matthew Exp $
1012 #
1013
1014 package URI::Escape;
1015 use strict;
1016
1017 =head1 NAME
1018
1019 URI::Escape - Escape and unescape unsafe characters
1020
1021 =head1 SYNOPSIS
1022
1023 use URI::Escape;
1024 $safe = uri_escape("10% is enough\n");
1025 $verysafe = uri_escape("foo", "\0-\377");
1026 $str = uri_unescape($safe);
1027
1028 =head1 DESCRIPTION
1029
1030 This module provides functions to escape and unescape URI strings as
1031 defined by RFC 2396 (and updated by RFC 2732).
1032 A URI consists of a restricted set of characters,
1033 denoted as C<uric> in RFC 2396. The restricted set of characters
1034 consists of digits, letters, and a few graphic symbols chosen from
1035 those common to most of the character encodings and input facilities
1036 available to Internet users:
1037
1038 "A" .. "Z", "a" .. "z", "0" .. "9",
1039 ";", "/", "?", ":", "@", "&", "=", "+", "$", ",", "[", "]", # reserved
1040 "-", "_", ".", "!", "~", "*", "'", "(", ")"
1041
1042 In addition, any byte (octet) can be represented in a URI by an escape
1043 sequence: a triplet consisting of the character "%" followed by two
1044 hexadecimal digits. A byte can also be represented directly by a
1045 character, using the US-ASCII character for that octet (iff the
1046 character is part of C<uric>).
1047
1048 Some of the C<uric> characters are I<reserved> for use as delimiters
1049 or as part of certain URI components. These must be escaped if they are
1050 to be treated as ordinary data. Read RFC 2396 for further details.
1051
1052 The functions provided (and exported by default) from this module are:
1053
1054 =over 4
1055
1056 =item uri_escape( $string )
1057
1058 =item uri_escape( $string, $unsafe )
1059
1060 Replaces each unsafe character in the $string with the corresponding
1061 escape sequence and returns the result. The $string argument should
1062 be a string of bytes. The uri_escape() function will croak if given a
1063 characters with code above 255. Use uri_escape_utf8() if you know you
1064 have such chars or/and want chars in the 128 .. 255 range treated as
1065 UTF-8.
1066
1067 The uri_escape() function takes an optional second argument that
1068 overrides the set of characters that are to be escaped. The set is
1069 specified as a string that can be used in a regular expression
1070 character class (between [ ]). E.g.:
1071
1072 "\x00-\x1f\x7f-\xff" # all control and hi-bit characters
1073 "a-z" # all lower case characters
1074 "^A-Za-z" # everything not a letter
1075
1076 The default set of characters to be escaped is all those which are
1077 I<not> part of the C<uric> character class shown above as well as the
1078 reserved characters. I.e. the default is:
1079
1080 "^A-Za-z0-9\-_.!~*'()"
1081
1082 =item uri_escape_utf8( $string )
1083
1084 =item uri_escape_utf8( $string, $unsafe )
1085
1086 Works like uri_escape(), but will encode chars as UTF-8 before
1087 escaping them. This makes this function able do deal with characters
1088 with code above 255 in $string. Note that chars in the 128 .. 255
1089 range will be escaped differently by this function compared to what
1090 uri_escape() would. For chars in the 0 .. 127 range there is no
1091 difference.
1092
1093 The call:
1094
1095 $uri = uri_escape_utf8($string);
1096
1097 will be the same as:
1098
1099 use Encode qw(encode);
1100 $uri = uri_escape(encode("UTF-8", $string));
1101
1102 but will even work for perl-5.6 for chars in the 128 .. 255 range.
1103
1104 Note: Javascript has a function called escape() that produce the
1105 sequence "%uXXXX" for chars in the 256 .. 65535 range. This function
1106 has really nothing to do with URI escaping but some folks got confused
1107 since it "does the right thing" in the 0 .. 255 range. Because of
1108 this you sometimes see "URIs" with these kind of escapes. The
1109 JavaScript encodeURI() function is similar to uri_escape_utf8().
1110
1111 =item uri_unescape($string,...)
1112
1113 Returns a string with each %XX sequence replaced with the actual byte
1114 (octet).
1115
1116 This does the same as:
1117
1118 $string =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
1119
1120 but does not modify the string in-place as this RE would. Using the
1121 uri_unescape() function instead of the RE might make the code look
1122 cleaner and is a few characters less to type.
1123
1124 In a simple benchmark test I did,
1125 calling the function (instead of the inline RE above) if a few chars
1126 were unescaped was something like 40% slower, and something like 700% slower if none were. If
1127 you are going to unescape a lot of times it might be a good idea to
1128 inline the RE.
1129
1130 If the uri_unescape() function is passed multiple strings, then each
1131 one is returned unescaped.
1132
1133 =back
1134
1135 The module can also export the C<%escapes> hash, which contains the
1136 mapping from all 256 bytes to the corresponding escape codes. Lookup
1137 in this hash is faster than evaluating C<sprintf("%%%02X", ord($byte))>
1138 each time.
1139
1140 =head1 SEE ALSO
1141
1142 L<URI>
1143
1144
1145 =head1 COPYRIGHT
1146
1147 Copyright 1995-2004 Gisle Aas.
1148
1149 This program is free software; you can redistribute it and/or modify
1150 it under the same terms as Perl itself.
1151
1152 =cut
1153
1154 use vars qw(@ISA @EXPORT @EXPORT_OK $VERSION);
1155 use vars qw(%escapes);
1156
1157 require Exporter;
1158 @ISA = qw(Exporter);
1159 @EXPORT = qw(uri_escape uri_unescape);
1160 @EXPORT_OK = qw(%escapes uri_escape_utf8);
1161 $VERSION = sprintf("%d.%02d", q$Revision: 1.2 $ =~ /(\d+)\.(\d+)/);
1162
1163 use Carp ();
1164
1165 # Build a char->hex map
1166 for (0..255) {
1167 $escapes{chr($_)} = sprintf("%%%02X", $_);
1168 }
1169
1170 my %subst; # compiled patternes
1171
1172 sub uri_escape
1173 {
1174 my($text, $patn) = @_;
1175 return undef unless defined $text;
1176 if (defined $patn){
1177 unless (exists $subst{$patn}) {
1178 # Because we can't compile the regex we fake it with a cached sub
1179 (my $tmp = $patn) =~ s,/,\\/,g;
1180 eval "\$subst{\$patn} = sub {\$_[0] =~ s/([$tmp])/\$escapes{\$1} || _fail_hi(\$1)/ge; }";
1181 Carp::croak("uri_escape: $@") if $@;
1182 }
1183 &{$subst{$patn}}($text);
1184 } else {
1185 # Default unsafe characters. RFC 2732 ^(uric - reserved)
1186 $text =~ s/([^A-Za-z0-9\-_.!~*'()])/$escapes{$1} || _fail_hi($1)/ge;
1187 }
1188 $text;
1189 }
1190
1191 sub _fail_hi {
1192 my $chr = shift;
1193 Carp::croak(sprintf "Can't escape \\x{%04X}, try uri_escape_utf8() instead", ord($chr));
1194 }
1195
1196 sub uri_escape_utf8
1197 {
1198 my $text = shift;
1199 if ($] < 5.008) {
1200 $text =~ s/([^\0-\x7F])/do {my $o = ord($1); sprintf("%c%c", 0xc0 | ($o >> 6), 0x80 | ($o & 0x3f)) }/ge;
1201 }
1202 else {
1203 utf8::encode($text);
1204 }
1205
1206 return uri_escape($text, @_);
1207 }
1208
1209 sub uri_unescape
1210 {
1211 # Note from RFC1630: "Sequences which start with a percent sign
1212 # but are not followed by two hexadecimal characters are reserved
1213 # for future extension"
1214 my $str = shift;
1215 if (@_ && wantarray) {
1216 # not executed for the common case of a single argument
1217 my @str = ($str, @_); # need to copy
1218 foreach (@str) {
1219 s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
1220 }
1221 return @str;
1222 }
1223 $str =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg if defined $str;
1224 $str;
1225 }
1226
1227 1;