Debian Codegraph @

lib/dop

raw
1 #!/usr/bin/perl -wT
2
3 # F*EX document output
4 #
5 # is a subprogram of fexsrv! do not run it directly!
6 #
7 # Author: Ulli Horlacher <[email protected]>
8 #
9
10 use File::Basename;
11 use Fcntl qw(:flock :seek :mode);
12 use POSIX qw(strftime locale_h);
13 use Cwd qw(getcwd abs_path);
14 # use utf8;
15 # use CGI::Carp qw(fatalsToBrowser);
16
17 # import from fex.pp
18 our ($bs,$tmpdir,@doc_dirs,$RA);
19
20 my $log = 'dop.log';
21
22 $RA ||= $ra;
23
24 # POSIX time format needed for HTTP header
25 setlocale(LC_TIME,'POSIX');
26
27 sub dop {
28 my $doc = shift;
29 my $source = shift;
30 my $seek = 0;
31 my $stop = 0;
32 my ($link,$host,$path,$range);
33
34 our $error = 'F*EX document output ERROR';
35
36 security_check($doc);
37
38 # reget?
39 if ($range = $ENV{HTTP_RANGE}) {
40 $seek = $1 if $range =~ /^bytes=(\d+)-/i;
41 $stop = $1 if $range =~ /^bytes=\d*-(\d+)/i;
42 }
43
44 # redirect on relative symlinks without "../"
45 if ($link = readlink($doc) and
46 $link !~ m:^/: and $link !~ m:\.\./: and $link !~ /^:.+:$/) {
47 $path = $ENV{REQUEST_URI};
48 $path =~ s:[^/]*$::;
49 $doc = "$path/$link";
50 $doc =~ s:/+:/:g;
51 $doc =~ s:^/::;
52 nvt_print(
53 "HTTP/1.1 302 Found",
54 "Location: /$doc",
55 "Content-Length: 0",
56 ""
57 );
58 &reexec;
59 }
60
61 # watchdog documents
62 if (@wdd and $wdd and grep { $doc =~ /$_/ } @wdd) { &$wdd($doc) }
63
64 my $dir = untaint(getcwd());
65 chdir(dirname($doc));
66 http_output($doc,$seek,$stop);
67 chdir($dir);
68 }
69
70 sub http_output {
71 my ($file,$seek,$stop) = @_;
72 my ($filename,$files,$streamfile,$size,$total_size);
73 my ($data,$type);
74 my ($var,$env,$con);
75 my @files;
76 my $htmldoc = '';
77 my $htauth;
78 my @s;
79 my $s = 0;
80 my $b = 0;
81 my $http_client = $ENV{HTTP_USER_AGENT} || '';
82 local $_;
83
84 # extra security check: document must not be in lib or spool directory
85 if (path_match($file,$FEXLIB) or path_match($file,$spooldir)) {
86 http_error(403);
87 }
88
89 security_check($file);
90 $htauth = dirname($file).'/.htauth';
91 require_auth($htauth,$file) if -f $htauth;
92
93 if (-f $file) {
94 # normal file
95 open $file,'<',$file or http_error(400);
96 security_check($file);
97 } elsif ($file =~ /(.+)\.gz$/ and -f $1) {
98 @files = ($1);
99 open $file,'-|',qw'gzip -c',@files or http_error(503);
100 } elsif ($file =~ /(.+)\.tgz$/ and -f "$1.tar") {
101 @files = ("$1.tar");
102 open $file,'-|',qw'gzip -c',@files or http_error(503);
103 } elsif ($file =~ /(.+)\.(tar|tgz|zip)$/ and
104 @s = lstat($streamfile = "$1.stream") and
105 ($s[4] == $< or $s[4] == 0))
106 {
107 # streaming file
108 chdir dirname($file);
109 security_check($file);
110 if (-l $streamfile and readlink($streamfile) =~ /^:(.+):$/) {
111 # special symlink pointer file for streaming
112 @files = split(/:/,$1);
113 } elsif (open $streamfile,$streamfile) {
114 # special streaming file
115 while (<$streamfile>) {
116 next if /^#/;
117 chomp;
118 s/\s+$//;
119 if (/^(\/.*):/) {
120 chdir $1;
121 security_check($1);
122 } else {
123 push @files,$_;
124 }
125 }
126 } else {
127 http_error(503);
128 }
129 close $streamfile;
130 foreach (@files) {
131 if (/^\// or /\.\.\//) {
132 # absolute path or relative path with parent directory is not allowed
133 errorlog("$streamfile: $_ is not allowed for streaming");
134 http_error(403);
135 }
136 unless (-e $_) {
137 errorlog("$streamfile: $_ does not exist");
138 http_error(404);
139 }
140 if (@s = stat($_) and not($s[2] & S_IRGRP) or not -r $_) {
141 # file must be readable by user and group
142 errorlog("$streamfile: $_ is not readable by user and group");
143 http_error(403);
144 }
145 }
146 http_error(416) if $ENV{HTTP_RANGE};
147 close STDERR;
148 if ($file =~ /\.tar$/) { @a = qw'tar --exclude *~ --exclude .* -cf -' }
149 elsif ($file =~ /\.tgz$/) { @a = qw'tar --exclude *~ --exclude .* -czf -' }
150 elsif ($file =~ /\.zip$/) { @a = qw'zip -x *~ */.*/* @ -rq -' }
151 else { http_error(400) }
152 open $file,'-|',@a,@files or http_error(503);
153 } else {
154 http_error(404);
155 }
156
157 $type = 'application/octet-stream';
158 if ($file =~ /\.html$/i) { $type = 'text/html' }
159 # elsif ($file =~ /\.txt$/) { $type = 'text/plain' }
160 elsif ($file =~ /\.css$/) { $type = 'text/css' }
161 elsif ($file =~ /\.js$/) { $type = 'text/javascript' }
162 elsif ($file =~ /\.ps$/) { $type = 'application/postscript' }
163 elsif ($file =~ /\.pdf$/i) { $type = 'application/pdf' }
164 elsif ($file =~ /\.jpg$/i) { $type = 'image/jpeg' }
165 elsif ($file =~ /\.png$/i) { $type = 'image/png' }
166 elsif ($file =~ /\.gif$/i) { $type = 'image/gif' }
167 elsif ($file !~ /\.(tar|tgz|zip|jar|rar|arj|7z|bz2?|gz)$/) {
168 my $qfile = untaint(abs_path($file));
169 $qfile =~ s/([^\/\.\+\w!=,_-])/\\$1/g;
170 $_ = `file $qfile`;
171 if (0 and /HTML/) {
172 $type = 'text/html';
173 } elsif (/text/i and not -x $file) {
174 $type = 'text/plain';
175 if (/\sASCII\s/) { $type .= "; charset=us-ascii" }
176 elsif (/(ISO-[\w-]+)/) { $type .= "; charset=".lc($1) }
177 else { $type .= "; charset=utf-8" }
178 }
179 }
180
181 # show sourcecode if URL ends with '!'
182 # to avoid this for a HTML file, simple do a: chmod o-r file
183 if ($type eq 'text/html') {
184 if ($htmlsource) {
185 if (@s = stat($file) and $s[2] & S_IROTH) {
186 $type = 'text/plain';
187 } else {
188 http_error(403);
189 }
190 }
191 } elsif ($ENV{'QUERY_STRING'} eq '!') {
192 $type = 'text/plain';
193 }
194
195
196 if ($type eq 'text/html') {
197 $seek = $stop = 0;
198 local $^W = 0;
199 local $/;
200 $htmldoc = <$file>;
201 while ($htmldoc =~ s/\n##.*?\n/\n/) {};
202 if ($::hostname =~ /uni-stuttgart/) {
203 while ($htmldoc =~ s/\n.*sex.*\n/\n/i) {}
204 }
205 # evaluate #if ... #else ... #elseif ... #endif blocks
206 my $mark = randstring(16);
207 while ($htmldoc =~ s/\n(#if\s+(.+?)\n.+?\n)#endif/\n$mark/s) {
208 $_ = $1;
209 # if block
210 if (eval $2) {
211 s/#if.*\n//;
212 s/\n#else.*//s;
213 $htmldoc =~ s/$mark/$_/;
214 } else {
215 # elseif blocks
216 while (s/.*?\n#elseif\s+(.+?)\n//s) {
217 if (eval $1) {
218 s/\n#else.*//s;
219 $htmldoc =~ s/$mark/$_/;
220 }
221 }
222 # else block left?
223 if ($htmldoc =~ /$mark/) {
224 s/.*\n#else\s*\n//s or $_ = '';
225 $htmldoc =~ s/$mark/$_/;
226 }
227 }
228 };
229 # evaluate #include
230 while ($htmldoc =~ s/\n#include "(.*?)"/\n$mark/s) {
231 my $file = $1;
232 my $include = '';
233 if (open $file,$file) {
234 $include = <$file>;
235 close $file;
236 }
237 $dynamic = $htmldoc =~ s/$mark/$include/;
238 }
239 # evaluate <<perl-code>> or <<<perl-code>>>
240 {
241 local $timeout = '';
242 local $SIG{ALRM} = sub { $timeout = '<h3>TIMEOUT!</h3>' };
243 alarm(10);
244 while ($htmldoc =~ /<<(.+?>?)>>/s) {
245 local $pc = $1;
246 if ($pc =~ s/^<(.+)>$/$1/) {
247 # eval code without output substitution
248 eval('package DOP;' . $pc);
249 last if $timeout;
250 $dynamic = $htmldoc =~ s/<<<(.+?)>>>//s;
251 } else {
252 # eval code with output substitution
253 local $__ = '';
254 local $^W = 0;
255 tie *STDOUT => "Buffer",\$__;
256 my $r .= eval('package DOP;' . $pc);
257 $__ .= $r if $pc !~ /;\s*$/;
258 untie *STDOUT;
259 last if $timeout;
260 $dynamic = $htmldoc =~ s/<<(.+?)>>/$__/s;
261 }
262 }
263 alarm(0);
264 $dynamic = $htmldoc =~ s/<<(.+?>?)>>/$timeout/sg if $timeout;
265 }
266 # substitute $variable$ with value from environment (if present)
267 while ($htmldoc =~ /\$([\w_]+)\$/g) {
268 $var = $1;
269 if (defined($env = $ENV{$var})) {
270 $htmldoc =~ s/\$$var\$/$env/g;
271 }
272 };
273 $total_size = $size = $s = length($htmldoc);
274 } else {
275 if (@files) {
276 $size = 0;
277 } else {
278 $total_size = -s $file || 0;
279 $size = $total_size - $seek - ($stop ? $total_size-$stop-1 : 0);
280 }
281 }
282
283 if ($size < 0) {
284 http_header('416 Requested Range Not Satisfiable');
285 exit;
286 }
287
288 alarm($timeout*10);
289
290 if ($seek or $stop) {
291 my $range;
292 if ($stop) {
293 $range = sprintf("bytes %s-%s/%s",$seek,$stop,$total_size);
294 } else {
295 $range = sprintf("bytes %s-%s/%s",$seek,$total_size-1,$total_size);
296 }
297 nvt_print(
298 'HTTP/1.1 206 Partial Content',
299 'Server: fexsrv',
300 "Content-Length: $size",
301 "Content-Range: $range",
302 "Content-Type: $type",
303 );
304 } else {
305 # streaming?
306 if (@files) {
307 nvt_print(
308 'HTTP/1.1 200 OK',
309 'Server: fexsrv',
310 "Expires: 0",
311 "Content-Type: $type",
312 );
313 } else {
314 # Java (clients) needs Last-Modified header!
315 # if there are locale versions, use actual time for Last-Modified
316 # to enforce reload of page
317 $file =~ m{/htdocs/(.+)};
318 my @lfiles = glob("$FEXHOME/locale/*/htdocs/$1");
319 my $date = ($dynamic or @lfiles > 1) ?
320 strftime("%a, %d %b %Y %T GMT",gmtime(time)) :
321 http_date($file);
322 nvt_print(
323 'HTTP/1.1 200 OK',
324 'Server: fexsrv',
325 "Last-Modified: $date",
326 "Expires: 0",
327 "Content-Length: $size",
328 "Content-Type: $type",
329 );
330 # nvt_print("Set-Cookie: locale=$locale") if $use_cookies and $locale;
331 }
332 }
333 nvt_print($_) foreach(@extra_header);
334 nvt_print('');
335
336 if ($ENV{REQUEST_METHOD} eq 'GET') {
337 if ($type eq 'text/html') {
338 alarm($timeout*10);
339 print $htmldoc;
340 $s = $size;
341 } elsif ($type =~ /^text/) {
342 while (<$file>) {
343 if (%censor) {
344 foreach my $rx (keys %censor) {
345 s/$rx/$censor{$rx}/g;
346 }
347 }
348 alarm($timeout);
349 print or last;
350 alarm(0);
351 }
352 } else {
353 # binary data # can be stream!
354 seek $file,$seek,0 if $seek;
355 while ($b = read($file,$data,$bs)) {
356 if ($stop and $s+$b > $size) {
357 $b = $size-$s;
358 $data = substr($data,0,$b)
359 }
360 $s += $b;
361 alarm($timeout*10);
362 print $data or last;
363 }
364 }
365 fdlog($log,$file,$s,$size) if $s;
366 }
367
368 alarm(0);
369 close $file;
370 exit if @files; # streaming end
371 return $s;
372 }
373
374
375 # show directory index
376 sub showindex {
377 my $dir = shift;
378 my ($htmldoc,$size);
379 my @links = ();
380 my @dirs = ();
381 my @files = ();
382 my $uri = $ENV{REQUEST_URI};
383 my $allowed;
384 my ($htindex,$htauth);
385 local $_;
386
387 $uri =~ s:/+$::;
388 $dir =~ s:/+$::;
389
390 security_check($dir);
391
392 $htindex = "$dir/.htindex";
393 $htauth = "$dir/.htauth";
394
395 open $htindex,$htindex or http_error(403);
396 require_auth($htauth,$dir) if -f $htauth;
397
398 # .htindex may contain listing regexp
399 chomp ($allowed = <$htindex>||'.');
400 close $htindex;
401
402 opendir $dir,$dir or http_error(503);
403 while (defined($_ = readdir $dir)) {
404 next if /^[.#]/ or /~$/;
405 if (@s = lstat "$dir/$_" and ($s[2] & (S_IRGRP|S_IROTH))) {
406 if (-l _) { push @links,$_ }
407 elsif (-d _) { push @dirs,$_ }
408 elsif (-f _) { push @files,$_ }
409 }
410 }
411 closedir $dir;
412
413 # parent directory listable?
414 if ($uri =~ m:(/.+)/.+: and -f "$dir/../.htindex") {
415 unshift @dirs,$1;
416 }
417
418 # first the (sub)directories
419 $htmldoc = "<HTML>\n<h1>$uri/</h1>\n";
420 foreach my $d (sort @dirs) {
421 my $du = urlencode($d);
422 my $dh = htmlencode($d);
423 if ($d =~ m:^/: and -f "$d/.htindex") {
424 $htmldoc .= "<b><a href=\"$du/\">$dh/</a></b><br>\n";
425 } elsif (-f "$dir/$d/.htindex") {
426 $htmldoc .= "<b><a href=\"$uri/$du/\">$uri/$dh/</a></b><br>\n";
427 }
428 }
429
430 # # then the symlinks
431 # $htmldoc .= "\n<pre>\n";
432 # my $link;
433 # foreach my $l (sort @links) {
434 # if ($l =~ /$allowed/ and $link = readlink "$dir/$l" and $link =~ /^[^.\/]/) {
435 # $htmldoc .= "$l -> <a href=\"$link\">$dir/$link</a>\n";
436 # }
437 # }
438
439 # then the files
440 $htmldoc .= "\n<pre>\n";
441 foreach my $f (sort @files) {
442 if ($f =~ /$allowed/) {
443 $htmldoc .= sprintf "%20s %20s <a href=\"%s/%s\">%s</a>\n",
444 isodate(mtime("$dir/$f")),
445 d3(-s "$dir/$f"||0),
446 $uri,urlencode($f),htmlencode($f);
447 }
448 }
449 $htmldoc .= "</pre>\n</HTML>\n";
450
451 $size = length($htmldoc);
452 nvt_print(
453 'HTTP/1.1 200 OK',
454 'Server: fexsrv',
455 "Content-Length: $size",
456 "Content-Type: text/html",
457 '',
458 );
459 print $htmldoc;
460 fdlog($log,"$dir/",$size,$size);
461 }
462
463
464 sub d3 {
465 local $_ = shift;
466 while (s/(\d)(\d\d\d\b)/$1,$2/) {};
467 return $_;
468 }
469
470
471 sub http_date {
472 my $file = shift;
473 my @stat;
474
475 if (@stat = stat($file)) {
476 return strftime("%a, %d %b %Y %T GMT",gmtime($stat[9]));
477 } else {
478 return 0;
479 }
480 }
481
482
483 sub path_match {
484 my $p1 = abs_path(shift);
485 my $p2 = abs_path(shift);
486
487 if (defined $p1 and defined $p2) {
488 return 1 if $p1 =~ /^\Q$p2/;
489 return 2 if dirname($p1) =~ /^\Q$p2/;
490 }
491 return 0;
492 }
493
494
495 # return real file name (from symlink)
496 sub realfilename {
497 my $file = shift;
498
499 return '' unless -e $file;
500
501 if (-l $file) {
502 return realfilename(readlink($file));
503 } else {
504 return $file;
505 }
506 }
507
508
509 sub security_check {
510 my $file = shift; # can be directory, too!
511 my $afile = abs_path($file)||$file;
512 my @s;
513
514 # client ip allowed?
515 access_check($file);
516
517 # documents with leading . are not allowed, but RFC5785 is accepted
518 if ($afile =~ /\/\./ and $afile !~ m:/.well-known/acme-challenge/:) {
519 errorlog("$afile with leading . in path");
520 http_error(403);
521 }
522
523 if (-f $file) {
524
525 # document filename must not contain @
526 if (realfilename($file) =~ /@/ or $afile =~ /@/) {
527 errorlog("$file contains @");
528 http_error(403);
529 }
530
531 # document filename must not end with ~
532 if (realfilename($file) =~ /~$/) {
533 errorlog("$file ends with ~");
534 http_error(403);
535 }
536
537 # file must be group or world readable
538 if (@s = stat($file) and not($s[2] & (S_IRGRP|S_IROTH))) {
539 errorlog("$file not group or world readable");
540 http_error(403);
541 }
542
543 # symlink to regular file and symlink owned by root or fex? ==> ok!
544 if (-l $file and path_match(dirname($file),$docdir)) {
545 @s = lstat($file);
546 return if $s[4] == 0 or $s[4] == $<;
547 }
548
549 }
550
551 # file in allowed directory? ==> ok!
552 foreach my $dir (@doc_dirs) {
553 return if path_match($file,$dir);
554 }
555
556 errorlog("$file not in \@doc_dirs");
557 http_error(403);
558 }
559
560 # security check: client ip allowed?
561 sub access_check {
562 my $file = abs_path(shift);
563 my $dir = $file;
564 my $af;
565 local $_;
566
567 $dir .= '/x' if -d $dir;
568
569 while ($dir = dirname($dir) and $dir ne '/') {
570 $af = "$dir/.htaccessfrom";
571 if (open $af,$af) {
572 while (<$af>) {
573 s/\s//g;
574 if (ipin($ra,$_)) {
575 close $af;
576 return;
577 }
578 }
579 errorlog("no access to $file by $af");
580 http_error(403);
581 }
582 }
583
584 }
585
586 # HTTP Basic authentication
587 sub require_auth {
588 my $htauth = shift;
589 my $doc = shift;
590 my ($realm,$auth);
591 my @http_auth;
592 my $uri = $ENV{REQUEST_URI} || '/';
593
594 $uri =~ s/\/index\.html$//;
595 $uri =~ s/\/$//;
596
597 if (-d $doc or $doc =~ /\/index\.html$/) {
598 $realm = $uri;
599 } else {
600 $realm = dirname($uri);
601 }
602
603 $auth = slurp($htauth);
604 unless ($auth and $realm) {
605 http_header("200 OK");
606 print html_header("$ENV{SERVER_NAME} no authentication");
607 pq(qq(
608 '<h3><code>$htauth</code> missing</h3>'
609 '</body></html>'
610 ));
611 exit;
612 }
613 chomp $auth;
614
615 if ($ENV{HTTP_AUTHORIZATION} and $ENV{HTTP_AUTHORIZATION} =~ /Basic\s+(.+)/)
616 { @http_auth = split(':',decode_b64($1)) }
617 if (@http_auth != 2 or $http_auth[1] ne $auth) {
618 http_header(
619 '401 Authorization Required',
620 "WWW-Authenticate: Basic realm=\"$realm\"",
621 'Content-Length: 0',
622 );
623 # control back to fexsrv for further HTTP handling
624 &reexec;
625 }
626 }
627
628
629 # function for <<perl-code>> inside HTML documents
630 sub out {
631 $__ .= join('',@_);
632 return '';
633 }
634
635 # tie STDOUT to buffer variable (redefining print and printf)
636 package Buffer;
637
638 sub TIEHANDLE {
639 my ($class,$buffer) = @_;
640 bless $buffer,$class;
641 }
642
643 sub PRINT {
644 my $buffer = shift;
645 $$buffer .= $_ foreach @_;
646 }
647
648 sub PRINTF {
649 my $buffer = shift;
650 my $fmt = shift @_;
651 $$buffer .= sprintf($fmt,@_);
652 }
653
654 1;