Debian Codegraph @

lib/fex.pp

raw
1 # -*- perl -*-
2
3 use 5.010;
4 # use utf8;
5 use Encode;
6 use Symbol qw(gensym);
7 use Cwd qw(abs_path);
8 use Fcntl qw(:flock :seek :mode);
9 use IO::Handle;
10 use IPC::Open3;
11 use Digest::MD5 qw(md5_hex);
12 # use Digest::SHA qw(hmac_sha512 hmac_sha512_base64);
13 use File::Basename;
14 use Sys::Hostname;
15 use Scalar::Util qw(tainted);
16
17 # set and untaint ENV if not in CLI (fexsrv provides clean ENV)
18 unless (-t) {
19 foreach my $v (keys %ENV) {
20 ($ENV{$v}) = ($ENV{$v} =~ /(.*)/s) if defined $ENV{$v};
21 }
22 $ENV{PATH} = $ENV{HOME}.'/bin:/usr/local/bin:/bin:/usr/bin';
23 $ENV{IFS} = " \t\n";
24 $ENV{BASH_ENV} = '';
25 }
26
27 unless ($FEXLIB = $ENV{FEXLIB} and -d $FEXLIB) {
28 die "$0: found no FEXLIB - fexsrv needs full path\n"
29 }
30
31 $FEXLIB =~ s:/+:/:g;
32 $FEXLIB =~ s:/$::;
33
34 # $FEXHOME is top-level directory of F*EX installation or vhost
35 # $ENV{HOME} is login-directory of user fex
36 # in default-installation both are equal, but they may differ
37 $FEXHOME = $ENV{FEXHOME} or $ENV{FEXHOME} = $FEXHOME = dirname($FEXLIB);
38 $RA = $ENV{REMOTE_ADDR} || 0;
39
40 umask 0077;
41
42 $| = 1;
43 binmode(STDOUT,':raw');
44 binmode(STDIN,':raw');
45
46 # defaults
47 $hostname = gethostname();
48 $tmpdir = $ENV{TMPDIR} || '/var/tmp';
49 $spooldir = $FEXHOME.'/spool';
50 $docdir = $FEXHOME.'/htdocs';
51 $logdir = $spooldir;
52 $autodelete = 'YES';
53 $overwrite = 'YES';
54 $limited_download = 'YES'; # multiple downloads only from same client
55 $fex_yourself = 'YES'; # allow SENDER = RECIPIENT
56 $keep_default = 5; # days
57 $keep_max = 99;
58 $recipient_quota = 0; # MB
59 $sender_quota = 0; # MB
60 $timeout = 30; # seconds
61 $bs = 2**16; # I/O blocksize (64 kB)
62 $DS = 60*60*24; # seconds in a day
63 $MB = 1024*1024; # binary Mega
64 $vp = '\d{8}_\d{6}'; # date_time version pattern # should be: $vrx
65 $arx = 'tar|tgz|zip|7z|gz'; # archive container regexp
66 $mrx = '[\w!^=~#_:.*+-]+\@\w[\w.-]*\.[a-zA-Z]+'; # mail regexp
67 $sendmail = '/usr/lib/sendmail';
68 $sendmail = '/usr/sbin/sendmail' unless -x $sendmail;
69 $mailmode = 'auto';
70 $bcc = 'fex';
71 $default_locale = '';
72 $charset = 'UTF-8';
73 $fop_auth = 0;
74 $mail_authid = 'YES';
75 $archive_sharing = 'NO';
76 $document_exchange = 'NO';
77 $fex_sender = 'NO';
78 $share_logging = 1;
79 $force_https = 0;
80 $debug = 0;
81 ## $enforce_EUCD = 'NO';
82 @forbidden_user_agents = ('FDM');
83
84 # https://securityheaders.io/
85 # https://scotthelme.co.uk/hardening-your-http-response-headers/
86 # https://scotthelme.co.uk/a-new-security-header-referrer-policy/
87 # http://content-security-policy.com/
88 @extra_header = (
89 # "Content-Security-Policy: sandbox allow-forms allow-scripts",
90 "Content-Security-Policy: script-src 'self' 'unsafe-inline'",
91 "Referrer-Policy: origin-when-cross-origin",
92 "X-Frame-Options: SAMEORIGIN",
93 "X-XSS-Protection: 1; mode=block",
94 "X-Content-Type-Options: nosniff",
95 );
96 push @extra_header,'X-Epoch: '.time();
97
98 $style = slurp("$FEXLIB/style.css") || qqq(qq(
99 'ul {'
100 ' list-style: disc outside none;'
101 ' padding: 0px 0px 0px 15px;'
102 ' margin: 0;'
103 '}'
104 'table {'
105 ' border-collapse: collapse;'
106 '}'
107 'table, th, td {'
108 # ' border-width: 1px;'
109 # ' border-color: black;'
110 # ' border-style: solid;'
111 # ' border: 1px solid black;'
112 ' padding: 3px;'
113 '}'
114 ));
115
116 $FHS = -f '/etc/fex/fex.ph' and -d '/usr/share/fex/lib';
117 # Debian FHS
118 if ($FHS) {
119 $ENV{FEXHOME} = $FEXHOME = '/usr/share/fex';
120 $spooldir = '/var/spool/fex';
121 $logdir = '/var/log/fex';
122 $docdir = '/var/lib/fex/htdocs';
123 $notify_newrelease = '';
124 }
125
126 # allowed download managers (HTTP User-Agent)
127 $adlm = '^(Axel|fex)';
128
129 # local config
130 require "$FEXLIB/fex.ph" or die "$0: cannot load $FEXLIB/fex.ph - $!";
131
132 $ENV{FEXSERVER} = $hostname;
133
134 $keep_default = $keep if $keep; # backward compatibilty to older fex.ph
135 ## $enforce_EUCD = 0 if $enforce_EUCD !~ /y/i;
136
137 chdir $spooldir or die "$spooldir - $!\n";
138
139 $fop_auth = 0 if $fop_auth =~ /no/i;
140 $mail_authid = 0 if $mail_authid =~ /no/i;
141 $force_https = 0 if $force_https =~ /no/i;
142 $debug = 0 if $debug =~ /no/i;
143 $archive_sharing = 0 if $archive_sharing =~ /no/i;
144 $document_exchange = 0 if $document_exchange =~ /no/i;
145 $share_logging = 0 if $share_logging =~ /no/i;
146 $fex_sender = 0 if $fex_sender =~ /no/i;
147
148 @logdir = ($logdir) unless @logdir;
149 $logdir = $logdir[0];
150
151 # allowed multi download recipients: from any ip, any times
152 if (@mailing_lists) {
153 $amdl = '^('.join('|',map { quotewild($_) } @mailing_lists).')$';
154 } else {
155 $amdl = '^-$';
156 }
157
158 # check for name based virtual host
159 $vhost = vhost($ENV{'HTTP_HOST'});
160
161 $RB = 0; # read POST bytes
162
163 push @doc_dirs,$docdir;
164 foreach my $ld (glob "$FEXHOME/locale/*/htdocs") {
165 push @doc_dirs,$ld;
166 }
167
168 $nomail = ($mailmode =~ /^MANUAL|nomail$/i);
169
170 if (not $nomail and not -x $sendmail) {
171 http_die("found no sendmail");
172 }
173 http_die("cannot determine the server hostname") unless $hostname;
174
175 $ENV{PROTO} = 'http' unless $ENV{PROTO};
176 $keep = $keep_default ||= $keep || 5;
177 $purge ||= 3*$keep;
178 $fra = $ENV{REMOTE_ADDR} || '';
179 $sid = $ENV{SID} || '';
180
181 $dkeydir = "$spooldir/.dkeys"; # download keys
182 $ukeydir = "$spooldir/.ukeys"; # upload keys
183 $akeydir = "$spooldir/.akeys"; # authentification keys
184 $skeydir = "$spooldir/.skeys"; # subuser authentification keys
185 $gkeydir = "$spooldir/.gkeys"; # group authentification keys
186 $xkeydir = "$spooldir/.xkeys"; # extra download keys
187 $lockdir = "$spooldir/.locks"; # download lock files
188
189 unless (-d $akeydir) {
190 mkdir $akeydir or http_die("$akeydir - $!");
191 }
192
193 if ($RA and $max_fail) {
194 mkdirp("$spooldir/.fail");
195 $faillog = "$spooldir/.fail/$RA";
196 }
197
198 # $ENV{SERVER_ADMIN} may be set empty in fex.ph!
199 $admin ||= $ENV{SERVER_ADMIN} || 'fex@'.$hostname;
200 $ENV{SERVER_ADMIN} ||= $admin;
201
202 $mdomain ||= '';
203
204 if (my $cookie = $ENV{HTTP_COOKIE}) {
205 if ($cookie =~ /\bakey=(\w+)/ and -f "$akeydir/$1/@") {
206 $akey = $1;
207 }
208 }
209
210 if (@locales) {
211 if ($default_locale and not grep /^$default_locale$/,@locales) {
212 push @locales,$default_locale;
213 }
214 if (@locales == 1) {
215 $default_locale = $locales[0];
216 }
217 }
218
219 $default_locale ||= 'english';
220
221 # $durl is first default fop download URL
222 # @durl is optional mandatory fop download URL list (from fex.ph)
223 unless ($durl) {
224 my $host = '';
225 my $port = 80;
226 my $xinetd = '/etc/xinetd.d/fex';
227
228 if (@durl) {
229 if ($ENV{PROTO} eq 'https') {
230 ($durl) = grep /https:/,@durl;
231 } else {
232 $durl = $durl[0];
233 }
234 } elsif ($ENV{HTTP_HOST} and $ENV{PROTO}) {
235
236 ($host,$port) = split(':',$ENV{HTTP_HOST}||'');
237 $host = $hostname;
238
239 unless ($port) {
240 $port = 80;
241 if (open $xinetd,$xinetd) {
242 while (<$xinetd>) {
243 if (/^\s*port\s*=\s*(\d+)/) {
244 $port = $1;
245 last;
246 }
247 }
248 close $xinetd;
249 }
250 }
251
252 # use same protocal as uploader for download
253 if ($ENV{PROTO} eq 'https' and $port == 443 or $port == 80) {
254 $durl = "$ENV{PROTO}://$host/fop";
255 } else {
256 $durl = "$ENV{PROTO}://$host:$port/fop";
257 }
258 } else {
259 if (open $xinetd,$xinetd) {
260 while (<$xinetd>) {
261 if (/^\s*port\s*=\s*(\d+)/) {
262 $port = $1;
263 last;
264 }
265 }
266 close $xinetd;
267 }
268 if ($port == 80) {
269 $durl = "http://$hostname/fop";
270 } else {
271 $durl = "http://$hostname:$port/fop";
272 }
273 }
274 }
275 @durl = ($durl) unless @durl;
276
277
278 sub reexec {
279 exec($FEXHOME.'/bin/fexsrv') if $ENV{KEEP_ALIVE};
280 exit;
281 }
282
283
284 sub jsredirect {
285 $url = shift;
286 $cont = shift || 'request accepted: continue';
287
288 http_header('200 ok');
289 print html_header($head||$ENV{SERVER_NAME});
290 pq(qq(
291 '<script type="text/javascript">'
292 ' window.location.replace("$url");'
293 '</script>'
294 '<noscript>'
295 ' <h3><a href="$url">$cont</a></h3>'
296 '</noscript>'
297 '</body></html>'
298 ));
299 &reexec;
300 }
301
302
303 sub debug {
304 print header(),"<pre>\n";
305 print "file = $file\n";
306 foreach $v (keys %ENV) {
307 print $v,' = "',$ENV{$v},"\"\n";
308 }
309 print "</pre><p>\n";
310 }
311
312
313 sub ssplit {
314 local $_ = "@_";
315 return split;
316 };
317
318
319 sub nvt_print {
320 local $_;
321 foreach (@_) {
322 my $x = $_;
323 $x = encode_utf8($x) if utf8::is_utf8($x);
324 syswrite STDOUT,"$x\r\n";
325 }
326 }
327
328
329 sub http_header {
330
331 my $status = shift;
332 my $msg = $status;
333
334 return if $HTTP_HEADER;
335 $HTTP_HEADER = $status;
336
337 $msg =~ s/^\d+\s*//;
338
339 nvt_print("HTTP/1.1 $status");
340 nvt_print("X-Message: $msg");
341 # nvt_print("X-SID: $ENV{SID}") if $ENV{SID};
342 nvt_print("Server: fexsrv");
343 nvt_print("Expires: 0");
344 nvt_print("Cache-Control: no-cache");
345 if ($force_https) {
346 # https://www.owasp.org/index.php/HTTP_Strict_Transport_Security
347 # https://scotthelme.co.uk/hsts-the-missing-link-in-tls/
348 nvt_print("Strict-Transport-Security: max-age=2851200; preload");
349 }
350 nvt_print($_) foreach(@extra_header);
351 if ($from and $id and not $akey and my $rid = readline1("$from/@")) {
352 $akey = genakey($from) if $id eq $rid;
353 }
354 if ($akey and -l "$akeydir/$akey") {
355 my $login = basename(readlink("$akeydir/$akey"));
356 nvt_print("Set-Cookie: akey=$akey; path=/; Max-Age=44444; Discard");
357 nvt_print("Set-Cookie: login=$login; path=/");
358 }
359 # if ($skey) {
360 # nvt_print("Set-Cookie: skey=$skey; Max-Age=9999; Discard");
361 # }
362 if ($locale) {
363 nvt_print("Set-Cookie: locale=$locale");
364 }
365 unless (grep /^Content-Type:/i,@_) {
366 # nvt_print("Content-Type: text/html; charset=ISO-8859-1");
367 nvt_print("Content-Type: text/html; charset=$charset");
368 }
369
370 nvt_print(@_,'');
371 }
372
373
374 sub html_header {
375 my $title = shift;
376 my $header = 'header.html';
377 my $fua = $ENV{HTTP_USER_AGENT}||'';
378 my $head;
379 my $h1;
380
381 # binmode(STDOUT,':utf8'); # for text/html !
382
383 $h1 = $title;
384 $title =~ s/<.*?>//g;
385 $style =~ s/\n+$//;
386
387 # http://www.w3.org/TR/html401/struct/global.html
388 # http://www.w3.org/International/O-charset
389 if ($fua =~ /^fex/) {
390 $head = "<html><body>\n";
391 } else {
392 $head = qqq(qq(
393 '<html>'
394 '<head>'
395 ' <meta http-equiv="expires" content="0">'
396 ' <meta http-equiv="Content-Type" content="text/html;charset=$charset">'
397 ' <title>$title</title>'
398 '</head>'
399 '<style>'
400 '$style'
401 '</style>'
402 ));
403 # '<!-- <style type="text/css">\@import "/fex.css";</style> -->'
404
405 if ($0 =~ /fexdev/) { $head .= "<body bgcolor=\"pink\">\n" }
406 else { $head .= "<body>\n" }
407
408 $h1 =~ s:F\*EX:<a href="/index.html">F*EX</a>:;
409
410 if (open $header,'<',"$docdir/$header") {
411 $head .= $_ while <$header>;
412 close $header;
413 }
414
415 $head .= &$prolog($title) if defined($prolog);
416
417 if (@H1_extra) {
418 $head .= sprintf(
419 qq'<h1><a href="%s"><img align=center src="%s" border=0></a>%s</h1>\n',
420 $H1_extra[0],$H1_extra[1]||'',$h1
421 );
422 } else {
423 $head .= "<h1>$h1</h1>\n";
424 }
425
426 $head .= qqq(qq(
427 '<font color="red">'
428 '<h2 id="jswarning">PLEASE ENABLE JAVASCRIPT TO USE THIS SERVICE</h2>'
429 '</font>'
430 '<script>'
431 'document.getElementById("jswarning").innerHTML = "";'
432 '</script>'
433 ''
434 ));
435 }
436
437 # Safari does not show popups (javascript window.open)
438 # if (($ENV{HTTP_USER_AGENT}||'') =~ /Apple.*Safari/) {
439 # $head .= qqq(qq(
440 # '<font color="orange">'
441 # '<h2>Your webbrowser (Safari) is not supported</h2>'
442 # '</font>'
443 # ));
444 # }
445
446 return $head;
447 }
448
449
450 sub http_error {
451 my $error = shift;
452 my $msg = shift;
453 my $URL = $ENV{REQUEST_URL}||'';
454 my $URI = $ENV{REQUEST_URI}||'';
455 my $isodate = isodate(time);
456
457 $URI =~ s/\?.*//;
458
459 if ($error eq 400) {
460 http_error_header("400 Bad Request");
461 nvt_print("Your request $URL is not acceptable.");
462 } elsif ($error eq 403) {
463 http_error_header("403 Forbidden");
464 if ($msg) {
465 nvt_print($msg);
466 } else {
467 nvt_print("You have no permission to request $URL");
468 }
469 } elsif ($error eq 404) {
470 http_error_header("404 Not Found");
471 nvt_print("The requested URI $URI was not found on this server.");
472 } elsif ($error eq 413) {
473 http_error_header("413 Payload Too Large");
474 nvt_print("Your HTTP header is too large.");
475 } elsif ($error eq 416) {
476 http_error_header("416 Requested Range Not Satisfiable");
477 } elsif ($error eq 503) {
478 http_error_header("503 Service Unavailable");
479 # nvt_print("No Perl ipv6 support on this server.");
480 } else {
481 http_error_header("555 Unknown Error");
482 nvt_print("The requested URL $URL produced an internal error.");
483 }
484 pq(qq(
485 '<p><hr><p>'
486 '$isodate<br>'
487 '$ENV{HTTP_HOST}<p>'
488 '<address>'
489 ' <a href="mailto:$admin">$admin</a>'
490 '</address>'
491 '</body></html>'
492 ));
493 exit;
494 }
495
496
497 sub http_error_header {
498 my $error = shift;
499 my $uri = $ENV{REQUEST_URI};
500
501 errorlog("$uri ==> $error") if $uri;
502 nvt_print(
503 "HTTP/1.1 $error",
504 "Connection: close",
505 "Content-Type: text/html; charset=iso-8859-1",
506 "",
507 '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">',
508 "<html>",
509 "<head><title>$error</title></head>",
510 "<body>",
511 "<h1>$error</h1>",
512 );
513 }
514
515
516 sub html_error {
517 my $error = shift;
518 my $msg = "@_";
519 my @msg = @_;
520 my $isodate = isodate(time);
521 local $_;
522
523 $x = encode_utf8($msg) if utf8::is_utf8($msg);
524 $msg =~ s/[\s\n]+/ /g;
525 $msg =~ s/<.+?>//g; # remove HTML
526 foreach (@msg) {
527 $_ = encode_utf8($_) if utf8::is_utf8($_);
528 s/<script.*?>//gi;
529 }
530
531 errorlog($msg);
532
533 $SIG{ALRM} = sub {
534 $SIG{__DIE__} = 'DEFAULT';
535 die "TIMEOUT\n";
536 };
537 alarm($timeout);
538
539 # cannot send standard HTTP Status-Code 400, because stupid
540 # Internet Explorer then refuses to display HTML body!
541 http_header("666 Bad Request - $msg");
542 print html_header($error);
543 print 'ERROR: ',join("<p>\n",@msg),"\n";
544 pq(qq(
545 '<p><hr><p>'
546 '$isodate<br>'
547 '$ENV{HTTP_HOST}<p>'
548 '<address>'
549 ' <a href="mailto:$admin">$admin</a>'
550 '</address>'
551 '</body></html>'
552 ));
553 exit;
554 }
555
556
557 sub http_die {
558
559 # not in CGI mode
560 unless ($ENV{GATEWAY_INTERFACE}) {
561 warn "$0: @_\n"; # must not die, because of fex_cleanup!
562 return;
563 }
564
565 debuglog("die: @_");
566
567 # create special error file on upload
568 if ($uid) {
569 my $ukey = "$spooldir/.ukeys/$uid";
570 $ukey .= "/error" if -d $ukey;
571 unlink $ukey;
572 if (open $ukey,'>',$ukey) {
573 print {$ukey} join("\n",@_),"\n";
574 close $ukey;
575 }
576 }
577
578 html_error($error||'',@_);
579 }
580
581
582 sub check_maint {
583 if (my $status = readlink '@MAINTENANCE') {
584 my $isodate = isodate(time);
585 http_header('666 MAINTENANCE');
586 print html_header($head||'');
587 pq(qq(
588 "<center>"
589 "<h1>Server is in maintenance mode</h1>"
590 "<h3>($status)</h3>"
591 "</center>"
592 "<p><hr><p>"
593 "<address>"
594 "Contact: $admin<br>"
595 "$ENV{HTTP_HOST} $isodate"
596 "</address>"
597 "</body></html>"
598 ));
599 exit;
600 }
601 }
602
603
604 sub check_status {
605 my $user = shift;
606
607 $user = lc $user;
608 $user .= '@'.$mdomain if $mdomain and $user !~ /@/;
609
610 if (my $disabled = slurp("$user/\@DISABLED")) {
611 if ($disabled =~ s/^!//) {
612 $disabled = "$user is disabled: $disabled";
613 } else {
614 $disabled = "$user is disabled";
615 }
616 my $isodate = isodate(time);
617 http_header('666 DISABLED');
618 print html_header($head);
619 pq(qq(
620 "<h3>$disabled</h3>"
621 "Contact $admin for details"
622 "<p><hr><p>"
623 "<address>$ENV{HTTP_HOST} $isodate</address>"
624 "</body></html>"
625 ));
626 exit;
627 }
628 }
629
630
631 sub isodate {
632 my $time = shift;
633 my $isodate = '????-??-?? ??:??:??';
634
635 if ($time) {
636 my @d = localtime $time;
637 $isodate = sprintf('%d-%02d-%02d %02d:%02d:%02d',
638 $d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0]);
639 }
640
641 return $isodate;
642 }
643
644
645
646 sub genakey {
647 my $user = shift;
648 my $fua = $ENV{HTTP_USER_AGENT}||'';
649 my $akey;
650
651 $akey = $ENV{AKEY} || randstring(16);
652 if ($fua !~ /^fex/) {
653 unlink "$akeydir/$akey";
654 symlink "../$user","$akeydir/$akey";
655 }
656 return $akey;
657 }
658
659
660 sub encode_Q {
661 my $s = shift;
662 $s =~ s{([\=\x00-\x20\x7F-\xA0])}{sprintf("=%02X",ord($1))}eog;
663 return $s;
664 }
665
666
667 # from MIME::Base64::Perl
668 sub decode_b64 {
669 local $_ = shift;
670 my $uu = '';
671 my ($i,$l);
672
673 tr|A-Za-z0-9+=/||cd;
674 s/=+$//;
675 tr|A-Za-z0-9+/| -_|;
676 return '' unless length;
677 $l = (length)-60;
678 for ($i = 0; $i <= $l; $i += 60) {
679 $uu .= "M" . substr($_,$i,60);
680 }
681 $_ = substr($_,$i);
682 $uu .= chr(32+(length)*3/4) . $_ if $_;
683 return unpack ("u",$uu);
684 }
685
686
687 # short base64 encoding
688 sub b64 {
689 local $_ = '';
690 my $x = 0;
691
692 pos($_[0]) = 0;
693 $_ = join '',map(pack('u',$_)=~ /^.(\S*)/, ($_[0]=~/(.{1,45})/gs));
694 tr|\` -_|AA-Za-z0-9+/|;
695 $x = (3 - length($_[0]) % 3) % 3;
696 s/.{$x}$//;
697
698 return $_;
699 }
700
701
702 # a secure "rm -rf":
703 # never remove '.' or '..'
704 # restricted to $spooldir
705 # returns number of deleted objects
706 sub rmrf {
707 my @files = @_;
708 my @caller;
709 my $spool = untaint(abs_path($spooldir));
710 my ($file,$dir);
711 my $n = 0;
712 local $_;
713
714 @caller = caller(1) or @caller = caller;
715
716 foreach $file (@files) {
717 next unless lstat $file;
718 my $afile = abs_path($file)||'';
719 if ($file =~ m:^/: and $afile !~ m:^\Q$spool/: or
720 $afile eq $spool or "/$file/" =~ m:\Q/../:)
721 {
722 http_die(
723 sprintf "rmrf() called by %s::%s() line %s with illegal '%s'",
724 $caller[1],$caller[3]||'',$caller[2],$file
725 );
726 }
727 if (tainted($file)) {
728 http_die(
729 sprintf "rmrf() called by %s::%s() line %s with tainted '%s'",
730 $caller[1],$caller[3]||'',$caller[2],$file
731 );
732 }
733 }
734
735 foreach $file (@files) {
736 if (lstat $file) {
737 system qw'rm -rf',$file;
738 $n++ unless lstat $file;
739 }
740 }
741
742 return $n;
743 }
744
745 ## does not work because of UTF8 vs ISO-Latin filenames :-(
746 # sub rmrf {
747 # my @files = @_;
748 # my $dels = 0;
749 # my @caller = caller(0);
750 # my $spool = untaint(abs_path($spooldir));
751 # my ($file,$dir);
752 # local $_;
753 #
754 # foreach $file (@files) {
755 # next unless lstat $file;
756 # my $afile = abs_path($file)||'';
757 # if ($file =~ m:^/: and $afile !~ m:^\Q$spool/:
758 # or $afile eq $spool or "/$file/" =~ m:\Q/../:)
759 # {
760 # http_die(
761 # sprintf "rmrf() called by %s::%s() line %s with illegal '%s'",
762 # $caller[1],$caller[3],$caller[2],$file
763 # );
764 # }
765 # if (tainted($file)) {
766 # http_die(
767 # sprintf "rmrf() called by %s::%s() line %s with tainted '%s'",
768 # $caller[1],$caller[3],$caller[2],$file
769 # );
770 # }
771 # if (-d $file and not -l $file) {
772 # $dir = $file;
773 # opendir $dir,$dir or next;
774 # while (defined(my $file = readdir $dir)) {
775 # next if $file eq '.' or $file eq '..';
776 # if ($charset =~ /utf/i) {
777 # $file = untaint(decode_utf8($file));
778 # } else {
779 # $file = untaint($file);
780 # }
781 # $dels += rmrf("$dir/$file");
782 # }
783 # closedir $dir;
784 # rmdir $dir and $dels++;
785 # } else {
786 # unlink $file and $dels++;
787 # }
788 # }
789 # return $dels;
790 # }
791
792
793 # remove recursive files matching regular expression
794 # return number of removed files
795 sub rmrx {
796 my $rx = shift;
797 my @files = @_;
798 my $dels = 0;
799 my @caller;
800 my $spool = untaint(abs_path($spooldir));
801 local $_;
802
803 @caller = caller(1) or @caller = caller;
804
805 foreach (@files) {
806 if (tainted($_)) {
807 http_die(
808 sprintf "rmrx() called by %s::%s() line %s with tainted '%s'",
809 $caller[1],$caller[3]||'',$caller[2],$_
810 );
811 }
812 if (m:^/: and abs_path($_) !~ m:^\Q$spool/:) {
813 http_die(
814 sprintf "rmrx() called by %s::%s() line %s with illegal '%s'",
815 $caller[1],$caller[3]||'',$caller[2],$_
816 );
817 }
818 $_ = untaint(abs_path('.')) if $_ eq '.';
819 next if /(^|\/)\.\.?$/;
820 if (-d and not -l) {
821 my $dir = $_;
822 if (basename($dir) =~ /$rx/) {
823 $dels += rmrf($dir);
824 } else {
825 opendir $dir,$dir or next;
826 while (defined(my $file = readdir $dir)) {
827 next if $file eq '.' or $file eq '..';
828 $dels += rmrx($rx,"$dir/".untaint($file));
829 }
830 closedir $dir;
831 }
832 } else {
833 if (basename($_) =~ /$rx/) {
834 unlink($_) and $dels++;
835 }
836 }
837 }
838 return $dels;
839 }
840
841
842 # remove recursive non-regular files (symlinks, etc)
843 sub doxunweed {
844 my $dir = shift;
845 my @caller;
846 my $spool = untaint(abs_path($spooldir));
847 local $_;
848
849 @caller = caller(1) or @caller = caller;
850
851 $dir = untaint(abs_path('.')) if $dir eq '.';
852
853 if (tainted($dir)) {
854 http_die(
855 sprintf "doxunweed() called by %s::%s() line %s with tainted '%s'",
856 $caller[1],$caller[3]||'',$caller[2],$dir
857 );
858 }
859 $dir = untaint(abs_path($dir));
860 if ($dir !~ m:^\Q$spool\E/.+\@.+/DOX/.+:) {
861 http_die(
862 sprintf "doxunweed() called by %s::%s() line %s with illegal '%s'",
863 $caller[1],$caller[3]||'',$caller[2],$dir
864 );
865 }
866 if (opendir $dir,$dir) {
867 while (defined(my $file = readdir $dir)) {
868 next if $file eq '.' or $file eq '..';
869 my $dfile = untaint("$dir/$file");
870 if (-l $dfile) {
871 unlink $dfile;
872 } elsif (-d $dfile) {
873 doxunweed($dfile) if $file ne '.fexdox';
874 } elsif (not -f $dfile) {
875 unlink $dfile;
876 }
877 }
878 closedir $dir;
879 }
880 }
881
882
883 # rename recursive files matching regular expression
884 # substitute character is '_'
885 sub rrrx {
886 my $rx = shift;
887 my @files = @_;
888 local $_;
889
890 foreach (@files) {
891 if (-d and not -l) {
892 my $dir = $_;
893 opendir $dir,$dir or next;
894 while (defined(my $file = readdir $dir)) {
895 next if $file eq '.' or $file eq '..';
896 $file = untaint($file);
897 rrrx($rx,"$dir/$file");
898 }
899 closedir $dir;
900 } else {
901 my $bname = basename($_);
902 my $dname = dirname($_);
903 $bname = s/$rx/_/g;
904 if ($_ ne "$dname/$bname") {
905 rename $_,"$dname/$bname";
906 }
907 }
908 }
909 }
910
911
912 sub gethostname {
913 my $hostname = hostname;
914 my $domain;
915 local $_;
916
917 unless ($hostname) {
918 $_ = `hostname 2>/dev/null`;
919 $hostname = /(.+)/ ? $1 : '';
920 }
921 if ($hostname !~ /\./ and open my $rc,'/etc/resolv.conf') {
922 while (<$rc>) {
923 if (/^\s*domain\s+([\w.-]+)/) {
924 $domain = $1;
925 last;
926 }
927 if (/^\s*search\s+([\w.-]+)/) {
928 $domain = $1;
929 }
930 }
931 close $rc;
932 $hostname .= ".$domain" if $domain;
933 }
934 if ($hostname !~ /\./ and $admin and $admin =~ /\@([\w.-]+)/) {
935 $hostname .= '.'.$1;
936 }
937
938 return $hostname;
939 }
940
941
942 # strip off path names (Windows or UNIX)
943 sub strip_path {
944 local $_ = shift;
945
946 s/.*\\// if /^([A-Z]:)?\\/;
947 s:.*/::;
948
949 return $_;
950 }
951
952
953 sub searchpath {
954 my $prg = shift;
955 my @PATH = split(':',$ENV{PATH});
956
957 if ($prg =~ m:/:) {
958 return $prg if -x $prg and -f $prg;
959 return '';
960 }
961
962 foreach my $path (@PATH) {
963 return $prg if -x "$path/$prg" and -f "$path/$prg";
964 }
965
966 return '';
967 }
968
969
970 # substitute all critical chars
971 sub normalize {
972 local $_ = shift;
973
974 return '' unless defined $_;
975
976 # we need perl native utf8 (see perldoc utf8)
977 $_ = decode_utf8($_) unless utf8::is_utf8($_);
978
979 s/[\r\n\t]+/ /g;
980 s/[\x00-\x1F\x80-\x9F]/_/g;
981 s/^\s+//;
982 s/\s+$//;
983
984 return encode_utf8($_);
985 }
986
987
988 # substitute all critcal chars
989 sub normalize_html {
990 local $_ = shift;
991
992 return '' unless defined $_;
993
994 $_ = normalize($_);
995 s/[\"<>]//g;
996
997 return $_;
998 }
999
1000
1001 # substitute all critcal chars with underscore
1002 sub normalize_filename {
1003 local $_ = shift;
1004
1005 # we need native utf8
1006 $_ = decode_utf8($_) unless utf8::is_utf8($_);
1007
1008 $_ = strip_path($_);
1009
1010 # substitute all critcal chars with underscore
1011 s/^\./_/;
1012 s/[:&<>\$\`\|\\]/_/g;
1013 s/[^a-z_\d@^~.,=+-]/_/gi;
1014
1015 return encode_utf8(untaint($_));
1016 }
1017
1018
1019 sub normalize_email {
1020 local $_ = lc shift;
1021
1022 s/[^\w_.+=!~#^\@\-]//g;
1023 s/^\./_/;
1024 /(.*)/;
1025 return $1;
1026 }
1027
1028
1029 sub normalize_user {
1030 my $user = shift;
1031
1032 $user = lc(urldecode(despace($user)));
1033 $user .= '@'.$mdomain if $mdomain and $user !~ /@/;
1034 $user =~ s:/:_:g;
1035 checkaddress($user) or http_die("$user is not a valid email address");
1036 return untaint($user);
1037 }
1038
1039
1040 sub untaint {
1041 local $_ = shift;
1042
1043 if (defined $_) {
1044 /(.*)/s;
1045 return $1;
1046 } else {
1047 @x = caller;
1048 die "untaint() @x";
1049 }
1050 }
1051
1052
1053 sub checkchars {
1054 my $input = shift;
1055 local $_ = shift;
1056
1057 if (/^([|+.])/) {
1058 http_die("\"$1\" is not allowed at beginning of $input");
1059 }
1060 if (/([\/\"\'\\<>;])/) {
1061 http_die(sprintf("\"&#%s;\" is not allowed in %s",ord($1),$input));
1062 }
1063 if (/(\|)$/) {
1064 http_die("\"$1\" is not allowed at end of $input");
1065 }
1066 if (/[\000-\037]/) {
1067 http_die("control characters are not allowed in $input");
1068 }
1069 /(.*)/;
1070 return $1;
1071 }
1072
1073
1074 sub checkaddress {
1075 my $a = shift;
1076 my $re;
1077 local $_;
1078 local ($domain,$dns);
1079
1080 $a =~ s/:\w+=.*//; # remove options from address
1081
1082 return $a if $a eq 'anonymous';
1083
1084 $a .= '@'.$mdomain if $mdomain and $a !~ /@/;
1085
1086 $re = '^[.@-]|@.*@|local(host|domain)$|[(){}<>/;,*?&"`\'\s\[\]\|\\\\]';
1087 if ($a =~ /$re/i) {
1088 debuglog("$a has illegal syntax ($re)");
1089 return '';
1090 }
1091
1092 if ($a !~ /.\@[\w.-]+$/) {
1093 debuglog("$a is not an email-address");
1094 return '';
1095 }
1096
1097 if ($a =~ /[\x00-\x20\x7f]/) {
1098 debuglog("$a has non-printable character");
1099 return '';
1100 }
1101
1102 if ($a =~ /[\xa0-\xff]/) {
1103 debuglog("$a has 8-bit character");
1104 return '';
1105 }
1106
1107 return $a if not $checkaddress or $checkaddress =~ /n/i;
1108
1109 $re = '^[\w!^=~#%:.+-]+\@(\w[\w.-]*\.[a-z]+)$';
1110 if ($a =~ /$re/i) {
1111 $domain = $dns = $1;
1112 {
1113 local $SIG{__DIE__} = sub { die "\n" };
1114 eval q{
1115 use Net::DNS;
1116 $dns = Net::DNS::Resolver->new->query($domain)||mx($domain);
1117 unless ($dns or mx('uni-stuttgart.de')) {
1118 http_die("Internal error: bad resolver");
1119 }
1120 }
1121 };
1122 if ($dns) {
1123 return untaint($a);
1124 } else {
1125 debuglog("no A or MX DNS record found for $domain");
1126 return '';
1127 }
1128 } else {
1129 debuglog("$a does not match email regexp ($re)");
1130 return '';
1131 }
1132 }
1133
1134
1135 # check forbidden addresses
1136 sub checkforbidden {
1137 my $a = shift;
1138 my ($fr,$pr);
1139 local $_;
1140
1141 $a .= '@'.$mdomain if $mdomain and $a !~ /@/;
1142 return $a if -d "$spooldir/$a"; # ok, if user already exists
1143 if (@forbidden_recipients) {
1144 foreach (@forbidden_recipients) {
1145 $fr = quotewild($_);
1146 # skip public recipients
1147 if (@public_recipients) {
1148 foreach $pr (@public_recipients) {
1149 return $a if $a eq lc $pr;
1150 }
1151 }
1152 return '' if $a =~ /^$fr$/i;
1153 }
1154 }
1155 return $a;
1156 }
1157
1158
1159 sub randstring {
1160 my $n = shift;
1161 my @rc = ('A'..'Z','a'..'z',0..9 );
1162 my $rn = @rc;
1163 my $rs;
1164
1165 for (1..$n) { $rs .= $rc[int(rand($rn))] };
1166 return $rs;
1167 }
1168
1169
1170 # emulate mkdir -p
1171 sub mkdirp {
1172 my $dir = shift;
1173
1174 unless (-d $dir) {
1175 $dir =~ s:/+$::;
1176 if (length($dir)) {
1177 mkdirp(dirname($dir));
1178 mkdir $dir,0770 or http_die("mkdir $dir - $!");
1179 } else {
1180 http_die("cannot mkdir /");
1181 }
1182 }
1183 }
1184
1185
1186 # hash with SID
1187 sub sidhash {
1188 my ($rid,$id) = @_;
1189
1190 if ($rid and $ENV{SID} and $id =~ /^MD5H:/) {
1191 $rid = 'MD5H:'.md5_hex($rid.$ENV{SID});
1192 }
1193 return $rid;
1194 }
1195
1196
1197 # test if ip is in iplist (ipv4/ipv6)
1198 # iplist is an array with ips and ip-ranges
1199 sub ipin {
1200 my ($ip,@list) = @_;
1201 my ($i,$ia,$ib);
1202
1203 $ipe = lc(ipe($ip));
1204 map { lc } @list;
1205
1206 foreach $i (@list) {
1207 if ($ip =~ /\./ and $i =~ /\./ or $ip =~ /:/ and $i =~ /:/) {
1208 if ($i =~ /(.+)-(.+)/) {
1209 ($ia,$ib) = ($1,$2);
1210 $ia = ipe($ia);
1211 $ib = ipe($ib);
1212 return $ip if $ipe ge $ia and $ipe le $ib;
1213 } else {
1214 return $ip if $ipe eq ipe($i);
1215 }
1216 }
1217 }
1218 return '';
1219 }
1220
1221 # ip expand (ipv4/ipv6)
1222 sub ipe {
1223 local $_ = shift;
1224
1225 if (/^\d+\.\d+\.\d+\.\d+$/) {
1226 s/\b(\d\d?)\b/sprintf "%03d",$1/ge;
1227 } elsif (/^[:\w]+:\w+$/) {
1228 s/\b(\w+)\b/sprintf "%04s",$1/ge;
1229 s/^:/0000:/;
1230 while (s/::/::0000:/) { last if length > 39 }
1231 s/::/:/;
1232 } else {
1233 $_ = '';
1234 }
1235 return $_;
1236 }
1237
1238
1239 sub filename {
1240 my $file = shift;
1241 my $filename;
1242
1243 if (open $file,'<',"$file/filename") {
1244 $filename = <$file>||'';
1245 chomp $filename;
1246 close $file;
1247 }
1248
1249 unless ($filename) {
1250 $filename = $file;
1251 $filename =~ s:.*/::;
1252 }
1253
1254 return $filename;
1255 }
1256
1257
1258 # emulate a "find $dir"
1259 sub find {
1260 my $dir = shift;
1261 my @files = ();
1262 local $_;
1263
1264 if (opendir $dir,$dir) {
1265 while (defined($_ = readdir $dir)) {
1266 next if /^\.\.?$/;
1267 my $df = "$dir/$_";
1268 push @files,$df;
1269 push @files,find($df) if -d $df and not -l $df;
1270 }
1271 closedir $dir;
1272 }
1273 return @files;
1274 }
1275
1276
1277 sub hexencode {
1278 local $_ = shift;
1279 s/%/%25/g;
1280 s/([^!-~])/sprintf "%%%X",ord($1)/ige;
1281 return $_;
1282 }
1283
1284
1285 sub hexdecode {
1286 local $_ = shift;
1287 s/%([a-f0-9]{2})/chr(hex($1))/ige;
1288 return $_;
1289 }
1290
1291
1292 sub urlencode {
1293 local $_ = shift;
1294 # $_ = encode_utf8($_) if utf8::is_utf8($_);
1295 s/(^[.~]|[^\d\/a-z_@.,=:~^+-])/sprintf "%%%X",ord($1)/ige;
1296 return $_;
1297 }
1298
1299
1300 sub urldecode {
1301 local $_ = shift;
1302 s/%([a-f0-9]{2})/chr(hex($1))/gie;
1303 return $_;
1304 }
1305
1306
1307 sub htmlencode {
1308 local $_ = shift;
1309 s/&/&amp;/g;
1310 s/</&lt;/g;
1311 return $_;
1312 }
1313
1314
1315 sub htmlquote {
1316 local $_ = shift;
1317 s/&/&amp;/g;
1318 s/</&lt;/g;
1319 s/\"/&quot;/g;
1320 s/\'/&apos;/g;
1321 return $_;
1322 }
1323
1324
1325 # shell pattern to Perl regular expression
1326 sub shp2prx {
1327 local $_ = shift;
1328 s:([^\w\[\]^/*?-]):\\$1:g;
1329 s:([^*])\*([^*]):$1\[^/\]*$2:g;
1330 s:([^*])\*$:$1\[^/\]*:;
1331 s:^\*([^*]):[^/]*$1:;
1332 s:\*\*:.*:g;
1333 s:\?:.:g;
1334 return $_;
1335 }
1336
1337
1338 # file archive sharing log
1339 sub faslog {
1340 my $shared = shift;
1341 my $msg = "@_";
1342 my $log = "$shared/log";
1343
1344 # do not log special share _
1345 return if basename($shared) eq '_';
1346
1347 $msg =~ s/\n/ /g;
1348 $msg =~ s/\s+$//;
1349 $msg = sprintf "%s %s %s\n",isodate(time),$RA,$msg;
1350
1351 if ($share_logging and open $log,'>>',$log) {
1352 flock $log,LOCK_EX;
1353 seek $log,0,SEEK_END;
1354 printf {$log} $msg;
1355 close $log;
1356 }
1357 }
1358
1359
1360 # file and document log
1361 sub fdlog {
1362 my ($log,$file,$s,$size) = @_;
1363 my $ra = $RA||'-';
1364 my $msg;
1365
1366 $ra .= '/'.$ENV{HTTP_X_FORWARDED_FOR} if $ENV{HTTP_X_FORWARDED_FOR};
1367 $ra =~ s/\s//g;
1368 $file =~ s:/data$::;
1369 $msg = sprintf "%s [%s_%s] %s %s %s/%s\n",
1370 isodate(time),$$,$ENV{REQUESTCOUNT},$ra,encode_Q($file),$s,$size;
1371
1372 writelog($log,$msg);
1373 }
1374
1375
1376 # extra (debug) log
1377 sub xdbglog {
1378 my @caller;
1379 my $log = '/tmp/fex.log';
1380 if (open $log,'>>',$log) {
1381 @caller = caller(1) or @caller = caller;
1382 printf {$log} "%s %s::%s() line %s:\n",
1383 isodate(time),$caller[1],$caller[3]||'',$caller[2];
1384 print {$log} "@_\n";
1385 close $log;
1386 }
1387 }
1388
1389
1390 sub debuglog {
1391 my $prg = $0;
1392 local $_;
1393
1394 return unless $debug and @_;
1395 unless ($debuglog and fileno $debuglog) {
1396 my $ddir = "$spooldir/.debug";
1397 mkdir $ddir,0770 unless -d $ddir;
1398 $prg =~ s:.*/::;
1399 $prg = untaint($prg);
1400 $debuglog = sprintf("%s/%s_%s_%s.%s",
1401 $ddir,time,$$,$ENV{REQUESTCOUNT}||0,$prg);
1402 $debuglog =~ s/\s/_/g;
1403 # http://perldoc.perl.org/perlunifaq.html#What-is-a-%22wide-character%22%3f
1404 # open $debuglog,'>>:encoding(UTF-8)',$debuglog or return;
1405 open $debuglog,'>>',$debuglog or return;
1406 # binmode($debuglog,":utf8");
1407 autoflush $debuglog 1;
1408 # printf {$debuglog} "\n### %s ###\n",isodate(time);
1409 }
1410 while ($_ = shift @_) {
1411 $_ = encode_utf8($_) if utf8::is_utf8($_);
1412 s/\n*$/\n/;
1413 # s/<.+?>//g; # remove HTML # can be <COMMENT>!
1414 print {$debuglog} $_;
1415 print "DEBUG: $_" if -t;
1416 }
1417 }
1418
1419
1420 # extra debug log
1421 sub errorlog {
1422 my $prg = $0;
1423 my $msg = "@_";
1424 my $ra = $RA||'-';
1425
1426 $ra .= '/'.$ENV{HTTP_X_FORWARDED_FOR} if $ENV{HTTP_X_FORWARDED_FOR};
1427 $ra =~ s/\s//g;
1428 $prg =~ s:.*/::;
1429 $msg =~ s/[\r\n]+$//;
1430 $msg =~ s/[\r\n]+/ /;
1431 $msg =~ s/\s*<p>.*//;
1432 $msg = sprintf "%s %s %s %s\n",isodate(time),$prg,$ra,$msg;
1433
1434 writelog('error.log',$msg);
1435 }
1436
1437
1438 sub writelog {
1439 my $log = shift;
1440 my $msg = shift;
1441
1442 $msg = encode_utf8($msg) if utf8::is_utf8($msg);
1443
1444 foreach my $logdir (@logdir) {
1445 if (open $log,'>>',"$logdir/$log") {
1446 flock $log,LOCK_EX;
1447 seek $log,0,SEEK_END;
1448 print {$log} $msg;
1449 close $log;
1450 }
1451 }
1452 }
1453
1454
1455 # failed authentification log
1456 sub faillog {
1457 my $request = shift;
1458 my $n = 1;
1459
1460 if ($RA and $faillog and open $faillog,"+>>$faillog") {
1461 flock($faillog,LOCK_EX);
1462 seek $faillog,0,SEEK_SET;
1463 $n++ while <$faillog>;
1464 printf {$faillog} "%s %s\n",isodate(time),$request;
1465 close $faillog;
1466 if ($max_fail and $n > $max_fail and
1467 not ($ENV{HTTP_X_FORWARDED_FOR}||$ENV{HTTP_VIA}) and
1468 ($ENV{HTTP_USER_AGENT}||'') !~ /^fex/)
1469 {
1470 if ($max_fail_handler) {
1471 &$max_fail_handler($RA);
1472 } else {
1473 http_die(
1474 "Too many login failures from $RA : IP BLOCKED",
1475 "Contact $admin for details."
1476 );
1477 }
1478 }
1479 }
1480 }
1481
1482 # remove all white space
1483 sub despace {
1484 local $_ = shift;
1485 s/\s//g;
1486 return $_;
1487 }
1488
1489
1490 # superquoting
1491 sub qqq {
1492 local $_ = shift;
1493 my ($s,@s);
1494 my $i = '';
1495 my $q = "[\'\"]"; # quote delimiter chars " and '
1496
1497 # remove comment
1498 while (s/\n#.*?\n/\n/) {}
1499
1500 # remove first newline and look for default indention
1501 s/^((\d+)?)?\n// and $i = ' ' x ($2||0);
1502
1503 # remove trailing spaces at end
1504 s/[ \t]*?$//;
1505
1506 @s = split "\n";
1507
1508 # first line have a quote delimiter char?
1509 if (/^\s+$q/) {
1510 # remove heading spaces and delimiter chars
1511 foreach (@s) {
1512 s/^\s*$q//;
1513 s/$q\s*$//;
1514 }
1515 } else {
1516 # find the line with the fewest heading spaces (and count them)
1517 # (beware of tabs!)
1518 $s = length;
1519 foreach (@s) {
1520 if (/^( *)\S/ and length($1) < $s) { $s = length($1) };
1521 }
1522 # adjust indention
1523 foreach (@s) {
1524 s/^ {$s}/$i/;
1525 }
1526 }
1527
1528 return join("\n",@s)."\n";
1529 }
1530
1531
1532 # print superquoted
1533 sub pq {
1534 my $H = STDOUT;
1535 local $_;
1536
1537 if (@_ > 1 and defined fileno $_[0]) { $H = shift }
1538 $_ = qqq(@_);
1539 # print needs need binary data, not wide characters
1540 ## binmode($H,':utf8'); # does not work correctly
1541 $_ = encode_utf8($_) if utf8::is_utf8($_);
1542 print {$H} $_;
1543 }
1544
1545
1546 # print needs need binary data, not wide characters
1547 sub printb {
1548 local $_;
1549
1550 foreach (@_) {
1551 print utf8::is_utf8($_) ? encode_utf8($_) : $_;
1552 }
1553 }
1554
1555
1556 # check sender quota
1557 sub check_sender_quota {
1558 my $sender = shift;
1559 my $squota = $sender_quota||0;
1560 my $du = 0;
1561 my ($file,$size,%file,$data,$upload,$share);
1562 local $_;
1563
1564 if (open $qf,'<',"$spooldir/$sender/\@QUOTA") {
1565 while (<$qf>) {
1566 s/#.*//;
1567 $squota = $1 if /sender.*?(\d+)/i;
1568 }
1569 close $qf;
1570 }
1571
1572 foreach $file (glob "$spooldir/*/$sender/*") {
1573 $data = "$file/data";
1574 $upload = "$file/upload";
1575 if (not -l $data and $size = -s $data) {
1576 # count hard links only once (= same inode)
1577 my $i = (stat($data))[1]||0;
1578 unless ($file{$i}) {
1579 $du += $size;
1580 $file{$i} = $i;
1581 }
1582 } elsif (-f $upload) {
1583 # count hard links only once (= same inode)
1584 my $i = (stat($upload))[1]||0;
1585 unless ($file{$i}) {
1586 $du += readlink("$file/size")||0;
1587 $file{$i} = $i;
1588 }
1589 }
1590 }
1591
1592 foreach $size (glob "$sender/SHARE/*/archives/*/*/size") {
1593 $du += readlink($size)||0;
1594 }
1595
1596 foreach (glob("$sender/DOX/.*.du")) {
1597 if (m:(.+)/\.(.+)\.du: and -d "$1/$2" and my $s = readlink) {
1598 $du += $s*1024;
1599 }
1600 }
1601
1602 return($squota,int($du/$MB));
1603 }
1604
1605
1606 # check recipient quota
1607 sub check_recipient_quota {
1608 my $recipient = shift;
1609 my $rquota = $recipient_quota||0;
1610 my $du = 0;
1611 my ($file,$size,$share);
1612 local $_;
1613
1614 if (open my $qf,'<',"$recipient/\@QUOTA") {
1615 while (<$qf>) {
1616 s/#.*//;
1617 $rquota = $1 if /recipient.*?(\d+)/i;
1618 }
1619 close $qf;
1620 }
1621
1622 foreach $file (glob "$recipient/*/*") {
1623 if (-f "$file/upload" and $size = readlink "$file/size") {
1624 $du += $size;
1625 } elsif (not -l "$file/data" and $size = -s "$file/data") {
1626 $du += $size;
1627 }
1628 }
1629
1630 foreach $size (glob "$recipient/SHARE/*/archives/*/*/size") {
1631 $du += readlink($size)||0;
1632 }
1633
1634 foreach my $d (glob("$recipient/DOX/.*.du")) {
1635 $du += (readlink($d)||0)*1024;
1636 }
1637
1638 return($rquota,int($du/$MB));
1639 }
1640
1641
1642 # dox disk usage
1643 sub doxdu {
1644 my $user = shift;
1645 my $folder = shift;
1646 my $doxd = "$spooldir/$user/DOX";
1647 my $duf;
1648 my @folder = ();
1649 local $_;
1650
1651 if (-d $doxd) {
1652 if (defined $folder) {
1653 @folder = ("$doxd/$folder");
1654 } else {
1655 foreach my $f (glob "$doxd/*") {
1656 push @folder,$f if -l $f and -d $f;
1657 }
1658 }
1659 foreach my $f (@folder) {
1660 if ($f =~ m:(.+)/(.+):) {
1661 $duf = "$1/.$2.du";
1662 } else {
1663 next;
1664 }
1665 unlink $duf;
1666 if (-l $f and -d $f) {
1667 if (my @f = grep m:\Q$f\E_\d+_\d+$:,glob($f.'_*')) {
1668 symlink untaint(ddu(@f)),$duf;
1669 }
1670 }
1671 }
1672 }
1673 }
1674
1675
1676 # directory disk usage (kB)
1677 sub ddu {
1678 my $du = 0;
1679 local %DU;
1680
1681 local $ddu = sub {
1682 my $dir = shift;
1683 my $du = 0;
1684 opendir $dir,$dir or return 0;
1685 while (defined (my $file = readdir $dir)) {
1686 next if $file eq '.' or $file eq '..';
1687 my $df = "$dir/$file";
1688 my @s = lstat($df) or next;
1689 if (-l _) {
1690 $du += 4;
1691 next;
1692 }
1693 if (-d _) {
1694 $du += 4;
1695 next if $file =~ /^\.snapshots?$/;
1696 $du += &$ddu($df);
1697 next;
1698 }
1699 if (-f _) {
1700 my $i = "$s[0]:$s[1]";
1701 $du += $DU{$i} ? 4 : int(($s[7]+4095)/4096)*4;
1702 $DU{$i}++;
1703 next;
1704 }
1705 $du += 4;
1706 }
1707 closedir $dir;
1708 return $du;
1709 };
1710
1711 foreach my $dir (@_) {
1712 $du += &$ddu($dir);
1713 }
1714 return $du;
1715 }
1716
1717
1718 sub getline {
1719 my $file = shift;
1720 local $_;
1721
1722 chomp($_ = <$file> // '');
1723 return $_;
1724 }
1725
1726
1727 sub readline1 {
1728 my $file = shift;
1729 local $_;
1730
1731 if (open $file,$file) {
1732 $_ = <$file> // '';
1733 close $file;
1734 chomp;
1735 }
1736 return $_;
1737 }
1738
1739
1740 # (shell) wildcard matching
1741 sub wcmatch {
1742 local $_ = shift;
1743 my $p = quotemeta shift;
1744
1745 $p =~ s/\\\*/.*/g;
1746 $p =~ s/\\\?/./g;
1747 $p =~ s/\\\[/[/g;
1748 $p =~ s/\\\]/]/g;
1749
1750 return /$p/;
1751 }
1752
1753
1754 sub logout {
1755 my $logout;
1756 if ($skey) { $logout = "/fup?logout=skey:$skey" }
1757 elsif ($gkey) { $logout = "/fup?logout=gkey:$gkey" }
1758 elsif ($akey) { $logout = "/fup?logout=akey:$akey" }
1759 else { $logout = "/fup?logout" }
1760 return qqq(qq(
1761 '<p>'
1762 '<form name="logout" action="$logout">'
1763 ' <input type="submit" name="logout" value="logout">'
1764 '</form>'
1765 '<p>'
1766 ));
1767 }
1768
1769
1770 # print data dump of global or local variables in HTML
1771 # input musst be a string, eg: '%ENV'
1772 sub DD {
1773 my $v = shift;
1774 local $_;
1775
1776 $n =~ s/.//;
1777 $_ = eval(qq(use Data::Dumper;Data::Dumper->Dump([\\$v])));
1778 s/\$VAR1/$v/;
1779 s/&/&amp;/g;
1780 s/</&lt;/g;
1781 print "<pre>\n$_\n</pre>\n";
1782 }
1783
1784 # make symlink
1785 sub mksymlink {
1786 my ($file,$link) = @_;
1787 unlink $file;
1788 return symlink untaint($link),$file;
1789 }
1790
1791
1792 # copy file (and modify) or symlink
1793 # returns chomped file contents or link name
1794 # preserves permissions and time stamps
1795 sub copy {
1796 my ($from,$to,$sx,$ss) = @_;
1797 my $link;
1798 local $/;
1799 local $_;
1800
1801 $to .= '/'.basename($from) if -d $to;
1802
1803 if (defined($link = readlink $from)) {
1804 mksymlink($to,$link);
1805 return $link;
1806 } else {
1807 open $from,'<',$from or return;
1808 open $to,'>',$to or return;
1809 $_ = <$from>;
1810 close $from;
1811 s/$sx/$ss/g if defined $ss;
1812 print {$to} $_;
1813 close $to or http_die("internal error: $to - $!");
1814 if (my @s = stat($from)) {
1815 chmod $s[2],$to;
1816 utime @s[8,9],$to unless $mod;
1817 }
1818 chomp;
1819 return $_;
1820 }
1821 }
1822
1823
1824 sub slurp {
1825 my $file = shift;
1826 local $_;
1827 local $/;
1828
1829 if (open $file,$file) {
1830 $_ = <$file>;
1831 close $file;
1832 }
1833
1834 return $_;
1835 }
1836
1837
1838 # read one line from STDIN (net socket) and assign it to $_
1839 # return number of read bytes
1840 # also set global variable $RB (read bytes)
1841 sub nvt_read {
1842 my $len = 0;
1843
1844 if (defined ($_ = <STDIN>)) {
1845 debuglog($_);
1846 $len = length;
1847 $RB += $len;
1848 s/\r?\n//;
1849 }
1850 return $len;
1851 }
1852
1853
1854 # read forward to given pattern
1855 sub nvt_skip_to {
1856 my $pattern = shift;
1857
1858 while (&nvt_read) { return if /$pattern/ }
1859 }
1860
1861
1862 # HTTP GET and POST parameters
1863 # (not used by fup)
1864 # fills global variable %PARAM :
1865 # normal parameter is $PARAM{$parameter}
1866 # file parameter is $PARAM{$parameter}{filename} $PARAM{$parameter}{data}
1867 sub parse_parameters {
1868 my $cl = $ENV{X_CONTENT_LENGTH} || $ENV{CONTENT_LENGTH} || 0;
1869 my $data = '';
1870 my $filename;
1871 local $_;
1872 our %PARAM = ();
1873
1874 if ($cl > 128*$MB) {
1875 http_die("request too large");
1876 }
1877
1878 # binmode(STDIN,':raw');
1879
1880 $_ = $ENV{QUERY_STRING};
1881 s/%5E/^/g;
1882 if (/&/) {
1883 foreach (split(/&/)) {
1884 if (/(.+?)=(.*)/) { $PARAM{$1} = $2 }
1885 else { $PARAM{$_} = $_ }
1886 }
1887 } elsif (/\?/) {
1888 foreach (split(/\?/)) {
1889 if (/(.+?)=(.*)/) { $PARAM{$1} = $2 }
1890 else { $PARAM{$_} = $_ }
1891 }
1892 } else {
1893 if (/(.+?)=(.*)/) { $PARAM{$1} = $2 }
1894 else { $PARAM{$_} = $_ }
1895 }
1896
1897 $_ = $ENV{CONTENT_TYPE}||'';
1898 if ($ENV{REQUEST_METHOD} eq 'POST' and /boundary=\"?([\w\-\+\/_]+)/) {
1899 my $boundary = $1;
1900 while ($RB<$cl and &nvt_read) { last if /^--\Q$boundary/ }
1901 # continuation lines are not checked!
1902 while ($RB<$cl and &nvt_read) {
1903 $filename = '';
1904 if (/^Content-Disposition:.*\s*filename="(.+?)"/i) {
1905 $filename = $1;
1906 }
1907 if (/^Content-Disposition:\s*form-data;\s*name="(.+?)"/i) {
1908 my $p = $1;
1909 # skip rest of mime part header
1910 while ($RB<$cl and &nvt_read) { last if /^\s*$/ }
1911 $data = '';
1912 while (<STDIN>) {
1913 if ($p =~ /password/i) {
1914 debuglog('*' x length)
1915 } else {
1916 debuglog($_)
1917 }
1918 $RB += length;
1919 last if /^--\Q$boundary/;
1920 $data .= $_;
1921 }
1922 unless (defined $_) { die "premature end of HTTP POST\n" }
1923 $data =~ s/\r?\n$//;
1924 if ($filename) {
1925 $PARAM{$p}{filename} = $filename;
1926 $PARAM{$p}{data} = $data;
1927 } else {
1928 $PARAM{$p} = $data;
1929 }
1930 last if /^--\Q$boundary--/;
1931 }
1932 }
1933 }
1934 }
1935
1936
1937 # name based virtual host?
1938 sub vhost {
1939 my $hh = shift; # HTTP_HOST
1940 my $vhost;
1941 my $locale = $ENV{LOCALE};
1942
1943 # memorized vhost? (default is in fex.ph)
1944 %vhost = split(':',$ENV{VHOST}) if $ENV{VHOST};
1945
1946 if (%vhost and $hh and $hh =~ s/^([\w\.-]+).*/$1/) {
1947 if ($vhost = $vhost{$hh} and -f "$vhost/lib/fex.ph") {
1948 $ENV{VHOST} = "$hh:$vhost"; # memorize vhost for next run
1949 $ENV{FEXLIB} = $FEXLIB = "$vhost/lib";
1950 $logdir = $spooldir = "$vhost/spool";
1951 $docdir = "$vhost/htdocs";
1952 @logdir = ($logdir);
1953 if ($locale and -e "$vhost/locale/$locale/lib/fex.ph") {
1954 $ENV{FEXLIB} = $FEXLIB = "$vhost/locale/$locale/lib";
1955 }
1956 require "$FEXLIB/fex.ph" or die "$0: cannot load $FEXLIB/fex.ph - $!";
1957 $ENV{SERVER_NAME} = $hostname;
1958 @doc_dirs = ($docdir);
1959 foreach my $ld (glob "$FEXHOME/locale/*/htdocs") {
1960 push @doc_dirs,$ld;
1961 }
1962 return $vhost;
1963 }
1964 }
1965 }
1966
1967
1968 sub gpg_encrypt {
1969 my ($plain,$to,$keyring,$from) = @_;
1970 my ($pid,$pi,$po,$pe,$enc,$err);
1971 local $_;
1972
1973 $pe = gensym;
1974
1975 $keyring =~ s/[;<>()|\`]//;
1976 $to =~ s/[;<>()|\`]//;
1977
1978 $pid = open3($po,$pi,$pe,untaint(
1979 "gpg --batch --trust-model always --keyring '$keyring'".
1980 " -a -e -r '$bcc' -r '$to'"
1981 )) or return;
1982
1983 print {$po} "\n",$plain,"\n";
1984 close $po;
1985
1986 $enc .= $_ while <$pi>;
1987 $err .= $_ while <$pe>;
1988 errorlog("($from --> $to) $err") if $err;
1989
1990 close $pi;
1991 close $pe;
1992 waitpid($pid,0);
1993
1994 return $enc;
1995 }
1996
1997
1998 sub fcrypt {
1999 my $encryption = shift;
2000 my $salt = shift || randstring(16);
2001 my $password = shift;
2002 my $hash;
2003 my $i = 1;
2004
2005 $password =~ s/\s//;
2006
2007 if ($encryption eq '64kHMACSHA512B') {
2008 $hash = hmac_sha512($password,$salt);
2009 foreach (2..2**16-1) {
2010 $i++;
2011 $hash = hmac_sha512($password,$hash.$i);
2012 }
2013 $i++;
2014 $hash = hmac_sha512_base64($password,$hash.$i);
2015 } elsif (ref($$encryption) eq 'CODE') {
2016 $hash = &$$encryption($password,$salt);
2017 } else {
2018 http_die("unknown encryption $encryption");
2019 exit 1;
2020 }
2021
2022 return "$encryption $salt $hash";
2023 }
2024
2025 ## example for fex.ph:
2026 # $encryption = 'NONE';
2027 # $NONE = sub { return $_[1] };
2028
2029
2030 sub move {
2031 our ($move);
2032 my $ddir = pop;
2033 my $move_errors = '';
2034 my @dstat = stat $ddir or return "cannot stat $ddir - $!\n";
2035
2036 unless (-d $ddir) {
2037 return "destination $ddir is not a directory\n";
2038 }
2039
2040 unless (-w $ddir) {
2041 return "destination directory $ddir is not writable\n";
2042 }
2043
2044 local $move = sub {
2045 my $sdir = shift;
2046 my @sstat;
2047 my $dfile;
2048 local $_;
2049
2050 foreach (my @__ = @_) {
2051 unless (@sstat = lstat) {
2052 $move_errors .= "cannot stat '$_' - $!\n";
2053 next;
2054 }
2055 if ($sstat[0] != $dstat[0]) {
2056 $move_errors .= "cannot link $_ to $ddir - different filesystem\n";
2057 next;
2058 }
2059 s:/+:/:g;
2060 s:/$::;
2061 $dfile = "$ddir/$sdir".basename($_);
2062 $dfile =~ s:/+:/:g;
2063 if (-l or not -d) {
2064 if (-d $dfile and not -l $dfile) {
2065 if ($opt_f) {
2066 system qw'rm -rf',$dfile;
2067 } else {
2068 $move_errors .= "cannot replace directory '$dfile'\n";
2069 next;
2070 }
2071 }
2072 if (my @s = lstat $dfile) {
2073 if ("@s" eq "@sstat") {
2074 unless (unlink) {
2075 $move_errors .= "cannot remove '$_' - $!\n";
2076 }
2077 next;
2078 }
2079 unless (unlink $dfile) {
2080 $move_errors .= "cannot remove '$dfile' - $!\n";
2081 next;
2082 }
2083 }
2084 if (rename $_,$dfile) {
2085 print "'$_' -> '$dfile'\n" if $opt_v;
2086 } else {
2087 $move_errors .= "cannot move '$_' to '$dfile' - $!\n";
2088 next;
2089 }
2090 } elsif (-d) {
2091 if (-d $dfile) {
2092 my $dir = $_;
2093 my @files = ();
2094 if (opendir $dir,$dir) {
2095 @files = grep { not /^\.\.?$/ } readdir($dir);
2096 closedir $dir;
2097 @files = sort { lc $a cmp lc $b } @files;
2098 foreach (@files) {
2099 /(.+)/;
2100 $_ = $dir.'/'.decode_utf8($1);
2101 }
2102 &$move($sdir.basename($dir).'/',@files);
2103 unless (rmdir $dir) {
2104 $move_errors .= "cannot rmdir $dir - $!\n";
2105 next;
2106 }
2107 } else {
2108 $move_errors .= "cannot read $dir - $!\n";
2109 next;
2110 }
2111 } else {
2112 if (lstat $dfile) {
2113 unlink $dfile;
2114 }
2115 if (rename $_,$dfile) {
2116 print "'$_' -> '$dfile'\n" if $opt_v;
2117 } else {
2118 $move_errors .= "cannot move '$_' to '$dfile' - $!\n";
2119 next;
2120 }
2121 }
2122 } else {
2123 $move_errors .= "unknown file type '$_'\n";
2124 next;
2125 }
2126 }
2127 };
2128
2129 &$move('',@_);
2130 return $move_errors;
2131 }
2132
2133
2134 sub mtime {
2135 my @s = stat(shift) or return;
2136 return $s[9];
2137 }
2138
2139
2140 sub lmtime {
2141 my @s = lstat(shift) or return;
2142 return @s?$s[9]:0;
2143 }
2144
2145
2146 # wildcard * to perl regexp
2147 sub quotewild {
2148 local $_ = quotemeta shift;
2149 s/\\\*/.*/g; # allow wildcard *
2150 return $_;
2151 }
2152
2153
2154 sub readlink_ {
2155 my $file = shift;
2156 return (readlink($file)||'');
2157 }
2158
2159
2160 sub asort {
2161 return sort { lc($a) cmp lc($b) } @_;
2162 }
2163
2164
2165 sub mhfrom {
2166 my $mfrom = shift;
2167 my $hfrom;
2168 my $fex_sender = $::fex_sender;
2169
2170 $mfrom .= '@'.$mdomain if $mdomain and $mfrom !~ /@/;
2171 $hfrom = $mfrom;
2172 $hfrom =~ s/@/(at)/g;
2173
2174 if ($fex_sender and @local_domains) {
2175 foreach my $ld (@local_domains) {
2176 $fex_sender = 0 if $mfrom =~ /\@\Q$ld\E$|\@.+\.\Q$ld\E$/;
2177 }
2178 }
2179 if ($fex_sender) {
2180 $mfrom =~ s/\@/_/;
2181 $mfrom = "fex+$mfrom\@$hostname";
2182 }
2183
2184
2185 return ($mfrom,$hfrom);
2186 }
2187
2188
2189 # extract locale functions into hash of subroutine references
2190 # e.g. \&german ==> $notify{german}
2191 sub locale_functions {
2192 my $locale = shift;
2193 local $/;
2194 local $_;
2195
2196 if ($locale and open my $fexpp,"$FEXHOME/locale/$locale/lib/fex.pp") {
2197 $_ = <$fexpp>;
2198 s/.*\n(\#\#\# locale functions)/$1/s;
2199 # sub xx {} ==> xx{$locale} = sub {}
2200 s/\nsub (\w+)/\n\$$1\{$locale\} = sub/gs;
2201 s/\n\}\n/\n\};\n/gs;
2202 eval $_;
2203 close $fexpp;
2204 }
2205 }
2206
2207 sub notify_locale {
2208 my $dkey = shift;
2209 my $status = shift || 'new';
2210 my ($to,$keep,$locale,$file,$filename,$comment,$autodelete,$replyto,$mtime);
2211 local $_;
2212
2213 if ($dkey =~ m:/.+/.+/:) {
2214 $file = $dkey;
2215 $dkey = readlink("$file/dkey")
2216 or http_die("internal error: no $file/dkey");
2217 } else {
2218 $file = readlink("$dkeydir/$dkey")
2219 or http_die("internal error: no DKEY $dkey");
2220 }
2221 $file = untaint($file);
2222 $file =~ s:^\.\./::;
2223 $filename = filename($file);
2224 $to = $file;
2225 $to =~ s:/.*::;
2226 $mtime = mtime("$file/data") or http_die("internal error: no $file/data");
2227 $comment = slurp("$file/comment") || '';
2228 $replyto = readlink "$file/replyto" || '';
2229 $autodelete = readlink "$file/autodelete"
2230 || readlink "$to/\@AUTODELETE"
2231 || $::autodelete;
2232 $keep = readlink "$file/keep"
2233 || readlink "$to/\@KEEP"
2234 || $keep_default;
2235
2236 $locale = readlink "$to/\@LOCALE" || readlink "$file/locale" || 'english';
2237 $_ = untaint("$FEXHOME/locale/$locale/lib/lf.pl");
2238 require if -f;
2239 $notify{'english'} = \&notify; # local default notify function, not via lf.pl
2240 unless ($notify{$locale}) {
2241 $locale = 'english';
2242 $notify{$locale} ||= \&notify;
2243 }
2244 # return notify(
2245 return &{$notify{$locale}}(
2246 status => $status,
2247 dkey => $dkey,
2248 filename => $filename,
2249 keep => $keep-int((time-$mtime)/$DS),
2250 comment => $comment,
2251 autodelete => $autodelete,
2252 replyto => $replyto,
2253 );
2254 }
2255
2256 ########################### locale functions ###########################
2257 # Will be extracted by install process and saved in $FEXHOME/lib/lf.pl #
2258 # You cannot modify them here without re-installing! #
2259 ########################################################################
2260
2261 # locale function!
2262 sub notify {
2263 # my ($status,$dkey,$filename,$keep,$warn,$comment,$autodelete) = @_;
2264 my %P = @_;
2265 my ($to,$from,$file,$mimefilename,$receiver,$warn,$comment,$status);
2266 my ($size,$bytes,$header,$data,$replyto,$uurl,$alist,$filed,$share);
2267 my ($mfrom,$mto,$dfrom,$dto,$hfrom);
2268 my $proto = 'http';
2269 my $days = 0;
2270 my $durl = $::durl;
2271 my $autodelete = '';
2272 my ($index,$tools);
2273 my $fileid = 0;
2274 my $fua = $ENV{HTTP_USER_AGENT}||'';
2275 my $warning = '';
2276 my $disclaimer = '';
2277 my $download = '';
2278 my $keyring;
2279 my $boundary = randstring(16);
2280 my ($body,$enc_body);
2281
2282 return if $nomail;
2283
2284 $status = $P{status};
2285 $warn = $P{warn}||2;
2286 $autodelete = $P{autodelete}||$::autodelete;
2287 $comment = $P{comment}||'';
2288 $comment = encode_utf8($P{comment}||'') if utf8::is_utf8($comment);
2289 $comment =~ s/^!\*!//; # multi download allow flag
2290 chomp $comment;
2291
2292 $index = $tools = $durl;
2293 $index =~ s/fop$/index.html/;
2294 $tools =~ s/fop$/tools.html/;
2295
2296 if ($share = $P{share}) {
2297 $filed = $P{filed};
2298 $to = $P{to};
2299 $from = $P{from};
2300 $file = $filename = $P{filename};
2301 $durl = $P{durl};
2302 } else {
2303 $filed = untaint(readlink("$dkeydir/$P{dkey}"));
2304 $filed =~ s/^\.\.\///;
2305 ($to,$from,$file) = split('/',$filed);
2306 $filename = strip_path($P{filename});
2307 }
2308
2309 return '' unless $to;
2310 return '' unless $from;
2311 return '' unless length($filename);
2312
2313 # make download protocal same as upload protocol
2314 if ($uurl = readlink("$filed/uurl") and $uurl =~ /^(https?):/) {
2315 $proto = $1;
2316 $durl =~ s/^https?:/$proto:/;
2317 $durl =~ s/:\d+\b// if $durl =~ /^https:/;
2318 }
2319 ($mfrom,$hfrom) = mhfrom($from);
2320 $mto = $to;
2321 $replyto = $P{replyto}||$from;
2322 $keyring = $to.'/@GPG';
2323 $header = "From: <$mfrom> ($hfrom via F*EX service $hostname)\n";
2324 $header .= "Reply-To: <$replyto>\n" if $replyto ne $mfrom;
2325 $header .= "To: <$mto>\n";
2326 $data = "$filed/data";
2327 $alist = "$filed/alist";
2328 $size = $bytes = -s $data;
2329 return unless $size;
2330
2331 $warning =
2332 "We recommend fexget or fexit for download,\n".
2333 "because these clients can resume the download after an interruption.\n".
2334 "See $tools";
2335 # if ($nowarning) {
2336 # $warning = '';
2337 # } else {
2338 # $warning =
2339 # "Please avoid download with Internet Explorer, ".
2340 # "because it has too many bugs.\n\n";
2341 # }
2342 if ($filename =~ /\.(tar|tgz|tar\.gz|zip|7z|arj|rar)$/) {
2343 $warning .= "\n\n".
2344 "$filename is a container file.\n".
2345 "You can unpack it for example with 7zip ".
2346 "(http://www.7-zip.org/download.html)";
2347 }
2348 if ($limited_download =~ /^y/i and $from ne $to) {
2349 $warning .=
2350 "\n\n".
2351 'This download link only works for you, you cannot distribute it.';
2352 }
2353 if ($size < 2048) {
2354 $size = "$size Bytes";
2355 } elsif ($size/1024 < 2048) {
2356 $size = int($size/1024)." kB";
2357 } else {
2358 $size = int($size/$MB)." MB";
2359 }
2360 if ($autodelete eq 'YES') {
2361 $autodelete = "WARNING: After download (or view with a web browser!), "
2362 . "the file will be deleted!";
2363 } elsif ($autodelete eq 'DELAY') {
2364 $autodelete = "WARNING: When you download the file it will be deleted "
2365 . "soon afterwards!";
2366 } else {
2367 $autodelete = '';
2368 }
2369
2370 if (-s $keyring) {
2371 $mimefilename = '';
2372 } else {
2373 $mimefilename = $filename;
2374 if ($mimefilename =~ s/([\?\=\x00-\x1F\x7F-\xFF])/sprintf("=%02X",ord($1))/eog) {
2375 $mimefilename =~ s/ /_/g;
2376 $mimefilename = '=?UTF-8?Q?'.$mimefilename.'?=';
2377 }
2378 }
2379
2380 unless ($fileid = readlink("$filed/id")) {
2381 my @s = stat($data);
2382 $fileid = @s ? $s[1].$s[9] : 0;
2383 }
2384
2385 if ($share) {
2386 $header .= "Subject: new F*EX share archive: $share:$mimefilename\n";
2387 } elsif ($status =~ /new/) {
2388 $days = $P{keep};
2389 $header .= "Subject: F*EX-upload: $mimefilename\n";
2390 } else {
2391 $days = $warn;
2392 $header .= "Subject: reminder F*EX-upload: $mimefilename\n";
2393 }
2394 $header .= "X-FEX-Client-Address: $fra\n" if $fra;
2395 $header .= "X-FEX-Client-Agent: $fua\n" if $fua;
2396 if ($share) {
2397 $download = "$durl\n";
2398 } else {
2399 foreach my $u (@durl?@durl:($durl)) {
2400 my $durl = sprintf("%s/%s/%s",$u,$P{dkey},urlencode($filename));
2401 $header .= "X-FEX-URL: $durl\n" unless -s $keyring;
2402 $download .= "$durl\n";
2403 }
2404 }
2405 $header .=
2406 "X-FEX-Filesize: $bytes\n".
2407 "X-FEX-File-ID: $fileid\n".
2408 "X-FEX-Fexmaster: $admin\n".
2409 "X-Mailer: F*EX\n".
2410 "MIME-Version: 1.0\n";
2411 if ($comment =~ s/^\[(\@(.*?))\]\s*//) {
2412 $receiver = "group $1";
2413 if ($_ = readlink "$from/\@GROUP/$2" and m:^../../(.+?)/:) {
2414 $receiver .= " (maintainer: $1)";
2415 }
2416 } else {
2417 $receiver = 'you';
2418 }
2419 if ($days == 1) { $days .= " day" }
2420 else { $days .= " days" }
2421
2422 # explicite sender set in fex.ph?
2423 if ($sender_from) {
2424 # obsoleted feature!
2425 map { s/^From: <\Q$mfrom/From: <$sender_from/ } $header;
2426 open $sendmail,'|-',$sendmail,$mto,$bcc
2427 or http_die("cannot start sendmail - $!");
2428 } else {
2429 # for special remote domains do not use same domain in From,
2430 # because remote MTA will probably reject this email
2431 $dfrom = $1 if $mfrom =~ /@(.+)/;
2432 $dto = $1 if $mto =~ /@(.+)/;
2433 if ($dfrom and $dto and @remote_domains and
2434 grep { $dfrom =~ /(^|\.)$_$/ and $dto =~ /(^|\.)$_$/ } @remote_domains)
2435 {
2436 $header =~ s/(From: <)\Q$mfrom\E(.*?)\n/$1$admin$2\nReply-To: $mfrom\n/;
2437 open $sendmail,'|-',$sendmail,$mto,$bcc
2438 or http_die("cannot start sendmail - $!");
2439 } else {
2440 open $sendmail,'|-',$sendmail,'-f',$mfrom,$mto,$bcc
2441 or http_die("cannot start sendmail - $!");
2442 }
2443 }
2444 if (length($comment)) {
2445 $comment = '. ' if $comment eq '.';
2446 $comment = "\n$comment\n"
2447 }
2448 if ($share) {
2449 $disclaimer = "\n$::disclaimer\n" if $::disclaimer;
2450 $body = qqq(qq(
2451 '$comment'
2452 '$from has uploaded the archive file'
2453 ' "$filename" ($size)'
2454 'for share $share. See'
2455 ''
2456 '$download'
2457 '$disclaimer'
2458 ));
2459 } else {
2460 if ($comment =~ s/\n!(shortmail|\.)!\s*//i
2461 or (readlink("$to/\@NOTIFICATION")||'') =~ /short/i
2462 ) {
2463 $body = $comment."\n".$download."\n".$size;
2464 } else {
2465 $disclaimer = slurp("$from/\@DISCLAIMER") || qqq(qq(
2466 '$warning'
2467 ''
2468 'F*EX is not an archive, it is a transfer system for personal files.'
2469 'For more information see $index'
2470 ''
2471 'Questions? ==> F*EX admin: $admin'
2472 ));
2473 $disclaimer .= "\n$::disclaimer\n" if $::disclaimer;
2474 $body = qqq(qq(
2475 '$comment'
2476 '$from has uploaded the file'
2477 ' "$filename" ($size)'
2478 'for $receiver. Use'
2479 ''
2480 '$download'
2481 'to download this file within $days.'
2482 ''
2483 '$autodelete'
2484 ''
2485 '$disclaimer'
2486 ));
2487 }
2488 }
2489 $body =~ s/\n\n+/\n\n/g;
2490 if (-s $keyring) {
2491 $enc_body = gpg_encrypt($body,$to,$keyring,$from);
2492 }
2493 if ($enc_body) {
2494 # RFC3156
2495 $header .= qqq(qq(
2496 'Content-Type: multipart/encrypted; protocol="application/pgp-encrypted";'
2497 '\tboundary="$boundary"'
2498 'Content-Disposition: inline'
2499 ));
2500 $body = qqq(qq(
2501 '--$boundary'
2502 'Content-Type: application/pgp-encrypted'
2503 'Content-Disposition: attachment'
2504 ''
2505 'Version: 1'
2506 ''
2507 '--$boundary'
2508 'Content-Type: application/octet-stream'
2509 'Content-Disposition: inline; filename="fex.pgp"'
2510 ''
2511 '$enc_body'
2512 '--$boundary--'
2513 ));
2514 } else {
2515 $header .=
2516 "Content-Type: text/plain; charset=UTF-8\n".
2517 "Content-Transfer-Encoding: 8bit\n";
2518 }
2519 print {$sendmail} $header,"\n",$body;
2520 close $sendmail and return $to;
2521 http_die("cannot send notification email (sendmail error $!)");
2522 }
2523
2524
2525 # locale function!
2526 sub reactivation {
2527 my ($expire,$user) = @_;
2528 my $fexsend = "$FEXHOME/bin/fexsend";
2529 my $reactivation = "$FEXLIB/reactivation.txt";
2530
2531 return if $nomail;
2532
2533 if (-x $fexsend) {
2534 if ($locale) {
2535 my $lr = "$FEXHOME/locale/$locale/lib/reactivation.txt";
2536 $reactivation = $lr if -f $lr and -s $lr;
2537 }
2538 $fexsend .= " -M -D -k 30 -C"
2539 ." 'Your F*EX account $user has been inactive for $expire days,"
2540 ." you must download this file to reactivate it."
2541 ." Otherwise your account will be deleted.'"
2542 ." $reactivation $user";
2543 # on error show STDOUT and STDERR
2544 my $fo = `$fexsend 2>&1`;
2545 warn $fexsend."\n".$fo if $?;
2546 } else {
2547 warn "$0: cannot execute $fexsend for reactivation()\n";
2548 }
2549 }
2550
2551 1;