bd347e42c8743448da9262f03d14e56fcd5b30b4
[android/platform/packages/providers/DownloadProvider.git] / src / com / android / providers / downloads / DownloadThread.java
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.android.providers.downloads;
18
19 import static android.provider.Downloads.Impl.STATUS_BAD_REQUEST;
20 import static android.provider.Downloads.Impl.STATUS_CANNOT_RESUME;
21 import static android.provider.Downloads.Impl.STATUS_FILE_ERROR;
22 import static android.provider.Downloads.Impl.STATUS_HTTP_DATA_ERROR;
23 import static android.provider.Downloads.Impl.STATUS_TOO_MANY_REDIRECTS;
24 import static android.provider.Downloads.Impl.STATUS_WAITING_TO_RETRY;
25 import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
26 import static com.android.providers.downloads.Constants.TAG;
27 import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
28 import static java.net.HttpURLConnection.HTTP_MOVED_PERM;
29 import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;
30 import static java.net.HttpURLConnection.HTTP_OK;
31 import static java.net.HttpURLConnection.HTTP_PARTIAL;
32 import static java.net.HttpURLConnection.HTTP_PRECON_FAILED;
33 import static java.net.HttpURLConnection.HTTP_SEE_OTHER;
34 import static java.net.HttpURLConnection.HTTP_UNAVAILABLE;
35
36 import android.content.ContentValues;
37 import android.content.Context;
38 import android.content.Intent;
39 import android.drm.DrmManagerClient;
40 import android.drm.DrmOutputStream;
41 import android.net.INetworkPolicyListener;
42 import android.net.NetworkPolicyManager;
43 import android.net.TrafficStats;
44 import android.os.FileUtils;
45 import android.os.PowerManager;
46 import android.os.Process;
47 import android.os.SystemClock;
48 import android.provider.Downloads;
49 import android.text.TextUtils;
50 import android.util.Log;
51 import android.util.Pair;
52
53 import com.android.providers.downloads.DownloadInfo.NetworkState;
54
55 import java.io.File;
56 import java.io.FileDescriptor;
57 import java.io.FileOutputStream;
58 import java.io.IOException;
59 import java.io.InputStream;
60 import java.io.OutputStream;
61 import java.io.RandomAccessFile;
62 import java.net.HttpURLConnection;
63 import java.net.MalformedURLException;
64 import java.net.URL;
65 import java.net.URLConnection;
66
67 import libcore.io.IoUtils;
68 import libcore.net.http.HttpEngine;
69
70 /**
71  * Task which executes a given {@link DownloadInfo}: making network requests,
72  * persisting data to disk, and updating {@link DownloadProvider}.
73  */
74 public class DownloadThread implements Runnable {
75
76     private static final int HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
77     private static final int HTTP_TEMP_REDIRECT = 307;
78
79     private static final int DEFAULT_TIMEOUT = (int) MINUTE_IN_MILLIS;
80
81     private final Context mContext;
82     private final DownloadInfo mInfo;
83     private final SystemFacade mSystemFacade;
84     private final StorageManager mStorageManager;
85     private final DownloadNotifier mNotifier;
86
87     private volatile boolean mPolicyDirty;
88
89     public DownloadThread(Context context, SystemFacade systemFacade, DownloadInfo info,
90             StorageManager storageManager, DownloadNotifier notifier) {
91         mContext = context;
92         mSystemFacade = systemFacade;
93         mInfo = info;
94         mStorageManager = storageManager;
95         mNotifier = notifier;
96     }
97
98     /**
99      * Returns the user agent provided by the initiating app, or use the default one
100      */
101     private String userAgent() {
102         String userAgent = mInfo.mUserAgent;
103         if (userAgent == null) {
104             userAgent = Constants.DEFAULT_USER_AGENT;
105         }
106         return userAgent;
107     }
108
109     /**
110      * State for the entire run() method.
111      */
112     static class State {
113         public String mFilename;
114         public String mMimeType;
115         public int mRetryAfter = 0;
116         public boolean mGotData = false;
117         public String mRequestUri;
118         public long mTotalBytes = -1;
119         public long mCurrentBytes = 0;
120         public String mHeaderETag;
121         public boolean mContinuingDownload = false;
122         public long mBytesNotified = 0;
123         public long mTimeLastNotification = 0;
124
125         /** Historical bytes/second speed of this download. */
126         public long mSpeed;
127         /** Time when current sample started. */
128         public long mSpeedSampleStart;
129         /** Bytes transferred since current sample started. */
130         public long mSpeedSampleBytes;
131
132         public long mContentLength = -1;
133         public String mContentDisposition;
134         public String mContentLocation;
135
136         public int mRedirectionCount;
137         public URL mUrl;
138
139         public State(DownloadInfo info) {
140             mMimeType = Intent.normalizeMimeType(info.mMimeType);
141             mRequestUri = info.mUri;
142             mFilename = info.mFileName;
143             mTotalBytes = info.mTotalBytes;
144             mCurrentBytes = info.mCurrentBytes;
145         }
146
147         public void resetBeforeExecute() {
148             // Reset any state from previous execution
149             mContentLength = -1;
150             mContentDisposition = null;
151             mContentLocation = null;
152             mRedirectionCount = 0;
153         }
154     }
155
156     @Override
157     public void run() {
158         Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
159         try {
160             runInternal();
161         } finally {
162             mNotifier.notifyDownloadSpeed(mInfo.mId, 0);
163         }
164     }
165
166     private void runInternal() {
167         // Skip when download already marked as finished; this download was
168         // probably started again while racing with UpdateThread.
169         if (DownloadInfo.queryDownloadStatus(mContext.getContentResolver(), mInfo.mId)
170                 == Downloads.Impl.STATUS_SUCCESS) {
171             Log.d(TAG, "Download " + mInfo.mId + " already finished; skipping");
172             return;
173         }
174
175         State state = new State(mInfo);
176         PowerManager.WakeLock wakeLock = null;
177         int finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
178         int numFailed = mInfo.mNumFailed;
179         String errorMsg = null;
180
181         final NetworkPolicyManager netPolicy = NetworkPolicyManager.from(mContext);
182         final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
183
184         try {
185             wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
186             wakeLock.acquire();
187
188             // while performing download, register for rules updates
189             netPolicy.registerListener(mPolicyListener);
190
191             Log.i(Constants.TAG, "Initiating download " + mInfo.mId);
192
193             // Network traffic on this thread should be counted against the
194             // requesting UID, and is tagged with well-known value.
195             TrafficStats.setThreadStatsTag(TrafficStats.TAG_SYSTEM_DOWNLOAD);
196             TrafficStats.setThreadStatsUid(mInfo.mUid);
197
198             try {
199                 // TODO: migrate URL sanity checking into client side of API
200                 state.mUrl = new URL(state.mRequestUri);
201             } catch (MalformedURLException e) {
202                 throw new StopRequestException(STATUS_BAD_REQUEST, e);
203             }
204
205             executeDownload(state);
206
207             if (Constants.LOGV) {
208                 Log.v(Constants.TAG, "download completed for " + mInfo.mUri);
209             }
210             finalizeDestinationFile(state);
211             finalStatus = Downloads.Impl.STATUS_SUCCESS;
212         } catch (StopRequestException error) {
213             // remove the cause before printing, in case it contains PII
214             errorMsg = error.getMessage();
215             String msg = "Aborting request for download " + mInfo.mId + ": " + errorMsg;
216             Log.w(Constants.TAG, msg);
217             if (Constants.LOGV) {
218                 Log.w(Constants.TAG, msg, error);
219             }
220             finalStatus = error.getFinalStatus();
221
222             if (finalStatus == STATUS_WAITING_TO_RETRY) {
223                 throw new IllegalStateException("Execution should always throw final error codes");
224             }
225
226             // Some errors should be retryable later, unless we fail too many times.
227             if (isStatusRetryable(finalStatus)) {
228                 if (state.mGotData) {
229                     numFailed = 1;
230                 } else {
231                     numFailed += 1;
232                 }
233
234                 if (numFailed < Constants.MAX_RETRIES) {
235                     finalStatus = STATUS_WAITING_TO_RETRY;
236                 }
237             }
238
239             // fall through to finally block
240         } catch (Throwable ex) {
241             errorMsg = ex.getMessage();
242             String msg = "Exception for id " + mInfo.mId + ": " + errorMsg;
243             Log.w(Constants.TAG, msg, ex);
244             finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
245             // falls through to the code that reports an error
246         } finally {
247             TrafficStats.clearThreadStatsTag();
248             TrafficStats.clearThreadStatsUid();
249
250             cleanupDestination(state, finalStatus);
251             notifyDownloadCompleted(state, finalStatus, errorMsg, numFailed);
252
253             netPolicy.unregisterListener(mPolicyListener);
254
255             if (wakeLock != null) {
256                 wakeLock.release();
257                 wakeLock = null;
258             }
259         }
260         mStorageManager.incrementNumDownloadsSoFar();
261     }
262
263     /**
264      * Fully execute a single download request. Setup and send the request,
265      * handle the response, and transfer the data to the destination file.
266      */
267     private void executeDownload(State state) throws StopRequestException {
268         state.resetBeforeExecute();
269         setupDestinationFile(state);
270
271         // skip when already finished; remove after fixing race in 5217390
272         if (state.mCurrentBytes == state.mTotalBytes) {
273             Log.i(Constants.TAG, "Skipping initiating request for download " +
274                   mInfo.mId + "; already completed");
275             return;
276         }
277
278         // TODO: compare mInfo.mNumFailed against Constants.MAX_RETRIES
279
280         while (state.mRedirectionCount++ < HttpEngine.MAX_REDIRECTS) {
281             // Open connection and follow any redirects until we have a useful
282             // response with body.
283             HttpURLConnection conn = null;
284             try {
285                 checkConnectivity();
286                 conn = (HttpURLConnection) state.mUrl.openConnection();
287                 conn.setInstanceFollowRedirects(false);
288                 conn.setConnectTimeout(DEFAULT_TIMEOUT);
289                 conn.setReadTimeout(DEFAULT_TIMEOUT);
290
291                 addRequestHeaders(state, conn);
292
293                 final int responseCode = conn.getResponseCode();
294                 switch (responseCode) {
295                     case HTTP_OK:
296                         if (state.mContinuingDownload) {
297                             throw new StopRequestException(
298                                     STATUS_CANNOT_RESUME, "Expected partial, but received OK");
299                         }
300                         processResponseHeaders(state, conn);
301                         transferData(state, conn);
302                         return;
303
304                     case HTTP_PARTIAL:
305                         if (!state.mContinuingDownload) {
306                             throw new StopRequestException(
307                                     STATUS_CANNOT_RESUME, "Expected OK, but received partial");
308                         }
309                         transferData(state, conn);
310                         return;
311
312                     case HTTP_MOVED_PERM:
313                     case HTTP_MOVED_TEMP:
314                     case HTTP_SEE_OTHER:
315                     case HTTP_TEMP_REDIRECT:
316                         final String location = conn.getHeaderField("Location");
317                         state.mUrl = new URL(state.mUrl, location);
318                         continue;
319
320                     case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE:
321                         throw new StopRequestException(
322                                 STATUS_CANNOT_RESUME, "Requested range not satisfiable");
323
324                     case HTTP_PRECON_FAILED:
325                         // TODO: probably means our etag precondition was
326                         // changed; flush and retry again
327                         StopRequestException.throwUnhandledHttpError(
328                                 responseCode, conn.getResponseMessage());
329
330                     case HTTP_UNAVAILABLE:
331                         parseRetryAfterHeaders(state, conn);
332                         throw new StopRequestException(
333                                 HTTP_UNAVAILABLE, conn.getResponseMessage());
334
335                     case HTTP_INTERNAL_ERROR:
336                         throw new StopRequestException(
337                                 HTTP_INTERNAL_ERROR, conn.getResponseMessage());
338
339                     default:
340                         StopRequestException.throwUnhandledHttpError(
341                                 responseCode, conn.getResponseMessage());
342                 }
343             } catch (IOException e) {
344                 // Trouble with low-level sockets
345                 throw new StopRequestException(STATUS_HTTP_DATA_ERROR, e);
346
347             } finally {
348                 if (conn != null) conn.disconnect();
349             }
350         }
351
352         throw new StopRequestException(STATUS_TOO_MANY_REDIRECTS, "Too many redirects");
353     }
354
355     /**
356      * Transfer data from the given connection to the destination file.
357      */
358     private void transferData(State state, HttpURLConnection conn) throws StopRequestException {
359         DrmManagerClient drmClient = null;
360         InputStream in = null;
361         OutputStream out = null;
362         FileDescriptor outFd = null;
363         try {
364             try {
365                 in = conn.getInputStream();
366             } catch (IOException e) {
367                 throw new StopRequestException(STATUS_HTTP_DATA_ERROR, e);
368             }
369
370             try {
371                 if (DownloadDrmHelper.isDrmConvertNeeded(state.mMimeType)) {
372                     drmClient = new DrmManagerClient(mContext);
373                     final RandomAccessFile file = new RandomAccessFile(
374                             new File(state.mFilename), "rw");
375                     out = new DrmOutputStream(drmClient, file, state.mMimeType);
376                     outFd = file.getFD();
377                 } else {
378                     out = new FileOutputStream(state.mFilename, true);
379                     outFd = ((FileOutputStream) out).getFD();
380                 }
381             } catch (IOException e) {
382                 throw new StopRequestException(STATUS_FILE_ERROR, e);
383             }
384
385             // Start streaming data, periodically watch for pause/cancel
386             // commands and checking disk space as needed.
387             transferData(state, in, out);
388
389             try {
390                 if (out instanceof DrmOutputStream) {
391                     ((DrmOutputStream) out).finish();
392                 }
393             } catch (IOException e) {
394                 throw new StopRequestException(STATUS_FILE_ERROR, e);
395             }
396
397         } finally {
398             if (drmClient != null) {
399                 drmClient.release();
400             }
401
402             IoUtils.closeQuietly(in);
403
404             try {
405                 if (out != null) out.flush();
406                 if (outFd != null) outFd.sync();
407             } catch (IOException e) {
408             } finally {
409                 IoUtils.closeQuietly(out);
410             }
411         }
412     }
413
414     /**
415      * Check if current connectivity is valid for this request.
416      */
417     private void checkConnectivity() throws StopRequestException {
418         // checking connectivity will apply current policy
419         mPolicyDirty = false;
420
421         final NetworkState networkUsable = mInfo.checkCanUseNetwork();
422         if (networkUsable != NetworkState.OK) {
423             int status = Downloads.Impl.STATUS_WAITING_FOR_NETWORK;
424             if (networkUsable == NetworkState.UNUSABLE_DUE_TO_SIZE) {
425                 status = Downloads.Impl.STATUS_QUEUED_FOR_WIFI;
426                 mInfo.notifyPauseDueToSize(true);
427             } else if (networkUsable == NetworkState.RECOMMENDED_UNUSABLE_DUE_TO_SIZE) {
428                 status = Downloads.Impl.STATUS_QUEUED_FOR_WIFI;
429                 mInfo.notifyPauseDueToSize(false);
430             }
431             throw new StopRequestException(status, networkUsable.name());
432         }
433     }
434
435     /**
436      * Transfer as much data as possible from the HTTP response to the
437      * destination file.
438      */
439     private void transferData(State state, InputStream in, OutputStream out)
440             throws StopRequestException {
441         final byte data[] = new byte[Constants.BUFFER_SIZE];
442         for (;;) {
443             int bytesRead = readFromResponse(state, data, in);
444             if (bytesRead == -1) { // success, end of stream already reached
445                 handleEndOfStream(state);
446                 return;
447             }
448
449             state.mGotData = true;
450             writeDataToDestination(state, data, bytesRead, out);
451             state.mCurrentBytes += bytesRead;
452             reportProgress(state);
453
454             if (Constants.LOGVV) {
455                 Log.v(Constants.TAG, "downloaded " + state.mCurrentBytes + " for "
456                       + mInfo.mUri);
457             }
458
459             checkPausedOrCanceled(state);
460         }
461     }
462
463     /**
464      * Called after a successful completion to take any necessary action on the downloaded file.
465      */
466     private void finalizeDestinationFile(State state) {
467         if (state.mFilename != null) {
468             // make sure the file is readable
469             FileUtils.setPermissions(state.mFilename, 0644, -1, -1);
470         }
471     }
472
473     /**
474      * Called just before the thread finishes, regardless of status, to take any necessary action on
475      * the downloaded file.
476      */
477     private void cleanupDestination(State state, int finalStatus) {
478         if (state.mFilename != null && Downloads.Impl.isStatusError(finalStatus)) {
479             if (Constants.LOGVV) {
480                 Log.d(TAG, "cleanupDestination() deleting " + state.mFilename);
481             }
482             new File(state.mFilename).delete();
483             state.mFilename = null;
484         }
485     }
486
487     /**
488      * Check if the download has been paused or canceled, stopping the request appropriately if it
489      * has been.
490      */
491     private void checkPausedOrCanceled(State state) throws StopRequestException {
492         synchronized (mInfo) {
493             if (mInfo.mControl == Downloads.Impl.CONTROL_PAUSED) {
494                 throw new StopRequestException(
495                         Downloads.Impl.STATUS_PAUSED_BY_APP, "download paused by owner");
496             }
497             if (mInfo.mStatus == Downloads.Impl.STATUS_CANCELED) {
498                 throw new StopRequestException(Downloads.Impl.STATUS_CANCELED, "download canceled");
499             }
500         }
501
502         // if policy has been changed, trigger connectivity check
503         if (mPolicyDirty) {
504             checkConnectivity();
505         }
506     }
507
508     /**
509      * Report download progress through the database if necessary.
510      */
511     private void reportProgress(State state) {
512         final long now = SystemClock.elapsedRealtime();
513
514         final long sampleDelta = now - state.mSpeedSampleStart;
515         if (sampleDelta > 500) {
516             final long sampleSpeed = ((state.mCurrentBytes - state.mSpeedSampleBytes) * 1000)
517                     / sampleDelta;
518
519             if (state.mSpeed == 0) {
520                 state.mSpeed = sampleSpeed;
521             } else {
522                 state.mSpeed = ((state.mSpeed * 3) + sampleSpeed) / 4;
523             }
524
525             state.mSpeedSampleStart = now;
526             state.mSpeedSampleBytes = state.mCurrentBytes;
527
528             mNotifier.notifyDownloadSpeed(mInfo.mId, state.mSpeed);
529         }
530
531         if (state.mCurrentBytes - state.mBytesNotified > Constants.MIN_PROGRESS_STEP &&
532             now - state.mTimeLastNotification > Constants.MIN_PROGRESS_TIME) {
533             ContentValues values = new ContentValues();
534             values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, state.mCurrentBytes);
535             mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
536             state.mBytesNotified = state.mCurrentBytes;
537             state.mTimeLastNotification = now;
538         }
539     }
540
541     /**
542      * Write a data buffer to the destination file.
543      * @param data buffer containing the data to write
544      * @param bytesRead how many bytes to write from the buffer
545      */
546     private void writeDataToDestination(State state, byte[] data, int bytesRead, OutputStream out)
547             throws StopRequestException {
548         mStorageManager.verifySpaceBeforeWritingToFile(
549                 mInfo.mDestination, state.mFilename, bytesRead);
550
551         boolean forceVerified = false;
552         while (true) {
553             try {
554                 out.write(data, 0, bytesRead);
555                 return;
556             } catch (IOException ex) {
557                 // TODO: better differentiate between DRM and disk failures
558                 if (!forceVerified) {
559                     // couldn't write to file. are we out of space? check.
560                     mStorageManager.verifySpace(mInfo.mDestination, state.mFilename, bytesRead);
561                     forceVerified = true;
562                 } else {
563                     throw new StopRequestException(Downloads.Impl.STATUS_FILE_ERROR,
564                             "Failed to write data: " + ex);
565                 }
566             }
567         }
568     }
569
570     /**
571      * Called when we've reached the end of the HTTP response stream, to update the database and
572      * check for consistency.
573      */
574     private void handleEndOfStream(State state) throws StopRequestException {
575         ContentValues values = new ContentValues();
576         values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, state.mCurrentBytes);
577         if (state.mContentLength == -1) {
578             values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, state.mCurrentBytes);
579         }
580         mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
581
582         final boolean lengthMismatched = (state.mContentLength != -1)
583                 && (state.mCurrentBytes != state.mContentLength);
584         if (lengthMismatched) {
585             if (cannotResume(state)) {
586                 throw new StopRequestException(STATUS_CANNOT_RESUME,
587                         "mismatched content length; unable to resume");
588             } else {
589                 throw new StopRequestException(STATUS_HTTP_DATA_ERROR,
590                         "closed socket before end of file");
591             }
592         }
593     }
594
595     private boolean cannotResume(State state) {
596         return (state.mCurrentBytes > 0 && !mInfo.mNoIntegrity && state.mHeaderETag == null)
597                 || DownloadDrmHelper.isDrmConvertNeeded(state.mMimeType);
598     }
599
600     /**
601      * Read some data from the HTTP response stream, handling I/O errors.
602      * @param data buffer to use to read data
603      * @param entityStream stream for reading the HTTP response entity
604      * @return the number of bytes actually read or -1 if the end of the stream has been reached
605      */
606     private int readFromResponse(State state, byte[] data, InputStream entityStream)
607             throws StopRequestException {
608         try {
609             return entityStream.read(data);
610         } catch (IOException ex) {
611             // TODO: handle stream errors the same as other retries
612             if ("unexpected end of stream".equals(ex.getMessage())) {
613                 return -1;
614             }
615
616             ContentValues values = new ContentValues();
617             values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, state.mCurrentBytes);
618             mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
619             if (cannotResume(state)) {
620                 throw new StopRequestException(STATUS_CANNOT_RESUME,
621                         "Failed reading response: " + ex + "; unable to resume", ex);
622             } else {
623                 throw new StopRequestException(STATUS_HTTP_DATA_ERROR,
624                         "Failed reading response: " + ex, ex);
625             }
626         }
627     }
628
629     /**
630      * Prepare target file based on given network response. Derives filename and
631      * target size as needed.
632      */
633     private void processResponseHeaders(State state, HttpURLConnection conn)
634             throws StopRequestException {
635         // TODO: fallocate the entire file if header gave us specific length
636
637         readResponseHeaders(state, conn);
638
639         state.mFilename = Helpers.generateSaveFile(
640                 mContext,
641                 mInfo.mUri,
642                 mInfo.mHint,
643                 state.mContentDisposition,
644                 state.mContentLocation,
645                 state.mMimeType,
646                 mInfo.mDestination,
647                 state.mContentLength,
648                 mInfo.mIsPublicApi, mStorageManager);
649
650         updateDatabaseFromHeaders(state);
651         // check connectivity again now that we know the total size
652         checkConnectivity();
653     }
654
655     /**
656      * Update necessary database fields based on values of HTTP response headers that have been
657      * read.
658      */
659     private void updateDatabaseFromHeaders(State state) {
660         ContentValues values = new ContentValues();
661         values.put(Downloads.Impl._DATA, state.mFilename);
662         if (state.mHeaderETag != null) {
663             values.put(Constants.ETAG, state.mHeaderETag);
664         }
665         if (state.mMimeType != null) {
666             values.put(Downloads.Impl.COLUMN_MIME_TYPE, state.mMimeType);
667         }
668         values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, mInfo.mTotalBytes);
669         mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
670     }
671
672     /**
673      * Read headers from the HTTP response and store them into local state.
674      */
675     private void readResponseHeaders(State state, HttpURLConnection conn)
676             throws StopRequestException {
677         state.mContentDisposition = conn.getHeaderField("Content-Disposition");
678         state.mContentLocation = conn.getHeaderField("Content-Location");
679
680         if (state.mMimeType == null) {
681             state.mMimeType = Intent.normalizeMimeType(conn.getContentType());
682         }
683
684         state.mHeaderETag = conn.getHeaderField("ETag");
685
686         final String transferEncoding = conn.getHeaderField("Transfer-Encoding");
687         if (transferEncoding == null) {
688             state.mContentLength = getHeaderFieldLong(conn, "Content-Length", -1);
689         } else {
690             Log.i(TAG, "Ignoring Content-Length since Transfer-Encoding is also defined");
691             state.mContentLength = -1;
692         }
693
694         state.mTotalBytes = state.mContentLength;
695         mInfo.mTotalBytes = state.mContentLength;
696
697         final boolean noSizeInfo = state.mContentLength == -1
698                 && (transferEncoding == null || !transferEncoding.equalsIgnoreCase("chunked"));
699         if (!mInfo.mNoIntegrity && noSizeInfo) {
700             throw new StopRequestException(STATUS_CANNOT_RESUME,
701                     "can't know size of download, giving up");
702         }
703     }
704
705     private void parseRetryAfterHeaders(State state, HttpURLConnection conn) {
706         state.mRetryAfter = conn.getHeaderFieldInt("Retry-After", -1);
707         if (state.mRetryAfter < 0) {
708             state.mRetryAfter = 0;
709         } else {
710             if (state.mRetryAfter < Constants.MIN_RETRY_AFTER) {
711                 state.mRetryAfter = Constants.MIN_RETRY_AFTER;
712             } else if (state.mRetryAfter > Constants.MAX_RETRY_AFTER) {
713                 state.mRetryAfter = Constants.MAX_RETRY_AFTER;
714             }
715             state.mRetryAfter += Helpers.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1);
716             state.mRetryAfter *= 1000;
717         }
718     }
719
720     /**
721      * Prepare the destination file to receive data.  If the file already exists, we'll set up
722      * appropriately for resumption.
723      */
724     private void setupDestinationFile(State state) throws StopRequestException {
725         if (!TextUtils.isEmpty(state.mFilename)) { // only true if we've already run a thread for this download
726             if (Constants.LOGV) {
727                 Log.i(Constants.TAG, "have run thread before for id: " + mInfo.mId +
728                         ", and state.mFilename: " + state.mFilename);
729             }
730             if (!Helpers.isFilenameValid(state.mFilename,
731                     mStorageManager.getDownloadDataDirectory())) {
732                 // this should never happen
733                 throw new StopRequestException(Downloads.Impl.STATUS_FILE_ERROR,
734                         "found invalid internal destination filename");
735             }
736             // We're resuming a download that got interrupted
737             File f = new File(state.mFilename);
738             if (f.exists()) {
739                 if (Constants.LOGV) {
740                     Log.i(Constants.TAG, "resuming download for id: " + mInfo.mId +
741                             ", and state.mFilename: " + state.mFilename);
742                 }
743                 long fileLength = f.length();
744                 if (fileLength == 0) {
745                     // The download hadn't actually started, we can restart from scratch
746                     if (Constants.LOGVV) {
747                         Log.d(TAG, "setupDestinationFile() found fileLength=0, deleting "
748                                 + state.mFilename);
749                     }
750                     f.delete();
751                     state.mFilename = null;
752                     if (Constants.LOGV) {
753                         Log.i(Constants.TAG, "resuming download for id: " + mInfo.mId +
754                                 ", BUT starting from scratch again: ");
755                     }
756                 } else if (mInfo.mETag == null && !mInfo.mNoIntegrity) {
757                     // This should've been caught upon failure
758                     if (Constants.LOGVV) {
759                         Log.d(TAG, "setupDestinationFile() unable to resume download, deleting "
760                                 + state.mFilename);
761                     }
762                     f.delete();
763                     throw new StopRequestException(Downloads.Impl.STATUS_CANNOT_RESUME,
764                             "Trying to resume a download that can't be resumed");
765                 } else {
766                     // All right, we'll be able to resume this download
767                     if (Constants.LOGV) {
768                         Log.i(Constants.TAG, "resuming download for id: " + mInfo.mId +
769                                 ", and starting with file of length: " + fileLength);
770                     }
771                     state.mCurrentBytes = (int) fileLength;
772                     if (mInfo.mTotalBytes != -1) {
773                         state.mContentLength = mInfo.mTotalBytes;
774                     }
775                     state.mHeaderETag = mInfo.mETag;
776                     state.mContinuingDownload = true;
777                     if (Constants.LOGV) {
778                         Log.i(Constants.TAG, "resuming download for id: " + mInfo.mId +
779                                 ", state.mCurrentBytes: " + state.mCurrentBytes +
780                                 ", and setting mContinuingDownload to true: ");
781                     }
782                 }
783             }
784         }
785     }
786
787     /**
788      * Add custom headers for this download to the HTTP request.
789      */
790     private void addRequestHeaders(State state, HttpURLConnection conn) {
791         for (Pair<String, String> header : mInfo.getHeaders()) {
792             conn.addRequestProperty(header.first, header.second);
793         }
794
795         // Only splice in user agent when not already defined
796         if (conn.getRequestProperty("User-Agent") == null) {
797             conn.addRequestProperty("User-Agent", userAgent());
798         }
799
800         if (state.mContinuingDownload) {
801             if (state.mHeaderETag != null) {
802                 conn.addRequestProperty("If-Match", state.mHeaderETag);
803             }
804             conn.addRequestProperty("Range", "bytes=" + state.mCurrentBytes + "-");
805         }
806     }
807
808     /**
809      * Stores information about the completed download, and notifies the initiating application.
810      */
811     private void notifyDownloadCompleted(
812             State state, int finalStatus, String errorMsg, int numFailed) {
813         notifyThroughDatabase(state, finalStatus, errorMsg, numFailed);
814         if (Downloads.Impl.isStatusCompleted(finalStatus)) {
815             mInfo.sendIntentIfRequested();
816         }
817     }
818
819     private void notifyThroughDatabase(
820             State state, int finalStatus, String errorMsg, int numFailed) {
821         ContentValues values = new ContentValues();
822         values.put(Downloads.Impl.COLUMN_STATUS, finalStatus);
823         values.put(Downloads.Impl._DATA, state.mFilename);
824         values.put(Downloads.Impl.COLUMN_MIME_TYPE, state.mMimeType);
825         values.put(Downloads.Impl.COLUMN_LAST_MODIFICATION, mSystemFacade.currentTimeMillis());
826         values.put(Downloads.Impl.COLUMN_FAILED_CONNECTIONS, numFailed);
827         values.put(Constants.RETRY_AFTER_X_REDIRECT_COUNT, state.mRetryAfter);
828
829         // save the error message. could be useful to developers.
830         if (!TextUtils.isEmpty(errorMsg)) {
831             values.put(Downloads.Impl.COLUMN_ERROR_MSG, errorMsg);
832         }
833         mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
834     }
835
836     private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
837         @Override
838         public void onUidRulesChanged(int uid, int uidRules) {
839             // caller is NPMS, since we only register with them
840             if (uid == mInfo.mUid) {
841                 mPolicyDirty = true;
842             }
843         }
844
845         @Override
846         public void onMeteredIfacesChanged(String[] meteredIfaces) {
847             // caller is NPMS, since we only register with them
848             mPolicyDirty = true;
849         }
850
851         @Override
852         public void onRestrictBackgroundChanged(boolean restrictBackground) {
853             // caller is NPMS, since we only register with them
854             mPolicyDirty = true;
855         }
856     };
857
858     public static long getHeaderFieldLong(URLConnection conn, String field, long defaultValue) {
859         try {
860             return Long.parseLong(conn.getHeaderField(field));
861         } catch (NumberFormatException e) {
862             return defaultValue;
863         }
864     }
865
866     /**
867      * Return if given status is eligible to be treated as
868      * {@link android.provider.Downloads.Impl#STATUS_WAITING_TO_RETRY}.
869      */
870     public static boolean isStatusRetryable(int status) {
871         switch (status) {
872             case STATUS_HTTP_DATA_ERROR:
873             case HTTP_UNAVAILABLE:
874             case HTTP_INTERNAL_ERROR:
875                 return true;
876             default:
877                 return false;
878         }
879     }
880 }