From 3467756bef398fda8aa1e3c626a3ca1f74f6c75e Mon Sep 17 00:00:00 2001 From: Dean Ellis Date: Tue, 9 Aug 2016 09:30:57 +0100 Subject: [PATCH] [Xamarin.Android.Build.Tasks] Corruption of zips if build stopped Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=41123 Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=41608 The current implementation of GetAdditionalResourcesFromAssemblies does not support resuming a download. It also does not support validating a zip file prior to extracting it. This commit modifies the download process to detect partial downloads and to attept to resume them. It does this by making use of the http `Range` header. This gives the server the offset it needs to restart the download. If we detect a partial zip we send the current file size to the server so that we can resume it. If the server returns that is cannot resume we will then delete the local file and try a full download again. We also make use of the LibZipSharp capability to validate the zip on opening so ensure it is extractable. In the case where it is not we attempt to download/resume the zip. Another issue was that if the download does NOT succeed we still wrote out the Cache file. As a result on the following build if the download failed the app would skip the download and attempt a normal build (which would fail). The fix here is to only write the cache file IF and ONLY IF we manage to succeed in downloading the required resources. If the file does not exist then the download will be resumed the next time around. --- .../GetAdditionalResourcesFromAssemblies.cs | 104 ++++++++++++++---- .../Utilities/Files.cs | 4 +- .../Utilities/MonoAndroidHelper.cs | 11 ++ 3 files changed, 97 insertions(+), 22 deletions(-) diff --git a/src/Xamarin.Android.Build.Tasks/Tasks/GetAdditionalResourcesFromAssemblies.cs b/src/Xamarin.Android.Build.Tasks/Tasks/GetAdditionalResourcesFromAssemblies.cs index 1c4d1620b41..acb68e5f400 100644 --- a/src/Xamarin.Android.Build.Tasks/Tasks/GetAdditionalResourcesFromAssemblies.cs +++ b/src/Xamarin.Android.Build.Tasks/Tasks/GetAdditionalResourcesFromAssemblies.cs @@ -13,6 +13,7 @@ using System.Net; using System.ComponentModel; using Xamarin.Android.Tools; +using Xamarin.Tools.Zip; using Java.Interop.Tools.Cecil; @@ -193,6 +194,66 @@ bool IsValidDownload(string file, string sha1) return string.Compare (hash, sha1, StringComparison.InvariantCultureIgnoreCase) == 0; } + void DoDownload (long totalBytes, long offset, Stream responseStream, Stream outputStream, Action progressCallback = null) + { + long readSoFar = offset; + byte [] buffer = new byte [8192]; + int bufferSize = buffer.Length; + int nread = 0; + float percent, tb = (float)totalBytes, lastPercent = 0; + outputStream.Seek (offset, SeekOrigin.Begin); + + while ((nread = responseStream.Read (buffer, 0, buffer.Length)) > 0) { + readSoFar += nread; + outputStream.Write (buffer, 0, nread); + percent = (float)readSoFar / tb * 100; + if (percent - lastPercent > 1) { + progressCallback?.Invoke (readSoFar, totalBytes, (int)percent); + lastPercent = percent; + } + outputStream.Flush (); + } + } + + void Download (string file, Uri uri, Action progressCallback = null) + { + var request = WebRequest.CreateHttp (uri); + int offset = 0; + if (File.Exists (file) && !MonoAndroidHelper.IsValidZip (file)) { + var fi = new FileInfo (file); + request.AddRange (fi.Length); + offset = (int)fi.Length; + LogMessage ("Partial download detected. Resuming from previous download progress."); + } + if (!File.Exists (file) || offset > 0) { + HttpWebResponse response = null; + try { + response = (HttpWebResponse)request.GetResponse (); + } + catch (WebException ex) { + var exceptionResponse = ex.Response as HttpWebResponse; + if (exceptionResponse?.StatusCode != HttpStatusCode.RequestedRangeNotSatisfiable) + throw; + // Download the entire file again. + request.Abort (); + request = WebRequest.CreateHttp (uri); + File.Delete (file); + offset = 0; + request.AddRange (0); + response = (HttpWebResponse)request.GetResponse (); + LogMessage ("Could not resume previous download. Starting again."); + } + if (response != null) { + long totalBytes = response.ContentLength + offset; + using (var responseStream = response.GetResponseStream ()) { + using (var outputStream = new FileStream (file, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)) { + DoDownload (totalBytes, offset, responseStream, outputStream, progressCallback); + } + } + } + } + } + string MakeSureLibraryIsInPlace (string destinationBase, string url, string version, string embeddedArchive, string sha1) { if (string.IsNullOrEmpty (url)) @@ -214,29 +275,26 @@ string MakeSureLibraryIsInPlace (string destinationBase, string url, string vers Directory.CreateDirectory (zipDir); string file = Path.Combine (zipDir, !uri.IsFile ? hash + ".zip" : Path.GetFileName (uri.AbsolutePath)); - if (!File.Exists (file) || !IsValidDownload (file, sha1)) { + if (!File.Exists (file) || !IsValidDownload (file, sha1) || !MonoAndroidHelper.IsValidZip (file)) { int progress = -1; - DownloadProgressChangedEventHandler downloadHandler = (o, e) => { - if (e.ProgressPercentage % 10 != 0 || progress == e.ProgressPercentage) + var downloadHandler = new Action((r,t,p) => { + if (p % 10 != 0 || progress == p) return; - progress = e.ProgressPercentage; - LogMessage ("\t({0}/{1}b), total {2:F1}%", e.BytesReceived, - e.TotalBytesToReceive, e.ProgressPercentage); - }; - using (var client = new System.Net.WebClient ()) { - client.DownloadProgressChanged += downloadHandler; - LogMessage (" Downloading {0} into {1}", url, zipDir); - try { - client.DownloadFileTaskAsync (url, file).Wait (Token); + progress = p; + LogMessage ("\t({0}/{1}b), total {2:F1}%", r, + t, p); + }); + LogMessage (" Downloading {0} into {1}", url, zipDir); + try { + Download (file, uri, downloadHandler); + if (MonoAndroidHelper.IsValidZip (file)) LogMessage (" Downloading Complete"); - } catch (Exception e) { - LogCodedError ("XA5208", "Download failed. Please download {0} and put it to the {1} directory.", url, destinationDir); - LogCodedError ("XA5208", "Reason: {0}", e.GetBaseException ().Message); - Log.LogMessage (MessageImportance.Low, e.ToString ()); - if (File.Exists (file)) - File.Delete (file); - } - client.DownloadProgressChanged -= downloadHandler; + else + LogCodedError ("XA5208", "Download succeeded but the zip file was not valid. Please do a clean build and try again."); + } catch (Exception e) { + LogCodedError ("XA5208", "Download failed. Please build again."); + LogCodedError ("XA5208", "Reason: {0}", e.GetBaseException ().Message); + Log.LogMessage (MessageImportance.Low, e.ToString ()); } } else @@ -338,6 +396,12 @@ public override bool Execute () var result = base.Execute (); + if (!result || Log.HasLoggedErrors) { + if (File.Exists (CacheFile)) + File.Delete (CacheFile); + return false; + } + var AdditionalAndroidResourcePaths = androidResources.ToArray (); var AdditionalJavaLibraryReferences = javaLibraries.ToArray (); var AdditionalNativeLibraryReferences = nativeLibraries diff --git a/src/Xamarin.Android.Build.Tasks/Utilities/Files.cs b/src/Xamarin.Android.Build.Tasks/Utilities/Files.cs index c9b38431e21..6148f3d401e 100644 --- a/src/Xamarin.Android.Build.Tasks/Utilities/Files.cs +++ b/src/Xamarin.Android.Build.Tasks/Utilities/Files.cs @@ -188,9 +188,9 @@ static string HashZip (string filename) return hashes; } - public static ZipArchive ReadZipFile (string filename) + public static ZipArchive ReadZipFile (string filename, bool strictConsistencyChecks = false) { - return ZipArchive.Open (filename, FileMode.Open); + return ZipArchive.Open (filename, FileMode.Open, strictConsistencyChecks: strictConsistencyChecks); } public static void ExtractAll(ZipArchive zip, string destination, Action progressCallback = null) diff --git a/src/Xamarin.Android.Build.Tasks/Utilities/MonoAndroidHelper.cs b/src/Xamarin.Android.Build.Tasks/Utilities/MonoAndroidHelper.cs index 976416e1424..dd4ab59a5d7 100644 --- a/src/Xamarin.Android.Build.Tasks/Utilities/MonoAndroidHelper.cs +++ b/src/Xamarin.Android.Build.Tasks/Utilities/MonoAndroidHelper.cs @@ -324,6 +324,17 @@ public static ZipArchive ReadZipFile (string filename) return Files.ReadZipFile (filename); } + public static bool IsValidZip (string filename) + { + try { + using (var zip = Files.ReadZipFile (filename, strictConsistencyChecks: true)) { + } + } catch (ZipIOException) { + return false; + } + return true; + } + public static string HashFile (string filename) { return Files.HashFile (filename);