blib/lib/EmbedIT/WebIT.pm

filter: Statementstmt 100% 30 / 30 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 10 / 10 Podpod n/a totaltotal 100% 40 / 40 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 package EmbedIT::WebIT;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use POSIX;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use HTTP::Date qw(time2str time2iso);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use IO::Socket;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use IO::Select;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use LWP::MediaTypes qw(guess_media_type read_media_types);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use IPC::Open3;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 2 ▶use Taint::Runtime qw(disable);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶no strict "refs";
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 our $VERSION = '1.6.3';
14 our $CRLF = "\015\012";
15  
16 2 ▶use vars qw(@childs $data);
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 # --------------------------------------------------------------------------------------
19 # Public functions
20 # --------------------------------------------------------------------------------------
21  
22 # --------------------------------------------------------------------------------------
23 # Create a new web server object
24 #
25  
26 sub new {
27 my ($class, %conf) = @_;
28  
29 if (not defined %conf) {
30 %conf = ();
31 }
32  
33 EmbedIT::WebIT::__fix_conf(\%conf);
34 EmbedIT::WebIT::__clean_env(\%conf);
35 EmbedIT::WebIT::__report(\%conf);
36  
37 my $start_time = time();
38 my $has_cgi_pm = undef;
39  
40 my $logging = $conf{"LOG_METHOD"};
41  
42 read_media_types($conf{"MIME_TYPES"});
43 Taint::Runtime::taint_stop;
44  
45 #open STDIN, '</dev/null';
46 #open STDOUT, '>>/dev/null';
47 #open STDERR, '>>/dev/null';
48
49 my @childs = ();
50 $SIG{CHLD} = 'IGNORE';
51 $SIG{SIGPIPE} = 'IGNORE';
52 $SIG{TERM} = \&__stop_server;
53 my $Server = undef;
54  
55 if (defined $conf{"USE_SSL"}) {
56 $Server = EmbedIT::WebIT::__start_server_ssl(\%conf);
57 } else {
58 $Server = EmbedIT::WebIT::__start_server_socket(\%conf);
59 }
60  
61 if (not defined $Server) {
62 &$logging("Unable to open socket");
63 return;
64 }
65  
66 if (defined $conf{"RUN_AS_USER"}) {
67 my $UID = EmbedIT::WebIT::__get_uid($conf{"RUN_AS_USER"});
68 $> = $UID;
69 }
70 if (defined $conf{"RUN_AS_GROUP"}) {
71 my $GID = EmbedIT::WebIT::__get_gid($conf{"RUN_AS_GROUP"});
72 $) = "$GID $GID";
73 $( = $GID;
74 }
75  
76 my $self = {
77 SERVER => $Server,
78 START_TIME => $start_time,
79 HAS_CGI_PM => $has_cgi_pm,
80 CONF => \%conf,
81 };
82  
83 bless $self;
84 return $self;
85 }
86  
87 # --------------------------------------------------------------------------------------
88 # Execute the server
89 #
90  
91 sub execute {
92 my ($self) = @_;
93  
94 my $logging = $self->{CONF}->{"LOG_METHOD"};
95  
96 if (defined $self->{SERVER}) {
97 $0 = $self->{CONF}->{"PROC_PREFIX"} . " starting ";
98 $self->__fork_workers();
99 if ($self->{CONF}->{"SERVERS"} == 0) {
100 $0 = $self->{CONF}->{"PROC_PREFIX"} . " server (" . $self->{CONF}->{"SERVER_IP"} . ":" . $self->{CONF}->{"SERVER_PORT"} . ")";
101 $self->__single_server(0, 1);
102 } else {
103 $self->__fork_servers();
104 $0 = $self->{CONF}->{"PROC_PREFIX"} . " master (" . $self->{CONF}->{"SERVER_IP"} . ":" . $self->{CONF}->{"SERVER_PORT"} . ")";
105 waitpid(-1,0);
106 }
107 &$logging("Shuting down");
108 } else {
109 &$logging("Failed to start");
110 }
111 }
112  
113 # --------------------------------------------------------------------------------------
114 # Get the process specific data
115 #
116  
117 sub data {
118 my ($self) = @_;
119 return $data;
120 }
121  
122 # --------------------------------------------------------------------------------------
123 # Get the process startup time
124 #
125  
126 sub start_time {
127 my ($self) = @_;
128 return $self->{START_TIME};
129 }
130  
131 # --------------------------------------------------------------------------------------
132 # Private functions
133 # --------------------------------------------------------------------------------------
134  
135 # --------------------------------------------------------------------------------------
136 # Stop the running web server
137 #
138  
139 sub __stop_server {
140 my ($self) = @_;
141 $self->{SERVER}->close();
142 kill "TERM", @childs;
143 }
144  
145 # --------------------------------------------------------------------------------------
146 # Fork off the servers
147 #
148  
149 sub __fork_servers {
150 my ($self) = @_;
151 my $conf = $self->{CONF};
152 for (my $i = 0; $i < $conf->{"SERVERS"}; $i++) {
153 my $pid = fork();
154 if ($pid == 0) {
155 $self->__single_server($i);
156 } else {
157 push @childs, $pid;
158 }
159 }
160 }
161  
162 # --------------------------------------------------------------------------------------
163 # Fork off the page workers
164 #
165  
166 sub __fork_workers {
167 my ($self) = @_;
168 my $conf = $self->{CONF};
169 if ($conf->{"FORK_CONN"}) { return; }
170 for (my $i = 0; $i < $conf->{"WORKERS"}; $i++) {
171 my $pid = fork();
172 if ($pid == 0) {
173 $self->__single_worker($i);
174 } else {
175 push @childs, $pid;
176 }
177 }
178 }
179  
180 # --------------------------------------------------------------------------------------
181 # Start single server
182 #
183  
184 sub __single_server {
185 my ($self, $i, $avoid) = @_;
186 my $conf = $self->{CONF};
187 if ($conf->{"FORK_CONN"} == 0) {
188 $self->__pre_fork("S$i");
189 }
190 if (not defined $avoid) {
191 $0 = $conf->{"PROC_PREFIX"} . " listener ($i)";
192 @childs = ();
193 }
194 if ($conf->{"FORK_CONN"} == 1) {
195 $SIG{TERM} = \&__stop_server;
196 $self->__fork_connections("S$i");
197 } else {
198 $self->__multiplex_connections("S$i");
199 }
200 if ($conf->{"FORK_CONN"} == 0) {
201 $self->__post_fork("S$i");
202 }
203 exit 0;
204 }
205  
206 # --------------------------------------------------------------------------------------
207 # Start single worker
208 #
209  
210 sub __single_worker {
211 my ($self, $i) = @_;
212 my $conf = $self->{CONF};
213 $self->__pre_fork("W$i");
214 $0 = $conf->{"PROC_PREFIX"} . " worker ($i)";
215 @childs = ();
216 $SIG{TERM} = 'DEFAULT';
217 select(undef,undef,undef,undef);
218 $self->__post_fork("W$i");
219 exit 0;
220 }
221  
222 # --------------------------------------------------------------------------------------
223 # Report configuration
224 #
225  
226 sub __report {
227 my ($conf) = @_;
228 my $logging = $conf->{"LOG_METHOD"};
229  
230 &$logging("Staring " . $conf->{"SOFTWARE"} . " web server on " .
231 $conf->{"SERVER_IP"} . ":" . $conf->{"SERVER_PORT"} .
232 " with " . $conf->{"QUEUE_SIZE"} . " connection queue limit");
233  
234 if ($conf->{"USE_SSL"}) {
235 &$logging("SSL will be used on all connections");
236 }
237  
238 if ($conf->{"SERVERS"} > 0) {
239 &$logging("PREFORKING " . $conf->{"SERVERS"} . " servers");
240 } else {
241 &$logging("SINGLE process server");
242 }
243  
244 if ($conf->{"FORK_CONN"}) {
245 &$logging("REQUESTS are forked");
246 } else {
247 &$logging("REQUESTS are multiplexed");
248 if ($conf->{"WORKERS"} > 0) {
249 &$logging("PREFORKING " . $conf->{"WORKERS"} . " page workers");
250 } else {
251 &$logging("WORKERS are embeded into SERVERS");
252 }
253 }
254  
255 if ($conf->{"WAIT_RESPONSE"}) {
256 &$logging("RESPONSE will be sent normaly");
257 if ($conf->{"IMMED_CLOSE"}) {
258 &$logging("CONNECTION will close immediatelly regardless of client request");
259 } else {
260 &$logging("CONNECTION will remain open per client request");
261 }
262 } else {
263 if (defined $conf->{"NO_WAIT_REPLY"}) {
264 &$logging("RESPONSE " . $conf->{"NO_WAIT_REPLY"} . " will be sent before page load");
265 } else {
266 &$logging("RESPONSE 204 will be sent before page load");
267 }
268 &$logging("CONNECTION will close immediatelly regardless of client request");
269 }
270  
271 if ($conf->{'LOG_PACKETS'}) {
272 &$logging("PACKET contents will be logged");
273 } elsif ($conf->{'LOG_HEADERS'}) {
274 &$logging("HEADERS will be logged");
275 }
276  
277 if (defined $conf->{"DOCUMENTS"}) {
278 if (defined $conf->{"DOCUMENT_ROOT"}) {
279 &$logging("EMBEDED pages with EXTERNAL pages on (" . $conf->{"DOCUMENT_ROOT"} . ")");
280 } else {
281 &$logging("EMBEDED pages");
282 }
283 } else {
284 &$logging("EXTERNAL pages on (" . $conf->{"DOCUMENT_ROOT"} . ")");
285 }
286  
287 if (defined $conf->{"CGI_PATH"}) {
288 if ($conf->{"EMBED_PERL"}) {
289 &$logging("CGI pages on (" . $conf->{"CGI_PATH_PRINT"} . ") with PERL embeded");
290 } else {
291 &$logging("CGI pages on (" . $conf->{"CGI_PATH_PRINT"} . ")");
292 }
293 }
294  
295 if (defined $conf->{"AUTH_PATH"}) {
296 if (not defined $conf->{"AUTH_METHOD"}) {
297 &$logging("AUTHENTICATION will always fail");
298 } else {
299 &$logging("AUTHENTICATION on (" . $conf->{"AUTH_PATH_PRINT"} . ")");
300 }
301 } else {
302 &$logging("AUTHENTICATION is not defined for any path");
303 }
304  
305 if (defined $conf->{"STARTUP"}) {
306 &$logging("STARTUP script can be found in (" . $conf->{"STARTUP"}. ")");
307 }
308  
309 }
310  
311 # --------------------------------------------------------------------------------------
312 # Start a single web server
313 #
314  
315 sub __start_server_socket {
316 my ($conf) = @_;
317 return new IO::Socket::INET( LocalAddr => $conf->{"SERVER_IP"},
318 LocalPort => $conf->{"SERVER_PORT"},
319 Proto => 'tcp',
320 Reuse => 1,
321 Listen => $conf->{"QUEUE_SIZE"}) || return undef;
322 }
323  
324 # --------------------------------------------------------------------------------------
325 # Start a single SSL web server
326 #
327  
328 sub __start_server_ssl {
329 my ($conf) = @_;
330 return new IO::Socket::INET( LocalAddr => $conf->{"SERVER_IP"},
331 LocalPort => $conf->{"SERVER_PORT"},
332 Proto => 'tcp',
333 Reuse => 1,
334 Listen => $conf->{"QUEUE_SIZE"}) || return undef;
335 }
336  
337 # --------------------------------------------------------------------------------------
338 # Start accepting connecitons
339 #
340  
341 sub __multiplex_connections {
342 my ($self, $id) = @_;
343 my $conf = $self->{CONF};
344 my $d = $self->{SERVER};
345  
346 $d->blocking(0);
347  
348 my %buffers = ();
349 my $logging = $conf->{"DEBLOG_METHOD"};
350 my $read_handles = new IO::Select();
351 my $write_handles = new IO::Select();
352 $read_handles->add($d);
353  
354 while (1) {
355 my @ret = IO::Select->select($read_handles, $write_handles, undef, undef);
356 if ((not defined @ret) || (@ret == 0)) { &$logging("[$id] has failed on select"); return; }
357 my ($rset, $wset, $eset) = @ret;
358  
359 my $r = scalar(@$rset);
360 my $w = scalar(@$wset);
361 my $e = scalar(@$eset);
362
363 foreach my $fh (@$rset) {
364 my $no = $fh->fileno;
365 if ($fh == $d) {
366 my $ns = $d->accept();
367 if (defined $ns) {
368 $ns->blocking(0);
369 $ns->autoflush(0);
370 $read_handles->add($ns);
371 $no = $ns->fileno;
372 $buffers{$no}{InBuffer} = '';
373 $buffers{$no}{OutBuffer} = '';
374 $buffers{$no}{AutoClose} = 0;
375 $buffers{$no}{CloseAfter} = 0;
376 $buffers{$no}{CLen} = -1;
377 $buffers{$no}{CPos} = 0;
378 $buffers{$no}{Socket} = $ns;
379 &$logging("[$id] NEW connection [$no] from " . $ns->peerhost . ":" . $ns->peerport);
380 }
381 } else {
382 if (!$self->__fill_buffer($id, $fh, \%{$buffers{$no}})) {
383 $read_handles->remove($fh);
384 $write_handles->remove($fh);
385 close($fh);
386 delete $buffers{$no};
387 &$logging("[$id] END connection (1) [$no]");
388 }
389  
390 if ($buffers{$no}{AutoClose}) {
391 $read_handles->remove($fh);
392 $write_handles->remove($fh);
393 delete $buffers{$no};
394 close($fh);
395 &$logging("[$id] END connection (2) [$no]");
396 } else {
397 if ($buffers{$no}{OutBuffer} ne '') {
398 $write_handles->add($fh);
399 $read_handles->remove($fh);
400 }
401 }
402 }
403 }
404  
405 foreach my $fh (@$wset) {
406  
407 my $no = $fh->fileno;
408 my $size = length($buffers{$no}{OutBuffer});
409  
410 if ($size == 0) {
411 $write_handles->remove($fh);
412 if ($buffers{$no}{CloseAfter}) {
413 $read_handles->remove($fh);
414 delete $buffers{$no};
415 close($fh);
416 &$logging("[$id] END connection (3) [$no]");
417 } else {
418 $read_handles->add($fh);
419 }
420 } else {
421 if (!$self->__socket_write($id, $fh, $size, \%{$buffers{$no}})) {
422 $read_handles->remove($fh);
423 $write_handles->remove($fh);
424 delete $buffers{$no};
425 close($fh);
426 &$logging("[$id] END connection (4) [$no]");
427 }
428 }
429  
430 }
431  
432 }
433  
434 }
435  
436 # --------------------------------------------------------------------------------------
437 # Start a single forking web server
438 #
439  
440 sub __fork_connections {
441 my ($self, $id) = @_;
442 my $conf = $self->{CONF};
443 my $d = $self->{SERVER};
444 my $logging = $conf->{"DEBLOG_METHOD"};
445 my $handles = new IO::Select();
446  
447 $d->blocking(0);
448 $handles->add($d);
449  
450 while (1) {
451 my @ret = IO::Select->select($handles, undef, undef, undef);
452 if (not defined @ret) { return; }
453 if (@ret == 0) { &$logging("[$id] has failed on select"); return; }
454 my ($rset, $wset, $eset) = @ret;
455  
456 my $c = $d->accept();
457 if (defined $c) {
458 $c->blocking(0);
459 $c->autoflush(0);
460 my $pid = fork();
461 if ($pid == 0) {
462 $self->__pre_fork("S$id");
463 $0 = $conf->{"PROC_PREFIX"} . " serving (" . $c->peerhost . ":" . $c->peerport . ")";
464 &$logging("NEW connection from " . $c->peerhost . ":" . $c->peerport);
465 $self->__forked_loop($id, $c);
466 $self->__post_fork("S$id");
467 exit 0;
468 } else {
469 push @childs, $pid;
470 my $ended = waitpid(-1,WNOHANG);
471 if ($ended > 0) {
472 for (my $i = 0; $i < @childs; $i++) {
473 if ($childs[$i] == $ended) {
474 splice(@childs,$i,1);
475 last;
476 }
477 }
478 }
479 }
480 }
481  
482 }
483 }
484  
485 # --------------------------------------------------------------------------------------
486 # Main loop of a forked child
487 #
488  
489 sub __forked_loop {
490 my ($self, $id, $c) = @_;
491 my $conf = $self->{CONF};
492 my $logging = $conf->{"DEBLOG_METHOD"};
493  
494 my %buffer = ();
495 $buffer{InBuffer} = '';
496 $buffer{OutBuffer} = '';
497 $buffer{AutoClose} = 0;
498 $buffer{CloseAfter} = 0;
499 $buffer{CLen} = -1;
500 $buffer{CPos} = 0;
501 $buffer{Socket} = $c;
502  
503 my $read_handles = new IO::Select();
504 my $write_handles = new IO::Select();
505 $read_handles->add($c);
506  
507 my $exit_loop = 0;
508  
509 while (1) {
510 if ($exit_loop) { last; }
511 my @ret = IO::Select->select($read_handles, $write_handles, undef, undef);
512 if ((not defined @ret) || (@ret == 0)) { &$logging("[$id] has failed on select"); return; }
513 my ($rset, $wset, $eset) = @ret;
514  
515 foreach my $fh (@$rset) {
516  
517 my $no = $fh->fileno;
518  
519 if (!$self->__fill_buffer($id, $fh, \%buffer)) {
520 $read_handles->remove($fh);
521 $write_handles->remove($fh);
522 close($fh);
523 &$logging("[$id] END connection [$no]");
524 $exit_loop = 1;
525 }
526  
527 if ($buffer{AutoClose}) {
528 $read_handles->remove($fh);
529 $write_handles->remove($fh);
530 close($fh);
531 &$logging("[$id] END connection [$no]");
532 $exit_loop = 1;
533 } else {
534 if ($buffer{OutBuffer} ne '') {
535 $write_handles->add($fh);
536 $read_handles->remove($fh);
537 }
538 }
539 }
540  
541 foreach my $fh (@$wset) {
542  
543 my $no = $fh->fileno;
544  
545 my $size = length($buffer{OutBuffer});
546  
547 if ($size == 0) {
548 $read_handles->add($fh);
549 $write_handles->remove($fh);
550 if ($buffer{CloseAfter}) {
551 $read_handles->remove($fh);
552 close($fh);
553 &$logging("[$id] END connection [$no]");
554 $exit_loop = 1;
555 }
556 } else {
557 if (!$self->__socket_write($id, $fh, $size, \%buffer)) {
558 $read_handles->remove($fh);
559 $write_handles->remove($fh);
560 close($fh);
561 &$logging("[$id] END connection [$no]");
562 $exit_loop = 1;
563 }
564 }
565  
566 }
567  
568 }
569  
570 }
571  
572 # --------------------------------------------------------------------------------------
573 # Try to fill out the buffer of the connection
574 #
575  
576 sub __fill_buffer {
577 my ($self, $id, $c, $buf) = @_;
578 my $conf = $self->{CONF};
579 my $res;
580
581 $res = $self->__socket_read($id, $c, $buf);
582 if ($res < 0) {
583 $buf->{InBuffer} = '';
584 $buf->{CLen} = -1;
585 $buf->{CPos} = 0;
586 return 0;
587 } elsif ($res == 1) {
588 my $r = $self->__parse_http_request($buf->{InBuffer});
589 $buf->{InBuffer} = '';
590 $buf->{CLen} = -1;
591 $buf->{CPos} = 0;
592 return $self->__handle_request($id, $c, $r, $buf);
593 } else {
594 return 1;
595 }
596 }
597  
598 # --------------------------------------------------------------------------------------
599 # Try to send out the buffer to the connection
600 #
601  
602 sub __socket_write {
603 my ($self, $id, $c, $size, $buf) = @_;
604 my $conf = $self->{CONF};
605
606 my $res;
607 eval {
608 #$res = $c->send($buf->{OutBuffer});
609 $res = syswrite($c, $buf->{OutBuffer}, length($buf->{OutBuffer}));
610 };
611 if ($@) {
612 my $logging = $conf->{'DEBLOG_METHOD'};
613 &$logging("[$id] " . $@);
614 return 0;
615 }
616  
617 if ($res) {
618 if ($res == 0) { return 0; }
619 $buf->{OutBuffer} = substr($buf->{OutBuffer}, $res);
620 return 1;
621 } else {
622 return 0;
623 }
624 }
625  
626 # --------------------------------------------------------------------------------------
627 # Read from socket and fill out the given buffer
628 #
629  
630 sub __socket_read {
631 my ($self, $id, $c, $buf) = @_;
632 my $conf = $self->{CONF};
633
634 my $tbuf = '';
635 my $read = 0;
636  
637 #$read = $c->read($tbuf, 8192);
638 $read = sysread($c, $tbuf, 8192);
639 if (not defined $read) {
640 my $errstr = $!;
641 my $errno = $! + 0;
642 if ($errno != 0) {
643 my $logging = $conf->{'DEBLOG_METHOD'};
644 &$logging("[$id] Socket read error was [$errno] ($errstr)");
645 }
646 return -1; # socket read got an error
647 }
648  
649 if ($read == 0) {
650 return -1; # socket closed
651 }
652  
653 $buf->{InBuffer} .= $tbuf;
654  
655 if ($buf->{CLen} < 0) {
656 my $pos;
657 if (($pos = index($buf->{InBuffer}, "$CRLF$CRLF")) > 0) { # we have full headers
658 if ($buf->{InBuffer} =~ /Content-Length:\s*(\d+)/io) {
659 $buf->{CLen} = $1;
660 } else {
661 $buf->{CLen} = 0;
662 }
663 $buf->{CPos} = $pos;
664 } else {
665 return 0; # not a complete packet yet
666 }
667 }
668  
669 if ($buf->{CLen} >= 0) {
670 my $expected = $buf->{CPos} + $buf->{CLen} + 4; # we have up to a point. Read the remaining
671 if (length($buf->{InBuffer}) < $expected) {
672 return 0;
673 }
674 } else {
675 return 0;
676 }
677  
678 return 1; # we have a complete packet
679 }
680  
681 # --------------------------------------------------------------------------------------
682 # Parse a request packet
683 #
684  
685 sub __parse_http_request {
686 my ($self, $packet) = @_;
687 my $conf = $self->{CONF};
688  
689 my $spacket = $packet;
690 my %request = ();
691  
692 my $head = '';
693  
694 $packet =~ s/^(.*)\n?//o;
695 my $line = $1;
696 $line =~ s/\r//gco;
697 $line =~ s/^\s*//go;
698 my ($meth, $uri, $ver) = split(/\s+/o, $line);
699  
700 $head .= $line . $CRLF;
701  
702 if ($uri =~ /(.*?)\?(.*)/o) {
703 $request{URI} = $1;
704 $request{QUERY_STRING} = $2;
705 } else {
706 $request{URI} = $uri;
707 $request{QUERY_STRING} = '';
708 }
709 $request{METHOD} = $meth;
710 $request{VERSION} = $ver;
711  
712 while (1) {
713 $packet =~ s/^(.*)\n?//o;
714 $line = $1;
715 $line =~ s/\r//gco;
716 $line =~ s/^\s*//go;
717 my ($k, $v) = ($line =~ /^\s*(.*?)\s*?\:\s*?(.*)/o);
718 if ($k ne '') {
719 $head .= $line . $CRLF;
720 $v =~ s/^\s*//go;
721 $v =~ s/\s*$//go;
722 $request{HEADERS}{uc($k)} = $v;
723 } else {
724 $head .= $CRLF;
725 last;
726 }
727 }
728  
729 my $logging = $conf->{"DEBLOG_METHOD"};
730  
731 if ($conf->{'LOG_PACKETS'}) {
732 &$logging($spacket);
733 } else {
734 if ($conf->{'LOG_HEADERS'}) {
735 &$logging($head);
736 }
737 }
738  
739 $request{CONTENT} = $packet;
740  
741 return \%request;
742 }
743  
744 # --------------------------------------------------------------------------------------
745 # Handle a request
746 #
747  
748 sub __handle_request {
749 my ($self, $id, $c, $r, $buf) = @_;
750 my $conf = $self->{CONF};
751  
752 if (not defined $r->{METHOD}) {
753 return 0;
754 } else {
755 if ($conf->{"WAIT_RESPONSE"} == 0) {
756 my $page = $self->__make_response($conf->{"NO_WAIT_REPLY"}, undef, undef, 0);
757 $c->blocking(1);
758 print $c, $page;
759 $buf->{AutoClose} = 1;
760 close($c);
761 $self->__get_page($id, $c->peerhost, $c->peerport, $r, 0);
762 } else {
763 my $page = $self->__get_page($id, $c->peerhost, $c->peerport, $r, 1);
764 $buf->{OutBuffer} .= $page;
765 if (($conf->{"IMMED_CLOSE"}) || ($r->{HEADERS}{'CONNECTION'} eq 'Close')) {
766 $buf->{CloseAfter} = 1;
767 }
768 }
769 }
770 return 1;
771 }
772  
773 # --------------------------------------------------------------------------------------
774 # Get the requested page
775 #
776  
777 sub __get_page {
778 my ($self, $id, $rhost, $rport, $r, $err) = @_;
779 my $conf = $self->{CONF};
780  
781 my $page = undef;
782  
783 my $logging = $conf->{"LOG_METHOD"};
784 my $logging2 = $conf->{"DEBLOG_METHOD"};
785 my $path = $r->{URI};
786 my $embed = undef;
787 my $script = undef;
788 my $inauth_space = 0;
789  
790 $path =~ s/\/\//\//gco;
791  
792 if ($path =~ /\/$/o) {
793 $path .= "index.html";
794 }
795  
796 if (exists $conf->{"DOCUMENTS"}{$path}) {
797 $embed = 1;
798 } else {
799 if (defined $conf->{"DOCUMENT_ROOT"}) {
800 my $fname = $conf->{"DOCUMENT_ROOT"} . $path;
801 $fname =~ s/\/\//\//gco;
802 if (! -e $fname) {
803 if (exists $conf->{"DOCUMENTS"}{'*'}) {
804 $embed = 1;
805 } else {
806 if ($path =~ /$conf->{"CGI_PATH"}/) {
807 if ($conf->{"SETUP_ENV"}) {
808 $script = 1;
809 $ENV{"SCRIPT_NAME"} = $path;
810 $ENV{"SCRIPT_FILENAME"} = $fname;
811 $ENV{"QUERY_STRING"} = "";
812 }
813 }
814 }
815 } else {
816 if ($path =~ /$conf->{"CGI_PATH"}/) {
817 if ($conf->{"SETUP_ENV"}) {
818 $script = 1;
819 $ENV{"SCRIPT_NAME"} = $path;
820 $ENV{"SCRIPT_FILENAME"} = $fname;
821 $ENV{"QUERY_STRING"} = "";
822 }
823 }
824 }
825 } else {
826 if (exists $conf->{"DOCUMENTS"}{'*'}) {
827 $embed = 1;
828 }
829 }
830 }
831  
832 # &$logging("[$id] Request was \n" . $r->as_string());
833  
834 $ENV{"REQUEST_URI"} = $path;
835  
836 my $pmeth = sprintf("%-4s", $r->{METHOD});
837  
838 my ($auth_ok, $page) = $self->__is_auth_ok($id, $rhost, $rport, $r, $path, $inauth_space, $err);
839 if ($auth_ok) {
840  
841 if ($conf->{"SETUP_ENV"}) {
842 $self->__fix_env($r);
843 }
844 $ENV{"REMOTE_PORT"} = $rport;
845 $ENV{"REMOTE_ADDR"} = $rhost;
846  
847 my $retval = undef;
848 my $reterr = undef;
849  
850 my $type = '';
851  
852 if ($r->{METHOD} =~ /GET|HEAD|POST/o) {
853 if ($script) {
854 if (($conf->{"EMBED_PERL"} == 1) && ($path =~ /\.pl$/o)) {
855 $type = 'PERL ';
856 ($retval, $reterr, $page) = $self->__do_perl($id, $path, $r, $inauth_space);
857 if (!$retval) {
858 &$logging2("[$id] Script error ($reterr) on (" . $r->{URI} . ")");
859 if ($err) {
860 $page = $self->__make_error($reterr, $inauth_space, $id, $rhost, $rport, $r);
861 }
862 }
863 } else {
864 $type = 'CGI ';
865 ($retval, $reterr, $page) = $self->__do_cgi($id, $path, $r, $inauth_space);
866 if (!$retval) {
867 &$logging2("[$id] Script error ($reterr) on (" . $r->{URI} . ")");
868 if ($err) {
869 $page = $self->__make_error($reterr, $inauth_space, $id, $rhost, $rport, $r);
870 }
871 }
872 }
873 } elsif ($embed) {
874 $type = 'EMBED';
875 ($retval, $reterr, $page) = $self->__do_embeded($id, $path, $r, $inauth_space);
876 if (!$retval) {
877 &$logging2("[$id] Embeded function error ($reterr) on ($path)");
878 if ($err) {
879 $page = $self->__make_error($reterr, $inauth_space, $id, $rhost, $rport, $r);
880 }
881 }
882 } else {
883 $type = 'FILE ';
884 ($retval, $reterr, $page) = $self->__do_file($path, $r, $inauth_space);
885 if (!$retval) {
886 &$logging2("[$id] FILE (" . $r->{URI} . ") not found");
887 if ($err) {
888 $page = $self->__make_error($reterr, $inauth_space, $id, $rhost, $rport, $r);
889 }
890 }
891 }
892 } else {
893 $type = 'FAIL ';
894 &$logging2("[$id] Method $pmeth for (" . $r->{URI} . ") is not implemented");
895 if ($err) {
896 $reterr = 405;
897 $page = $self->__make_error($reterr, $inauth_space, $id, $rhost, $rport, $r);
898 }
899 }
900  
901 &$logging("[$id] $pmeth [$type] from $rhost:$rport ($path) got ($reterr " . $conf->{'HTML_CODES'}{$reterr}. ")");
902  
903 } else {
904 &$logging("[$id] $pmeth from $rhost:$rport ($path) failed authentication");
905 }
906  
907 return $page;
908 }
909  
910 # --------------------------------------------------------------------------------------
911 # Get the authorization from the packet -- packet
912 #
913  
914 sub __get_authorization {
915 my ($self, $r, $log) = @_;
916  
917 my $h = $r->{HEADERS}->{'AUTHORIZATION'};
918  
919 if (defined $h) {
920 $h =~ s/^\s*Basic\s+//gco;
921 require MIME::Base64;
922 my $val = MIME::Base64::decode_base64($h);
923 return $val unless wantarray;
924 return split(/:/, $val, 2);
925 }
926 return;
927 }
928  
929 # --------------------------------------------------------------------------------------
930 # Check if we are in a path with authentication and authentication data exists
931 #
932  
933 sub __is_auth_ok {
934 my ($self, $id, $rhost, $rport, $r, $path, $inauth_space, $err) = @_;
935 my $conf = $self->{CONF};
936  
937 if (not defined $conf->{"AUTH_PATH"}) { return (1, undef); }
938  
939 my $auth_f = $conf->{"AUTH_METHOD"};
940 my $logging = $conf->{"DEBLOG_METHOD"};
941 my $logging2 = $conf->{"LOG_METHOD"};
942 my $page = undef;
943  
944 if ($path =~ /$conf->{"AUTH_PATH"}/) {
945 my $five = 5;
946 $_[$five] = 1;
947 my ($user, $pass) = $self->__get_authorization($r, $logging);
948 if (not defined $user) {
949 $page = $self->__make_response("401", undef, undef, 1);
950 &$logging("[$id] AUTH to $rhost:$rport ($path)");
951 return (0, $page);
952 } else {
953 if (not defined $auth_f) {
954 if ($conf->{"SETUP_ENV"}) {
955 $ENV{"REMOTE_USER"} = $user;
956 $ENV{"AUTH_TYPE"} = "Basic";
957 }
958 return (1, $page);
959 } elsif (&$auth_f($user, $pass)) {
960 if ($conf->{"SETUP_ENV"}) {
961 $ENV{"REMOTE_USER"} = $user;
962 $ENV{"AUTH_TYPE"} = "Basic";
963 }
964 return (1, $page);
965 } else {
966 if ($err) {
967 $page = $self->__make_error("403", 1, $id, $rhost, $rport, $r);
968 }
969 &$logging2("[$id] REJECT to $rhost:$rport for ($user) on ($path)");
970 return (0, $page);
971 }
972 }
973 }
974 return (1, $page);
975 }
976  
977 # --------------------------------------------------------------------------------------
978 # get the expiration time for a given media type
979 #
980  
981 sub __get_type_expiration {
982 my ($self, $type) = @_;
983 my $conf = $self->{CONF};
984  
985 my $exp = undef; # default is not defined
986  
987 if (exists $conf->{'EXPIRATIONS'}) {
988 if (exists $conf->{'EXPIRATIONS'}->{$type}) {
989 $exp = $conf->{'EXPIRATIONS'}->{$type};
990 } else {
991 if (exists $conf->{'EXPIRATIONS'}->{'ALL'}) {
992 $exp = $conf->{'EXPIRATIONS'}->{'ALL'};
993 }
994 }
995 }
996  
997 return $exp;
998 }
999  
1000 # --------------------------------------------------------------------------------------
1001 # send file
1002 #
1003  
1004 sub __do_file {
1005 my ($self, $p, $r, $auth) = @_;
1006 my $conf = $self->{CONF};
1007  
1008 my $res = "";
1009 my $page = undef;
1010  
1011 if ($conf->{"WAIT_RESPONSE"} == 0) {
1012 return (1, 200, $self->__make_response("200", undef, undef, undef));
1013 }
1014  
1015 if (not defined $conf->{"DOCUMENT_ROOT"}) {
1016 return (0, 404, $self->__make_response("404", undef, undef, undef));
1017 }
1018  
1019 $p = $conf->{"DOCUMENT_ROOT"} . $p;
1020  
1021 if (-e $p) {
1022 my %headers = ();
1023  
1024 if ($r->{METHOD} eq "HEAD") {
1025 return (1, 200, $self->__make_response("200", undef, undef, $auth));
1026 } else {
1027 my @s = stat($p);
1028 my $nine = 9;
1029 my $seven = 7;
1030 my $mdate = time2str($s[$nine]);
1031 my $size = $s[$seven];
1032  
1033 my ($type, $enc) = guess_media_type($p);
1034 my $expiration = $self->__get_type_expiration($type);
1035  
1036 if ($r->{HEADERS}{"IF-MODIFIED-SINCE"} eq $mdate) {
1037 $headers{'Date'} = time2str(time);
1038 $headers{'Last-Modified'} = $mdate;
1039 if ((defined $expiration) && ($expiration =~ /\d+/)) {
1040 $headers{'Cache-Control'} = "max-age=$expiration, must-revalidate";
1041 $headers{'Expires'} = time2str(time + $expiration);
1042 }
1043  
1044 return (1, 304, $self->__make_response("304", \%headers, undef, $auth));
1045 }
1046  
1047 # if ($r->{HEADERS}{"IF-UNMODIFIED-SINCE"} ne $mdate) {
1048 # return (1, 412, __make_response("412", undef, undef, $auth, $conf));
1049 # }
1050  
1051 $res = $self->__load_file($p);
1052 if (not defined $res) {
1053 return (0, 404, $self->__make_response("404", undef, undef, $auth));
1054 }
1055  
1056 if (length($res) > 0) {
1057 if ($enc ne '') {
1058 $headers{'Content-Encoding'} = $enc;
1059 }
1060  
1061 $headers{'Content-Type'} = $type;
1062 $headers{'Date'} = time2str(time);
1063 $headers{'Last-Modified'} = $mdate;
1064 if ((defined $expiration) && ($expiration =~ /\d+/)) {
1065 $headers{'Cache-Control'} = "max-age=$expiration, must-revalidate";
1066 $headers{'Expires'} = time2str(time + $expiration);
1067 }
1068  
1069 $res = $CRLF . $CRLF . $res;
1070  
1071 return (1, 200, $self->__make_response("200", \%headers, $res, $auth));
1072 }
1073 }
1074 }
1075  
1076 return (0, 404, $self->__make_response("404", undef, undef, $auth));
1077 }
1078  
1079 # --------------------------------------------------------------------------------------
1080 # Run an embeded function
1081 #
1082  
1083 sub __do_embeded {
1084 my ($self, $id, $s, $r, $auth) = @_;
1085 my $conf = $self->{CONF};
1086  
1087 my $logging = $conf->{"DEBLOG_METHOD"};
1088 my $p = $r->{CONTENT};
1089 my $page = undef;
1090 my $post = 0;
1091 my $sub = $conf->{"DOCUMENTS"}{$s};
1092  
1093 if (not defined $sub) {
1094 $sub = $conf->{"DOCUMENTS"}{'*'};
1095 }
1096
1097 if ((defined $sub) && (exists &$sub)) {
1098 $ENV{'REQUEST_METHOD'} = $r->{METHOD};
1099 if ($r->{METHOD} =~ /GET|HEAD/o) {
1100 $ENV{"QUERY_STRING"} = $r->{'QUERY_STRING'};
1101 } else {
1102 $post = 1;
1103 }
1104 if ($r->{METHOD} =~ /GET/o) {
1105 if ($r->{HEADERS}{"IF-MODIFIED-SINCE"} eq time2str($self->{START_TIME})) {
1106 my %headers = ();
1107 $headers{'Date'} = time2str($self->{START_TIME});
1108 $headers{'Last-Modified'} = time2str($self->{START_TIME});
1109  
1110 my $expiration = undef;
1111 if (exists $conf->{'EXPIRATIONS'}->{'ALL'}) {
1112 $expiration = $conf->{'EXPIRATIONS'}->{'ALL'};
1113 }
1114 if ((defined $expiration) && ($expiration =~ /\d+/)) {
1115 $headers{'Cache-Control'} = "max-age=$expiration, must-revalidate";
1116 $headers{'Expires'} = time2str($self->{START_TIME} + $expiration);
1117 }
1118  
1119 return (1, 304, $self->__make_response("304", \%headers, undef, $auth));
1120 }
1121 }
1122 if ($conf->{"SETUP_ENV"}) {
1123 if (exists $r->{HEADERS}{"CONTENT-TYPE"}) { $ENV{"CONTENT_TYPE"} = $r->{HEADERS}{"CONTENT-TYPE"}; }
1124 if (exists $r->{HEADERS}{"CONTENT-ENCODING"}) { $ENV{"CONTENT_ENCODING"} = $r->{HEADERS}{"CONTENT-ENCODING"}; }
1125 if (exists $r->{HEADERS}{"CONTENT-LENGTH"}) { $ENV{"CONTENT_LENGTH"} = $r->{HEADERS}{"CONTENT-LENGTH"}; }
1126 if (exists $r->{HEADERS}{"CONTENT-LANGUAGE"}) { $ENV{"CONTENT_LANGUAGE"} = $r->{HEADERS}{"CONTENT-LANGUAGE"}; }
1127 }
1128  
1129 my $res = '';
1130 my $errs = '';
1131 my $evalerrs = '';
1132  
1133 # save all STD files
1134 open OLDERR, ">&STDERR";
1135 open OLDOUT, ">&STDOUT";
1136 open OLDIN, "<&STDIN";
1137  
1138 # reopen STDIN to $p string if we have POST
1139 close STDIN;
1140 open STDIN, "<", \$p;
1141 binmode STDIN;
1142  
1143 # reopen STDOUT to $res string
1144 close STDOUT;
1145 open STDOUT, ">", \$res;
1146 binmode STDOUT;
1147  
1148 # reopen STDERR to $errs string
1149 close STDERR;
1150 open STDERR, ">", \$errs;
1151  
1152 if ($self->{HAS_CGI_PM}) {
1153 eval('CGI::initialize_globals();');
1154 } else {
1155 for my $k (keys %INC) {
1156 if ($k eq 'CGI.pm') {
1157 $self->{HAS_CGI_PM} = 1;
1158 eval('CGI::initialize_globals();');
1159 last;
1160 }
1161 }
1162 }
1163  
1164 eval {
1165 &$sub($data);
1166 };
1167
1168 $evalerrs = $@;
1169  
1170 # restore STD files
1171 close STDOUT;
1172 open STDOUT, ">&OLDOUT";
1173 close OLDOUT;
1174 close STDERR;
1175 open STDERR, ">&OLDERR";
1176 close OLDERR;
1177 close STDIN;
1178 open STDIN, "<&OLDIN";
1179 close OLDIN;
1180  
1181 if ($conf->{"SETUP_ENV"}) {
1182 delete $ENV{"QUERY_STRING"};
1183 delete $ENV{"CONTENT_TYPE"};
1184 delete $ENV{"CONTENT_ENCODING"};
1185 delete $ENV{"CONTENT_LENGTH"};
1186 delete $ENV{"CONTENT_LANGUAGE"};
1187 }
1188  
1189 $errs .= $evalerrs;
1190
1191 if (length($errs) > 0) {
1192 &$logging("[$id] ($s) \n$errs");
1193 }
1194  
1195 if ($conf->{"WAIT_RESPONSE"} == 0) { return (1, 200, $page); }
1196  
1197 if ($evalerrs ne '') {
1198 return (0, 500, $self->__make_response("500", undef, undef, $auth));
1199 } else {
1200 if ($r->{METHOD} eq "HEAD") {
1201 return (1, 200, $self->__make_response("200", undef, undef, $auth));
1202 } else {
1203 return (1, 200, $self->__make_response("200", undef, $res, $auth));
1204 }
1205 }
1206 } else {
1207 return (0, 404, $page);
1208 }
1209 }
1210  
1211 # --------------------------------------------------------------------------------------
1212 # Run a perl script
1213 #
1214  
1215 sub __do_perl {
1216 my ($self, $id, $s, $r, $auth) = @_;
1217 my $conf = $self->{CONF};
1218  
1219 my $logging = $conf->{"DEBLOG_METHOD"};
1220 my $p = $r->{'CONTENT'};
1221 my $page = undef;
1222 my $post = 0;
1223  
1224 $s = $conf->{"DOCUMENT_ROOT"} . $s;
1225  
1226 if (-e $s) {
1227 $ENV{'REQUEST_METHOD'} = $r->{METHOD};
1228 if ($r->{METHOD} =~ /GET|HEAD/o) {
1229 $ENV{"QUERY_STRING"} = $r->{'QUERY_STRING'};
1230 } else {
1231 $post = 1;
1232 }
1233 if ($conf->{"SETUP_ENV"}) {
1234 if (exists $r->{HEADERS}{"CONTENT-TYPE"}) { $ENV{"CONTENT_TYPE"} = $r->{HEADERS}{"CONTENT-TYPE"}; }
1235 if (exists $r->{HEADERS}{"CONTENT-ENCODING"}) { $ENV{"CONTENT_ENCODING"} = $r->{HEADERS}{"CONTENT-ENCODING"}; }
1236 if (exists $r->{HEADERS}{"CONTENT-LENGTH"}) { $ENV{"CONTENT_LENGTH"} = $r->{HEADERS}{"CONTENT-LENGTH"}; }
1237 if (exists $r->{HEADERS}{"CONTENT-LANGUAGE"}) { $ENV{"CONTENT_LANGUAGE"} = $r->{HEADERS}{"CONTENT-LANGUAGE"}; }
1238 }
1239  
1240 my $script = $self->__load_file($s);
1241 if (not defined $script) { return (0, 400, $page); }
1242  
1243 my $res = '';
1244 my $errs = '';
1245 my $evalerrs = '';
1246  
1247 # save all STD files
1248 open OLDERR, ">&STDERR";
1249 open OLDOUT, ">&STDOUT";
1250 open OLDIN, "<&STDIN";
1251  
1252 # reopen STDIN to $p string if we have POST
1253 close STDIN;
1254 open STDIN, "<", \$p;
1255 binmode STDIN;
1256  
1257 # reopen STDOUT to $res string
1258 close STDOUT;
1259 open STDOUT, ">", \$res;
1260 binmode STDOUT;
1261  
1262 # reopen STDERR to $errs string
1263 close STDERR;
1264 open STDERR, ">", \$errs;
1265  
1266 if ($self->{HAS_CGI_PM}) {
1267 eval('CGI::initialize_globals();');
1268 } else {
1269 for my $k (keys %INC) {
1270 if ($k eq 'CGI.pm') {
1271 $self->{HAS_CGI_PM} = 1;
1272 eval('CGI::initialize_globals();');
1273 }
1274 }
1275 }
1276  
1277 eval {
1278 eval($script);
1279 $evalerrs = $@;
1280 };
1281  
1282 # restore STD files
1283 close STDOUT;
1284 open STDOUT, ">&OLDOUT";
1285 close OLDOUT;
1286 close STDERR;
1287 open STDERR, ">&OLDERR";
1288 close OLDERR;
1289 close STDIN;
1290 open STDIN, "<&OLDIN";
1291 close OLDIN;
1292  
1293 if ($conf->{"SETUP_ENV"}) {
1294 delete $ENV{"QUERY_STRING"};
1295 delete $ENV{"CONTENT_TYPE"};
1296 delete $ENV{"CONTENT_ENCODING"};
1297 delete $ENV{"CONTENT_LENGTH"};
1298 delete $ENV{"CONTENT_LANGUAGE"};
1299 }
1300
1301 $errs .= $evalerrs;
1302  
1303 if (length($errs) > 0) {
1304 &$logging("[$id] ($s) \n$errs");
1305 }
1306  
1307 if ($conf->{"WAIT_RESPONSE"} == 0) { return (1, 200, $page); }
1308  
1309 if ($evalerrs ne '') {
1310 return (0, 500, $page);
1311 } else {
1312 if ($r->{METHOD} eq "HEAD") {
1313 return (1, 200, $self->__make_response("200", undef, undef, $auth));
1314 } else {
1315 return (1, 200, $self->__make_response("200", undef, $res, $auth));
1316 }
1317 }
1318 } else {
1319 return (0, 404, $page);
1320 }
1321 }
1322  
1323 # --------------------------------------------------------------------------------------
1324 # Run a CGI script
1325 #
1326  
1327 sub __do_cgi {
1328 my ($self, $id, $s, $r, $auth) = @_;
1329 my $conf = $self->{CONF};
1330  
1331 my $logging = $conf->{"DEBLOG_METHOD"};
1332 my $p = $r->{'CONTENT'};
1333 my $page = undef;
1334 my $post = 0;
1335  
1336 $s = $conf->{"DOCUMENT_ROOT"} . $s;
1337  
1338 if (-e $s) {
1339 $ENV{'REQUEST_METHOD'} = $r->{METHOD};
1340 if ($r->{METHOD} =~ /GET|HEAD/o) {
1341 $ENV{"QUERY_STRING"} = $r->{'QUERY_STRING'};
1342 } else {
1343 $post = 1;
1344 }
1345 if ($conf->{"SETUP_ENV"}) {
1346 if (exists $r->{HEADERS}{"CONTENT-TYPE"}) { $ENV{"CONTENT_TYPE"} = $r->{HEADERS}{"CONTENT-TYPE"}; }
1347 if (exists $r->{HEADERS}{"CONTENT-ENCODING"}) { $ENV{"CONTENT_ENCODING"} = $r->{HEADERS}{"CONTENT-ENCODING"}; }
1348 if (exists $r->{HEADERS}{"CONTENT-LENGTH"}) { $ENV{"CONTENT_LENGTH"} = $r->{HEADERS}{"CONTENT-LENGTH"}; }
1349 if (exists $r->{HEADERS}{"CONTENT-LANGUAGE"}) { $ENV{"CONTENT_LANGUAGE"} = $r->{HEADERS}{"CONTENT-LANGUAGE"}; }
1350 }
1351
1352 my $pid;
1353 my $res;
1354 my $errs;
1355  
1356 my ($IN, $OUT, $ERR);
1357  
1358 use Symbol;
1359 $ERR = Symbol::gensym;
1360  
1361 if ($r->{METHOD} =~ /GET|HEAD/o) {
1362 $pid = IPC::Open3::open3($IN,$OUT,$ERR,$s,$p) or return (0, 503, $page);
1363 } else {
1364 $pid = IPC::Open3::open3($IN,$OUT,$ERR,$s) or return (0, 503, $page);
1365
1366 binmode $IN;
1367 print $IN $p;
1368 close $IN;
1369 }
1370  
1371 my $sel = new IO::Select;
1372  
1373 $sel->add($OUT,$ERR);
1374  
1375 while(my @ready = $sel->can_read) {
1376 foreach my $fh (@ready) {
1377 my $line = <$fh>;
1378 if (not defined $line) {
1379 $sel->remove($fh);
1380 next;
1381 }
1382 if ($fh == $OUT) { $res .= $line; }
1383 elsif ($fh == $ERR) { $errs .= $line; }
1384 }
1385 }
1386  
1387 if ($conf->{"SETUP_ENV"}) {
1388 delete $ENV{"QUERY_STRING"};
1389 delete $ENV{"CONTENT_TYPE"};
1390 delete $ENV{"CONTENT_ENCODING"};
1391 delete $ENV{"CONTENT_LENGTH"};
1392 delete $ENV{"CONTENT_LANGUAGE"};
1393 }
1394
1395 if (length($errs) > 0) {
1396 &$logging("[$id] ($s) \n$errs");
1397 }
1398
1399 if ($conf->{"WAIT_RESPONSE"} == 0) { return (1, 200, $page); }
1400  
1401 if ($r->{METHOD} eq "HEAD") {
1402 return (1, 200, $self->__make_response("200", undef, undef, $auth));
1403 } else {
1404 return (1, 200, $self->__make_response("200", undef, $res, $auth));
1405 }
1406 } else {
1407 return (0, 404, $page);
1408 }
1409 }
1410  
1411 # --------------------------------------------------------------------------------------
1412 # Make response to client given variable contents
1413 #
1414  
1415 sub __make_response {
1416 my ($self, $code, $headers, $cont, $auth) = @_;
1417 my $conf = $self->{CONF};
1418  
1419 my $logging = $conf->{"DEBLOG_METHOD"};
1420 my $msg = $conf->{"HTML_CODES"}{$code};
1421 my $len = 0;
1422 my $page = undef;
1423 my $base_headers = '';
1424 if ($auth) {
1425 $base_headers = "WWW-Authenticate: Basic realm=\"" . $conf->{"AUTH_REALM"} . "\"$CRLF";
1426 }
1427 my $http = "HTTP/1.1 $code ($msg) $CRLF";
1428 my $len = "Content-Length: 0$CRLF";
1429  
1430 $base_headers .= "Server: WebIT $VERSION$CRLF";
1431  
1432 my $extra_headers = '';
1433  
1434 if (defined $headers) {
1435 if (ref($headers) eq 'HASH') {
1436 for my $k (keys %$headers) {
1437 $extra_headers .= $k . ': ' . $headers->{$k} . $CRLF;
1438 }
1439 } elsif (ref($headers) eq '') {
1440 $extra_headers = $headers;
1441 }
1442 }
1443  
1444 my $hr = $cont;
1445 if (defined $cont) {
1446 my $split;
1447 ($hr, $split, $cont) = split(/($CRLF$CRLF|\n\n)/, $cont, 2);
1448 if (($cont eq '') && ($split eq '')) {
1449 $cont = $hr;
1450 $hr = '';
1451 }
1452 $hr =~ s/($CRLF|\n)$//gc;
1453 if ($hr ne '') {
1454 $http .= $hr . $CRLF;
1455 }
1456 $len = "Content-Length: " . length($cont) . $CRLF;
1457 }
1458  
1459 my $total_headers = $http . $base_headers . $extra_headers . $len . $CRLF;
1460  
1461 $page = $total_headers . $cont;
1462  
1463 if ($conf->{'LOG_PACKETS'}) {
1464 &$logging($page);
1465 } else {
1466 if ($conf->{'LOG_HEADERS'}) {
1467 &$logging($total_headers);
1468 }
1469 }
1470  
1471 return $page;
1472 }
1473  
1474 # --------------------------------------------------------------------------------------
1475 # Make response given error and check if there is an error page to send as well
1476 #
1477  
1478 sub __make_error {
1479 my ($self, $code, $auth, $id, $rhost, $rport, $r) = @_;
1480 my $conf = $self->{CONF};
1481  
1482 my $msg = $conf->{"HTML_CODES"}{$code};
1483 my $logging = $conf->{"LOG_METHOD"};
1484  
1485 my $page = undef;
1486  
1487 if ($conf->{'SETUP_ENV'}) {
1488 $ENV{'ERROR_CODE'} = $code;
1489 $ENV{'ERROR_TEXT'} = $msg;
1490 $ENV{'ERROR_URI'} = $r->{URI};
1491 $ENV{'ERROR_METHOD'} = $r->{METHOD};
1492 }
1493  
1494 if (exists $conf->{'ERROR_PAGES'}) {
1495 if ((exists $conf->{'ERROR_PAGES'}{$code}) &&
1496 ((-e $conf->{'DOCUMENT_ROOT'}.$conf->{'ERROR_PAGES'}{$code}) ||
1497 (exists $conf->{'DOCUMENTS'}{$conf->{'ERROR_PAGES'}{$code}})
1498 )
1499 ) {
1500 $r->{METHOD} = 'GET';
1501 $r->{URI} = $conf->{'ERROR_PAGES'}{$code};
1502 my $page = $self->__get_page($id, $rhost, $rport, $r, 0);
1503 if (defined $page) {
1504 $page =~ s/^(.+)\s+\d+\s+\(.*\)(\s*$CRLF)/$1 $code ($msg)$2/;
1505 }
1506 return $page;
1507  
1508 } elsif ((exists $conf->{'ERROR_PAGES'}{'ALL'}) &&
1509 ((-e $conf->{'DOCUMENT_ROOT'}.$conf->{'ERROR_PAGES'}{'ALL'}) ||
1510 (exists $conf->{'DOCUMENTS'}{$conf->{'ERROR_PAGES'}{'ALL'}})
1511 )
1512 ) {
1513 $r->{METHOD} = 'GET';
1514 $r->{URI} = $conf->{'ERROR_PAGES'}{'ALL'};
1515 my $page = $self->__get_page($id, $rhost, $rport, $r, 0);
1516 if (defined $page) {
1517 $page =~ s/^(.+)\s+\d+\s+\(.*\)(\s*$CRLF)/$1 $code ($msg)$2/;
1518 }
1519 return $page;
1520  
1521 }
1522 }
1523  
1524
1525 my $pmeth = sprintf("%-4s", $r->{METHOD});
1526 &$logging("[$id] $pmeth [ERROR] from $rhost:$rport got ($code " . $msg. ")");
1527  
1528 my $cont = "<html><head><title>$code $msg</title></head><body><h1>$code $msg</h1></body></html>";
1529  
1530 my %headers = ();
1531 $headers{'Content-type'} = 'text/html';
1532  
1533 return $self->__make_response($code, \%headers, $cont, $auth);
1534 }
1535  
1536 # --------------------------------------------------------------------------------------
1537 # Perform fork start initialization
1538 #
1539  
1540 sub __pre_fork {
1541 my ($self, $id) = @_;
1542 my $rconf = $self->{CONF};
1543  
1544 # Pre fork is only for workers
1545 # if ($id =~ /^S\d+$/) { return; }
1546  
1547 if (defined $rconf->{"STARTUP"}) {
1548 $0 = $rconf->{"PROC_PREFIX"} . " loading startup ";
1549 if (!$self->__load_startup()) {
1550 return;
1551 }
1552 }
1553  
1554 my $f = $rconf->{"CHILD_START"};
1555 if (defined $f) {
1556  
1557 $0 = $rconf->{"PROC_PREFIX"} . " running pre-fork ";
1558  
1559 my $logging = $rconf->{"DEBLOG_METHOD"};
1560 my $logging2 = $rconf->{"LOG_METHOD"};
1561 my $errs = '';
1562 my $res = '';
1563  
1564 # save all STD files
1565 open OLDERR, ">&STDERR";
1566 open OLDOUT, ">&STDOUT";
1567  
1568 # reopen STDERR to $errs string
1569 close STDERR;
1570 open STDERR, ">", \$errs;
1571  
1572 # reopen STDOUT to $res string
1573 close STDOUT;
1574 open STDOUT, ">", \$res;
1575 binmode STDOUT;
1576  
1577 my $evalerr;
1578 eval {
1579 $data = &$f;
1580 $evalerr = $@;
1581 };
1582  
1583 close STDOUT;
1584 open STDOUT, ">&OLDOUT";
1585 close OLDOUT;
1586 close STDERR;
1587 open STDERR, ">&OLDERR";
1588 close OLDERR;
1589  
1590 $errs .= $evalerr;
1591  
1592 if (length($errs) > 0) {
1593 &$logging("[$id] (Child start) \n$errs");
1594 }
1595  
1596 &$logging2("[$id] Child ready\n");
1597 }
1598  
1599 return;
1600 }
1601  
1602 # --------------------------------------------------------------------------------------
1603 # Perform fork stop de-initialization
1604 #
1605  
1606 sub __post_fork {
1607 my ($self, $id) = @_;
1608 my $rconf = $self->{CONF};
1609  
1610 # Post fork is only for workers
1611 # if ($id =~ /^S\d+$/) { return; }
1612  
1613 my $f = $rconf->{"CHILD_END"};
1614 if (defined $f) {
1615  
1616 my $logging = $rconf->{"DEBLOG_METHOD"};
1617 my $logging2 = $rconf->{"LOG_METHOD"};
1618 my $errs = '';
1619 my $res = '';
1620
1621 # save all STD files
1622 open OLDERR, ">&STDERR";
1623 open OLDOUT, ">&STDOUT";
1624  
1625 # reopen STDERR to $errs string
1626 close STDERR;
1627 open STDERR, ">", \$errs;
1628  
1629 # reopen STDOUT to $res string
1630 close STDOUT;
1631 open STDOUT, ">", \$res;
1632 binmode STDOUT;
1633  
1634 my $evalerr;
1635 eval {
1636 &$f($data);
1637 $evalerr = $@;
1638 };
1639  
1640 close STDOUT;
1641 open STDOUT, ">&OLDOUT";
1642 close OLDOUT;
1643 close STDERR;
1644 open STDERR, ">&OLDERR";
1645 close OLDERR;
1646  
1647 $errs .= $evalerr;
1648  
1649 if (length($errs) > 0) {
1650 &$logging("[$id] (Child end) \n$errs");
1651 }
1652  
1653 &$logging2("[$id] Child finished\n");
1654 }
1655  
1656 return;
1657 }
1658  
1659 # --------------------------------------------------------------------------------------
1660 # Patch configuration for our needs
1661 #
1662  
1663 sub __fix_conf {
1664 my ($rconf) = @_;
1665  
1666 if (not defined $rconf->{"SERVER_NAME"}) {
1667 $rconf->{"SERVER_NAME"} = "localhost"
1668 }
1669 if (not defined $rconf->{"SERVER_IP"}) {
1670 $rconf->{"SERVER_IP"} = "127.0.0.1";
1671 }
1672 if (not defined $rconf->{"SERVER_PORT"}) {
1673 $rconf->{"SERVER_PORT"} = 80;
1674 }
1675 if (not defined $rconf->{"WAIT_RESPONSE"}) {
1676 $rconf->{"WAIT_RESPONSE"} = 1;
1677 }
1678 if (not defined $rconf->{"NO_WAIT_REPLY"}) {
1679 $rconf->{"NO_WAIT_REPLY"} = 204;
1680 }
1681 if (not defined $rconf->{"IMMED_CLOSE"}) {
1682 $rconf->{"IMMED_CLOSE"} = 0;
1683 }
1684 if (not defined $rconf->{"SOFTWARE"}) {
1685 $rconf->{"SOFTWARE"} = "WebIT/$VERSION";
1686 }
1687 if (not defined $rconf->{"SIGNATURE"}) {
1688 $rconf->{"SIGNATURE"} = "<br/>WebIT/$VERSION for Perl<br/>";
1689 }
1690 if (not defined $rconf->{"PROC_PREFIX"}) {
1691 $rconf->{"PROC_PREFIX"} = 'WebIT';
1692 }
1693 $rconf->{"PROC_PREFIX"} =~ s/\s\s/\s/go;
1694 if (not defined $rconf->{"EMBED_PERL"}) {
1695 $rconf->{"EMBED_PERL"} = 1;
1696 }
1697 if (not defined $rconf->{"QUEUE_SIZE"}) {
1698 $rconf->{"QUEUE_SIZE"} = 5;
1699 }
1700 if (defined $rconf->{"DOCUMENT_ROOT"}) {
1701 if ($rconf->{"DOCUMENT_ROOT"} !~ /\/$/) {
1702 $rconf->{"DOCUMENT_ROOT"} .= "/";
1703 }
1704 } else {
1705 $rconf->{"DOCUMENT_ROOT"} = undef;
1706 }
1707  
1708 if (not defined $rconf->{"SETUP_ENV"}) {
1709 $rconf->{"SETUP_ENV"} = 1;
1710 }
1711  
1712 if (length($rconf->{"STARTUP"}) > 0) {
1713 $rconf->{"STARTUP"} =~ s/\/\//\//gco;
1714 }
1715  
1716 if (not defined $rconf->{"ENV_KEEP"}) {
1717 push(@{$rconf->{"ENV_KEEP"}}, 'PATH');
1718 }
1719  
1720 if (not defined $rconf->{"ENV_ADD"}) {
1721 $rconf->{"ENV_ADD"} = ();
1722 }
1723  
1724 if (not defined $rconf->{"MIME_TYPES"}) {
1725 $rconf->{"MIME_TYPES"} = '/etc/mime.types';
1726 }
1727  
1728 if (not defined $rconf->{"SERVERS"}) {
1729 $rconf->{"SERVERS"} = 0;
1730 }
1731  
1732 if (not defined $rconf->{"WORKERS"}) {
1733 $rconf->{"WORKERS"} = 0;
1734 }
1735  
1736 if (not defined $rconf->{"FORK_CONN"}) {
1737 $rconf->{"FORK_CONN"} = 0;
1738 }
1739  
1740 if ($rconf->{"FORK_CONN"}) {
1741 $rconf->{"WORKERS"} = 0;
1742 }
1743  
1744 if (not defined $rconf->{"USE_SSL"}) {
1745 $rconf->{"USE_SSL"} = 0;
1746 $rconf->{"SSL_CERTIFICATE"} = undef;
1747 $rconf->{"SSL_KEY"} = undef;
1748 }
1749  
1750 if (not defined $rconf->{"LOG_METHOD"}) {
1751 if ($rconf->{"NO_LOGGING"}) {
1752 $rconf->{"LOG_METHOD"} = 'EmbedIT::WebIT::__no_logging';
1753 } else {
1754 $rconf->{"LOG_METHOD"} = 'EmbedIT::WebIT::__logging';
1755 }
1756 }
1757 if (not defined $rconf->{"DEBLOG_METHOD"}) {
1758 $rconf->{"DEBLOG_METHOD"} = $rconf->{"LOG_METHOD"};
1759 }
1760  
1761 if (not defined $rconf->{"LOG_HEADERS"}) {
1762 $rconf->{"LOG_HEADERS"} = 0;
1763 }
1764  
1765 if (not defined $rconf->{"LOG_PACKETS"}) {
1766 $rconf->{"LOG_PACKETS"} = 0;
1767 }
1768  
1769 if ($rconf->{'LOG_PACKETS'}) {
1770 $rconf->{"LOG_HEADERS"} = 1;
1771 }
1772  
1773 if (defined $rconf->{"CGI_PATH"}) {
1774 $rconf->{"CGI_PATH_PRINT"} = $rconf->{"CGI_PATH"};
1775 # transform CGI_PATH to a regular expression for single step matching
1776 $rconf->{"CGI_PATH"} =~ s/\s(:|;)\s/$1/g;
1777 $rconf->{"CGI_PATH"} =~ s/(:|;)/\/$1/g;
1778 $rconf->{"CGI_PATH"} =~ s/$/\//g;
1779 $rconf->{"CGI_PATH"} =~ s/\/\//\//g;
1780 $rconf->{"CGI_PATH"} =~ s/\//\\\//g;
1781 $rconf->{"CGI_PATH"} =~ s/^(.)/($1/g;
1782 $rconf->{"CGI_PATH"} =~ s/(.)$/$1)/g;
1783 $rconf->{"CGI_PATH"} =~ s/(:|;)/)|(/g;
1784 $rconf->{"CGI_PATH"} =~ s/\)/.*?\\\..*)/g;
1785 }
1786 if (defined $rconf->{"AUTH_PATH"}) {
1787 $rconf->{"AUTH_PATH_PRINT"} = $rconf->{"AUTH_PATH"};
1788 # transform AUTH_PATH to a regular expression for single step matching
1789 $rconf->{"AUTH_PATH"} =~ s/\s(:|;)\s/$1/g;
1790 $rconf->{"AUTH_PATH"} =~ s/(:|;)/\/$1/g;
1791 $rconf->{"AUTH_PATH"} =~ s/$/\//g;
1792 $rconf->{"AUTH_PATH"} =~ s/\/\//\//g;
1793 $rconf->{"AUTH_PATH"} =~ s/\//\\\//g;
1794 $rconf->{"AUTH_PATH"} =~ s/^(.)/($1/g;
1795 $rconf->{"AUTH_PATH"} =~ s/(.)$/$1)/g;
1796 $rconf->{"AUTH_PATH"} =~ s/(:|;)/)|(/g;
1797 }
1798  
1799 if (not exists $rconf->{"HTML_CODES"}) {
1800 $rconf->{"HTML_CODES"} = {
1801 100 => "Continue",
1802 101 => "Switching Protocols",
1803 200 => "OK",
1804 201 => "Created",
1805 202 => "Accepted",
1806 203 => "Non-Authoritative Information",
1807 204 => "No Content",
1808 205 => "Reset Content",
1809 206 => "Partial Content",
1810 300 => "Multiple Choices",
1811 301 => "Moved Permanently",
1812 302 => "Found",
1813 303 => "See Other",
1814 304 => "Not Modified",
1815 305 => "Use Proxy",
1816 306 => "No Longer Used",
1817 307 => "Temporary Redirect",
1818 400 => "Bad Request",
1819 401 => "Not Authorised",
1820 402 => "Payment Required",
1821 403 => "Forbidden",
1822 404 => "Not Found",
1823 405 => "Method Not Allowed",
1824 406 => "Not Acceptable",
1825 407 => "Proxy Authentication Required",
1826 408 => "Request Timeout",
1827 409 => "Conflict",
1828 410 => "Gone",
1829 411 => "Length Required",
1830 412 => "Precondition Failed",
1831 413 => "Request Entity Too Large",
1832 414 => "Request URI Too Long",
1833 415 => "Unsupported Media Type",
1834 416 => "Requested Range Not Satisfiable",
1835 417 => "Expectation Failed",
1836 500 => "Internal Server Error",
1837 501 => "Not Implemented",
1838 502 => "Bad Gateway",
1839 503 => "Service Unavailable",
1840 504 => "Gateway Timeout",
1841 505 => "HTTP Version Not Supported",
1842 };
1843 }
1844 }
1845  
1846 # --------------------------------------------------------------------------------------
1847 # Clean up the process environment variables
1848 #
1849  
1850 sub __clean_env {
1851 my ($conf) = @_;
1852  
1853 foreach my $k (keys %ENV) {
1854 my $found = 0;
1855 foreach my $w (@{$conf->{"ENV_KEEP"}}) {
1856 if ($k eq $w) { $found = 1; }
1857 }
1858 if (!$found) { delete $ENV{$k} };
1859 }
1860  
1861 if ($conf->{"SETUP_ENV"}) {
1862 $ENV{"SERVER_NAME"} = $conf->{"SERVER_NAME"};
1863 $ENV{"SERVER_PORT"} = $conf->{"SERVER_PORT"};
1864 $ENV{"SERVER_ADMIN"} = $conf->{"SERVER_ADMIN"};
1865 $ENV{"DOCUMENT_ROOT"} = $conf->{"DOCUMENT_ROOT"};
1866 $ENV{"SERVER_PROTOCOL"} = "HTTP/1.1";
1867 $ENV{"SERVER_SOFTWARE"} = $conf->{"SOFTWARE"};
1868 $ENV{"SERVER_SIGNATURE"} = $conf->{"SIGNATURE"};
1869 $ENV{"GATEWAY_INTERFACE"} = "CGI/1.1 WebIT for Perl";
1870 if ($conf->{"EMBED_PERL"}) {
1871 $ENV{"WEBIT_DATA"} = "INTERNAL";
1872 }
1873 }
1874 foreach my $k (keys %{$conf->{"ENV_ADD"}}) {
1875 $ENV{$k} = $conf->{"ENV_ADD"}->{$k};
1876 }
1877 }
1878  
1879 # --------------------------------------------------------------------------------------
1880 # Fix environment variables for current request
1881 #
1882  
1883 sub __fix_env {
1884 my ($self, $r) = @_;
1885  
1886 for my $k (keys %{ $r->{HEADERS} }) {
1887 if ($k !~ /CONTENT-LENGTH|COOKIE/) {
1888 my $l = $k;
1889 $l =~ s/[^A-Za-z0-9_]/_/gco;
1890 $l = 'HTTP_' . $l;
1891 $ENV{$l} = $r->{HEADERS}{$k};
1892 }
1893 }
1894 if (exists $r->{HEADERS}{'COOKIE'}) {
1895 $ENV{'COOKIE'} = $r->{HEADERS}{'COOKIE'};
1896 } else {
1897 delete $ENV{'COOKIE'};
1898 }
1899 }
1900  
1901 # --------------------------------------------------------------------------------------
1902 # Load a file a return its contents or undef on error
1903 #
1904  
1905 sub __load_file {
1906 my ($self, $f) = @_;
1907  
1908 open FILE, $f || return undef;
1909 binmode FILE;
1910 my @l = <FILE>;
1911 close FILE;
1912  
1913 return join('',@l);
1914 }
1915  
1916 # --------------------------------------------------------------------------------------
1917 # Load startup file to fix server environment
1918 #
1919  
1920 sub __load_startup {
1921 my ($self) = @_;
1922 my $conf = $self->{CONF};
1923  
1924 my $logging = $conf->{"DEBLOG_METHOD"};
1925  
1926 my $scr = $self->__load_file($conf->{"STARTUP"});
1927 if (not defined $scr) {
1928 &$logging("Startup file cannot be loaded");
1929 return 0;
1930 }
1931  
1932 my $errs = '';
1933 my $res = '';
1934
1935 # save all STD files
1936 open OLDERR, ">&STDERR";
1937 open OLDOUT, ">&STDOUT";
1938  
1939 # reopen STDERR to $errs string
1940 close STDERR;
1941 open STDERR, ">", \$errs;
1942  
1943 # reopen STDOUT to $res string
1944 close STDOUT;
1945 open STDOUT, ">", \$res;
1946 binmode STDOUT;
1947  
1948 my $evalerr;
1949 eval {
1950 eval($scr);
1951 $evalerr = $@;
1952 };
1953  
1954 close STDOUT;
1955 open STDOUT, ">&OLDOUT";
1956 close OLDOUT;
1957 close STDERR;
1958 open STDERR, ">&OLDERR";
1959 close OLDERR;
1960  
1961 $errs .= $evalerr;
1962  
1963 if (length($errs) > 0) {
1964 &$logging("(" . $conf->{"STARTUP"} . ") \n$errs");
1965 }
1966  
1967 if ($evalerr ne '') { return 0; }
1968  
1969 return 1;
1970 }
1971  
1972 # --------------------------------------------------------------------------------------
1973 # get user id from given id or name
1974 #
1975  
1976 sub __get_uid {
1977 my ($i_id) = @_;
1978  
1979 my ($n, $p, $uid, $gid, $quota, $comment, $gcos, $dir, $shell, $expire) = getpwnam($i_id);
1980 if (not defined $uid) {
1981 ($n, $p, $uid, $gid, $quota, $comment, $gcos, $dir, $shell, $expire) = getpwuid($i_id);
1982 if (not defined $uid) {
1983 return 0;
1984 }
1985 }
1986  
1987 return $uid;
1988 }
1989  
1990 # --------------------------------------------------------------------------------------
1991 # get group id from given id or name
1992 #
1993  
1994 sub __get_gid {
1995 my ($i_id) = @_;
1996  
1997 my ($n, $p, $gid, $members) = getgrnam($i_id);
1998 if (not defined $gid) {
1999 ($n, $p, $gid, $members) = getgrgid($i_id);
2000 if (not defined $gid) {
2001 return 0;
2002 }
2003 }
2004 return $gid;
2005 }
2006  
2007 # --------------------------------------------------------------------------------------
2008 # Empty logger
2009 #
2010  
2011 sub __no_logging {
2012 }
2013  
2014 # --------------------------------------------------------------------------------------
2015 # Elementary log
2016 #
2017  
2018 sub __logging {
2019 my ($self, $str) = @_;
2020 if (ref($self) eq '') {
2021 print STDERR time2iso(time) . " - $self\n";
2022 } else {
2023 print STDERR time2iso(time) . " - $str\n";
2024 }
2025 }
2026  
2027 # --------------------------------------------------------------------------------------
2028  
2029 1;
2030  
2031 =head1 NAME
2032  
2033 EmbedIT::WebIT - A small yet very effective embeded web server for any perl application
2034  
2035 =head1 Synopsis
2036  
2037 use EmbedIT::WebIT;
2038  
2039 $server = new EmbedIT::WebIT( SERVER_NAME => 'www.my.org',
2040 SERVER_IP => '127.0.0.1',
2041 SERVER_PORT => 8080,
2042 SOFTWARE => 'MyApp web server',
2043 QUEUE_SIZE => 100,
2044 RUN_AS_USER => nobody,
2045 RUN_AS_GROUP => nogroup,
2046 WAIT_RESPONSE => 1,
2047 IMMED_CLOSE => 1,
2048 EMBED_PERL => 1,
2049 FORK_CONN => 0,
2050 SETUP_ENV => 1,
2051 SERVER_ADMIN => 'info@my.org',
2052 SERVERS => 3,
2053 WORKERS => 1,
2054 DOCUMENT_ROOT => '/opt/my/web',
2055 DOCUMENTS => {
2056 '/index.html' => 'WPages::index',
2057 '/error.html' => 'WPages::error',
2058 '/style.css' => 'WPages::style',
2059 '/print.css' => 'WPages::print',
2060 '/404.html' => 'WPages::error404',
2061 '*' => 'WPages::pageHandle',
2062 },
2063 ERROR_PAGES => {
2064 '404' => '/404.html', # embeded subroutine error
2065 'ALL' => '/error.html', # simple html file error
2066 },
2067 EXPIRATIONS => {
2068 'image/jpg' => 86400,
2069 'ALL' => 3600,
2070 },
2071 PROC_PREFIX => 'my:',
2072 CHILD_START => 'WControl::start_db',
2073 CHILD_END => 'WControl::stop_db',
2074 LOG_METHOD => 'WControl::logInfo',
2075 DEBLOG_METHOD => 'WControl::logDebug',
2076 LOG_HEADERS => 0,
2077 LOG_PACKETS => 0,
2078 CGI_PATH => '/cgi',
2079 ENV_KEEP => [ 'PERL5LIB', 'LD_LIBRARY_PATH' ],
2080 NO_LOGGING => 0,
2081 );
2082  
2083 $server->execute();
2084  
2085 =head1 Description
2086  
2087 The WebIT embeded web server was created a long time ago to make a pure perl application that will interact
2088 directly with I<Kannel>. The need was to relieve I<Kannel> from the need to wait for the web server to run
2089 its scripts before going back to serve another SMS message. In this respect WebIT is a hack and can be
2090 configured to behave in a manner which is not according to the RFC's for HTTP. Yet, creating Perl applications
2091 with WebIT using embeded html pages as perl functions outperforms Apache with mod_perl installations.
2092  
2093 For this reason I was asked by a few to release this code so that they can use it for their applications.
2094  
2095 So even though WebIT is not complete (Workers and SSL not implemented yet) WebIT is already used by
2096 14 perl applications that I know of excluding my personal work.
2097  
2098 To work with WebIT all you need to do is to create a new server object by giving to it the parameters
2099 that you want, and then at any point in time call the execute method to run the server. The execute method
2100 returns only when the server has finished execution, and that can only be done by sending a TERM signal to
2101 the process.
2102  
2103 Once the server has started it will fork the predefined number of servers and workers. Since workers are not
2104 implemented yet you are advised to ask for 0 workers on startup. From then on, WebIT will serve HTTP requests
2105 by using external files in a configured directory and/or internal pages served by perl subroutines. The code
2106 of the cgi pages and subroutines is as you already know by Apache and mod_perl. You can use the CGI module to
2107 get the request parameters, print on the standard output to form the response to the caller, and print to
2108 standard error to log text to the logger of the server.
2109  
2110 =head1 Things to avoid
2111  
2112 =over
2113  
2114 =item *
2115  
2116 Dont use perl threads ! Perl does not really have threads anyway, so dont use them. Threads that do not by
2117 default share their data are not threads, they are forks, and in perl threads are isolated. If you are really
2118 inclined to use threads move to another language like Java.
2119  
2120 =item *
2121  
2122 Dont use IPC. The server already uses IPC, and some things you can do might break the server.
2123  
2124 =back
2125  
2126 Just use the server for what it is, and that is an embeded web server for applications, not for hacks, thus you
2127 should not need any of the above to create you application. Now if for any reason you really have to use some of
2128 the above, then WebIT is not for you.
2129  
2130 =head1 Configuration
2131  
2132 Now lets take a look at the configuration hash of the server.
2133  
2134 =over 4
2135  
2136 =item SERVER_NAME
2137  
2138 The DNS name of the server (default is localhost)
2139  
2140 =item SERVER_IP
2141  
2142 The IP address to bind to (default is 127.0.0.1)
2143  
2144 =item SERVER_PORT
2145  
2146 The TCP port to use (default is 80)
2147  
2148 =item QUEUE_SIZE
2149  
2150 The number of connections to queue per child (default is 5)
2151  
2152 =item USE_SSL
2153  
2154 The server will work in SSL mode accepting https connections only. (default is undef)
2155 B<This feature is not implemented yet>
2156  
2157 =item SSL_CERTIFICATE
2158  
2159 The servers SSL certificate path and file. If not defined no certificate file will be
2160 used for the connection. You can pass the actual certificate here as is. The value is
2161 first tested to see if it matches an existing file, and if not it will be used as an
2162 actual certificate. (default is undef)
2163 B<This feature is not implemented yet>
2164  
2165 =item SSL_KEY
2166  
2167 The servers SSL key path and file. If not defined no key will be used for the
2168 connection. You can pass the actual key here as is. The value is first tested
2169 to see if it matches an existing file, and if not it will be used as an
2170 actual key. (default is undef).
2171 B<This feature is not implemented yet>
2172  
2173 =item WAIT_RESPONSE
2174  
2175 Directs the server to wait until a response is generated. If 0 server will
2176 close connection before running scripts or getting pages and returns 204
2177 (No Content) to client (default is 1 and the server will wait for responses)
2178  
2179 =item NO_WAIT_REPLY
2180  
2181 The code to send when WAIT_RESPONCE is 0. (default is undef and 204 is returned)
2182  
2183 =item IMMED_CLOSE
2184  
2185 Close connection immediately after serving request. Ignored if WAIT_RESPONSE is 0. (default is 0)
2186 If it is set to 0 the server will respect the client's request about the handling of the connection (might be
2187 immediate close or keep open)
2188  
2189 =item RUN_AS_USER
2190  
2191 The user under which the server should run as
2192  
2193 =item RUN_AS_GROUP
2194  
2195 The group under which the server should run as
2196  
2197 =item SETUP_ENV
2198  
2199 Allow the server to setup the children environment. This requires some milliseconds for each request
2200 served since the server will have to contruct the environment for each call. If you are not using the CGI
2201 module and you know what you are doing you can set this to 0-false and save some time for running requests
2202 (default is 1)
2203  
2204 =item ENV_KEEP
2205  
2206 List of environment variables to keep for scripts. For normal execution all environment variables are cleared
2207 and CGI and embeded pages run in a clean environment. If however you need to preserve some, like database variables
2208 you can specify their names here in an array, and they will be preserved for your scripts.
2209  
2210 =item ENV_ADD
2211  
2212 Hash with environment variables and values to set for scripts. These environment variables and their values will be
2213 added to the environment of your CGI and embeded pages.
2214  
2215 =item MIME_TYPES
2216  
2217 Path and file where the server can find valid mimetypes. (default is /etc/mime.types)
2218  
2219 =item EMBED_PERL
2220  
2221 Run perl CGI scripts inside the server, not in a separate process. Faster than Apache and mod_perl. (default is 0)
2222  
2223 =item SERVER_ADMIN
2224  
2225 The email of the server administrator. This text will appear in the environment variables of the CGI / embeded pages (default is empty)
2226  
2227 =item DOCUMENT_ROOT
2228  
2229 The path where the site documents and scripts are stored. (default is undef)
2230  
2231 =item DOCUMENTS
2232  
2233 A hash of documents and their subroutines to execute within the server. This is
2234 used to create fully embeded web servers that respond to specific URL's using
2235 specific subroutines. A special page name '*' can be used to direct all unknown
2236 page requests to be directed to the subroutine of this special page.
2237 Can be used in conjunction with and has precedence over DOCUMENT_ROOT (default is undef)
2238  
2239 =item ERROR_PAGES
2240  
2241 A hash with the site supplied error pages. It contains the error code as a key and
2242 the page path within DOCUMENT_ROOT or DOCUMENTS of the page for the error. Alternatevly there can
2243 be an entry with keyword ALL where all errors without a specific entry in the hash
2244 will find their error pages. Error pages can be cgi's or plain html. (default is undef)
2245 For all error pages the server sets 4 extra environment variables. These are:
2246  
2247 =over 4
2248  
2249 =item ERROR_CODE
2250  
2251 This contains the numeric value of the error, eg 404.
2252  
2253 =item ERROR_TEXT
2254  
2255 This contains the text value of the error, eg Page not found.
2256  
2257 =item ERROR_URI
2258  
2259 This contains the URI that generated the error.
2260  
2261 =item ERROR_METHOD
2262  
2263 This contains the method used to access the URI, eg POST
2264  
2265 =back
2266  
2267 Along with all other environment variables used you can track all errors to their fullest detail, and handle
2268 them not just for display but for administrator notifications as well.
2269  
2270 =item EXPIRATIONS
2271  
2272 A hash with expiration times. It contains the content type as a key and the expiration
2273 time in seconds. A special entry called ALL specifies the expiration time of any type NOT
2274 already defined in the hash.
2275  
2276 =item SERVERS
2277  
2278 Number of servers to prefork. Default is 0 where only the master instance exists
2279  
2280 =item WORKERS
2281  
2282 Number of page workers to prefork. Default is 0 where only the master instance exists
2283 B<Wrokers are not implemented yet>
2284  
2285 =item FORK_CONN
2286  
2287 Create a child everytime a new connection arrives. (default is 0) Usefull for hard headed
2288 perl modules like SOAP::WSDL that retain information between calls and confuse the server. Not to be
2289 used with time sensitive HTTP applications like SMS applications with I<Kannel> because with perl, forking
2290 requires quite some time to be performed.
2291  
2292 =item STARTUP
2293  
2294 Run this script at startup to load the environment for the pages. Can only be an external perl script.
2295 Embeded pages startup code can be done in many ways without the need of external scripts.
2296  
2297 =item CHILD_START
2298  
2299 Subroutine to call on every fork for initialization. Returned values of this
2300 subroutine are passed to internally called functions (default is undef) Persistant database connections
2301 and other paraphenalia that are required for your application should be initialized in the method
2302 defined here. All values that are needed by your application should be returned in a hash or an array
2303 by your method, so that they can be retrieved later on by your CGI's and embeded pages.
2304  
2305 =item CHILD_END
2306  
2307 Subrouting to call on termination of a forked child. It is passed the return values of the start subroutine
2308 (default is undef) All values initialized by the method defined in CHILD_START that require some form
2309 of proper termination should be treated by the method defined here. The parameter passed to that method
2310 is the pointer returned by the CHILD_START, so you should know how to deal with it.
2311  
2312 =item PROC_PREFIX
2313  
2314 Text line to be used as prefix for the process name of the childs. (default is WebIT) This is
2315 just for decorating the ps listing of those OS's that give us the ability to change the name of the process.
2316  
2317 =item LOG_METHOD
2318  
2319 Subroutine to call for logging. It is passed a single string to log.
2320 (default is internal logging to stderr)
2321  
2322 =item DEBLOG_METHOD
2323  
2324 Subroutine to call for debug logging. It is passed a single string to log.
2325 (default is the same with LOG_METHOD)
2326  
2327 =item LOG_HEADERS
2328  
2329 Log input and output packet headers as those come and go to and from the server (default is 0)
2330  
2331 =item LOG_PACKETS
2332  
2333 Log input and output packets as those come and go to anf from the server. By turning on packet logging you will
2334 implicity get header logging. (default is 0)
2335  
2336 =item NO_LOGGING
2337  
2338 When set to 1-true the server will avoid all possible logging speeding up processing to the max. (default is 0)
2339  
2340 =item CGI_PATH
2341  
2342 A colon or semicolon separated list of paths under the DOCUMENT_ROOT where
2343 CGI scripts exist. (default is undef)
2344  
2345 =item AUTH_PATH
2346  
2347 A colon or semicolon separated list of paths under the DOCUMENT_ROOT where
2348 authentication is needed. Works with embeded pages as well. (default is undef)
2349  
2350 =item AUTH_REALM
2351  
2352 A string specifying the realm of the authentication for the AUTH_PATH's. There is only one
2353 realm (default is undef)
2354  
2355 =item AUTH_METHOD
2356  
2357 Subroutine to call for authenticating remote users. Parameters are the returned values of
2358 the child start subroutine preceeded by a username and a password. (default is undef)
2359  
2360 =item SOFTWARE
2361  
2362 Text with software name and version. This text will appear in the environment variables of the CGI / embeded pages
2363 (default is WebIT/$VESRION)
2364  
2365 =item SIGNATURE
2366  
2367 Text with web server signature. This text will appear in the environment variables of the CGI / embeded pages. (default is <br\>WebIT/$VERSION for Perl<br\>)`
2368  
2369 =back
2370  
2371 =head1 Methods
2372  
2373 The methods that are available to use are the following:
2374  
2375 =over
2376  
2377 =item new()
2378  
2379 This is the constructor of the object. It takes as a parameter a hash with keys and values as described above.
2380  
2381 =item execute()
2382  
2383 This is the routing to enter the execution loop of the server. This method will never return, so if you need to do
2384 anyting more with your application you might want to call this method from a forked process.
2385  
2386 =item data()
2387  
2388 This method returns the server child data as those were returned by the CHILD_START method.
2389  
2390 Lets assume that you have a CHILD_START method as follows:
2391  
2392 sub start_up {
2393 %res = ();
2394 $db = DBI->connect("DBI:Oracle:sid=pits;host=127.0.0.2;port=3127", "user", "pass");
2395  
2396 $res{DATABASE} = $db;
2397  
2398 return \%res;
2399 }
2400  
2401 If you want to retrieve that connection from inside a CGI script or an embeded page what you need to do is the
2402 following:
2403  
2404 $res = EmbedIT::WebIT::data();
2405 $db = $res->{DATABASE};
2406  
2407 or if you have access to you server object you can do the following:
2408  
2409 $res = $server->data();
2410 $db = $res->{DATABASE};
2411  
2412 =item start_time()
2413  
2414 This method returns the timestamp of the server startup time. Usefull for applications that need to know when
2415 the server started in order to perform some functions.
2416  
2417 =back
2418  
2419 =head1 WebIT and SOAP::WSDL
2420  
2421 One of the main reasons why I use now days WebIT, is to expose soap methods. SOAP::WSDL (and not SOAP::Lite) is the
2422 best possible soap package available for perl. If you want to use WebIT as a server for SOAP::WSDL this is what you
2423 have to do:
2424  
2425 First of all you need to specify FORK_CONN as true (1 for perl) to force the server to fork a new child for each
2426 new connection. Then you need to specify the embeded pages that will serve the methods exposed by the WSDL. For
2427 example, assume you need to expose a method test that takes a string as input and returns another string as output.
2428  
2429 Create you WSDL
2430  
2431 <?xml version="1.0" encoding="utf-8"?>
2432 <wsdl:definitions xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
2433 xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
2434 xmlns:xs="http://www.w3.org/2001/XMLSchema"
2435 xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
2436 xmlns:tns="http://tempuri.org/"
2437 xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/"
2438 xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
2439 targetNamespace="http://tempuri.org/"
2440 xmlns:wc="http://tempuri.org/"
2441 xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
2442 <wsdl:types>
2443 <xs:schema elementFormDefault="unqualified" targetNamespace="http://tempuri.org/">
2444 <xs:element name="InputFlag">
2445 <xs:complexType>
2446 <xs:sequence>
2447 <xs:element name="Flag" type="xs:string" minOccurs="1" maxOccurs="1"/>
2448 </xs:sequence>
2449 </xs:complexType>
2450 </xs:element>
2451
2452 <xs:element name="OutputFlag">
2453 <xs:complexType>
2454 <xs:sequence>
2455 <xs:element name="Flag" type="xs:string" minOccurs="1" maxOccures="1"/>
2456 </xs:sequence>
2457 </xs:complexType>
2458 </xs:element>
2459 </xs:schema>
2460 </wsdl:types>
2461
2462 <wsdl:message name="MsgIn"> <wsdl:part element="tns:InputFlag" name="MessageIn"/> </wsdl:message>
2463 <wsdl:message name="MsgOut"> <wsdl:part element="tns:OutputFlag" name="MessageOut"/> </wsdl:message>
2464
2465 <wsdl:portType name="TestPort">
2466 <wsdl:operation name="Test">
2467 <wsdl:input message="tns:MsgIn" />
2468 <wsdl:output message="tns:MsgOut" />
2469 </wsdl:operation>
2470 </wsdl:portType>
2471
2472 <wsdl:binding name="TestBind" type="tns:TestPort">
2473 <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
2474
2475 <wsdl:operation name="Test">
2476 <soap:operation soapAction="urn:Test#Test" style="document" />
2477
2478 <wsdl:input> <soap:body use="literal"/> </wsdl:input>
2479 <wsdl:output> <soap:body use="literal"/> </wsdl:output>
2480 </wsdl:operation>
2481
2482 </wsdl:binding>
2483  
2484 <wsdl:service name="Test">
2485 <wsdl:port name="Test" binding="tns:TestBind">
2486 <soap:address location="http://127.0.0.1:8089/WS/Test" />
2487 </wsdl:port>
2488  
2489 </wsdl:service>
2490 </wsdl:definitions>
2491  
2492 and compile it with wsdl2perl
2493  
2494 Then create your handling object (use SOAP::WSDL documentation to see what you need to do) as follows:
2495  
2496 package WebService
2497  
2498 our $VERSION = "1.0";
2499  
2500 sub new {
2501 my $self = {};
2502 bless $self;
2503 return $self;
2504 }
2505  
2506 sub Test {
2507 my ($self,$body,$header) = @_;
2508 my %idata = ();
2509
2510 $idata{Flag} = $body->get_Flag() . "";
2511
2512 return MyElements::OutputFlag->new(\%idata);
2513 }
2514  
2515 and finally create your embeded page that will handle the HTTP request.
2516  
2517 sub WebService {
2518 eval {
2519 unshift @INC, $lib_path; # add at run time the library path of the generated classes from wsdl2perl
2520 require MyServer::Test::Test; # use the server class generated by wsdl2perl
2521
2522 my $t = WebService->new(); # create a WebService handling object
2523 my $server = MyServer::Test::Test->new({ dispatch_to => 'WebService',
2524 transport_class => 'SOAP::WSDL::Server::CGI' });
2525 $server->handle();
2526 };
2527 if ($@) { print "just do something ...the call has failed\n"; }
2528 }
2529  
2530 On your WebIT configuration hash you need to remember to add the above subroutine as the handler
2531 for a page like so:
2532  
2533 $server = new EmbedIT::WebIT( SERVER_NAME => 'name.org',
2534 ...
2535 FORK_CONN => 1,
2536 ...
2537 DOCUMENTS => {
2538 'WS/Test' => 'main::WebService',
2539 },
2540 ...
2541 );
2542  
2543 and thats it. You have exposed web services working with WebIT as an embeded web server.
2544  
2545 =head1 Requirements
2546  
2547 You need to have installed the following packages for WebIT to work.
2548  
2549 =over 4
2550  
2551 =item HTTP::Date
2552  
2553 =item IO::Socket
2554  
2555 =item IO::Select
2556  
2557 =item LWP::MediaTypes
2558  
2559 =item IPC::Open3
2560  
2561 =item Taint::Runtime
2562  
2563 =item MIME::Base64
2564  
2565 =back
2566  
2567 =head1 Copyright
2568  
2569 Copyright 2008 D. Evmorfopoulos <devmorfo@gmail.com>
2570  
2571 Permission is granted to copy, distribute and/or modify this
2572 document under the terms of the GNU Free Documentation
2573 License, Version 1.2 or any later version published by the
2574 Free Software Foundation; with no Invariant Sections, with
2575 no Front-Cover Texts, and with no Back-Cover Texts.
2576  
2577 =cut
↑ Summary