public static Stream CreateSDVPatch(string sdv_origin, string sdv_patched) { Stream output = new MemoryStream(); BinaryPatchUtility.Create(File.ReadAllBytes(sdv_origin), File.ReadAllBytes(sdv_patched), output); return(output); }
private async void patchButton_Click(object sender, System.EventArgs e) { var uiContext = SynchronizationContext.Current; var createBackup = MessageBox.Show("Do you wish to create a backup of your original RemotePlay.exe ?", "Create backup ?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes; await Task.Run(() => { uiContext.Post(UpdateCurrentOperation, "Patching..."); uiContext.Post(EnablePatchButton, false); var originalRemotePlay = File.ReadAllBytes(_remotePlayPath); if (createBackup) { File.Move(_remotePlayPath, Path.ChangeExtension(_remotePlayPath, ".exe.bak")); } File.Delete(_remotePlayPath); using (var originalRemotePlayStream = new MemoryStream(originalRemotePlay)) using (var outputStream = File.OpenWrite(_remotePlayPath)) { BinaryPatchUtility.Apply(originalRemotePlayStream, () => new MemoryStream(_patch), outputStream); } uiContext.Post(UpdateCurrentOperation, "Done !"); }); }
public static Stream CreatePatch(byte[] origin, byte[] dest) { Stream output = new MemoryStream(); BinaryPatchUtility.Create(origin, dest, output); return(output); }
public static Stream GetPatched(Stream origin, byte[] patchdata) { Stream output = new MemoryStream(); BinaryPatchUtility.Apply(origin, () => new MemoryStream(patchdata), output); return(output); }
private void OnMergePatchEnter(int eventID, FSMState preState, FSMState currentState) { PreloadingUIView.SetProgressName("正在解压安装文件..."); PreloadingUIView.ResetProgress(); Debug.Log("正在合并apk包"); string current = Application.get_dataPath(); string newApk = this.GetNewApkPath(); string patch = this.GetNewPatchPath(); string directoryName = Path.GetDirectoryName(newApk); DirectoryUtil.CreateIfNotExist(directoryName); this.ApkMerging = false; Loom.Current.RunAsync(delegate { FileHelper.DeleteIfExist(newApk); this.ApkMerging = true; using (FileStream fileStream = File.Open(current, 3, 1, 1)) { using (FileStream fileStream2 = File.Open(newApk, 2, 2)) { BinaryPatchUtility.Apply(fileStream, () => File.Open(patch, 3, 1, 1), fileStream2); } } this.ReactSync(UpdateEvent2.Next); }); }
private void InstallByApkPatch() { this.InstallUpdate = new Action(this.InstallByApkPatchUpdate); Debug.LogFormat("InstallByApkPatch", new object[0]); string newApk = this.GetNewApkPath(); string current = NativeCallManager.GetApkPath(); string patch = this.GetNewPatchPath(); Loom.Current.RunAsync(delegate { FileInfo fileInfo = new FileInfo(newApk); if (fileInfo.get_Exists() && fileInfo.get_Length() >= (long)this.UpdateInfo.CurrentApkInfo.ApkFileInfo.FileSize) { string text = MD5Util.EncryptFile(newApk); if (this.UpdateInfo.CurrentApkInfo.ApkFileInfo.Md5.Equals(text)) { Loom.Current.QueueOnMainThread(delegate { NativeCallManager.InstallPackage(newApk); this.InstallNext(); }); } else { this.ClearApk(); this.ClearApkPatch(); Action onClick = delegate { this.ReactSync(UpdateEvent.False); }; Loom.Current.QueueOnMainThread(delegate { this.ShowDownloadFailed(onClick); }); } } else { string directoryName = Path.GetDirectoryName(newApk); DirectoryUtil.CreateIfNotExist(directoryName); FileHelper.DeleteIfExist(newApk); this.MergeFile = new FileInfo(newApk); using (FileStream fileStream = File.Open(current, 3, 1, 1)) { using (FileStream fileStream2 = File.Open(newApk, 2, 2)) { BinaryPatchUtility.Apply(fileStream, () => File.Open(patch, 3, 1, 1), fileStream2); } } Loom.Current.QueueOnMainThread(delegate { this.InstallByApkPatch(); }); } }); }
public static Stream PatchSDV(string sdv_origin, string patch) { FileStream file_sdv_o = new FileStream(sdv_origin, FileMode.Open, FileAccess.Read); Stream output = new MemoryStream(); //BinaryPatchUtility.Apply(file_sdv_o, () => new FileStream(patch, FileMode.Open, FileAccess.Read), output); BinaryPatchUtility.Apply(file_sdv_o, () => new MemoryStream(Resource1.patch), output); file_sdv_o.Close(); return(output); }
public GameState Apply(GameState fromState) { if (fromState.Sequence != FromSequence) { throw new Exception("Cannot apply GameStateDelta. Sequence incorrect."); } byte[] fromBuffer = fromState.GetSerializedDataStream().ToArray(); var toStream = new MemoryStream(); BinaryPatchUtility.Apply(new MemoryStream(fromBuffer), () => new MemoryStream(deltaBytes.ToArray()), toStream); toStream.Seek(0, SeekOrigin.Begin); return((GameState)Serializer.Deserialize(toStream)); }
private void ApplyPatch(string oldFile, string newFile, string patchFile) { try { using (var input = new FileStream(oldFile, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var output = new FileStream(newFile, FileMode.Create)) { BinaryPatchUtility.Apply(input, () => new FileStream(patchFile, FileMode.Open, FileAccess.Read, FileShare.Read), output); } } catch (Exception ex) { _writer.WriteLine("Error while patching VR: " + ex); } }
public void Apply_bs_diff() { FileHelper.InitDir("test/bin", "test/update"); File.WriteAllText("test/bin/app.exe", "123"); using (var diff = File.Create("test/update/app.exe.bsdiff")) BinaryPatchUtility.Create(Encoding.UTF8.GetBytes("123"), Encoding.UTF8.GetBytes("123456"), diff); File.WriteAllText("test/update/version.txt", "1.0"); MainWindow.Update(-1, "test/bin/app.exe", "test/update"); var files = Directory.GetFiles("test/bin").Select(f => Path.GetFileName(f)); Assert.AreEqual("app.exe", files.Implode()); Assert.AreEqual("123456", File.ReadAllText("test/bin/app.exe")); }
public bool ApplyPatch(string folder, string exeName) { string oldFile = folder + exeName; string newFile = folder + @"tConfig.exe"; try { using (FileStream input = new FileStream(oldFile, FileMode.Open, FileAccess.Read, FileShare.Read)) using (FileStream output = new FileStream(newFile, FileMode.Create)) BinaryPatchUtility.Apply(input, () => new MemoryStream(Patch.TerrariaConfigMod), output); } catch (Exception ex) { Console.Error.WriteLine(ex); return(false); } return(true); }
/// <inheritdoc cref="IDeltaUpdate.CreateDeltaFile"/> public bool CreateDeltaFile( TemporaryFolder tempFolder, string originalFileLocation, string newFileLocation, string deltaFileLocation, out Stream?deltaFileStream, Action <double>?progress = null) { deltaFileStream = new MemoryStream(); var success = BinaryPatchUtility.Create( File.ReadAllBytes(originalFileLocation), File.ReadAllBytes(newFileLocation), deltaFileStream, progress); if (!success) { deltaFileStream.Dispose(); deltaFileStream = null; } deltaFileStream?.Seek(0, SeekOrigin.Begin); return(success); }
static void Main(string[] args) { // check for correct usage if (args.Length != 3) { args = Console.ReadLine().Split(' '); } string oldFile = args[0]; string newFile = args[1]; string patchFile = args[2]; try { using (FileStream input = new FileStream(oldFile, FileMode.Open, FileAccess.Read, FileShare.Read)) using (FileStream output = new FileStream(newFile, FileMode.Create)) BinaryPatchUtility.Apply(input, () => new FileStream(patchFile, FileMode.Open, FileAccess.Read, FileShare.Read), output); } catch (FileNotFoundException ex) { Console.Error.WriteLine("Could not open '{0}'.", ex.FileName); } }
private static void CopyFiles(IEnumerable <string> sources, string path) { foreach (var source in sources) { if (Path.GetExtension(source).Match(".bsdiff")) { var dst = Path.Combine(path, Path.GetFileNameWithoutExtension(source)); var src = dst + ".old"; log.Debug($"Применяю патч {source} > {dst}"); SafeFromAv(() => File.Delete(src)); SafeFromAv(() => File.Move(dst, src)); using (var srcStream = File.OpenRead(src)) using (var dstStream = File.Create(dst)) BinaryPatchUtility.Apply(srcStream, () => File.OpenRead(source), dstStream); SafeFromAv(() => File.Delete(src)); } else { var dst = Path.Combine(path, Path.GetFileName(source)); log.Debug($"Копирую {source} > {dst}"); SafeFromAv(() => File.Copy(source, dst, true)); } } }
private void ApplyDiffToFile(string deltaPath, string relativeFilePath, string workingDirectory) { var inputFile = Path.Combine(deltaPath, relativeFilePath); var finalTarget = Path.Combine(workingDirectory, Regex.Replace(relativeFilePath, @"\.(bs)?diff$", "")); Utility.WithTempFile(out var tempTargetFile, localAppDirectory); try { // NB: Zero-length diffs indicate the file hasn't actually changed if (new FileInfo(inputFile).Length == 0) { Log.InfoFormat("{0} exists unchanged, skipping", relativeFilePath); return; } if (relativeFilePath.EndsWith(".bsdiff", StringComparison.InvariantCultureIgnoreCase)) { using (var of = File.OpenWrite(tempTargetFile)) using (var inf = File.OpenRead(finalTarget)) { Log.InfoFormat("Applying BSDiff to {0}", relativeFilePath); BinaryPatchUtility.Apply(inf, () => File.OpenRead(inputFile), of); } VerifyPatchedFile(relativeFilePath, inputFile, tempTargetFile); } else if (relativeFilePath.EndsWith(".diff", StringComparison.InvariantCultureIgnoreCase)) { Log.InfoFormat("Applying MSDiff to {0}", relativeFilePath); var msDelta = new MsDeltaCompression(); msDelta.ApplyDelta(inputFile, finalTarget, tempTargetFile); VerifyPatchedFile(relativeFilePath, inputFile, tempTargetFile); } else { using (var of = File.OpenWrite(tempTargetFile)) using (var inf = File.OpenRead(inputFile)) { Log.InfoFormat("Adding new file: {0}", relativeFilePath); inf.CopyTo(of); } } if (File.Exists(finalTarget)) { File.Delete(finalTarget); } var targetPath = Directory.GetParent(finalTarget); if (!targetPath.Exists) { targetPath.Create(); } File.Move(tempTargetFile, finalTarget); } finally { if (File.Exists(tempTargetFile)) { Utility.DeleteFileHarder(tempTargetFile, true); } } }
public async Task ApplyPatch(VersionModel patchInfo) { try { CurrentState = UpdateState.DownloadingPatch; OnUpdateProgress(new UpdateProgressModel { State = CurrentState, TotalBytes = 1, CompletedBytes = 0 }); if (!_updateFilesDir.Exists) { _updateFilesDir.Create(); } else { _updateFilesDir.Delete(true); _updateFilesDir.Create(); } var patchZipFile = new FileInfo(_updateFilesDir + "\\patch.zip"); var extractedDir = new DirectoryInfo(_updateFilesDir + "\\Patch"); using (var wc = new WebClient()) { wc.DownloadProgressChanged += Wc_DownloadProgressChanged; await wc.DownloadFileTaskAsync(_websiteUrl + $"/{patchInfo.Version}.zip", patchZipFile.FullName); } CurrentState = UpdateState.ApplyingPatch; ZipFile.ExtractToDirectory(patchZipFile.FullName, extractedDir.FullName); var patch = JsonConvert.DeserializeObject <PatchModel>(File.ReadAllText(extractedDir.FullName + "\\Info.json")); var totalBytes = patch.NewFiles.Sum(q => q.Size) + patch.UpdatedFiles.Sum(q => q.Size); long loadedBytes = 0; OnUpdateProgress(new UpdateProgressModel { State = CurrentState, TotalBytes = totalBytes, CompletedBytes = loadedBytes }); var patchContentDir = new DirectoryInfo(extractedDir.FullName + "\\Data"); using (var log = new UpdaterLog(LogPath, true)) { if (patch.UpdatedFiles != null) { foreach (var updatedFileName in patch.UpdatedFiles) { var fi = new FileInfo(_workingDir.FullName + updatedFileName.RelativePath); if (fi.Directory.Exists == false) { fi.Directory.Create(); } string realFileName; bool isPatch = false; if (fi.FullName.EndsWith(".patch", StringComparison.InvariantCultureIgnoreCase)) { realFileName = fi.FullName.Substring(0, fi.FullName.Length - 6); isPatch = true; } else { realFileName = fi.FullName; } File.Delete(realFileName + ".bak"); File.Move(realFileName, realFileName + ".bak"); log.WriteUpdate(realFileName, realFileName + ".bak"); if (isPatch) { using (var input = File.OpenRead(realFileName + ".bak")) using (var output = File.OpenWrite(realFileName)) { BinaryPatchUtility.Apply(input, () => File.Open(patchContentDir.FullName + updatedFileName.RelativePath, FileMode.Open, FileAccess.Read, FileShare.Read), output); } File.Delete(patchContentDir.FullName + updatedFileName.RelativePath); } loadedBytes += updatedFileName.Size; OnUpdateProgress(new UpdateProgressModel { State = CurrentState, TotalBytes = totalBytes, CompletedBytes = loadedBytes }); Thread.Sleep(1); } } if (patch.NewFiles != null) { foreach (var newFileName in patch.NewFiles) { var fi = new FileInfo(_workingDir.FullName + newFileName.RelativePath); if (fi.Directory.Exists == false) { fi.Directory.Create(); } log.WriteAdd(fi.FullName); if (fi.Exists) { fi.Delete(); } File.Move(patchContentDir.FullName + newFileName.RelativePath, fi.FullName); loadedBytes += newFileName.Size; OnUpdateProgress(new UpdateProgressModel { State = CurrentState, TotalBytes = totalBytes, CompletedBytes = loadedBytes }); Thread.Sleep(1); } } if (patch.DeletedFiles != null) { foreach (var patchDeletedFile in patch.DeletedFiles) { var fi = new FileInfo(_workingDir + patchDeletedFile); File.Delete(fi.FullName + ".bak"); File.Move(fi.FullName, fi.FullName + ".bak"); log.WriteDelete(fi.FullName, fi.FullName + ".bak"); } } log.Complete(); } _updaterConfig.VersionProvider.SaveVersion(patch.Version); CurrentState = UpdateState.Idle; _updateFilesDir.Delete(true); OnPatchingCompleted(patch); } catch (Exception e) { CurrentState = UpdateState.Idle; OnPatchingError(e); Rollback(); } }
/// <inheritdoc cref="IDeltaUpdate.ApplyDeltaFile"/> public async Task <bool> ApplyDeltaFile( TemporaryFolder tempFolder, string originalFileLocation, string newFileLocation, string deltaFileName, Stream deltaFileStream, Action <double>?progress = null) { Stream?inputStream = null; /*If this is the same file then we * want to copy it to mem and not read from disk*/ if (deltaFileName == originalFileLocation) { inputStream = new MemoryStream(); using var fileStream = StreamUtil.SafeOpenRead(originalFileLocation); if (fileStream == null) { _logger.Error("Wasn't able to grab {0} for applying a BSDiff update", originalFileLocation); return(false); } await fileStream.CopyToAsync(inputStream); inputStream.Seek(0, SeekOrigin.Begin); } inputStream ??= StreamUtil.SafeOpenRead(originalFileLocation); if (inputStream == null) { _logger.Error("Wasn't able to grab {0} for applying a BSDiff update", originalFileLocation); return(false); } //Create a memory stream if seeking is not possible as that is needed if (!deltaFileStream.CanSeek) { var patchMemStream = new MemoryStream(); await deltaFileStream.CopyToAsync(patchMemStream); deltaFileStream.Dispose(); deltaFileStream = patchMemStream; } var outputStream = FileHelper.OpenWrite(newFileLocation, inputStream.Length); var successfulUpdate = await BinaryPatchUtility.Apply(inputStream, () => { //Copy the files over in a memory stream var memStream = new MemoryStream(); deltaFileStream.Seek(0, SeekOrigin.Begin); deltaFileStream.CopyTo(memStream); memStream.Seek(0, SeekOrigin.Begin); return(memStream); }, outputStream, progress); outputStream.Dispose(); inputStream.Dispose(); deltaFileStream.Dispose(); return(successfulUpdate); }
public FileDownloadDialog(MainWindow window, string url, string destPath) { InitializeComponent(); this.Window = window; lblStatus.Content = "Downloading " + System.IO.Path.GetFileName(destPath); // sketchy code to replace current exe if (File.Exists(destPath) && destPath.ToLower() == Process.GetCurrentProcess().MainModule.FileName.ToLower()) { if (File.Exists(destPath + ".old")) { File.Delete(destPath + ".old"); } File.Move(destPath, destPath + ".old"); } wc.DownloadProgressChanged += (s, e) => { DownloadProgress.Value = e.ProgressPercentage; }; wc.DownloadFileCompleted += (s, e) => { DownloadProgress.Value = 100; if (e.Error != null) { this.DialogResult = false; Error = e.Error; } else { this.DialogResult = true; } var patchFileExtension = ".bspatch"; if (destPath.EndsWith(patchFileExtension)) { string destFilePath = destPath.Substring(0, destPath.Length - patchFileExtension.Length); string destFileName = destFilePath.Replace(Window.BasePath, ""); if (destFileName.StartsWith("\\") || destFileName.StartsWith("/")) { destFileName = destFileName.Substring(1); } // patch file string backupFolder = Path.Combine(Window.BasePath, "_dewbackup"); string backupFile = Path.Combine(backupFolder, destFileName); if (File.Exists(backupFile)) { // backup exists, copy backup over original file and patch orig if (File.Exists(destFilePath)) { File.Delete(destFilePath); } //File.Copy(backupFile, destFilePath); } else { // if backup don't exist we're assuming the main form made sure current one is fine // b-b-b-b-back it up backupFolder = Path.GetDirectoryName(backupFile); if (!Directory.Exists(backupFolder)) { Directory.CreateDirectory(backupFolder); } File.Copy(destFilePath, backupFile); File.Delete(destFilePath); } lblStatus.Content = "Applying patch file..."; Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { })); using (FileStream input = new FileStream(backupFile, FileMode.Open, FileAccess.Read, FileShare.Read)) using (FileStream output = new FileStream(destFilePath, FileMode.Create)) BinaryPatchUtility.Apply(input, () => new FileStream(destPath, FileMode.Open, FileAccess.Read, FileShare.Read), output); File.Delete(destPath); } this.Close(); }; wc.DownloadFileAsync(new Uri(url), destPath); }
private void BuildPatchFile(MyFileInfo oldFile, MyFileInfo newFile, string patchFile) { using (var outputStream = File.OpenWrite(patchFile)) BinaryPatchUtility.Create(oldFile.ReadBytes(), newFile.ReadBytes(), outputStream); }
private void CreateDeltaForSingleFile(FileInfo targetFile, DirectoryInfo workingDirectory, Dictionary <string, string> baseFileListing) { // NB: There are three cases here that we'll handle: // // 1. Exists only in new => leave it alone, we'll use it directly. // 2. Exists in both old and new => write a dummy file so we know // to keep it. // 3. Exists in old but changed in new => create a delta file // // The fourth case of "Exists only in old => delete it in new" // is handled when we apply the delta package var relativePath = targetFile.FullName.Replace(workingDirectory.FullName, ""); if (!baseFileListing.ContainsKey(relativePath)) { Log.InfoFormat("{0} not found in base package, marking as new", relativePath); return; } var oldData = File.ReadAllBytes(baseFileListing[relativePath]); var newData = File.ReadAllBytes(targetFile.FullName); if (BytesAreIdentical(oldData, newData)) { Log.InfoFormat("{0} hasn't changed, writing dummy file", relativePath); File.Create(targetFile.FullName + ".diff").Dispose(); File.Create(targetFile.FullName + ".shasum").Dispose(); targetFile.Delete(); return; } Log.InfoFormat("Delta patching {0} => {1}", baseFileListing[relativePath], targetFile.FullName); var msDelta = new MsDeltaCompression(); if (targetFile.Extension.Equals(".exe", StringComparison.OrdinalIgnoreCase) || targetFile.Extension.Equals(".dll", StringComparison.OrdinalIgnoreCase) || targetFile.Extension.Equals(".node", StringComparison.OrdinalIgnoreCase)) { try { msDelta.CreateDelta(baseFileListing[relativePath], targetFile.FullName, targetFile.FullName + ".diff"); goto exit; } catch (Exception) { Log.WarnFormat("We couldn't create a delta for {0}, attempting to create bsdiff", targetFile.Name); } } try { using (var of = File.Create(targetFile.FullName + ".bsdiff")) { BinaryPatchUtility.Create(oldData, newData, of); // NB: Create a dummy corrupt .diff file so that older // versions which don't understand bsdiff will fail out // until they get upgraded, instead of seeing the missing // file and just removing it. File.WriteAllText(targetFile.FullName + ".diff", "1"); } } catch (Exception ex) { Log.Warn($"We really couldn't create a delta for {targetFile.Name}", ex); Utility.DeleteFileHarder(targetFile.FullName + ".bsdiff", true); Utility.DeleteFileHarder(targetFile.FullName + ".diff", true); return; } exit: var rl = ReleaseEntry.GenerateFromFile(new MemoryStream(newData), targetFile.Name + ".shasum"); File.WriteAllText(targetFile.FullName + ".shasum", rl.EntryAsString, Encoding.UTF8); targetFile.Delete(); }
public void Create(GameState fromState, GameState toState) { Sequence = toState.Sequence; FromSequence = fromState.Sequence; BinaryPatchUtility.Create(fromState.GetSerializedDataBuffer(), toState.GetSerializedDataBuffer(), deltaBytes); }