package __CMVR_PACKAGE__; import java.io.*; import java.net.*; import java.security.MessageDigest; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; /** APK bytes stay in native background threads; progress never gates network reads. */ public final class CmvrPackageTransfer { public interface Progress { void update(String phase, long bytes, long total, int connections); } private final Set active = ConcurrentHashMap.newKeySet(); private final AtomicBoolean cancelled = new AtomicBoolean(); private final AtomicLong received = new AtomicLong(); private long lastEvent; private long lastBytes; private String lastPhase=""; private final Progress progress; private final String address, hash; private final Map headers; private final File target; private final long size; private final int requested; public CmvrPackageTransfer(String address, Map headers, File target, long size, String hash, int connections, Progress progress) { this.address=address;this.headers=headers;this.target=target;this.size=size;this.hash=hash;this.requested=Math.max(1,Math.min(4,connections));this.progress=progress; if(size<1||size>250L*1024*1024||!hash.matches("[a-f0-9]{64}"))throw new IllegalArgumentException("安装包版本信息无效"); } public void cancel() { cancelled.set(true);for(HttpURLConnection c:active)c.disconnect(); } private void check() throws IOException { if(cancelled.get()||Thread.currentThread().isInterrupted())throw new IOException("下载已取消"); } private synchronized void report(String phase,long bytes,int connections,boolean force) { if(!phase.equals(lastPhase)){lastPhase=phase;lastBytes=0;}bytes=Math.max(lastBytes,bytes);lastBytes=bytes; long now=System.nanoTime();if(force||now-lastEvent>=150_000_000L){lastEvent=now;progress.update(phase,bytes,size,connections);} } private HttpURLConnection connect(long start,long end,boolean range) throws IOException { check();HttpURLConnection c=(HttpURLConnection)new URL(address).openConnection();active.add(c); try { c.setInstanceFollowRedirects(false);c.setConnectTimeout(15000);c.setReadTimeout(30000);c.setUseCaches(false); for(Map.Entry h:headers.entrySet())c.setRequestProperty(h.getKey(),h.getValue()); c.setRequestProperty("Accept-Encoding","identity");if(range)c.setRequestProperty("Range","bytes="+start+"-"+end); int status=c.getResponseCode();check(); if(status==401)throw new IOException("AUTH_EXPIRED"); if(status!=200&&status!=206)throw new IOException("无法下载安装包,请重新检查更新("+status+")"); String type=Objects.toString(c.getContentType(),"").toLowerCase(Locale.ROOT); if(!type.startsWith("application/vnd.android.package-archive")&&!type.startsWith("application/octet-stream"))throw new IOException("服务未返回安装包文件"); if(!Objects.toString(c.getContentEncoding(),"identity").equalsIgnoreCase("identity"))throw new IOException("安装包传输格式不正确"); return c; }catch(IOException e){close(c);throw e;} } private void close(HttpURLConnection c){active.remove(c);c.disconnect();} private void rangeHeaders(HttpURLConnection c,long start,long end) throws IOException { if(c.getResponseCode()!=206||!Objects.equals(c.getHeaderField("Content-Range"),"bytes "+start+"-"+end+"/"+size)||c.getContentLengthLong()!=end-start+1) throw new IOException("安装包分段响应不正确,请重新下载"); } public int run() throws Exception { int count=1;ExecutorService pool=null; try { check();report("downloading",0,1,true); // Reuse the full response if the server does not support Range. HttpURLConnection probe=connect(0,0,requested>1&&size>=8L*1024*1024); try { if(probe.getResponseCode()==206){rangeHeaders(probe,0,0);try(InputStream in=probe.getInputStream()){if(in.read()<0||in.read()!=-1)throw new IOException("安装包分段响应不完整");}count=requested;} else { sequential(probe);check();return 1; } }finally{close(probe);} try(RandomAccessFile file=new RandomAccessFile(target,"rw")){file.setLength(size);} final int workers=count;pool=Executors.newFixedThreadPool(workers);List> tasks=new ArrayList<>(); long block=(size+workers-1)/workers; for(int i=0;i{try{part(start,end,workers);}catch(Exception e){throw new CompletionException(e);}}));} try{for(Future task:tasks)task.get();}catch(ExecutionException e){throw new IOException(message(e),e);} check();if(received.get()!=size||target.length()!=size)throw new IOException("安装包下载不完整,请重试"); report("downloading",size,workers,true);MessageDigest digest=MessageDigest.getInstance("SHA-256");long checked=0;byte[] buffer=new byte[256*1024];report("verifying",0,workers,true); try(InputStream in=new FileInputStream(target)){for(int n;(n=in.read(buffer))!=-1;){check();digest.update(buffer,0,n);checked+=n;report("verifying",checked,workers,false);}} verify(digest,checked);report("verifying",size,workers,true);return count; }catch(Exception e){cancel();throw e;} finally{if(pool!=null){pool.shutdownNow();pool.awaitTermination(35,TimeUnit.SECONDS);}if(cancelled.get())target.delete();} } private static String message(Throwable e){while(e.getCause()!=null)e=e.getCause();return Objects.toString(e.getMessage(),"安装包下载失败,请重试");} private void sequential(HttpURLConnection c) throws Exception { if(c.getContentLengthLong()!=size)throw new IOException("安装包大小不匹配,请重新检查更新"); MessageDigest digest=MessageDigest.getInstance("SHA-256");byte[] buffer=new byte[256*1024];long total=0; try(InputStream in=c.getInputStream();OutputStream out=new BufferedOutputStream(new FileOutputStream(target),256*1024)){ for(int n;(n=in.read(buffer))!=-1;){check();total+=n;if(total>size)throw new IOException("安装包大小不匹配");out.write(buffer,0,n);digest.update(buffer,0,n);received.set(total);report("downloading",total,1,false);} } check();report("downloading",total,1,true);report("verifying",total,1,true);verify(digest,total); } private void verify(MessageDigest digest,long total)throws IOException { StringBuilder actual=new StringBuilder();for(byte b:digest.digest())actual.append(String.format(Locale.ROOT,"%02x",b)); if(total!=size||target.length()!=size||!hash.equals(actual.toString()))throw new IOException("安装包校验失败,请重新下载"); } private void part(long start,long end,int connections)throws Exception { long position=start;byte[] buffer=new byte[256*1024]; for(int attempt=0;position<=end;attempt++) { check();HttpURLConnection c=null; try { c=connect(position,end,true);rangeHeaders(c,position,end); try(InputStream in=c.getInputStream();RandomAccessFile out=new RandomAccessFile(target,"rw")) { out.seek(position); while(position<=end){check();int n=in.read(buffer,0,(int)Math.min(buffer.length,end-position+1));if(n<0)throw new EOFException("安装包分段下载中断");out.write(buffer,0,n);position+=n;long done=received.addAndGet(n);report("downloading",done,connections,false);} if(in.read()!=-1)throw new IOException("安装包分段大小不匹配"); } }catch(IOException e){if(cancelled.get()||position>end||attempt>=2||Objects.equals(e.getMessage(),"AUTH_EXPIRED"))throw e;} finally{if(c!=null)close(c);} } } }