download.pl 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. use strict;
  10. use warnings;
  11. use File::Basename;
  12. use File::Copy;
  13. use Text::ParseWords;
  14. use JSON::PP;
  15. @ARGV > 2 or die "Syntax: $0 <target dir> <filename> <hash> <url filename> [<mirror> ...]\n";
  16. my $url_filename;
  17. my $target = glob(shift @ARGV);
  18. my $filename = shift @ARGV;
  19. my $file_hash = shift @ARGV;
  20. $url_filename = shift @ARGV unless $ARGV[0] =~ /:\/\//;
  21. my $scriptdir = dirname($0);
  22. my @mirrors;
  23. my $ok;
  24. my $check_certificate = $ENV{DOWNLOAD_CHECK_CERTIFICATE} eq "y";
  25. my $custom_tool = $ENV{DOWNLOAD_TOOL_CUSTOM};
  26. my $download_tool;
  27. $url_filename or $url_filename = $filename;
  28. sub localmirrors {
  29. my @mlist;
  30. open LM, "$scriptdir/localmirrors" and do {
  31. while (<LM>) {
  32. chomp $_;
  33. push @mlist, $_ if $_;
  34. }
  35. close LM;
  36. };
  37. open CONFIG, "<".$ENV{'TOPDIR'}."/.config" and do {
  38. while (<CONFIG>) {
  39. /^CONFIG_LOCALMIRROR="(.+)"/ and do {
  40. chomp;
  41. my @local_mirrors = split(/;/, $1);
  42. push @mlist, @local_mirrors;
  43. };
  44. }
  45. close CONFIG;
  46. };
  47. my $mirror = $ENV{'DOWNLOAD_MIRROR'};
  48. $mirror and push @mlist, split(/;/, $mirror);
  49. return @mlist;
  50. }
  51. sub projectsmirrors {
  52. my $project = shift;
  53. my $append = shift;
  54. open (PM, "$scriptdir/projectsmirrors.json") ||
  55. die "Can´t open $scriptdir/projectsmirrors.json: $!\n";
  56. local $/;
  57. my $mirror_json = <PM>;
  58. my $mirror = decode_json $mirror_json;
  59. foreach (@{$mirror->{$project}}) {
  60. push @mirrors, $_ . "/" . ($append or "");
  61. }
  62. }
  63. sub which($) {
  64. my $prog = shift;
  65. my $res = `command -v $prog`;
  66. $res or return undef;
  67. return $res;
  68. }
  69. sub hash_cmd() {
  70. my $len = length($file_hash);
  71. my $cmd;
  72. $len == 64 and return "$ENV{'MKHASH'} sha256";
  73. $len == 32 and return "$ENV{'MKHASH'} md5";
  74. return undef;
  75. }
  76. sub tool_present {
  77. my $tool_name = shift;
  78. my $compare_line = shift;
  79. my $present = 0;
  80. if (open TOOL, "$tool_name --version 2>/dev/null |") {
  81. if (defined(my $line = readline TOOL)) {
  82. $present = 1 if $line =~ /^$compare_line /;
  83. }
  84. close TOOL;
  85. }
  86. return $present
  87. }
  88. sub select_tool {
  89. $custom_tool =~ tr/"//d;
  90. if ($custom_tool) {
  91. return $custom_tool;
  92. }
  93. # Try to use curl if available
  94. if (tool_present("curl", "curl")) {
  95. return "curl";
  96. }
  97. # No tool found, fallback to wget
  98. return "wget";
  99. }
  100. sub download_cmd {
  101. my $url = shift;
  102. my $filename = shift;
  103. if ($download_tool eq "curl") {
  104. return (qw(curl -f --connect-timeout 20 --retry 5 --location),
  105. $check_certificate ? () : '--insecure',
  106. shellwords($ENV{CURL_OPTIONS} || ''),
  107. $url);
  108. } elsif ($download_tool eq "wget") {
  109. return (qw(wget --tries=5 --timeout=20 --output-document=-),
  110. $check_certificate ? () : '--no-check-certificate',
  111. shellwords($ENV{WGET_OPTIONS} || ''),
  112. $url);
  113. } elsif ($download_tool eq "aria2c") {
  114. my $additional_mirrors = join(" ", map "$_/$filename", @_);
  115. my @chArray = ('a'..'z', 'A'..'Z', 0..9);
  116. my $rfn = join '', "${filename}_", map{ $chArray[int rand @chArray] } 0..9;
  117. @mirrors=();
  118. return join(" ", "[ -d $ENV{'TMPDIR'}/aria2c ] || mkdir $ENV{'TMPDIR'}/aria2c;",
  119. "touch $ENV{'TMPDIR'}/aria2c/${rfn}_spp;",
  120. qw(aria2c --stderr -c -x2 -s10 -j10 -k1M), $url, $additional_mirrors,
  121. $check_certificate ? () : '--check-certificate=false',
  122. "--server-stat-of=$ENV{'TMPDIR'}/aria2c/${rfn}_spp",
  123. "--server-stat-if=$ENV{'TMPDIR'}/aria2c/${rfn}_spp",
  124. "--daemon=false --no-conf", shellwords($ENV{ARIA2C_OPTIONS} || ''),
  125. "-d $ENV{'TMPDIR'}/aria2c -o $rfn;",
  126. "cat $ENV{'TMPDIR'}/aria2c/$rfn;",
  127. "rm $ENV{'TMPDIR'}/aria2c/$rfn $ENV{'TMPDIR'}/aria2c/${rfn}_spp");
  128. } else {
  129. return join(" ", $download_tool, $url);
  130. }
  131. }
  132. my $hash_cmd = hash_cmd();
  133. $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";
  134. sub download
  135. {
  136. my $mirror = shift;
  137. my $download_filename = shift;
  138. my @additional_mirrors = @_;
  139. $mirror =~ s!/$!!;
  140. if ($mirror =~ s!^file://!!) {
  141. if (! -d "$mirror") {
  142. print STDERR "Wrong local cache directory -$mirror-.\n";
  143. cleanup();
  144. return;
  145. }
  146. if (! -d "$target") {
  147. system("mkdir", "-p", "$target/");
  148. }
  149. if (! open TMPDLS, "find $mirror -follow -name $filename 2>/dev/null |") {
  150. print("Failed to search for $filename in $mirror\n");
  151. return;
  152. }
  153. my $link;
  154. while (defined(my $line = readline TMPDLS)) {
  155. chomp ($link = $line);
  156. if ($. > 1) {
  157. print("$. or more instances of $filename in $mirror found . Only one instance allowed.\n");
  158. return;
  159. }
  160. }
  161. close TMPDLS;
  162. if (! $link) {
  163. print("No instances of $filename found in $mirror.\n");
  164. return;
  165. }
  166. print("Copying $filename from $link\n");
  167. copy($link, "$target/$filename.dl");
  168. $hash_cmd and do {
  169. if (system("cat '$target/$filename.dl' | $hash_cmd > '$target/$filename.hash'")) {
  170. print("Failed to generate hash for $filename\n");
  171. return;
  172. }
  173. };
  174. } else {
  175. my @cmd = download_cmd("$mirror/$download_filename", $download_filename, @additional_mirrors);
  176. print STDERR "+ ".join(" ",@cmd)."\n";
  177. open(FETCH_FD, '-|', @cmd) or die "Cannot launch aria2c, curl or wget.\n";
  178. $hash_cmd and do {
  179. open MD5SUM, "| $hash_cmd > '$target/$filename.hash'" or die "Cannot launch $hash_cmd.\n";
  180. };
  181. open OUTPUT, "> $target/$filename.dl" or die "Cannot create file $target/$filename.dl: $!\n";
  182. my $buffer;
  183. while (read FETCH_FD, $buffer, 1048576) {
  184. $hash_cmd and print MD5SUM $buffer;
  185. print OUTPUT $buffer;
  186. }
  187. $hash_cmd and close MD5SUM;
  188. close FETCH_FD;
  189. close OUTPUT;
  190. if ($? >> 8) {
  191. print STDERR "Download failed.\n";
  192. cleanup();
  193. return;
  194. }
  195. }
  196. $hash_cmd and do {
  197. my $sum = `cat "$target/$filename.hash"`;
  198. $sum =~ /^(\w+)\s*/ or die "Could not generate file hash\n";
  199. $sum = $1;
  200. if ($sum ne $file_hash) {
  201. print STDERR "Hash of the downloaded file does not match (file: $sum, requested: $file_hash) - deleting download.\n";
  202. cleanup();
  203. return;
  204. }
  205. };
  206. unlink "$target/$filename";
  207. system("mv", "$target/$filename.dl", "$target/$filename");
  208. cleanup();
  209. }
  210. sub cleanup
  211. {
  212. unlink "$target/$filename.dl";
  213. unlink "$target/$filename.hash";
  214. }
  215. @mirrors = localmirrors();
  216. foreach my $mirror (@ARGV) {
  217. if ($mirror =~ /^\@SF\/(.+)$/) {
  218. # give sourceforge a few more tries, because it redirects to different mirrors
  219. for (1 .. 5) {
  220. projectsmirrors '@SF', $1;
  221. }
  222. } elsif ($mirror =~ /^\@OPENWRT$/) {
  223. # use OpenWrt source server directly
  224. } elsif ($mirror =~ /^\@DEBIAN\/(.+)$/) {
  225. projectsmirrors '@DEBIAN', $1;
  226. } elsif ($mirror =~ /^\@APACHE\/(.+)$/) {
  227. projectsmirrors '@APACHE', $1;
  228. } elsif ($mirror =~ /^\@GITHUB\/(.+)$/) {
  229. # give github a few more tries (different mirrors)
  230. for (1 .. 5) {
  231. projectsmirrors '@GITHUB', $1;
  232. }
  233. } elsif ($mirror =~ /^\@GNU\/(.+)$/) {
  234. projectsmirrors '@GNU', $1;
  235. } elsif ($mirror =~ /^\@SAVANNAH\/(.+)$/) {
  236. projectsmirrors '@SAVANNAH', $1;
  237. } elsif ($mirror =~ /^\@KERNEL\/(.+)$/) {
  238. my @extra = ( $1 );
  239. if ($filename =~ /linux-\d+\.\d+(?:\.\d+)?-rc/) {
  240. push @extra, "$extra[0]/testing";
  241. } elsif ($filename =~ /linux-(\d+\.\d+(?:\.\d+)?)/) {
  242. push @extra, "$extra[0]/longterm/v$1";
  243. }
  244. foreach my $dir (@extra) {
  245. projectsmirrors '@KERNEL', $dir;
  246. }
  247. } elsif ($mirror =~ /^\@GNOME\/(.+)$/) {
  248. projectsmirrors '@GNOME', $1;
  249. } else {
  250. push @mirrors, $mirror;
  251. }
  252. }
  253. projectsmirrors '@OPENWRT';
  254. if (-f "$target/$filename") {
  255. $hash_cmd and do {
  256. if (system("cat '$target/$filename' | $hash_cmd > '$target/$filename.hash'")) {
  257. die "Failed to generate hash for $filename\n";
  258. }
  259. my $sum = `cat "$target/$filename.hash"`;
  260. $sum =~ /^(\w+)\s*/ or die "Could not generate file hash\n";
  261. $sum = $1;
  262. cleanup();
  263. exit 0 if $sum eq $file_hash;
  264. die "Hash of the local file $filename does not match (file: $sum, requested: $file_hash) - deleting download.\n";
  265. unlink "$target/$filename";
  266. };
  267. }
  268. $download_tool = select_tool();
  269. while (!-f "$target/$filename") {
  270. my $mirror = shift @mirrors;
  271. $mirror or die "No more mirrors to try - giving up.\n";
  272. download($mirror, $url_filename, @mirrors);
  273. if (!-f "$target/$filename" && $url_filename ne $filename) {
  274. download($mirror, $filename, @mirrors);
  275. }
  276. }
  277. $SIG{INT} = \&cleanup;