scripts/download.pl: generilize and simplify download tool check
[openwrt/staging/stintel.git] / scripts / download.pl
1 #!/usr/bin/env perl
2 #
3 # Copyright (C) 2006 OpenWrt.org
4 # Copyright (C) 2016 LEDE project
5 #
6 # This is free software, licensed under the GNU General Public License v2.
7 # See /LICENSE for more information.
8 #
9
10 use strict;
11 use warnings;
12 use File::Basename;
13 use File::Copy;
14 use Text::ParseWords;
15
16 @ARGV > 2 or die "Syntax: $0 <target dir> <filename> <hash> <url filename> [<mirror> ...]\n";
17
18 my $url_filename;
19 my $target = glob(shift @ARGV);
20 my $filename = shift @ARGV;
21 my $file_hash = shift @ARGV;
22 $url_filename = shift @ARGV unless $ARGV[0] =~ /:\/\//;
23 my $scriptdir = dirname($0);
24 my @mirrors;
25 my $ok;
26
27 my $check_certificate = $ENV{DOWNLOAD_CHECK_CERTIFICATE} eq "y";
28
29 $url_filename or $url_filename = $filename;
30
31 sub localmirrors {
32 my @mlist;
33 open LM, "$scriptdir/localmirrors" and do {
34 while (<LM>) {
35 chomp $_;
36 push @mlist, $_ if $_;
37 }
38 close LM;
39 };
40 open CONFIG, "<".$ENV{'TOPDIR'}."/.config" and do {
41 while (<CONFIG>) {
42 /^CONFIG_LOCALMIRROR="(.+)"/ and do {
43 chomp;
44 my @local_mirrors = split(/;/, $1);
45 push @mlist, @local_mirrors;
46 };
47 }
48 close CONFIG;
49 };
50
51 my $mirror = $ENV{'DOWNLOAD_MIRROR'};
52 $mirror and push @mlist, split(/;/, $mirror);
53
54 return @mlist;
55 }
56
57 sub which($) {
58 my $prog = shift;
59 my $res = `command -v $prog`;
60 $res or return undef;
61 return $res;
62 }
63
64 sub hash_cmd() {
65 my $len = length($file_hash);
66 my $cmd;
67
68 $len == 64 and return "$ENV{'MKHASH'} sha256";
69 $len == 32 and return "$ENV{'MKHASH'} md5";
70 return undef;
71 }
72
73 sub tool_present {
74 my $tool_name = shift;
75 my $compare_line = shift;
76 my $present = 0;
77
78 if (open TOOL, "$tool_name --version 2>/dev/null |") {
79 if (defined(my $line = readline TOOL)) {
80 $present = 1 if $line =~ /^$compare_line /;
81 }
82 close TOOL;
83 }
84
85 return $present
86 }
87
88 sub download_cmd {
89 my $url = shift;
90 my $filename = shift;
91 my $additional_mirrors = join(" ", map "$_/$filename", @_);
92
93 my @chArray = ('a'..'z', 'A'..'Z', 0..9);
94 my $rfn = join '', "${filename}_", map{ $chArray[int rand @chArray] } 0..9;
95
96 if (tool_present('aria2c', 'aria2')) {
97 @mirrors=();
98 return join(" ", "[ -d $ENV{'TMPDIR'}/aria2c ] || mkdir $ENV{'TMPDIR'}/aria2c;",
99 "touch $ENV{'TMPDIR'}/aria2c/${rfn}_spp;",
100 qw(aria2c --stderr -c -x2 -s10 -j10 -k1M), $url, $additional_mirrors,
101 $check_certificate ? () : '--check-certificate=false',
102 "--server-stat-of=$ENV{'TMPDIR'}/aria2c/${rfn}_spp",
103 "--server-stat-if=$ENV{'TMPDIR'}/aria2c/${rfn}_spp",
104 "-d $ENV{'TMPDIR'}/aria2c -o $rfn;",
105 "cat $ENV{'TMPDIR'}/aria2c/$rfn;",
106 "rm $ENV{'TMPDIR'}/aria2c/$rfn $ENV{'TMPDIR'}/aria2c/${rfn}_spp");
107 } elsif (tool_present('curl', 'curl')) {
108 return (qw(curl -f --connect-timeout 20 --retry 5 --location),
109 $check_certificate ? () : '--insecure',
110 shellwords($ENV{CURL_OPTIONS} || ''),
111 $url);
112 } else {
113 return (qw(wget --tries=5 --timeout=20 --output-document=-),
114 $check_certificate ? () : '--no-check-certificate',
115 shellwords($ENV{WGET_OPTIONS} || ''),
116 $url);
117 }
118 }
119
120 my $hash_cmd = hash_cmd();
121 $hash_cmd or ($file_hash eq "skip") or die "Cannot find appropriate hash command, ensure the provided hash is either a MD5 or SHA256 checksum.\n";
122
123 sub download
124 {
125 my $mirror = shift;
126 my $download_filename = shift;
127 my @additional_mirrors = @_;
128
129 $mirror =~ s!/$!!;
130
131 if ($mirror =~ s!^file://!!) {
132 if (! -d "$mirror") {
133 print STDERR "Wrong local cache directory -$mirror-.\n";
134 cleanup();
135 return;
136 }
137
138 if (! -d "$target") {
139 system("mkdir", "-p", "$target/");
140 }
141
142 if (! open TMPDLS, "find $mirror -follow -name $filename 2>/dev/null |") {
143 print("Failed to search for $filename in $mirror\n");
144 return;
145 }
146
147 my $link;
148
149 while (defined(my $line = readline TMPDLS)) {
150 chomp ($link = $line);
151 if ($. > 1) {
152 print("$. or more instances of $filename in $mirror found . Only one instance allowed.\n");
153 return;
154 }
155 }
156
157 close TMPDLS;
158
159 if (! $link) {
160 print("No instances of $filename found in $mirror.\n");
161 return;
162 }
163
164 print("Copying $filename from $link\n");
165 copy($link, "$target/$filename.dl");
166
167 $hash_cmd and do {
168 if (system("cat '$target/$filename.dl' | $hash_cmd > '$target/$filename.hash'")) {
169 print("Failed to generate hash for $filename\n");
170 return;
171 }
172 };
173 } else {
174 my @cmd = download_cmd("$mirror/$download_filename", $download_filename, @additional_mirrors);
175 print STDERR "+ ".join(" ",@cmd)."\n";
176 open(FETCH_FD, '-|', @cmd) or die "Cannot launch aria2c, curl or wget.\n";
177 $hash_cmd and do {
178 open MD5SUM, "| $hash_cmd > '$target/$filename.hash'" or die "Cannot launch $hash_cmd.\n";
179 };
180 open OUTPUT, "> $target/$filename.dl" or die "Cannot create file $target/$filename.dl: $!\n";
181 my $buffer;
182 while (read FETCH_FD, $buffer, 1048576) {
183 $hash_cmd and print MD5SUM $buffer;
184 print OUTPUT $buffer;
185 }
186 $hash_cmd and close MD5SUM;
187 close FETCH_FD;
188 close OUTPUT;
189
190 if ($? >> 8) {
191 print STDERR "Download failed.\n";
192 cleanup();
193 return;
194 }
195 }
196
197 $hash_cmd and do {
198 my $sum = `cat "$target/$filename.hash"`;
199 $sum =~ /^(\w+)\s*/ or die "Could not generate file hash\n";
200 $sum = $1;
201
202 if ($sum ne $file_hash) {
203 print STDERR "Hash of the downloaded file does not match (file: $sum, requested: $file_hash) - deleting download.\n";
204 cleanup();
205 return;
206 }
207 };
208
209 unlink "$target/$filename";
210 system("mv", "$target/$filename.dl", "$target/$filename");
211 cleanup();
212 }
213
214 sub cleanup
215 {
216 unlink "$target/$filename.dl";
217 unlink "$target/$filename.hash";
218 }
219
220 @mirrors = localmirrors();
221
222 foreach my $mirror (@ARGV) {
223 if ($mirror =~ /^\@SF\/(.+)$/) {
224 # give sourceforge a few more tries, because it redirects to different mirrors
225 for (1 .. 5) {
226 push @mirrors, "https://downloads.sourceforge.net/$1";
227 }
228 } elsif ($mirror =~ /^\@OPENWRT$/) {
229 # use OpenWrt source server directly
230 } elsif ($mirror =~ /^\@DEBIAN\/(.+)$/) {
231 push @mirrors, "https://ftp.debian.org/debian/$1";
232 push @mirrors, "https://mirror.leaseweb.com/debian/$1";
233 push @mirrors, "https://mirror.netcologne.de/debian/$1";
234 } elsif ($mirror =~ /^\@APACHE\/(.+)$/) {
235 push @mirrors, "https://mirror.netcologne.de/apache.org/$1";
236 push @mirrors, "https://mirror.aarnet.edu.au/pub/apache/$1";
237 push @mirrors, "https://mirror.csclub.uwaterloo.ca/apache/$1";
238 push @mirrors, "https://archive.apache.org/dist/$1";
239 push @mirrors, "http://mirror.cogentco.com/pub/apache/$1";
240 push @mirrors, "http://mirror.navercorp.com/apache/$1";
241 push @mirrors, "http://ftp.jaist.ac.jp/pub/apache/$1";
242 push @mirrors, "ftp://apache.cs.utah.edu/apache.org/$1";
243 push @mirrors, "ftp://apache.mirrors.ovh.net/ftp.apache.org/dist/$1";
244 } elsif ($mirror =~ /^\@GITHUB\/(.+)$/) {
245 # give github a few more tries (different mirrors)
246 for (1 .. 5) {
247 push @mirrors, "https://raw.githubusercontent.com/$1";
248 }
249 } elsif ($mirror =~ /^\@GNU\/(.+)$/) {
250 push @mirrors, "https://mirror.csclub.uwaterloo.ca/gnu/$1";
251 push @mirrors, "https://mirror.netcologne.de/gnu/$1";
252 push @mirrors, "http://ftp.kddilabs.jp/GNU/gnu/$1";
253 push @mirrors, "http://www.nic.funet.fi/pub/gnu/gnu/$1";
254 push @mirrors, "http://mirror.internode.on.net/pub/gnu/$1";
255 push @mirrors, "http://mirror.navercorp.com/gnu/$1";
256 push @mirrors, "ftp://mirrors.rit.edu/gnu/$1";
257 push @mirrors, "ftp://download.xs4all.nl/pub/gnu/$1";
258 push @mirrors, "https://ftp.gnu.org/gnu/$1";
259 } elsif ($mirror =~ /^\@SAVANNAH\/(.+)$/) {
260 push @mirrors, "https://mirror.netcologne.de/savannah/$1";
261 push @mirrors, "https://mirror.csclub.uwaterloo.ca/nongnu/$1";
262 push @mirrors, "http://ftp.acc.umu.se/mirror/gnu.org/savannah/$1";
263 push @mirrors, "http://nongnu.uib.no/$1";
264 push @mirrors, "http://ftp.igh.cnrs.fr/pub/nongnu/$1";
265 push @mirrors, "ftp://cdimage.debian.org/mirror/gnu.org/savannah/$1";
266 push @mirrors, "ftp://ftp.acc.umu.se/mirror/gnu.org/savannah/$1";
267 } elsif ($mirror =~ /^\@KERNEL\/(.+)$/) {
268 my @extra = ( $1 );
269 if ($filename =~ /linux-\d+\.\d+(?:\.\d+)?-rc/) {
270 push @extra, "$extra[0]/testing";
271 } elsif ($filename =~ /linux-(\d+\.\d+(?:\.\d+)?)/) {
272 push @extra, "$extra[0]/longterm/v$1";
273 }
274 foreach my $dir (@extra) {
275 push @mirrors, "https://cdn.kernel.org/pub/$dir";
276 push @mirrors, "https://download.xs4all.nl/ftp.kernel.org/pub/$dir";
277 push @mirrors, "https://mirrors.mit.edu/kernel/$dir";
278 push @mirrors, "http://ftp.nara.wide.ad.jp/pub/kernel.org/$dir";
279 push @mirrors, "http://www.ring.gr.jp/archives/linux/kernel.org/$dir";
280 push @mirrors, "ftp://ftp.riken.jp/Linux/kernel.org/$dir";
281 push @mirrors, "ftp://www.mirrorservice.org/sites/ftp.kernel.org/pub/$dir";
282 }
283 } elsif ($mirror =~ /^\@GNOME\/(.+)$/) {
284 push @mirrors, "https://download.gnome.org/sources/$1";
285 push @mirrors, "https://mirror.csclub.uwaterloo.ca/gnome/sources/$1";
286 push @mirrors, "http://ftp.acc.umu.se/pub/GNOME/sources/$1";
287 push @mirrors, "http://ftp.kaist.ac.kr/gnome/sources/$1";
288 push @mirrors, "http://www.mirrorservice.org/sites/ftp.gnome.org/pub/GNOME/sources/$1";
289 push @mirrors, "http://mirror.internode.on.net/pub/gnome/sources/$1";
290 push @mirrors, "http://ftp.belnet.be/ftp.gnome.org/sources/$1";
291 push @mirrors, "ftp://ftp.cse.buffalo.edu/pub/Gnome/sources/$1";
292 push @mirrors, "ftp://ftp.nara.wide.ad.jp/pub/X11/GNOME/sources/$1";
293 } else {
294 push @mirrors, $mirror;
295 }
296 }
297
298 push @mirrors, 'https://sources.cdn.openwrt.org';
299 push @mirrors, 'https://sources.openwrt.org';
300 push @mirrors, 'https://mirror2.openwrt.org/sources';
301
302 if (-f "$target/$filename") {
303 $hash_cmd and do {
304 if (system("cat '$target/$filename' | $hash_cmd > '$target/$filename.hash'")) {
305 die "Failed to generate hash for $filename\n";
306 }
307
308 my $sum = `cat "$target/$filename.hash"`;
309 $sum =~ /^(\w+)\s*/ or die "Could not generate file hash\n";
310 $sum = $1;
311
312 cleanup();
313 exit 0 if $sum eq $file_hash;
314
315 die "Hash of the local file $filename does not match (file: $sum, requested: $file_hash) - deleting download.\n";
316 unlink "$target/$filename";
317 };
318 }
319
320 while (!-f "$target/$filename") {
321 my $mirror = shift @mirrors;
322 $mirror or die "No more mirrors to try - giving up.\n";
323
324 download($mirror, $url_filename, @mirrors);
325 if (!-f "$target/$filename" && $url_filename ne $filename) {
326 download($mirror, $filename, @mirrors);
327 }
328 }
329
330 $SIG{INT} = \&cleanup;