-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwoof.pl
More file actions
executable file
·1439 lines (1133 loc) · 44.4 KB
/
Copy pathwoof.pl
File metadata and controls
executable file
·1439 lines (1133 loc) · 44.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env perl
# -*- encoding: utf-8 -*-
#
# woof.pl -- an ad-hoc single file webserver
# Perl port of woof by Simon Budig <simon@budig.de>
#
# Copyright (C) 2025, Francesco P Lovergine <pobox@lovergine.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# A copy of the GNU General Public License is available at
# http://www.fsf.org/licenses/gpl.txt, you can also write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
use strict;
use warnings;
use File::Basename;
use File::Temp qw(tempfile);
use File::Find;
use File::Copy;
use File::Spec;
use Fcntl qw(:flock :DEFAULT O_WRONLY O_CREAT O_EXCL);
use Errno qw(EEXIST);
use Cwd qw(abs_path getcwd);
use POSIX qw(:sys_wait_h :signal_h);
use Getopt::Long qw(:config gnu_getopt);
use Config::IniFiles;
use Term::ReadLine;
use IO::Socket::INET;
use Socket qw(inet_ntoa sockaddr_in);
use URI::Escape;
use LWP::UserAgent;
use HTTP::Status qw(:constants status_message);
use Archive::Tar;
use Archive::Zip;
use IO::Compress::Gzip qw(gzip $GzipError);
use IO::Compress::Bzip2 qw(bzip2 $Bzip2Error);
# Global variables
our %GLOBS = (
maxdownloads => 1,
compressed => 'gz',
upload => 0,
upload_dir => '.',
show_progress => 1,
filename => '',
archive_ext => '',
server_running => 1,
downloads_count => 0,
redirect_count => 0,
);
# Set up signal handling for parent/child communication
$SIG{CHLD} = \&sig_child_handler;
$SIG{USR1} = \&sig_download_complete;
$SIG{INT} = \&sig_interrupt_handler;
$SIG{TERM} = \&sig_terminate_handler;
# Signal handlers
sub sig_child_handler {
# Reap dead child processes
while ((my $pid = waitpid(-1, WNOHANG)) > 0) {
# Child process terminated
}
$SIG{CHLD} = \&sig_child_handler; # Reset handler
}
sub sig_download_complete {
$GLOBS{downloads_count}++;
warn "Download completed. Count: $GLOBS{downloads_count}/$GLOBS{maxdownloads}\n";
if ($GLOBS{downloads_count} >= $GLOBS{maxdownloads}) {
warn "Maximum downloads reached. Shutting down server...\n";
$GLOBS{server_running} = 0;
}
$SIG{USR1} = \&sig_download_complete; # Reset handler
}
sub sig_interrupt_handler {
warn "\nReceived interrupt signal. Shutting down server...\n";
$GLOBS{server_running} = 0;
}
sub sig_terminate_handler {
warn "\nReceived termination signal. Shutting down server...\n";
$GLOBS{server_running} = 0;
}
# Utility function to guess the IP (as a string) where the server can be
# reached from the outside. Quite nasty problem actually.
sub find_ip {
# We get a UDP-socket for the TEST-networks reserved by IANA.
# It is highly unlikely, that there is special routing used
# for these networks, hence the socket later should give us
# the ip address of the default route.
# We're doing multiple tests, to guard against the computer being
# part of a test installation.
my @candidates = ();
for my $test_ip ("192.0.2.0", "198.51.100.0", "203.0.113.0") {
my $sock = IO::Socket::INET->new(
Proto => 'udp',
PeerAddr => $test_ip,
PeerPort => 80,
);
if ($sock) {
my $ip_addr = $sock->sockhost;
$sock->close();
if (grep { $_ eq $ip_addr } @candidates) {
return $ip_addr;
}
push @candidates, $ip_addr;
}
}
return $candidates[0] if @candidates;
return "127.0.0.1"; # Fallback
}
# Determine MIME type of a file
sub get_mime_type($) {
my ($file_name) = @_;
my $mime_type;
# Try to use File::MimeInfo::Magic if available
if (eval { require File::MimeInfo::Magic; 1 }) {
$mime_type = File::MimeInfo::Magic::mimetype($file_name);
}
# Fallback to basic extension mapping
if (!$mime_type) {
my %mime_map = (
'txt' => 'text/plain',
'html' => 'text/html',
'htm' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'png' => 'image/png',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'svg' => 'image/svg+xml',
'pdf' => 'application/pdf',
'zip' => 'application/zip',
'gz' => 'application/gzip',
'tar' => 'application/x-tar',
'mp3' => 'audio/mpeg',
'mp4' => 'video/mp4',
);
if ($file_name =~ /\.([^.]+)$/) {
my $ext = lc($1);
$mime_type = $mime_map{$ext} if exists $mime_map{$ext};
}
}
# Fallback to binary type
return $mime_type || 'application/octet-stream';
}
# Send HTTP response header
sub send_http_header($$$$$$) {
my ($client, $code, $message, $content_type, $content_length, $headers) = @_;
$headers ||= {};
print $client "HTTP/1.0 $code $message\r\n";
print $client "Content-Type: $content_type\r\n";
print $client "Content-Length: $content_length\r\n" if defined $content_length;
print $client "Server: woof-perl/1.0\r\n";
for my $key (keys %$headers) {
print $client "$key: $headers->{$key}\r\n";
}
print $client "\r\n";
}
# Parse HTTP request
sub parse_http_request($) {
my ($client) = @_;
my $request = {};
# Read request line
my $request_line = <$client>;
return undef unless defined $request_line;
chomp $request_line;
$request_line =~ s/\r$//;
if ($request_line =~ /^(GET|POST|HEAD) ([^ ]+) HTTP\/(\d\.\d)$/) {
$request->{method} = $1;
$request->{uri} = $2;
$request->{http_version} = $3;
} else {
return undef;
}
# Read headers
$request->{headers} = {};
my $content_length = 0;
while (my $line = <$client>) {
chomp $line;
$line =~ s/\r$//;
last if $line eq '';
if ($line =~ /^([^:]+):\s*(.*)$/) {
my ($key, $value) = (lc($1), $2);
$request->{headers}{$key} = $value;
$content_length = $value if $key eq 'content-length';
}
}
# Read POST data if applicable
if ($request->{method} eq 'POST' && $content_length > 0) {
$request->{content} = '';
my $remaining = $content_length;
while ($remaining > 0) {
my $buffer;
my $bytes_read = read($client, $buffer, $remaining > 8192 ? 8192 : $remaining);
last if !defined $bytes_read || $bytes_read == 0;
$request->{content} .= $buffer;
$remaining -= $bytes_read;
}
}
return $request;
}
# Parse multipart form data
sub parse_multipart_form($$) {
my ($content, $boundary) = @_;
my $form_data = {};
# Split content by boundary
my @parts = split(/--\Q$boundary\E(?:--)?\r?\n/, $content);
# Process each part (skip first empty part)
for my $part (@parts[1..$#parts]) {
next if $part =~ /^\s*$/;
my ($headers, $body) = split(/\r?\n\r?\n/, $part, 2);
my $headers_hash = {};
# Parse headers
for my $header (split(/\r?\n/, $headers)) {
if ($header =~ /^([^:]+):\s*(.*)$/) {
$headers_hash->{lc($1)} = $2;
}
}
# Extract Content-Disposition info
my $name;
my $file_name;
if ($headers_hash->{'content-disposition'} =~ /form-data; name="([^"]+)"/) {
$name = $1;
}
if ($headers_hash->{'content-disposition'} =~ /filename="([^"]+)"/) {
$file_name = $1;
# Handle file uploads
$form_data->{$name} = {
filename => $file_name,
content => $body,
type => $headers_hash->{'content-type'} || 'application/octet-stream',
};
} else {
# Handle regular form fields
$form_data->{$name} = $body;
}
}
return $form_data;
}
# Handle file upload
sub handle_upload($) {
my ($request) = @_;
if (!$GLOBS{upload}) {
return (HTTP_NOT_IMPLEMENTED, status_message(HTTP_NOT_IMPLEMENTED), "text/plain", "Uploads are disabled");
}
# Parse Content-Type to get boundary
my $boundary;
if ($request->{headers}{'content-type'} =~ /boundary=(.+)$/) {
$boundary = $1;
} else {
return (400, "Bad Request", "text/plain", "No boundary found in multipart/form-data");
}
# Parse form data
my $form_data = parse_multipart_form($request->{content}, $boundary);
# Check for uploaded file
if (!exists $form_data->{upfile}) {
return (403, "Forbidden", "text/plain", "No upload provided");
}
my $upfile = $form_data->{upfile};
my $upfilename = $upfile->{filename};
# Extract filename from path and sanitize
if ($upfilename =~ /[\\\/]/) {
$upfilename = basename($upfilename);
}
# Basic security: Prevent directory traversal
$upfilename =~ s/[^a-zA-Z0-9_\-\.]/_/g;
$upfilename =~ s/\.\./_/g;
my $destfile;
my $destfilename;
# Try multiple filenames
for my $suffix ('', '.1', '.2', '.3', '.4', '.5', '.6', '.7', '.8', '.9') {
$destfilename = File::Spec->catfile($GLOBS{upload_dir}, $upfilename . $suffix);
if (sysopen($destfile, $destfilename, O_WRONLY | O_CREAT | O_EXCL, 0644)) {
last;
} elsif ($! != EEXIST) {
return (HTTP_INTERNAL_SERVER_ERROR, status_message(HTTP_INTERNAL_SERVER_ERROR), "text/plain", "Failed to open $destfilename: $!");
}
}
# If all failed, use tempfile
if (!defined $destfile) {
($destfile, $destfilename) = tempfile($upfilename . ".XXXXXX", DIR => $GLOBS{upload_dir});
}
warn "Accepting uploaded file: $upfilename -> $destfilename\n";
# Write file content
print $destfile $upfile->{content};
close($destfile);
my $html = <<HTML;
<!DOCTYPE html>
<html>
<head>
<title>Woof Upload</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
h1 { color: #4CAF50; }
.success { background-color: #e8f5e9; border-left: 5px solid #4CAF50; padding: 10px; }
</style>
</head>
<body>
<h1>Woof Upload Complete</h1>
<div class="success">
<p>File successfully uploaded as: <strong>$destfilename</strong></p>
<p>File size: <strong>@{[length($upfile->{content})]} bytes</strong></p>
</div>
<p><a href="/">Upload another file</a></p>
</body>
</html>
HTML
return (HTTP_OK, status_message(HTTP_OK), "text/html", $html);
}
# Handle HTTP requests
sub handle_request($) {
my ($client) = @_;
# Get peer address
my $peeraddr = getpeername($client);
my ($port, $addr) = sockaddr_in($peeraddr);
my $client_ip = inet_ntoa($addr);
my $client_port = $port;
warn "Connection from $client_ip:$client_port\n";
# Parse HTTP request
my $request = parse_http_request($client);
if (!defined $request) {
my $msg = status_message(HTTP_BAD_REQUEST);
send_http_header($client, HTTP_BAD_REQUEST, $msg, "text/plain", length($msg), undef);
print $client $msg;
close($client);
return;
}
warn "Request: $request->{method} $request->{uri}\n";
# Handle different HTTP methods
if ($request->{method} eq 'POST') {
my ($code, $message, $content_type, $content) = handle_upload($request);
send_http_header($client, $code, $message, $content_type, length($content), undef);
print $client $content;
close($client);
}
elsif ($request->{method} eq 'GET' || $request->{method} eq 'HEAD') {
if ($GLOBS{upload}) {
# Serve upload form
my $html = <<HTML;
<!DOCTYPE html>
<html>
<head>
<title>Woof Upload</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
h1 { color: #2196F3; }
.upload-form { background-color: #e3f2fd; padding: 20px; border-radius: 5px; }
.upload-form input[type="file"] { margin: 10px 0; }
.upload-form input[type="submit"] {
background-color: #2196F3; color: white; padding: 10px 15px;
border: none; border-radius: 4px; cursor: pointer;
}
.upload-form input[type="submit"]:hover { background-color: #0b7dda; }
</style>
</head>
<body>
<h1>Woof Upload</h1>
<div class="upload-form">
<form name="upload" method="POST" enctype="multipart/form-data">
<p>Select file to share:</p>
<input type="file" name="upfile" />
<p><input type="submit" value="Upload!" /></p>
</form>
</div>
</body>
</html>
HTML
my $msg = status_message(HTTP_OK);
send_http_header($client, HTTP_OK, $msg, "text/html", length($html), undef);
print $client $html if $request->{method} eq 'GET';
close($client);
}
else {
# Redirect any request to the filename of the file to serve
my $path = $request->{uri};
my $location = "/";
if ($GLOBS{filename}) {
$location .= uri_escape(basename($GLOBS{filename}));
if (-d $GLOBS{filename}) {
if ($GLOBS{compressed} eq 'gz') {
$location .= ".tar.gz";
} elsif ($GLOBS{compressed} eq 'bz2') {
$location .= ".tar.bz2";
} elsif ($GLOBS{compressed} eq 'zip') {
$location .= ".zip";
} else {
$location .= ".tar";
}
}
}
if ($path ne $location) {
# Send redirect
my $code = HTTP_FOUND;
my $msg = status_message($code);
my $html = <<HTML;
<!DOCTYPE html>
<html>
<head><title>$code $msg</title></head>
<body>$code $msg <a href="$location">here</a>.</body>
</html>
HTML
send_http_header($client, $code, $msg, "text/html", length($html), {
'Location' => $location
});
print $client $html if $request->{method} eq 'GET';
close($client);
$GLOBS{redirect_count}++;
}
else {
# Serve the file
warn "$request->{method} request received for: " . basename($GLOBS{filename}) . "\n";
# For HEAD requests, serve headers only and don't fork or count
if ($request->{method} eq 'HEAD') {
handle_head_request($client);
close($client);
}
else {
# Create a child process to handle GET downloads
my $pid = fork();
if (!defined $pid) {
# Fork failed
warn "Fork failed: $!\n";
my $msg = status_message(HTTP_INTERNAL_SERVER_ERROR);
send_http_header($client, HTTP_INTERNAL_SERVER_ERROR, $msg, "text/plain", length($msg), undef);
print $client $msg;
close($client);
}
elsif ($pid == 0) {
# Child process - handle the download
eval {
serve_file($client, $request->{method});
};
warn "Error serving file: $@" if $@;
# Only signal completion for GET requests (actual downloads)
kill USR1 => getppid();
# Exit child process
exit(0);
}
else {
# Parent process - close our copy of the client socket and continue
close($client);
}
}
}
}
}
else {
# Method not implemented
my $msg = status_message(HTTP_NOT_IMPLEMENTED);
send_http_header($client, HTTP_NOT_IMPLEMENTED, $msg, "text/plain", length($msg), undef);
print $client $msg;
close($client);
}
}
# Handle HEAD requests - just send headers without counting as a download
sub handle_head_request($) {
my ($client) = @_;
my $type = undef;
$type = "file" if -f $GLOBS{filename};
$type = "dir" if -d $GLOBS{filename};
return unless $type;
my $download_filename = basename($GLOBS{filename});
$download_filename .= $GLOBS{archive_ext} if defined $GLOBS{archive_ext} && $GLOBS{archive_ext} ne '';
my $content_type;
my $headers = {
'Content-Disposition' => 'attachment; filename="' . uri_escape($download_filename) . '"'
};
if ($type eq "file") {
$content_type = get_mime_type($GLOBS{filename});
my $filesize = -s $GLOBS{filename};
$headers->{'Content-Length'} = $filesize if defined $filesize;
} else {
# For directories, use appropriate type based on compression
if ($GLOBS{compressed} eq 'zip') {
$content_type = 'application/zip';
} elsif ($GLOBS{compressed} eq 'gz') {
$content_type = 'application/gzip';
} elsif ($GLOBS{compressed} eq 'bz2') {
$content_type = 'application/x-bzip2';
} else {
$content_type = 'application/x-tar';
}
}
# Send headers only for HEAD request
send_http_header($client, HTTP_OK, status_message(HTTP_OK), $content_type,
($type eq "file" ? (-s $GLOBS{filename}) : undef), $headers);
warn "HEAD request handled without download count increment\n";
}
# Serve a file or directory
sub serve_file($$) {
my ($client, $method) = @_;
my $type = undef;
$type = "file" if -f $GLOBS{filename};
$type = "dir" if -d $GLOBS{filename};
die "can only serve files or directories. Aborting.\n" if !$type;
my $download_filename = basename($GLOBS{filename});
$download_filename .= $GLOBS{archive_ext} if defined $GLOBS{archive_ext} && $GLOBS{archive_ext} ne '';
my $content_type;
my $headers = {
'Content-Disposition' => 'attachment; filename="' . uri_escape($download_filename) . '"'
};
if ($type eq "file") {
$content_type = get_mime_type($GLOBS{filename});
my $filesize = -s $GLOBS{filename};
$headers->{'Content-Length'} = $filesize if defined $filesize;
} else {
# For directories, use appropriate type based on compression
if ($GLOBS{compressed} eq 'zip') {
$content_type = 'application/zip';
} elsif ($GLOBS{compressed} eq 'gz') {
$content_type = 'application/gzip';
} elsif ($GLOBS{compressed} eq 'bz2') {
$content_type = 'application/x-bzip2';
} else {
$content_type = 'application/x-tar';
}
}
send_http_header($client, HTTP_OK, status_message(HTTP_OK), $content_type,
($type eq "file" ? (-s $GLOBS{filename}) : undef), $headers);
# Only send content for GET requests
return if $method eq 'HEAD';
warn "Serving content: " . basename($GLOBS{filename}) .
($GLOBS{archive_ext} ? $GLOBS{archive_ext} : '') . "\n";
if ($type eq "file") {
open(my $datafile, "<", $GLOBS{filename}) or die "Can't open $GLOBS{filename} $!";
binmode($datafile);
binmode($client);
my $filesize = -s $GLOBS{filename};
my $bytes_sent = 0;
my $last_percent = 0;
my $buffer;
while (my $bytes_read = read($datafile, $buffer, 8192)) {
print $client $buffer;
# Update progress if enabled
if ($GLOBS{show_progress} && $filesize > 0) {
$bytes_sent += $bytes_read;
my $percent = int($bytes_sent * 100 / $filesize);
if ($percent >= $last_percent + 10) {
warn "Transfer progress: $percent%\n";
$last_percent = $percent;
}
}
}
close($datafile);
}
elsif ($type eq "dir") {
binmode($client);
warn "Creating archive for directory: $GLOBS{filename}\n";
# Determine the base directory path for proper path handling
my $dir_path = $GLOBS{filename};
my $base_name = basename($dir_path);
my $parent_dir = dirname($dir_path);
if ($GLOBS{compressed} eq 'zip') {
my $zip = Archive::Zip->new();
warn "Creating ZIP archive...\n";
my $file_count = 0;
# Change to parent directory to handle relative paths
my $cwd = getcwd();
chdir($parent_dir) or die "Cannot change to directory $parent_dir: $!";
# Use a relative path for Find to preserve proper structure
find(sub {
return if -d $File::Find::name;
$file_count++;
# Use a path relative to parent directory
my $rel_path = $File::Find::name;
$rel_path =~ s!^\Q$parent_dir\E/!!;
# Add with relative path
$zip->addFile($File::Find::name, $rel_path);
# Occasionally report progress
warn "Added $file_count files to archive...\n" if $file_count % 100 == 0;
}, $base_name);
# Restore original directory
chdir($cwd) or die "Cannot change back to directory $cwd: $!";
warn "Writing ZIP archive with $file_count files...\n";
$zip->writeToFileHandle($client);
}
else {
warn "Creating TAR archive...\n";
# Create a tar archive with proper relative paths
my $tar = Archive::Tar->new();
# Change to parent directory to handle relative paths
my $cwd = getcwd();
chdir($parent_dir) or die "Cannot change to directory $parent_dir: $!";
# Add files with relative paths
my @files_to_add = ();
find(sub {
# Get path relative to parent dir
my $rel_path = $File::Find::name;
$rel_path =~ s!^\Q$parent_dir\E/!!;
push @files_to_add, $rel_path;
}, $base_name);
# Add files with proper relative paths
$tar->add_files(@files_to_add);
# Restore original directory
chdir($cwd) or die "Cannot change back to directory $cwd: $!";
if ($GLOBS{compressed} eq 'gz') {
warn "Compressing with gzip...\n";
my $tar_data = $tar->write();
gzip \$tar_data => $client or die "gzip failed: $GzipError\n";
}
elsif ($GLOBS{compressed} eq 'bz2') {
warn "Compressing with bzip2...\n";
my $tar_data = $tar->write();
bzip2 \$tar_data => $client or die "bzip2 failed: $Bzip2Error\n";
}
else {
warn "Writing uncompressed tar...\n";
$tar->write($client);
}
}
}
warn "Download complete for: " . basename($GLOBS{filename}) .
($GLOBS{archive_ext} ? $GLOBS{archive_ext} : '') . "\n";
# Close the client connection after serving the file
close($client);
}
# Convert time diffs to hh:mm:ss
sub time_to_hms($) {
my $time = shift;
my $hours = int($time / 3600);
my $minutes = int(($time % 3600) / 60);
my $seconds = $time % 60;
return ($hours, $minutes, $seconds);
}
# Main server function
sub serve_files($$$$) {
my ($filename_to_serve, $maxdown, $ip_addr, $port) = @_;
$GLOBS{maxdownloads} = $maxdown;
$GLOBS{filename}= $filename_to_serve;
$GLOBS{downloads_count} = 0;
$GLOBS{redirect_count} = 0;
$GLOBS{server_running} = 1;
$GLOBS{archive_ext} = "";
if ($GLOBS{filename} && -d $GLOBS{filename}) {
if ($GLOBS{compressed} eq 'gz') {
$GLOBS{archive_ext} = ".tar.gz";
} elsif ($GLOBS{compressed} eq 'bz2') {
$GLOBS{archive_ext} = ".tar.bz2";
} elsif ($GLOBS{compressed} eq 'zip') {
$GLOBS{archive_ext} = ".zip";
} else {
$GLOBS{archive_ext} = ".tar";
}
}
# Create listening socket
my $server = IO::Socket::INET->new(
LocalAddr => $ip_addr || '0.0.0.0',
LocalPort => $port,
Proto => 'tcp',
ReuseAddr => 1,
Listen => 5,
) or die "Cannot create socket: $!\n";
# Get real IP address if not specified
$ip_addr = find_ip() if !$ip_addr;
if ($ip_addr) {
my $location;
if ($GLOBS{filename}) {
$location = "http://$ip_addr:$port/" .
uri_escape(basename($GLOBS{filename}) . $GLOBS{archive_ext});
} else {
$location = "http://$ip_addr:$port/";
}
print "Now serving on $location\n";
print "Server will exit after $GLOBS{maxdownloads} download(s). Press CTRL-C to abort.\n";
}
# Set up non-blocking mode for server socket
my $flags = fcntl($server, F_GETFL, 0)
or die "Can't get flags for socket: $!\n";
fcntl($server, F_SETFL, $flags | O_NONBLOCK)
or die "Can't set socket to non-blocking mode: $!\n";
# Main server loop
my $start_time = time();
while ($GLOBS{server_running} && $GLOBS{downloads_count} < $GLOBS{maxdownloads}) {
# Accept new connections (non-blocking)
my $client = $server->accept();
handle_request($client) if $client;
# Give other processes a chance to run
select(undef, undef, undef, 0.1);
# Periodically show server status if running for a while
if (time() - $start_time > 300 && (time() - $start_time) % 300 < 1) {
my $runtime = time() - $start_time;
my ($hours, $minutes, $seconds) = time_to_hms($runtime);
warn sprintf("Server status: running for %d:%02d:%02d, served %d/%d downloads\n",
$hours, $minutes, $seconds, $GLOBS{downloads_count}, $GLOBS{maxdownloads});
}
}
my $runtime = time() - $start_time;
my ($hours, $minutes, $seconds) = time_to_hms($runtime);
print "\nServer stopped after serving $GLOBS{downloads_count} of $GLOBS{maxdownloads} download(s)\n";
printf "Total runtime: %d:%02d:%02d\n", $hours, $minutes, $seconds;
print "Received $GLOBS{redirect_count} connection(s) total\n";
close($server);
}
sub woof_client($) {
my ($url) = @_;
# Support for non-interactive testing
my $noninteractive = defined $ENV{WOOF_NONINTERACTIVE} && $ENV{WOOF_NONINTERACTIVE};
my $overwrite_existing = defined $ENV{WOOF_OVERWRITE_EXISTING} && $ENV{WOOF_OVERWRITE_EXISTING};
# Check if URL is valid
if ($url !~ m{^(http|https)://}) {
return undef;
}
print "Connecting to $url...\n";
# Set up signal handling for clean interruption
local $SIG{INT} = sub {
print "\nDownload interrupted by user.\n";
exit 1;
};
# Create a user agent with minimal configuration
my $ua = LWP::UserAgent->new(
timeout => 60,
keep_alive => 1,
);
# First make a HEAD request to get headers without downloading content
my $head_response = $ua->head($url);
if (!$head_response->is_success) {
die "Failed to connect to $url: " . $head_response->status_line . "\n";
}
# Get filename from Content-Disposition header or from URL
my $fname;
my $disposition = $head_response->header('Content-Disposition');
if ($disposition && $disposition =~ /^attachment;\s*filename="?([^"]+)"?/i) {
$fname = $1;
} else {
$fname = basename($url);
$fname =~ s/\?.*$//; # Remove query parameters
}
$fname = "woof-out.bin" if !$fname;
$fname = uri_unescape($fname);
$fname = basename($fname);
# Get content type and size - ensure we have a clean numeric value
my $content_type = $head_response->header('Content-Type') || 'application/octet-stream';
my $content_length = $head_response->header('Content-Length');
$content_length = 0 + $content_length if defined $content_length; # Force numeric context
# Override with environment variable if in non-interactive mode
if ($noninteractive && defined $ENV{WOOF_DEFAULT_FILENAME} && $ENV{WOOF_DEFAULT_FILENAME} ne '') {
$fname = $ENV{WOOF_DEFAULT_FILENAME};
print "Using target filename: $fname (non-interactive mode)\n";
} else {
# Ask user for the target filename
my $term = Term::ReadLine->new('woof');
$term->ornaments(0);
$term->add_history($fname);
my $input = $term->readline("Enter target filename [$fname]: ");
$fname = $input || $fname;
}
my $destfilename = $fname =~ m{^/} ? $fname : "./$fname";
my $fh; # File handle declaration moved outside of blocks for wider scope
# Try to create a new file
my $create_new = eval {
sysopen($fh, $destfilename, O_WRONLY | O_CREAT | O_EXCL, 0644);
};
# Handle file exists case
if (!$create_new && $! == EEXIST) {
my $override;
if ($noninteractive) {
$override = $overwrite_existing;
print "File exists. " . ($override ? "Overwriting" : "Not overwriting") . " (non-interactive mode)\n";
} else {
my $term = Term::ReadLine->new('woof');
$term->ornaments(0);
my $input = $term->readline("File exists. Overwrite (y/n)? ");
$override = ($input =~ /^y(es)?$/i);
}
if ($override) {
# Create a new file, truncating if it exists
unless (open($fh, ">", $destfilename)) {
die "Failed to open $destfilename for overwriting: $!\n";
}
} else {
# Try alternative filenames
my $found = 0;
for my $suffix (".1", ".2", ".3", ".4", ".5", ".6", ".7", ".8", ".9") {
my $alt_name = $destfilename . $suffix;
if (sysopen($fh, $alt_name, O_WRONLY | O_CREAT | O_EXCL, 0644)) {
$destfilename = $alt_name;
$found = 1;
last;
} elsif ($! != EEXIST) {
die "Failed to open $alt_name: $!\n";
}
}
# If still not found, use tempfile
if (!$found) {
($fh, $destfilename) = tempfile("$fname.XXXXXX", DIR => ".");
}
print "alternate filename is: $destfilename\n";
}
} elsif (!$create_new) {
die "Failed to open $destfilename: $!\n";
}
binmode($fh); # Ensure binary mode for files
print "downloading file: $fname -> $destfilename\n";
if ($content_length) {
printf "File size: %d bytes (%s)\n", $content_length, format_size($content_length);
}
# Now make a request for the actual content, with streaming download
my $request = HTTP::Request->new(GET => $url);
my $total_bytes = 0;
my $last_percent = 0;
my $start_time = time();
# Use a callback to process chunks of data as they arrive
my $response = $ua->request(
$request,
sub {
my ($data, $response, $protocol) = @_;
# Write chunk to file
print $fh $data;
my $chunk_size = length($data);
$total_bytes += $chunk_size;
# Update progress display if needed
if ($GLOBS{show_progress} && $content_length && $content_length > 0) {
my $percent = int(($total_bytes * 100) / $content_length);
# Only update display when percent changes significantly
if ($percent >= $last_percent + 5) {
my $elapsed = time() - $start_time;
my $rate = $elapsed > 0 ? $total_bytes / $elapsed : 0;
printf("\rProgress: %d%% (%s / %s) - %s/sec ",
$percent,