package com.droiddeck.launcher.runtime; import com.droiddeck.launcher.core.AddonPack; import android.content.Context; import android.util.Log; import com.droiddeck.launcher.R; import com.droiddeck.launcher.session.SessionPrefs; import com.droiddeck.launcher.core.ArchivePaths; import com.droiddeck.launcher.core.Downloader; import com.droiddeck.launcher.core.Hashes; import com.droiddeck.launcher.core.FileUtils; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.compressors.zstandard.ZstdCompressorInputStream; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; public final class LinuxRuntimeInstaller { private static final String TAG = "LinuxRuntimeInstaller"; public static final String CATALOG_URL = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/main/linuxfs-ubuntu.json"; private static final String VERSION_FILE = ".version"; public enum Step { DOWNLOADING, VERIFYING, OTHER } public interface ProgressListener { void onProgress(String stage, int percent); default void onProgress(Step step, String stage, int percent) { onProgress(stage, percent); } } public static final class Release { public final String version; public final String url; public final String sha256; public final long size; public Release(String version, String url, String sha256, long size) { this.version = version; this.url = url; this.sha256 = sha256; this.size = size; } } private static final class Job { final CopyOnWriteArrayList listeners = new CopyOnWriteArrayList<>(); final CountDownLatch done = new CountDownLatch(1); volatile String stage; volatile Step step = Step.OTHER; volatile int percent = -1; volatile boolean ok; final boolean removal; boolean maintenance; Job(boolean removal, String stage) { this.removal = removal; this.stage = stage; } } private static final Object JOB_LOCK = new Object(); private static Job running; private static volatile String removalError; private LinuxRuntimeInstaller() {} public static String installedVersion(Context context) { File marker = new File(LinuxRuntime.rootDir(context), VERSION_FILE); if (!marker.isFile() || !LinuxRuntime.isInstalled(context)) return null; String v = FileUtils.readString(marker); return v == null ? null : v.trim(); } private static String catalogUrl() { if (!com.droiddeck.launcher.BuildConfig.DEBUG) return CATALOG_URL; try { Object value = Class.forName("android.os.SystemProperties").getMethod("get", String.class) .invoke(null, "debug.droiddeck.linuxfs"); if (value instanceof String && ((String) value).startsWith("http")) return (String) value; } catch (ReflectiveOperationException e) { Log.w(TAG, "catalog override: " + e); } return CATALOG_URL; } public static Release fetchRelease() { String body = Downloader.downloadString(catalogUrl()); if (body == null || body.isEmpty()) return null; try { JSONObject json = new JSONObject(body); String version = json.optString("version", ""); String url = json.optString("url", ""); String sha256 = json.optString("sha256", ""); if (version.isEmpty() || url.isEmpty() || sha256.isEmpty()) return null; return new Release(version, url, sha256, json.optLong("size", 0L)); } catch (Exception e) { Log.w(TAG, "catalog: " + e); return null; } } private static final String USER_DATA = "root"; public static boolean install(Context context, Release release, ProgressListener listener) { Job job; boolean owner; synchronized (JOB_LOCK) { if (running != null && (running.removal || running.maintenance)) return false; owner = running == null; if (owner) { running = new Job(false, context.getString(R.string.user_apps_starting)); removalError = null; } job = running; if (listener != null) job.listeners.add(listener); } if (!owner) return join(job, listener); try { Context app = context.getApplicationContext(); ProgressListener progress = new ProgressListener() { @Override public void onProgress(String stage, int percent) { onProgress(Step.OTHER, stage, percent); } @Override public void onProgress(Step step, String stage, int percent) { job.step = step; job.stage = stage; job.percent = percent; for (ProgressListener l : job.listeners) l.onProgress(step, stage, percent); } }; boolean desktop = DesktopCatalog.INSTANCE.desktopInstalled(app); job.ok = installOnce(app, release, progress); if (job.ok && desktop) keepDesktop(app, progress); return job.ok; } finally { synchronized (JOB_LOCK) { running = null; } job.done.countDown(); } } private static void keepDesktop(Context context, ProgressListener progress) { String problem; try { problem = DesktopCatalog.INSTANCE.install(context, DesktopCatalog.INSTANCE.desktopEntry(context), progress); } catch (RuntimeException e) { problem = e.toString(); } if (problem == null) { Log.i(TAG, "desktop installed again for the new runtime"); return; } Log.w(TAG, "desktop not installed again for the new runtime: " + problem); boolean started = false; for (DesktopCatalog.Entry entry : DesktopCatalog.INSTANCE.interrupted(context)) { if (DesktopCatalog.DESKTOP_ID.equals(entry.getId())) started = true; } if (!started) return; String undone = DesktopCatalog.INSTANCE.removeDesktop(context, progress); if (undone == null) Log.i(TAG, "rolled back the partial desktop install"); else Log.w(TAG, "could not roll back the partial desktop install: " + undone); } public static boolean isInstalling() { synchronized (JOB_LOCK) { return running != null && !running.removal && !running.maintenance; } } public static boolean isBusy() { synchronized (JOB_LOCK) { return running != null; } } public static boolean isRemoving() { synchronized (JOB_LOCK) { return running != null && running.removal; } } public static boolean isMaintaining() { synchronized (JOB_LOCK) { return running != null && running.maintenance; } } public static Maintenance beginMaintenance(Context context, String stage) { if (com.droiddeck.launcher.session.SessionState.INSTANCE.getRunning()) return null; com.droiddeck.launcher.session.SessionPhase phase = com.droiddeck.launcher.session.SessionState.INSTANCE.getPhase(); if (phase != com.droiddeck.launcher.session.SessionPhase.IDLE && phase != com.droiddeck.launcher.session.SessionPhase.FAILED) return null; synchronized (JOB_LOCK) { if (running != null) return null; removalError = null; running = new Job(false, stage); running.maintenance = true; return new Maintenance(running); } } public interface MaintenanceWork { String run(ProgressListener listener); } public static final class Maintenance { private final Job job; private final java.util.concurrent.atomic.AtomicBoolean started = new java.util.concurrent.atomic.AtomicBoolean(); private Maintenance(Job job) { this.job = job; } public boolean run(ProgressListener listener, MaintenanceWork work) { if (!started.compareAndSet(false, true)) return join(job, listener); if (listener != null) job.listeners.add(listener); try { removalError = work.run((stage, percent) -> { job.stage = stage; job.percent = percent; for (ProgressListener l : job.listeners) l.onProgress(stage, percent); }); job.ok = removalError == null; return job.ok; } catch (Exception e) { removalError = e.getMessage(); Log.e(TAG, "maintenance", e); return false; } finally { synchronized (JOB_LOCK) { running = null; } job.done.countDown(); if (listener != null) job.listeners.remove(listener); } } } public static String removalError() { return removalError; } public static boolean hasRemovalPending(Context context) { return removalDirectory(LinuxRuntime.rootDir(context)).exists(); } private static File removalDirectory(File root) { return new File(root.getParentFile(), root.getName() + ".removing"); } public static Boolean attach(ProgressListener listener) { Job job; synchronized (JOB_LOCK) { job = running; if (job == null) return null; if (listener != null) job.listeners.add(listener); } return join(job, listener); } private static boolean join(Job job, ProgressListener listener) { try { if (listener != null) listener.onProgress(job.step, job.stage, job.percent); job.done.await(); return job.ok; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } finally { if (listener != null) job.listeners.remove(listener); } } static String archiveName(Release release) { String version = release.version.replaceAll("[^A-Za-z0-9._-]", "_"); String sum = release.sha256.replaceAll("[^A-Za-z0-9]", ""); if (sum.length() > 12) sum = sum.substring(0, 12); return "linuxfs-" + version + "-" + sum + ".tar.zst"; } private static void deleteOtherArchives(File dir, String keep) { File[] files = dir.listFiles((d, name) -> name.startsWith("linuxfs") && name.endsWith(".tar.zst") && !name.equals(keep)); if (files == null) return; for (File file : files) file.delete(); } private static boolean installOnce(Context context, Release release, ProgressListener listener) { File archive = new File(context.getCacheDir(), archiveName(release)); boolean keepPartial = false; try { deleteOtherArchives(context.getCacheDir(), archive.getName()); File pendingRemoval = removalDirectory(LinuxRuntime.rootDir(context)); if (pendingRemoval.exists() && listener != null) listener.onProgress(context.getString(R.string.rtinst_removing_leftovers), -1); if (!discard(pendingRemoval, null)) throw new IOException("Cannot clear the previous runtime: " + pendingRemoval); emptyTrash(LinuxRuntime.rootDir(context).getParentFile()); String downloading = context.getString(R.string.rtinst_downloading); if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0); if (!LinuxRuntime.patchedProot(context) && !AddonPack.PROOT.await(context) && !SessionPrefs.allowStockProot(context)) throw new IOException("Cannot download proot"); if (!AddonPack.DIRECTAUDIO.await(context)) throw new IOException("Cannot download DirectAudio"); boolean ok = Downloader.downloadFile(release.url, archive, true, release.sha256, (fraction) -> { if (listener != null) { listener.onProgress(Step.DOWNLOADING, downloading, fraction < 0 ? -1 : Math.round(fraction * 100f)); } }); if (!ok) { Log.w(TAG, "download failed"); keepPartial = true; return false; } if (listener != null) listener.onProgress(Step.VERIFYING, context.getString(R.string.rtinst_verifying), -1); String actual = Hashes.sha256(archive); if (!release.sha256.equalsIgnoreCase(actual)) { Log.w(TAG, "checksum mismatch: wanted " + release.sha256 + ", got " + actual); return false; } File root = LinuxRuntime.rootDir(context); File staging = new File(root.getParentFile(), LinuxRuntime.DIR + ".new"); File old = new File(root.getParentFile(), LinuxRuntime.DIR + ".old"); recoverInterruptedSwap(root, staging, old); if (!discard(staging, null) || !staging.mkdirs()) return false; if (listener != null) listener.onProgress(context.getString(R.string.rtinst_extracting), -1); if (!extract(context, archive, staging, root, listener)) { RuntimeFileTree.delete(staging, null); return false; } FileUtils.writeString(new File(staging, VERSION_FILE), release.version); if (!discard(old, null)) { discard(staging, null); return false; } java.util.List carryPaths = root.isDirectory() ? RuntimeFileTree.existingUserPaths(root, staging) : java.util.Collections.emptyList(); if (root.isDirectory() && !root.renameTo(old)) { RuntimeFileTree.delete(staging, null); return false; } File carryMarker = new File(staging, CARRY_MARKER); java.util.List encodedPaths = new java.util.ArrayList<>(); for (String rel : carryPaths) encodedPaths.add(java.net.URLEncoder.encode(rel, "UTF-8")); if (!FileUtils.writeString(carryMarker, String.join("\n", encodedPaths))) { if (old.isDirectory() && !old.renameTo(root)) Log.w(TAG, "could not restore the previous runtime; retained at " + old); discard(staging, null); return false; } java.util.List carried; try { carried = RuntimeFileTree.carryUserData(old, staging, false, carryPaths); } catch (IOException e) { Log.w(TAG, "could not carry user data across the update; rolling back", e); if (old.isDirectory() && !old.renameTo(root)) Log.w(TAG, "could not restore the previous runtime; retained at " + old); if (e.getSuppressed().length == 0) { new File(staging, CARRY_MARKER).delete(); try { RuntimeFileTree.delete(staging, null); } catch (IOException cleanup) { Log.w(TAG, "could not clear the failed staging tree", cleanup); } } else { Log.w(TAG, "incomplete rollback; retaining user data in " + staging); } return false; } if (!staging.renameTo(root)) { if (old.isDirectory()) { try { RuntimeFileTree.carryBack(staging, old, carried); new File(staging, CARRY_MARKER).delete(); } catch (IOException e) { Log.w(TAG, "could not move all user data back after a failed swap", e); } old.renameTo(root); } return false; } new File(root, CARRY_MARKER).delete(); try { RuntimeFileTree.dropStaleState(root); } catch (IOException e) { Log.w(TAG, "could not clear caches left by the previous runtime", e); } discard(old, null); try { com.droiddeck.launcher.session.SessionFiles.INSTANCE.stage(context, root, false); } catch (Exception e) { Log.w(TAG, "could not stage the session files into the new runtime", e); } return LinuxRuntime.isInstalled(context); } catch (Exception e) { Log.e(TAG, "install", e); return false; } finally { if (!keepPartial) archive.delete(); } } static final String CARRY_MARKER = ".droiddeck-carry"; static void recoverInterruptedSwap(File root, File staging, File old) throws IOException { if (!root.isDirectory() && old.isDirectory()) { if (!old.renameTo(root)) throw new IOException("Cannot restore the previous runtime at " + old); Log.w(TAG, "restored the previous runtime after an interrupted update"); } File marker = new File(staging, CARRY_MARKER); if (!RuntimeFileTree.exists(marker.toPath())) return; File target = root.isDirectory() ? root : old; String markerContent = FileUtils.readString(marker); if (markerContent == null) throw new IOException("Cannot read runtime recovery marker: " + marker); if (!markerContent.equals("1")) { java.util.List intended = new java.util.ArrayList<>(); for (String rel : markerContent.split("\\n")) if (!rel.isEmpty()) intended.add(java.net.URLDecoder.decode(rel, "UTF-8")); if (target.isDirectory()) RuntimeFileTree.recoverCarriedPaths(staging, target, intended); if (staging.isDirectory() && RuntimeFileTree.hasPaths(staging, intended)) throw new IOException("User data still needs recovery from " + staging); marker.delete(); return; } File stagedHome = new File(staging, USER_DATA); File home = new File(target, USER_DATA); if (target.isDirectory() && stagedHome.isDirectory() && (!RuntimeFileTree.exists(home.toPath()) || isEmptyDir(home))) { RuntimeFileTree.carryHome(staging, target); Log.w(TAG, "recovered " + USER_DATA + " from an interrupted update"); } if (target.isDirectory() && staging.isDirectory()) { java.util.List rest = RuntimeFileTree.carryUserData(staging, target, true); if (!rest.isEmpty()) Log.w(TAG, "recovered " + rest + " from an interrupted update"); } if (staging.isDirectory() && RuntimeFileTree.hasUserData(staging, target)) throw new IOException("User data still needs recovery from " + staging); new File(staging, CARRY_MARKER).delete(); } static final String TRASH = ".runtime-trash"; static boolean discard(File tree, java.util.function.LongConsumer progress) { if (RuntimeFileTree.deleteWhatCan(tree, progress)) return true; File trash = new File(tree.getParentFile(), TRASH); trash.mkdirs(); File aside = new File(trash, tree.getName() + "-" + System.currentTimeMillis()); if (tree.renameTo(aside)) { Log.w(TAG, "could not delete all of " + tree + "; set the rest aside in " + aside); return true; } Log.w(TAG, "could not delete or set aside " + tree); return !tree.exists(); } static void emptyTrash(File parent) { File trash = new File(parent, TRASH); if (trash.exists() && !RuntimeFileTree.deleteWhatCan(trash, null)) Log.i(TAG, "some runtime leftovers still cannot be deleted: " + trash); } private static boolean isEmptyDir(File dir) throws IOException { try (java.nio.file.DirectoryStream entries = java.nio.file.Files.newDirectoryStream(dir.toPath())) { return !entries.iterator().hasNext(); } } public static Removal beginUninstall(Context context) { if (sessionInUse()) return null; return beginUninstall(context.getApplicationContext(), LinuxRuntime.rootDir(context)); } private static boolean sessionInUse() { com.droiddeck.launcher.session.SessionState session = com.droiddeck.launcher.session.SessionState.INSTANCE; com.droiddeck.launcher.session.SessionPhase phase = session.getPhase(); return session.getRunning() || (phase != com.droiddeck.launcher.session.SessionPhase.IDLE && phase != com.droiddeck.launcher.session.SessionPhase.FAILED); } static Removal beginUninstall(Context app, File root) { synchronized (JOB_LOCK) { if (running != null) return null; removalError = null; running = new Job(true, text(app, R.string.rtinst_removing)); return new Removal(app, root, running); } } private static String text(Context app, int id) { return app == null ? "" : app.getString(id); } public static final class Removal { private final Context app; private final File root; private final Job job; private final java.util.concurrent.atomic.AtomicBoolean started = new java.util.concurrent.atomic.AtomicBoolean(); private Removal(Context app, File root, Job job) { this.app = app; this.root = root; this.job = job; } public boolean run(ProgressListener listener) { if (!started.compareAndSet(false, true)) return join(job, listener); if (listener != null) job.listeners.add(listener); try { requireStopped(); report(text(app, R.string.rtinst_removing), -1); final long[] removed = {0}; final long[] lastShown = {0}; java.util.function.LongConsumer progress = ignored -> { removed[0]++; long now = System.nanoTime(); if (removed[0] == 1 || now - lastShown[0] >= 200_000_000L) { lastShown[0] = now; report(app == null ? "" : app.getResources().getQuantityString( R.plurals.rtinst_removing_entries, (int) Math.min(removed[0], Integer.MAX_VALUE), removed[0]), -1); } }; File pending = removalDirectory(root); if (root.exists()) { if (!discard(pending, progress) || !root.renameTo(pending)) throw new IOException("Cannot prepare the runtime for removal"); } else if (!pending.isDirectory() && !pending.mkdirs()) { throw new IOException("Cannot prepare the runtime for removal"); } for (File leftover : new File[]{ new File(root.getParentFile(), root.getName() + ".new"), new File(root.getParentFile(), root.getName() + ".old"), pending}) { if (!discard(leftover, progress)) throw new IOException("Cannot remove " + leftover); } emptyTrash(root.getParentFile()); requireStopped(); if (app != null) RuntimeFileTree.delete(new File(app.getNoBackupFilesDir(), "guest-runtime"), null); job.ok = true; report(text(app, R.string.rtinst_removed), 100); return true; } catch (IOException e) { removalError = text(app, R.string.rtinst_removal_failed); Log.w(TAG, "runtime removal incomplete", e); report(removalError, -1); return false; } finally { synchronized (JOB_LOCK) { running = null; } job.done.countDown(); } } private void requireStopped() throws IOException { if (Thread.currentThread().isInterrupted()) throw new IOException("Runtime removal was interrupted"); if (app != null && sessionInUse()) throw new IOException("A session is still using the runtime"); } private void report(String stage, int percent) { job.stage = stage; job.percent = percent; for (ProgressListener listener : job.listeners) listener.onProgress(stage, percent); } } public static boolean extract(Context context, File archive, File destination, ProgressListener listener) { return extract(context, archive, destination, destination, listener); } static boolean extract(Context context, File archive, File destination, File linkRoot, ProgressListener listener) { long entries = 0; String extracting = context.getString(R.string.rtinst_extracting); java.util.LinkedHashMap links = new java.util.LinkedHashMap<>(); try (InputStream in = new ZstdCompressorInputStream( new BufferedInputStream(new FileInputStream(archive), 1 << 16)); TarArchiveInputStream tar = new TarArchiveInputStream(in)) { TarArchiveEntry entry; while ((entry = tar.getNextTarEntry()) != null) { File file = ArchivePaths.inside(destination, entry.getName()); if (file == null) { Log.w(TAG, "skipping entry outside the rootfs: " + entry.getName()); continue; } if (entry.isDirectory()) { file.mkdirs(); continue; } File parent = file.getParentFile(); if (parent != null && !parent.isDirectory()) parent.mkdirs(); if (entry.isSymbolicLink()) { links.remove(file); links.put(file, entry.getLinkName()); } else if (entry.isLink()) { File target = hardLinkTarget(destination, entry.getLinkName()); if (target == null) { Log.w(TAG, "skipping hard link outside the rootfs: " + entry.getLinkName()); continue; } links.remove(file); File part = partFile(file); part.delete(); try { Files.createLink(part.toPath(), target.toPath()); } catch (IOException | UnsupportedOperationException e) { if (!l2sLink(target, part, destination, linkRoot) && target.isFile()) { Files.copy(target.toPath(), part.toPath(), StandardCopyOption.REPLACE_EXISTING); } } if (Files.exists(part.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)) place(part, file); } else if (entry.isFile()) { links.remove(file); File part = partFile(file); try (OutputStream out = new FileOutputStream(part)) { byte[] buffer = new byte[1 << 16]; int read; while ((read = tar.read(buffer)) != -1) out.write(buffer, 0, read); } if ((entry.getMode() & 0111) != 0) part.setExecutable(true, false); place(part, file); } else { continue; } if (++entries % 2000 == 0 && listener != null) { listener.onProgress(extracting, -1); } } for (java.util.Map.Entry link : links.entrySet()) { File file = link.getKey(); File part = partFile(file); try { Files.deleteIfExists(part.toPath()); Files.createSymbolicLink(part.toPath(), java.nio.file.Paths.get(link.getValue())); place(part, file); } catch (IOException e) { Log.w(TAG, "symlink " + file + " -> " + link.getValue() + ": " + e); part.delete(); } } return true; } catch (Exception e) { Log.e(TAG, "extract", e); return false; } } static File hardLinkTarget(File destination, String name) throws IOException { java.nio.file.Path path = java.nio.file.Paths.get(name).normalize(); java.nio.file.Path last = path.getFileName(); if (last == null || last.toString().isEmpty() || last.toString().equals("..")) return null; java.nio.file.Path parent = path.getParent(); File dir = parent == null ? destination : ArchivePaths.inside(destination, parent.toString()); return dir == null ? null : new File(dir, last.toString()); } private static final String L2S = ".l2s."; static boolean l2sLink(File target, File link) { return l2sLink(target, link, null, null); } static boolean l2sLink(File target, File link, File tree, File linkTree) { java.nio.file.Path here = tree == null ? null : tree.toPath().toAbsolutePath().normalize(); java.nio.file.Path there = linkTree == null ? here : linkTree.toPath().toAbsolutePath().normalize(); java.util.function.UnaryOperator shown = path -> { java.nio.file.Path p = path.toAbsolutePath().normalize(); return here == null || !p.startsWith(here) ? p : there.resolve(here.relativize(p)); }; java.util.function.UnaryOperator actual = path -> { java.nio.file.Path p = path.toAbsolutePath().normalize(); return there == null || !p.startsWith(there) ? p : here.resolve(there.relativize(p)); }; try { java.nio.file.Path original = target.toPath().toAbsolutePath().normalize(); java.nio.file.Path intermediate; if (Files.isSymbolicLink(original)) { intermediate = actual.apply(Files.readSymbolicLink(original)); if (!intermediate.getFileName().toString().startsWith(L2S) || !Files.isSymbolicLink(intermediate)) return false; java.nio.file.Path fin = actual.apply(Files.readSymbolicLink(intermediate)); String name = fin.getFileName().toString(); int count = Integer.parseInt(name.substring(name.length() - 4)) + 1; java.nio.file.Path next = fin.resolveSibling(name.substring(0, name.length() - 4) + String.format(java.util.Locale.ROOT, "%04d", count)); Files.move(fin, next, StandardCopyOption.ATOMIC_MOVE); Files.delete(intermediate); Files.createSymbolicLink(intermediate, shown.apply(next)); } else { if (!Files.isRegularFile(original, java.nio.file.LinkOption.NOFOLLOW_LINKS)) return false; java.nio.file.Path dir = original.getParent(); String base = L2S + original.getFileName(); int suffix = 1; do { intermediate = dir.resolve(base + String.format(java.util.Locale.ROOT, "%04d", suffix++)); } while (Files.exists(intermediate, java.nio.file.LinkOption.NOFOLLOW_LINKS) && suffix < 1000); java.nio.file.Path fin = dir.resolve(intermediate.getFileName() + ".0002"); Files.move(original, fin, StandardCopyOption.ATOMIC_MOVE); Files.createSymbolicLink(intermediate, shown.apply(fin)); Files.createSymbolicLink(original, shown.apply(intermediate)); } Files.deleteIfExists(link.toPath()); Files.createSymbolicLink(link.toPath(), shown.apply(intermediate)); return true; } catch (IOException | RuntimeException e) { Log.w(TAG, "l2s link " + link + " -> " + target + ": " + e); return false; } } static File partFile(File file) { return new File(file.getParentFile(), ".dd-part-" + Integer.toHexString(file.getName().hashCode())); } private static void place(File part, File file) throws IOException { java.nio.file.Path path = file.toPath(); if (Files.isDirectory(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)) Files.delete(path); Files.move(part.toPath(), path, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } }