bug:3338089 print better error msg in DownloadThread when exception occurs
[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 org.apache.http.conn.params.ConnRouteParams;
20
21 import android.content.ContentValues;
22 import android.content.Context;
23 import android.content.Intent;
24 import android.drm.mobile1.DrmRawContent;
25 import android.net.http.AndroidHttpClient;
26 import android.net.Proxy;
27 import android.os.FileUtils;
28 import android.os.PowerManager;
29 import android.os.Process;
30 import android.provider.Downloads;
31 import android.provider.DrmStore;
32 import android.text.TextUtils;
33 import android.util.Log;
34 import android.util.Pair;
35
36 import org.apache.http.Header;
37 import org.apache.http.HttpResponse;
38 import org.apache.http.client.methods.HttpGet;
39
40 import java.io.File;
41 import java.io.FileNotFoundException;
42 import java.io.FileOutputStream;
43 import java.io.IOException;
44 import java.io.InputStream;
45 import java.io.SyncFailedException;
46 import java.net.URI;
47 import java.net.URISyntaxException;
48 import java.util.Locale;
49
50 /**
51  * Runs an actual download
52  */
53 public class DownloadThread extends Thread {
54
55     private final Context mContext;
56     private final DownloadInfo mInfo;
57     private final SystemFacade mSystemFacade;
58     private final StorageManager mStorageManager;
59
60     public DownloadThread(Context context, SystemFacade systemFacade, DownloadInfo info,
61             StorageManager storageManager) {
62         mContext = context;
63         mSystemFacade = systemFacade;
64         mInfo = info;
65         mStorageManager = storageManager;
66     }
67
68     /**
69      * Returns the user agent provided by the initiating app, or use the default one
70      */
71     private String userAgent() {
72         String userAgent = mInfo.mUserAgent;
73         if (userAgent != null) {
74         }
75         if (userAgent == null) {
76             userAgent = Constants.DEFAULT_USER_AGENT;
77         }
78         return userAgent;
79     }
80
81     /**
82      * State for the entire run() method.
83      */
84     static class State {
85         public String mFilename;
86         public FileOutputStream mStream;
87         public String mMimeType;
88         public boolean mCountRetry = false;
89         public int mRetryAfter = 0;
90         public int mRedirectCount = 0;
91         public String mNewUri;
92         public boolean mGotData = false;
93         public String mRequestUri;
94
95         public State(DownloadInfo info) {
96             mMimeType = sanitizeMimeType(info.mMimeType);
97             mRedirectCount = info.mRedirectCount;
98             mRequestUri = info.mUri;
99             mFilename = info.mFileName;
100         }
101     }
102
103     /**
104      * State within executeDownload()
105      */
106     private static class InnerState {
107         public int mBytesSoFar = 0;
108         public String mHeaderETag;
109         public boolean mContinuingDownload = false;
110         public String mHeaderContentLength;
111         public String mHeaderContentDisposition;
112         public String mHeaderContentLocation;
113         public int mBytesNotified = 0;
114         public long mTimeLastNotification = 0;
115     }
116
117     /**
118      * Raised from methods called by executeDownload() to indicate that the download should be
119      * retried immediately.
120      */
121     private class RetryDownload extends Throwable {}
122
123     /**
124      * Executes the download in a separate thread
125      */
126     @Override
127     public void run() {
128         Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
129
130         State state = new State(mInfo);
131         AndroidHttpClient client = null;
132         PowerManager.WakeLock wakeLock = null;
133         int finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
134         String errorMsg = null;
135
136         try {
137             PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
138             wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
139             wakeLock.acquire();
140
141
142             if (Constants.LOGV) {
143                 Log.v(Constants.TAG, "initiating download for " + mInfo.mUri);
144             }
145
146             client = AndroidHttpClient.newInstance(userAgent(), mContext);
147
148             boolean finished = false;
149             while(!finished) {
150                 Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId);
151                 // Set or unset proxy, which may have changed since last GET request.
152                 // setDefaultProxy() supports null as proxy parameter.
153                 ConnRouteParams.setDefaultProxy(client.getParams(),
154                         Proxy.getPreferredHttpHost(mContext, state.mRequestUri));
155                 HttpGet request = new HttpGet(state.mRequestUri);
156                 try {
157                     executeDownload(state, client, request);
158                     finished = true;
159                 } catch (RetryDownload exc) {
160                     // fall through
161                 } finally {
162                     request.abort();
163                     request = null;
164                 }
165             }
166
167             if (Constants.LOGV) {
168                 Log.v(Constants.TAG, "download completed for " + mInfo.mUri);
169             }
170             finalizeDestinationFile(state);
171             finalStatus = Downloads.Impl.STATUS_SUCCESS;
172         } catch (StopRequestException error) {
173             // remove the cause before printing, in case it contains PII
174             errorMsg = "Aborting request for download " + mInfo.mId + ": " + error.getMessage();
175             Log.w(Constants.TAG, errorMsg);
176             if (Constants.LOGV) {
177                 Log.w(Constants.TAG, errorMsg, error);
178             }
179             finalStatus = error.mFinalStatus;
180             // fall through to finally block
181         } catch (Throwable ex) { //sometimes the socket code throws unchecked exceptions
182             errorMsg = "Exception for id " + mInfo.mId + ": " + ex.getMessage();
183             Log.w(Constants.TAG, errorMsg, ex);
184             finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
185             // falls through to the code that reports an error
186         } finally {
187             if (wakeLock != null) {
188                 wakeLock.release();
189                 wakeLock = null;
190             }
191             if (client != null) {
192                 client.close();
193                 client = null;
194             }
195             cleanupDestination(state, finalStatus);
196             notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter,
197                                     state.mRedirectCount, state.mGotData, state.mFilename,
198                                     state.mNewUri, state.mMimeType, errorMsg);
199             mInfo.mHasActiveThread = false;
200         }
201         mStorageManager.incrementNumDownloadsSoFar();
202     }
203
204     /**
205      * Fully execute a single download request - setup and send the request, handle the response,
206      * and transfer the data to the destination file.
207      */
208     private void executeDownload(State state, AndroidHttpClient client, HttpGet request)
209             throws StopRequestException, RetryDownload {
210         InnerState innerState = new InnerState();
211         byte data[] = new byte[Constants.BUFFER_SIZE];
212
213         setupDestinationFile(state, innerState);
214         addRequestHeaders(innerState, request);
215
216         // check just before sending the request to avoid using an invalid connection at all
217         checkConnectivity(state);
218
219         HttpResponse response = sendRequest(state, client, request);
220         handleExceptionalStatus(state, innerState, response);
221
222         if (Constants.LOGV) {
223             Log.v(Constants.TAG, "received response for " + mInfo.mUri);
224         }
225
226         processResponseHeaders(state, innerState, response);
227         InputStream entityStream = openResponseEntity(state, response);
228         transferData(state, innerState, data, entityStream);
229     }
230
231     /**
232      * Check if current connectivity is valid for this request.
233      */
234     private void checkConnectivity(State state) throws StopRequestException {
235         int networkUsable = mInfo.checkCanUseNetwork();
236         if (networkUsable != DownloadInfo.NETWORK_OK) {
237             int status = Downloads.Impl.STATUS_WAITING_FOR_NETWORK;
238             if (networkUsable == DownloadInfo.NETWORK_UNUSABLE_DUE_TO_SIZE) {
239                 status = Downloads.Impl.STATUS_QUEUED_FOR_WIFI;
240                 mInfo.notifyPauseDueToSize(true);
241             } else if (networkUsable == DownloadInfo.NETWORK_RECOMMENDED_UNUSABLE_DUE_TO_SIZE) {
242                 status = Downloads.Impl.STATUS_QUEUED_FOR_WIFI;
243                 mInfo.notifyPauseDueToSize(false);
244             }
245             throw new StopRequestException(status,
246                     mInfo.getLogMessageForNetworkError(networkUsable));
247         }
248     }
249
250     /**
251      * Transfer as much data as possible from the HTTP response to the destination file.
252      * @param data buffer to use to read data
253      * @param entityStream stream for reading the HTTP response entity
254      */
255     private void transferData(State state, InnerState innerState, byte[] data,
256                                  InputStream entityStream) throws StopRequestException {
257         for (;;) {
258             int bytesRead = readFromResponse(state, innerState, data, entityStream);
259             if (bytesRead == -1) { // success, end of stream already reached
260                 handleEndOfStream(state, innerState);
261                 return;
262             }
263
264             state.mGotData = true;
265             writeDataToDestination(state, data, bytesRead);
266             innerState.mBytesSoFar += bytesRead;
267             reportProgress(state, innerState);
268
269             if (Constants.LOGVV) {
270                 Log.v(Constants.TAG, "downloaded " + innerState.mBytesSoFar + " for "
271                       + mInfo.mUri);
272             }
273
274             checkPausedOrCanceled(state);
275         }
276     }
277
278     /**
279      * Called after a successful completion to take any necessary action on the downloaded file.
280      */
281     private void finalizeDestinationFile(State state) throws StopRequestException {
282         if (isDrmFile(state)) {
283             transferToDrm(state);
284         } else {
285             // make sure the file is readable
286             FileUtils.setPermissions(state.mFilename, 0644, -1, -1);
287             syncDestination(state);
288         }
289     }
290
291     /**
292      * Called just before the thread finishes, regardless of status, to take any necessary action on
293      * the downloaded file.
294      */
295     private void cleanupDestination(State state, int finalStatus) {
296         closeDestination(state);
297         if (state.mFilename != null && Downloads.Impl.isStatusError(finalStatus)) {
298             new File(state.mFilename).delete();
299             state.mFilename = null;
300         }
301     }
302
303     /**
304      * Sync the destination file to storage.
305      */
306     private void syncDestination(State state) {
307         FileOutputStream downloadedFileStream = null;
308         try {
309             downloadedFileStream = new FileOutputStream(state.mFilename, true);
310             downloadedFileStream.getFD().sync();
311         } catch (FileNotFoundException ex) {
312             Log.w(Constants.TAG, "file " + state.mFilename + " not found: " + ex);
313         } catch (SyncFailedException ex) {
314             Log.w(Constants.TAG, "file " + state.mFilename + " sync failed: " + ex);
315         } catch (IOException ex) {
316             Log.w(Constants.TAG, "IOException trying to sync " + state.mFilename + ": " + ex);
317         } catch (RuntimeException ex) {
318             Log.w(Constants.TAG, "exception while syncing file: ", ex);
319         } finally {
320             if(downloadedFileStream != null) {
321                 try {
322                     downloadedFileStream.close();
323                 } catch (IOException ex) {
324                     Log.w(Constants.TAG, "IOException while closing synced file: ", ex);
325                 } catch (RuntimeException ex) {
326                     Log.w(Constants.TAG, "exception while closing file: ", ex);
327                 }
328             }
329         }
330     }
331
332     /**
333      * @return true if the current download is a DRM file
334      */
335     private boolean isDrmFile(State state) {
336         return DrmRawContent.DRM_MIMETYPE_MESSAGE_STRING.equalsIgnoreCase(state.mMimeType);
337     }
338
339     /**
340      * Transfer the downloaded destination file to the DRM store.
341      */
342     private void transferToDrm(State state) throws StopRequestException {
343         File file = new File(state.mFilename);
344         Intent item = DrmStore.addDrmFile(mContext.getContentResolver(), file, null);
345         file.delete();
346
347         if (item == null) {
348             throw new StopRequestException(Downloads.Impl.STATUS_UNKNOWN_ERROR,
349                     "unable to add file to DrmProvider");
350         } else {
351             state.mFilename = item.getDataString();
352             state.mMimeType = item.getType();
353         }
354     }
355
356     /**
357      * Close the destination output stream.
358      */
359     private void closeDestination(State state) {
360         try {
361             // close the file
362             if (state.mStream != null) {
363                 state.mStream.close();
364                 state.mStream = null;
365             }
366         } catch (IOException ex) {
367             if (Constants.LOGV) {
368                 Log.v(Constants.TAG, "exception when closing the file after download : " + ex);
369             }
370             // nothing can really be done if the file can't be closed
371         }
372     }
373
374     /**
375      * Check if the download has been paused or canceled, stopping the request appropriately if it
376      * has been.
377      */
378     private void checkPausedOrCanceled(State state) throws StopRequestException {
379         synchronized (mInfo) {
380             if (mInfo.mControl == Downloads.Impl.CONTROL_PAUSED) {
381                 throw new StopRequestException(Downloads.Impl.STATUS_PAUSED_BY_APP,
382                         "download paused by owner");
383             }
384         }
385         if (mInfo.mStatus == Downloads.Impl.STATUS_CANCELED) {
386             throw new StopRequestException(Downloads.Impl.STATUS_CANCELED, "download canceled");
387         }
388     }
389
390     /**
391      * Report download progress through the database if necessary.
392      */
393     private void reportProgress(State state, InnerState innerState) {
394         long now = mSystemFacade.currentTimeMillis();
395         if (innerState.mBytesSoFar - innerState.mBytesNotified
396                         > Constants.MIN_PROGRESS_STEP
397                 && now - innerState.mTimeLastNotification
398                         > Constants.MIN_PROGRESS_TIME) {
399             ContentValues values = new ContentValues();
400             values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, innerState.mBytesSoFar);
401             mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
402             innerState.mBytesNotified = innerState.mBytesSoFar;
403             innerState.mTimeLastNotification = now;
404         }
405     }
406
407     /**
408      * Write a data buffer to the destination file.
409      * @param data buffer containing the data to write
410      * @param bytesRead how many bytes to write from the buffer
411      */
412     private void writeDataToDestination(State state, byte[] data, int bytesRead)
413             throws StopRequestException {
414         for (;;) {
415             try {
416                 if (state.mStream == null) {
417                     state.mStream = new FileOutputStream(state.mFilename, true);
418                 }
419                 mStorageManager.verifySpaceBeforeWritingToFile(mInfo.mDestination, null, bytesRead);
420                 state.mStream.write(data, 0, bytesRead);
421                 if (mInfo.mDestination == Downloads.Impl.DESTINATION_EXTERNAL
422                             && !isDrmFile(state)) {
423                     closeDestination(state);
424                 }
425                 return;
426             } catch (IOException ex) {
427                 mStorageManager.verifySpace(mInfo.mDestination, null, bytesRead);
428             }
429         }
430     }
431
432     /**
433      * Called when we've reached the end of the HTTP response stream, to update the database and
434      * check for consistency.
435      */
436     private void handleEndOfStream(State state, InnerState innerState) throws StopRequestException {
437         ContentValues values = new ContentValues();
438         values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, innerState.mBytesSoFar);
439         if (innerState.mHeaderContentLength == null) {
440             values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, innerState.mBytesSoFar);
441         }
442         mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
443
444         boolean lengthMismatched = (innerState.mHeaderContentLength != null)
445                 && (innerState.mBytesSoFar != Integer.parseInt(innerState.mHeaderContentLength));
446         if (lengthMismatched) {
447             if (cannotResume(innerState)) {
448                 throw new StopRequestException(Downloads.Impl.STATUS_CANNOT_RESUME,
449                         "mismatched content length");
450             } else {
451                 throw new StopRequestException(getFinalStatusForHttpError(state),
452                         "closed socket before end of file");
453             }
454         }
455     }
456
457     private boolean cannotResume(InnerState innerState) {
458         return innerState.mBytesSoFar > 0 && !mInfo.mNoIntegrity && innerState.mHeaderETag == null;
459     }
460
461     /**
462      * Read some data from the HTTP response stream, handling I/O errors.
463      * @param data buffer to use to read data
464      * @param entityStream stream for reading the HTTP response entity
465      * @return the number of bytes actually read or -1 if the end of the stream has been reached
466      */
467     private int readFromResponse(State state, InnerState innerState, byte[] data,
468                                  InputStream entityStream) throws StopRequestException {
469         try {
470             return entityStream.read(data);
471         } catch (IOException ex) {
472             logNetworkState();
473             ContentValues values = new ContentValues();
474             values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, innerState.mBytesSoFar);
475             mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
476             if (cannotResume(innerState)) {
477                 String message = "while reading response: " + ex.toString()
478                 + ", can't resume interrupted download with no ETag";
479                 throw new StopRequestException(Downloads.Impl.STATUS_CANNOT_RESUME,
480                         message, ex);
481             } else {
482                 throw new StopRequestException(getFinalStatusForHttpError(state),
483                         "while reading response: " + ex.toString(), ex);
484             }
485         }
486     }
487
488     /**
489      * Open a stream for the HTTP response entity, handling I/O errors.
490      * @return an InputStream to read the response entity
491      */
492     private InputStream openResponseEntity(State state, HttpResponse response)
493             throws StopRequestException {
494         try {
495             return response.getEntity().getContent();
496         } catch (IOException ex) {
497             logNetworkState();
498             throw new StopRequestException(getFinalStatusForHttpError(state),
499                     "while getting entity: " + ex.toString(), ex);
500         }
501     }
502
503     private void logNetworkState() {
504         if (Constants.LOGX) {
505             Log.i(Constants.TAG,
506                     "Net " + (Helpers.isNetworkAvailable(mSystemFacade) ? "Up" : "Down"));
507         }
508     }
509
510     /**
511      * Read HTTP response headers and take appropriate action, including setting up the destination
512      * file and updating the database.
513      */
514     private void processResponseHeaders(State state, InnerState innerState, HttpResponse response)
515             throws StopRequestException {
516         if (innerState.mContinuingDownload) {
517             // ignore response headers on resume requests
518             return;
519         }
520
521         readResponseHeaders(state, innerState, response);
522
523         state.mFilename = Helpers.generateSaveFile(
524                 mContext,
525                 mInfo.mUri,
526                 mInfo.mHint,
527                 innerState.mHeaderContentDisposition,
528                 innerState.mHeaderContentLocation,
529                 state.mMimeType,
530                 mInfo.mDestination,
531                 (innerState.mHeaderContentLength != null) ?
532                         Long.parseLong(innerState.mHeaderContentLength) : 0,
533                 mInfo.mIsPublicApi, mStorageManager);
534         try {
535             state.mStream = new FileOutputStream(state.mFilename);
536         } catch (FileNotFoundException exc) {
537             throw new StopRequestException(Downloads.Impl.STATUS_FILE_ERROR,
538                     "while opening destination file: " + exc.toString(), exc);
539         }
540         if (Constants.LOGV) {
541             Log.v(Constants.TAG, "writing " + mInfo.mUri + " to " + state.mFilename);
542         }
543
544         updateDatabaseFromHeaders(state, innerState);
545         // check connectivity again now that we know the total size
546         checkConnectivity(state);
547     }
548
549     /**
550      * Update necessary database fields based on values of HTTP response headers that have been
551      * read.
552      */
553     private void updateDatabaseFromHeaders(State state, InnerState innerState) {
554         ContentValues values = new ContentValues();
555         values.put(Downloads.Impl._DATA, state.mFilename);
556         if (innerState.mHeaderETag != null) {
557             values.put(Constants.ETAG, innerState.mHeaderETag);
558         }
559         if (state.mMimeType != null) {
560             values.put(Downloads.Impl.COLUMN_MIME_TYPE, state.mMimeType);
561         }
562         values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, mInfo.mTotalBytes);
563         mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
564     }
565
566     /**
567      * Read headers from the HTTP response and store them into local state.
568      */
569     private void readResponseHeaders(State state, InnerState innerState, HttpResponse response)
570             throws StopRequestException {
571         Header header = response.getFirstHeader("Content-Disposition");
572         if (header != null) {
573             innerState.mHeaderContentDisposition = header.getValue();
574         }
575         header = response.getFirstHeader("Content-Location");
576         if (header != null) {
577             innerState.mHeaderContentLocation = header.getValue();
578         }
579         if (state.mMimeType == null) {
580             header = response.getFirstHeader("Content-Type");
581             if (header != null) {
582                 state.mMimeType = sanitizeMimeType(header.getValue());
583             }
584         }
585         header = response.getFirstHeader("ETag");
586         if (header != null) {
587             innerState.mHeaderETag = header.getValue();
588         }
589         String headerTransferEncoding = null;
590         header = response.getFirstHeader("Transfer-Encoding");
591         if (header != null) {
592             headerTransferEncoding = header.getValue();
593         }
594         if (headerTransferEncoding == null) {
595             header = response.getFirstHeader("Content-Length");
596             if (header != null) {
597                 innerState.mHeaderContentLength = header.getValue();
598                 mInfo.mTotalBytes = Long.parseLong(innerState.mHeaderContentLength);
599             }
600         } else {
601             // Ignore content-length with transfer-encoding - 2616 4.4 3
602             if (Constants.LOGVV) {
603                 Log.v(Constants.TAG,
604                         "ignoring content-length because of xfer-encoding");
605             }
606         }
607         if (Constants.LOGVV) {
608             Log.v(Constants.TAG, "Content-Disposition: " +
609                     innerState.mHeaderContentDisposition);
610             Log.v(Constants.TAG, "Content-Length: " + innerState.mHeaderContentLength);
611             Log.v(Constants.TAG, "Content-Location: " + innerState.mHeaderContentLocation);
612             Log.v(Constants.TAG, "Content-Type: " + state.mMimeType);
613             Log.v(Constants.TAG, "ETag: " + innerState.mHeaderETag);
614             Log.v(Constants.TAG, "Transfer-Encoding: " + headerTransferEncoding);
615         }
616
617         boolean noSizeInfo = innerState.mHeaderContentLength == null
618                 && (headerTransferEncoding == null
619                     || !headerTransferEncoding.equalsIgnoreCase("chunked"));
620         if (!mInfo.mNoIntegrity && noSizeInfo) {
621             throw new StopRequestException(Downloads.Impl.STATUS_HTTP_DATA_ERROR,
622                     "can't know size of download, giving up");
623         }
624     }
625
626     /**
627      * Check the HTTP response status and handle anything unusual (e.g. not 200/206).
628      */
629     private void handleExceptionalStatus(State state, InnerState innerState, HttpResponse response)
630             throws StopRequestException, RetryDownload {
631         int statusCode = response.getStatusLine().getStatusCode();
632         if (statusCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) {
633             handleServiceUnavailable(state, response);
634         }
635         if (statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307) {
636             handleRedirect(state, response, statusCode);
637         }
638
639         if (Constants.LOGV) {
640             Log.i(Constants.TAG, "recevd_status = " + statusCode +
641                     ", mContinuingDownload = " + innerState.mContinuingDownload);
642         }
643         int expectedStatus = innerState.mContinuingDownload ? 206 : Downloads.Impl.STATUS_SUCCESS;
644         if (statusCode != expectedStatus) {
645             handleOtherStatus(state, innerState, statusCode);
646         }
647     }
648
649     /**
650      * Handle a status that we don't know how to deal with properly.
651      */
652     private void handleOtherStatus(State state, InnerState innerState, int statusCode)
653             throws StopRequestException {
654         int finalStatus;
655         if (Downloads.Impl.isStatusError(statusCode)) {
656             finalStatus = statusCode;
657         } else if (statusCode >= 300 && statusCode < 400) {
658             finalStatus = Downloads.Impl.STATUS_UNHANDLED_REDIRECT;
659         } else if (innerState.mContinuingDownload && statusCode == Downloads.Impl.STATUS_SUCCESS) {
660             finalStatus = Downloads.Impl.STATUS_CANNOT_RESUME;
661         } else {
662             finalStatus = Downloads.Impl.STATUS_UNHANDLED_HTTP_CODE;
663         }
664         throw new StopRequestException(finalStatus, "http error " +
665                 statusCode + ", mContinuingDownload: " + innerState.mContinuingDownload);
666     }
667
668     /**
669      * Handle a 3xx redirect status.
670      */
671     private void handleRedirect(State state, HttpResponse response, int statusCode)
672             throws StopRequestException, RetryDownload {
673         if (Constants.LOGVV) {
674             Log.v(Constants.TAG, "got HTTP redirect " + statusCode);
675         }
676         if (state.mRedirectCount >= Constants.MAX_REDIRECTS) {
677             throw new StopRequestException(Downloads.Impl.STATUS_TOO_MANY_REDIRECTS,
678                     "too many redirects");
679         }
680         Header header = response.getFirstHeader("Location");
681         if (header == null) {
682             return;
683         }
684         if (Constants.LOGVV) {
685             Log.v(Constants.TAG, "Location :" + header.getValue());
686         }
687
688         String newUri;
689         try {
690             newUri = new URI(mInfo.mUri).resolve(new URI(header.getValue())).toString();
691         } catch(URISyntaxException ex) {
692             if (Constants.LOGV) {
693                 Log.d(Constants.TAG, "Couldn't resolve redirect URI " + header.getValue()
694                         + " for " + mInfo.mUri);
695             }
696             throw new StopRequestException(Downloads.Impl.STATUS_HTTP_DATA_ERROR,
697                     "Couldn't resolve redirect URI");
698         }
699         ++state.mRedirectCount;
700         state.mRequestUri = newUri;
701         if (statusCode == 301 || statusCode == 303) {
702             // use the new URI for all future requests (should a retry/resume be necessary)
703             state.mNewUri = newUri;
704         }
705         throw new RetryDownload();
706     }
707
708     /**
709      * Handle a 503 Service Unavailable status by processing the Retry-After header.
710      */
711     private void handleServiceUnavailable(State state, HttpResponse response)
712             throws StopRequestException {
713         if (Constants.LOGVV) {
714             Log.v(Constants.TAG, "got HTTP response code 503");
715         }
716         state.mCountRetry = true;
717         Header header = response.getFirstHeader("Retry-After");
718         if (header != null) {
719            try {
720                if (Constants.LOGVV) {
721                    Log.v(Constants.TAG, "Retry-After :" + header.getValue());
722                }
723                state.mRetryAfter = Integer.parseInt(header.getValue());
724                if (state.mRetryAfter < 0) {
725                    state.mRetryAfter = 0;
726                } else {
727                    if (state.mRetryAfter < Constants.MIN_RETRY_AFTER) {
728                        state.mRetryAfter = Constants.MIN_RETRY_AFTER;
729                    } else if (state.mRetryAfter > Constants.MAX_RETRY_AFTER) {
730                        state.mRetryAfter = Constants.MAX_RETRY_AFTER;
731                    }
732                    state.mRetryAfter += Helpers.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1);
733                    state.mRetryAfter *= 1000;
734                }
735            } catch (NumberFormatException ex) {
736                // ignored - retryAfter stays 0 in this case.
737            }
738         }
739         throw new StopRequestException(Downloads.Impl.STATUS_WAITING_TO_RETRY,
740                 "got 503 Service Unavailable, will retry later");
741     }
742
743     /**
744      * Send the request to the server, handling any I/O exceptions.
745      */
746     private HttpResponse sendRequest(State state, AndroidHttpClient client, HttpGet request)
747             throws StopRequestException {
748         try {
749             return client.execute(request);
750         } catch (IllegalArgumentException ex) {
751             throw new StopRequestException(Downloads.Impl.STATUS_HTTP_DATA_ERROR,
752                     "while trying to execute request: " + ex.toString(), ex);
753         } catch (IOException ex) {
754             logNetworkState();
755             throw new StopRequestException(getFinalStatusForHttpError(state),
756                     "while trying to execute request: " + ex.toString(), ex);
757         }
758     }
759
760     private int getFinalStatusForHttpError(State state) {
761         if (!Helpers.isNetworkAvailable(mSystemFacade)) {
762             return Downloads.Impl.STATUS_WAITING_FOR_NETWORK;
763         } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
764             state.mCountRetry = true;
765             return Downloads.Impl.STATUS_WAITING_TO_RETRY;
766         } else {
767             Log.w(Constants.TAG, "reached max retries for " + mInfo.mId);
768             return Downloads.Impl.STATUS_HTTP_DATA_ERROR;
769         }
770     }
771
772     /**
773      * Prepare the destination file to receive data.  If the file already exists, we'll set up
774      * appropriately for resumption.
775      */
776     private void setupDestinationFile(State state, InnerState innerState)
777             throws StopRequestException {
778         if (!TextUtils.isEmpty(state.mFilename)) { // only true if we've already run a thread for this download
779             if (Constants.LOGV) {
780                 Log.i(Constants.TAG, "have run thread before for id: " + mInfo.mId +
781                         ", and state.mFilename: " + state.mFilename);
782             }
783             if (!Helpers.isFilenameValid(state.mFilename,
784                     mStorageManager.getDownloadDataDirectory())) {
785                 // this should never happen
786                 throw new StopRequestException(Downloads.Impl.STATUS_FILE_ERROR,
787                         "found invalid internal destination filename");
788             }
789             // We're resuming a download that got interrupted
790             File f = new File(state.mFilename);
791             if (f.exists()) {
792                 if (Constants.LOGV) {
793                     Log.i(Constants.TAG, "resuming download for id: " + mInfo.mId +
794                             ", and state.mFilename: " + state.mFilename);
795                 }
796                 long fileLength = f.length();
797                 if (fileLength == 0) {
798                     // The download hadn't actually started, we can restart from scratch
799                     f.delete();
800                     state.mFilename = null;
801                     if (Constants.LOGV) {
802                         Log.i(Constants.TAG, "resuming download for id: " + mInfo.mId +
803                                 ", BUT starting from scratch again: ");
804                     }
805                 } else if (mInfo.mETag == null && !mInfo.mNoIntegrity) {
806                     // This should've been caught upon failure
807                     f.delete();
808                     throw new StopRequestException(Downloads.Impl.STATUS_CANNOT_RESUME,
809                             "Trying to resume a download that can't be resumed");
810                 } else {
811                     // All right, we'll be able to resume this download
812                     if (Constants.LOGV) {
813                         Log.i(Constants.TAG, "resuming download for id: " + mInfo.mId +
814                                 ", and starting with file of length: " + fileLength);
815                     }
816                     try {
817                         state.mStream = new FileOutputStream(state.mFilename, true);
818                     } catch (FileNotFoundException exc) {
819                         throw new StopRequestException(Downloads.Impl.STATUS_FILE_ERROR,
820                                 "while opening destination for resuming: " + exc.toString(), exc);
821                     }
822                     innerState.mBytesSoFar = (int) fileLength;
823                     if (mInfo.mTotalBytes != -1) {
824                         innerState.mHeaderContentLength = Long.toString(mInfo.mTotalBytes);
825                     }
826                     innerState.mHeaderETag = mInfo.mETag;
827                     innerState.mContinuingDownload = true;
828                     if (Constants.LOGV) {
829                         Log.i(Constants.TAG, "resuming download for id: " + mInfo.mId +
830                                 ", and setting mContinuingDownload to true: ");
831                     }
832                 }
833             }
834         }
835
836         if (state.mStream != null && mInfo.mDestination == Downloads.Impl.DESTINATION_EXTERNAL
837                 && !isDrmFile(state)) {
838             closeDestination(state);
839         }
840     }
841
842     /**
843      * Add custom headers for this download to the HTTP request.
844      */
845     private void addRequestHeaders(InnerState innerState, HttpGet request) {
846         for (Pair<String, String> header : mInfo.getHeaders()) {
847             request.addHeader(header.first, header.second);
848         }
849
850         if (innerState.mContinuingDownload) {
851             if (innerState.mHeaderETag != null) {
852                 request.addHeader("If-Match", innerState.mHeaderETag);
853             }
854             request.addHeader("Range", "bytes=" + innerState.mBytesSoFar + "-");
855         }
856     }
857
858     /**
859      * Stores information about the completed download, and notifies the initiating application.
860      */
861     private void notifyDownloadCompleted(
862             int status, boolean countRetry, int retryAfter, int redirectCount, boolean gotData,
863             String filename, String uri, String mimeType, String errorMsg) {
864         notifyThroughDatabase(
865                 status, countRetry, retryAfter, redirectCount, gotData, filename, uri, mimeType,
866                 errorMsg);
867         if (Downloads.Impl.isStatusCompleted(status)) {
868             mInfo.sendIntentIfRequested();
869         }
870     }
871
872     private void notifyThroughDatabase(
873             int status, boolean countRetry, int retryAfter, int redirectCount, boolean gotData,
874             String filename, String uri, String mimeType, String errorMsg) {
875         ContentValues values = new ContentValues();
876         values.put(Downloads.Impl.COLUMN_STATUS, status);
877         values.put(Downloads.Impl._DATA, filename);
878         if (uri != null) {
879             values.put(Downloads.Impl.COLUMN_URI, uri);
880         }
881         values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimeType);
882         values.put(Downloads.Impl.COLUMN_LAST_MODIFICATION, mSystemFacade.currentTimeMillis());
883         values.put(Constants.RETRY_AFTER_X_REDIRECT_COUNT, retryAfter + (redirectCount << 28));
884         if (!countRetry) {
885             values.put(Constants.FAILED_CONNECTIONS, 0);
886         } else if (gotData) {
887             values.put(Constants.FAILED_CONNECTIONS, 1);
888         } else {
889             values.put(Constants.FAILED_CONNECTIONS, mInfo.mNumFailed + 1);
890         }
891         // STOPSHIP begin delete the following lines
892         if (!TextUtils.isEmpty(errorMsg)) {
893             values.put(Downloads.Impl.COLUMN_ERROR_MSG, errorMsg);
894         }
895         // STOPSHIP end
896         mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
897     }
898
899     /**
900      * Clean up a mimeType string so it can be used to dispatch an intent to
901      * view a downloaded asset.
902      * @param mimeType either null or one or more mime types (semi colon separated).
903      * @return null if mimeType was null. Otherwise a string which represents a
904      * single mimetype in lowercase and with surrounding whitespaces trimmed.
905      */
906     private static String sanitizeMimeType(String mimeType) {
907         try {
908             mimeType = mimeType.trim().toLowerCase(Locale.ENGLISH);
909
910             final int semicolonIndex = mimeType.indexOf(';');
911             if (semicolonIndex != -1) {
912                 mimeType = mimeType.substring(0, semicolonIndex);
913             }
914             return mimeType;
915         } catch (NullPointerException npe) {
916             return null;
917         }
918     }
919 }