-<tr><td > DLMGR_A_6 </td><td > Downloads MUST be reliable even on unreliable network connections, within the capabilities of the underlying protocol and of the server. </td><td > &nbsp; </td><td > <b>YES</b> done in 1.0 </td></tr>

-<tr><td > DLMGR_A_7 </td><td > User-accessible files MUST be stored on the external storage card, and only files that are explicitly supported by an installed application must be downloaded. </td><td > &nbsp; </td><td > <b>YES</b> done in 1.0 </td></tr>

-<tr><td > <code>com.android.providers.downloads.DownloadInfo</code> </td><td > Once we only store information in RAM about downloads that are explicitly active, can be merged with <code>DownloadThread</code>. </td></tr>

-<tr><td > <code>com.android.providers.downloads.DownloadNotification</code> </td><td > Looks like it could be merged with <code>DownloadProvider</code> or <code>DownloadService</code>. </td></tr>

-<tr><td > <code>com.android.providers.downloads.DownloadProvider.DatabaseHelper</code> </td><td > Can probably be eliminated by re-implementing by hand the logic of <code>SQLiteOpenHelper</code>. </td></tr>

-<tr><td > <code>com.android.providers.downloads.DownloadService.DownloadManagerContentObserver</code> </td><td > Extends <code>ContentObserver</code>, can be eliminated if the download manager can be re-architected to not depend on <code>ContentObserver</code> any more. </td></tr>

-<tr><td > <code>com.android.providers.downloads.DownloadService.MediaScannerConnection</code> </td><td > Can probably be merged into another class. </td></tr>

-<tr><td > <code>com.android.providers.downloads.DownloadService.UpdateThread</code> </td><td > Can probably be made to implement <code>Runnable</code> instead and merged into another class, can be eliminated if the download manager can be re-architected to not depend on <code>ContentObserver</code> any more. </td></tr>

-<tr><td > <code>com.android.providers.downloads.DownloadThread</code> </td><td > Can probably be made to implement <code>Runnable</code> instead. Unclear whether this can be eliminated as we will probably need one object that represents an ongoing download (unless the entire state can be stored on the stack with primitive types, which is unlikely). </td></tr>

-<tr><td > <code>com.android.providers.downloads.Helpers</code> </td><td > Can't be instantiated, can be merged into another class. </td></tr>

-<tr><td > <code>com.android.providers.downloads.Helpers.Lexer</code> </td><td > Keeps state about an ongoing lex, can probably be merged into another class by making the lexer <code>synchronized</code>, since the operation is short-lived. </td></tr>

-Security in the download provider is primarily enforced with two separate mechanisms:

-<p />

-<ul>

-<li> Column restrictions, such that only a small number of the download provider's columns can be read or queried by applications.

-</li>

-<li> UID restrictions, such that only the application that initiated a download can access information about that download.

-</li>

-</ul>

-<p />

-The first mechanism is expected to be fairly robust (the implementation is quite simple, based on projection maps, which are highly

-structured), but the second one relies on arbitrary strings (URIs and SQL fragments) passed by applications and is therefore at a

-higher risk of being compromised. Therefore, sensitive information stored in unrestricted columns (for which the first mechanism

-doesn't apply) is at a greater risk than other information.

-<p />

-Here's the list of columns that can currently be read/queried, with comments:

-<p />

-<table border="1" cellspacing="1" cellpadding="2">

-<tr><th > Column </th><th > Notes </th></tr>

-<tr><td > <code>_ID</code> </td><td > Needs to be visible so that the app can uniquely identify downloads. No security concern: those numbers are sequential and aren't hard to guess. </td></tr>

-<tr><td > <code>_DATA</code> </td><td > Probably should not be visible to applications. <b>WARNING</b> Security concern: This holds filenames, including those of private files. While file permissions are supposed to kick in and protect the files, hiding private filenames deeper in would probably be a reasonable idea. </td></tr>

-<tr><td > <code>MIMETYPE</code> </td><td > Needs to be visible so that app can display the icon matching the mime type. Intended to be visible by 3rd-party download UIs. <b>TODO</b> Security TBD before we implement support for 3rd-party UIs. </td></tr>

-<tr><td > <code>VISIBILITY</code> </td><td > Needs to be visible in case an app has both visible and invisible downloads. No obvious security concern. </td></tr>

-<tr><td > <code>LAST_MODIFICATION</code> </td><td > Needs to be visible, e.g. so that apps can sort downloads by date of last activity, or discard old downloads. No obvious security concern. </td></tr>

-The <code>URI</code> column is visible to the initiating application, which is a mild security risk. It should be hidden, but the OTA update mechanism relies on it to check duplicate downloads and to display the download that's currently ongoing in the settings app. If another string column was exposed to the initiating applications, the OTA update mechanism could use that one, and <code>URI</code> could then be hidden. For Cupcake, without changing the database schema, the <code>ENTITY</code> column could be re-used as it's currently unused.

-<p />

-<h3><a name="Handling_redirects"> </a> Handling redirects </h3>

-<p />

-There are two important aspects to handle redirects:

-<p />

-<ul>

-<li> Storing the intermediate URIs in the provider.

-</li>

-<li> Protecting against redirect loops.

-</li>

-</ul>

-<p />

-If the <code>URI</code> column gets hidden, it could be used to store the intermediate URIs. After 1.0 the only available integer columns were <code>METHOD</code> and <code>CONTROL</code>. <code>CONTROL</code> was re-exposed to applications and can't be used. <code>METHOD</code> is slated to be re-used for 503 retry-after delays. It could be split into two halves, one for retry-after and one for the redirect count. It would make more sense to count the redirect loop with <code>FAILED_CONNECTIONS</code>, but since there's already quite some code using it it'd take a bit more effort. Ideally handling of redirects would be delayed until a future release, with a cleanup of the database schema (going along with the cleanup of the handling of filenames).

-<p />

-Because of the pattern used to read/write <code>DownloadInfo</code> and <code>DownloadProvider</code>, it's impractical to store multiple small integers into a large one. Therefore, since there are no integer columns left in the database, redirects will have to wait beyond Cupcake.

-In order to allow a UI that can "see" all the relevant downloads, there'll need to be a separate URI (or set of URIs) in the content provider: trying to use the exact same URIs for regular download control and for UI purposes (distinguishing them based on the permissions of the caller) will break down if a same app (or actually a same UID) tries to do both. It'll also break down if the system process tries to do regular download activities, since it has all permissions.

-<p />

-Beyond that, there's little technical challenge: there are already mechanisms in place to restrict the list of columns that can be inserted, queried and updated (inserting of course makes no sense through the UI channel), they just need to be duplicated for the case of the UI. The download provider also knows how to check the permissions of its caller, there isn't anything new here.

-Right now <code>OTHER_UID</code> is used by checkin/update to allow the settings app to display the name of an ongoing OTA update, and by Market to allow the system to install the new apks. It is however a dangerous feature, at least because it touches a part of the code that is critical to the download manager security (separation of applications).

-<p />

-Getting rid of <code>OTHER_UID</code> would be beneficial for the download manager, but the existing functionality has to be worked around. At this point, the idea that I consider the most likely would be to have checkin and market implement =ContentProvider= wrappers around their downloads, and expose those content providers to whichever app they want, with whichever security mechanism they wish to have.

-<p />

-<h3><a name="Only_using_SDK_APIs_"> </a> Only using SDK APIs. </h3>

-<p />

-It'd be good if the download manager could be built against the SDK as much as possible.

-<p />

-Here's the list of APIs as of Nov 5 2008 that aren't in the current public API but that are used by the download manager:

-<p />

-<pre>

-com.google.android.collect.Lists

-android.drm.mobile1.DrmRawContent

-android.media.IMediaScannerService

-android.net.http.AndroidHttpClient

-android.os.FileUtils

-android.provider.DrmStore

-</pre>

-<p />

-<!-- ---++ Sales Validation-->

-<!--_>small<Whether there's a market for the product/feature.>/small<_-->

-<p />

-<!--The 1.0 "must" features are all mandatory in all versions of Android.-->

-<p />

-<!-- ---++ Business Case-->

-<!--_>small<Whether the high-level evaluations (technical and sales) done so far justify further investment.>/small<_-->

-<p />

-<!--There are enough common requirements between the various applications that need to perform reliable background downloads that implementing a centralized download manager is more cost-effective than having each application implement their own subset of the overall feature set.-->

-<tr><td > 2005 </td><td > Cupcake <b>YES</b> </td><td > Cupcake P2 <b>YES</b> </td><td > Resume after socket closed </td><td > The download manager resumes incomplete downloads after the socket gets cleanly closed </td><td > This is necessary in order to reliably download through GFEs, though it pushes us further away from being able to download from servers that don't implement pipelining. </td></tr>

-<tr><td > 4001 </td><td > 1.0 <b>NO</b> </td><td > &nbsp; </td><td > Download Manager UI </td><td > The download manager provides a UI that lets user get information about current downloads and control them. </td><td > Didn't get spec on time to be able to even consider it. </td></tr>

-<!--_>small<Details of all the interfaces exposed by all the modules that implement the product/feature.>/small<_-->

-<p />

-<b>WARNING</b> Since none of those APIs are public, they are all subject to change. If you're working in the Android source tree, do <em>NOT</em> use the explicit values, <em>ONLY</em> use the symbolic constants, unless you <em>REALLY</em> know what you're doing and are willing to deal with the consequences; you've been warned.

-<p />

-The various constants that are meant to be used by applications are all defined in the <code>android.provider.Downloads</code> class. Whenever possible, the constants should be used instead of the explicit values.

-<tr><td > <code>Downloads.PERMISSION_ACCESS</code> </td><td > <code>"android.permission.ACCESS_DOWNLOAD_MANAGER"</code> </td><td > Signature or System </td><td > Applications that want to access the Download Manager MUST have this permission. </td></tr>

-<tr><td > <code>Downloads.PERMISSION_ACCESS_ADVANCED</code> </td><td > <code>"android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED"</code> </td><td > Signature or System </td><td > This permission protects some legacy APIs that new applications SHOULD NOT use. </td></tr>

-<tr><td > <code>Downloads.PERMISSION_CACHE</code> </td><td > <code>"android.permission.ACCESS_CACHE_FILESYSTEM"</code> </td><td > Signature </td><td > This permission allows an app to access the /cache filesystem, and is only needed by the Update code. Other applications SHOULD NOT use this permission </td></tr>

-<tr><td > <code>Downloads.PERMISSION_SEND_INTENTS</code> </td><td > <code>"android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS"</code> </td><td > Signature </td><td > The download manager holds this permission, and the receivers through which applications get intents of completed downloads SHOULD require this permission from the sender </td></tr>

-</table>

-<p />

-<h3><a name="Content_Provider"> </a> Content Provider </h3>

-<p />

-The primary interface that applications use to communicate with the download manager is exposed as a ContentProvider.

-<tr><td > <code>Downloads.CONTENT_URI</code> </td><td > <code>Uri.parse("content://downloads/download")</code> </td><td > The URI of the whole Content Provider, used to insert new rows, or to query all rows. </td></tr>

-<tr><td > <code>Downloads.DESTINATION_CACHE_PARTITION_PURGEABLE</code> </td><td > <code>2</code> </td><td > Saves the file to the internal cache partition. </td><td > The download can get deleted at any time by the download manager when it needs space. </td></tr>

-<tr><td > <code>Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED</code> </td><td > <code>0</code> </td><td > The download is visible in download UIs, and it shows up in the notification area during download and after completion. </td><td > Default value for external downloads. </td></tr>

-<tr><td > <code>Downloads.VISIBILITY_VISIBLE</code> </td><td > <code>1</code> </td><td > The download is visible in download UIs, and it shows up in the notification area during download but not after completion. </td><td > &nbsp; </td></tr>

-<tr><td > <code>Downloads.STATUS_NOT_ACCEPTABLE</code> </td><td > <code>406</code> </td><td > No handler to view the file (external downloads), or server response 406. </td><td > External downloads are meant to be user-visible, and are aborted if there's no application to handle the relevant MIME type. </td></tr>

-<tr><td > <code>Downloads.STATUS_LENGTH_REQUIRED</code> </td><td > <code>411</code> </td><td > The download manager can't know the length of the download. </td><td > Because of the unreliability of cell networks, the download manager only performs downloads when it can verify that it has received all the data for a download, except if the initiating app sets the <code>Downloads.NO_INTEGRITY</code> flag. </td></tr>

-<tr><td > <code>Downloads.STATUS_CANCELED</code> </td><td > <code>490</code> </td><td > The download was canceled by a cause outside the Download Manager. </td><td > Formerly known as <code>Downloads.STATUS_CANCELLED</code>. Might be impossible to observe in 1.0. </td></tr>

-<tr><td > <code>Downloads.STATUS_UNKNOWN_ERROR</code> </td><td > <code>491</code> </td><td > The download was aborted because of an unknown error. </td><td > Formerly known as <code>Downloads.STATUS_ERROR</code>. Typically the result of a runtime exception that is not explicitly handled. </td></tr>

-<tr><td > <code>Downloads.STATUS_FILE_ERROR</code> </td><td > <code>492</code> </td><td > The download was aborted because the data couldn't be saved. </td><td > Most commonly happens when the filesystem is full. </td></tr>

-<tr><td > <code>Downloads.STATUS_HTTP_DATA_ERROR</code> </td><td > <code>496</code> </td><td > The download was aborted because of an unrecoverable error trying to get data over the network. </td><td > Typically this happens when the download manager received several I/O Exceptions in a row while the network is available and without being able to download any data. </td></tr>

-The download manager sends an intent broadcast <code>Downloads.NOTIFICATION_CLICKED_ACTION</code> when the user clicks a download notification that doesn't match a download that can be opened (e.g. because the notification is for several downloads at a time, or because it's for an incomplete download, or because it's for a private download).

-<p />

-The download manager starts an activity with <code>Intent.ACTION_VIEW</code> when the user clicks a download notification that matches a download that can be opened.

-<li> The list of columns that can be updated by apps is limited: <code>APP_DATA</code>, <code>VISIBILITY</code>, <code>CONTROL</code>, <code>TITLE</code>, <code>DESCRIPTION</code>.

-</li>

-<li> Downloads to the SD card default to have notifications that are visible after completion, internal downloads default to notifications that are always hidden.

-</li>

-<li> The constant FILENAME was renamed Downloads._DATA.

-</li>

-<li> Downloads can be paused and resumed by writing to the CONTROL column. <code>Downloads.CONTROL_RUN</code> (Default) makes the download go, <code>Downloads.CONTROL_PAUSED</code> pauses it.

-</li>

-<li> New column APP_DATA that is untouched by the download manager, used to store app-specific info about the downloads.

-</li>

-<li> Minor differences unlikely to affect applications:

-<ul>

-<li> The notification class/package must now match the UID.

-</li>

-<li> The backdoor to see the entire provider (which was intended to implement UIs) is gone.

-</li>

-<li> Private column names were removed from the public API.

-</li>

-</ul>

-</li>

-</ul>

-<p />

-<h4><a name="Writing_code_that_works_on_both_"> </a> Writing code that works on both the 1.0 and Cupcake versions of the download manager. </h4>

-<p />

-If you're not 100% sure that you need to be reading this chapter, don't read it.

-<p />

-Basic rule: don't use features that only exist in one of the two implementations (POST, downloads to /data...).

-<p />

-Also, don't use columns in 1.0 that are protected or hidden in Cupcake.

-<p />

-Unfortunately, that's not always entirely possible.

-<p />

-Areas of concern:

-<ul>

-<li> Some columns were renamed. FILENAME became Downloads._DATA ("_data"), and ENTITY became APP_DATA ("entity").

-<ul>

-<li> The difference can be used to distinguish between 1.0 and Cupcake, though reflection.

-</li>

-<li> The difference prevents from using any of the symbolic constants directly in source code: if the same binary wants to run on both 1.0 and Cupcake, it will have to hard-code the values of those constants or use reflection to get to them.

-</li>

-</ul>

-</li>

-<li> URI column accessible in 1.0 but protected in Cupcake. Code that relies on being able to re-read its URI should be using APP_DATA in Cupcake, but that column doesn't exist as such in 1.0.

-<ul>

-<li> If the code detects that it's running on Cupcake, write URI to APP_DATA in addition to URI, and query and read from the appropriate column.

-</li>

-<li> Since the underlying column for APP_DATA exists in both 1.0 and Cupcake even though it has different names, it can actually be used in both cases (see note above about renamed columns).

-</li>

-</ul>

-</li>

-<li> Some of the error codes have been renumbered. STATUS_UNHANDLED_HTTP_CODE and STATUS_HTTP_DATA_ERROR were bumped up from 494 and 495 to 495 and 496.

-</li>

-<li> Backward compatibility is not guaranteed: the download manager APIs weren't meant to be backward compatible yet. As such it's impossible to guarantee that code that uses the Cupcake download manager will be binary-compatible with future versions.

-<ul>

-<li> I intend to eventually change the column name for APP_DATA to "app_data". Because of that, code should use reflection to get to that name instead of hard-coding "entity", so that it always gets the right value for the string.

-</li>

-<li> I intend to refine the handling of filenames and content URIs, exposing separate columns for situations where a download can be accessed both as a file and through a content URI (e.g. stuff that is recognized by the media scanner). Unfortunately at this point this feature isn't clear in my mind. I'd recommend using reflection to look for the Downloads._DATA column, and if it isn't there to look for the FILENAME column (which has the advantage of also dealing with the difference between 1.0 and Cupcake).

-</li>

-<li> I intend to renumber the error codes, especially those in the 4xx range, and especially those below 490 (which overlap with standard HTTP error codes but will probably be separated). Reflection would improve the probability to getting to them in the future. Unfortunately, the names of the constants are likely to change in the process, in order to disambiguate codes coming from HTTP from those generated locally. I might try to stick to the following pattern: where a constant is currently named STATUS_XXX, its locally-generated version in the future might be named STATUS_LOCAL_XXX while the current constant name might disappear. Using reflection to try to get to the possible new name instead of using the old name might improve the probability of compatibility in the future. That being said, it is critically important to properly handle the full ranges or error codes, especially the 4xx range, as "expected" errors, and it is far preferable to not try to distinguish between those codes at all: use the functions Downloads.isError and Downloads.isClientError to easily recognize those entire ranges. In order of probability, the 1xx range is the second most likely to be affected.

-The download manager is built primarily around a ContentProvider and a Service. The ContentProvider part is the front end, i.e. applications communicate with the download manager through the provider. The Service part is the back end, which contains the actual download logic, running as a background process.

-<p />

-As a first approach, the provider is essentially a canonical provider backed by a SQLite3 database. The biggest difference between the download provider and a "plain" provider is that the download provider aggressively validates its inputs, for security reasons.

-<p />

-The service is a background process that performs the actual downloads as requested by the applications. The service doesn't offer any bindable interface, the service object exists strictly so that the system knows how to prioritize the download manager's process against other processes when memory is tight.

-<p />

-Communication between the provider and the service is done through public Android APIs, so that the two components are deeply decoupled (they could in fact run in different processes). The download manager starts the service whenever a change is made that can start or restart a download. The service observes and queries the provider for changes, and updates the provider as the download progresses.

-<p />

-<p />

-There are a few secondary classes that provide auxiliary functions.

-<p />

-A Receiver listens to several broadcasts. Is receives some system broadcasts when the system boots (so that the download manager can resume downloads that were interrupted when the system was turned off) or when the connectivity changes (so that the download manager can restart downloads that were interrupted when connectivity was lost). It also receives intents when the user selects a download notification.

-<p />

-<p />

-Finally, some helper classes provide support functions.

-<p />

-Most significantly, DownloadThread is responsible for performing the actual downloads as part of the DownloadService's functionality, while UpdateThread is responsible for updating the DownloadInfo whenever the DownloadProvider data changes.

-<p />

-DownloadInfo and DownloadFileInfo hold pure data structures, with little or no actual logic.

-<p />

-Lexer takes care of validating the snippets of SQL data that are received from applications, to avoid cases of SQL injection.

-<p />

-<p />

-<p />

-<p />

-<p />

-<p />

-The service keeps a copy of the provider data in RAM, so that it can determine what changed in the provider when it receives a change notification through the ContentObserver. That data is kept in an array of DownloadInfo structures.

-<p />

-Each DownloadThread performs the operations for a single download (or, more precisely, for a single HTTP transaction). Each DownloadThread is backed by a DownloadInfo object. which is in fact on of the objects kept by the DownloadService. While a download is running, the DownloadService can influence the download by writing data into the relevant DownloadInfo object, and the DownloadThread checks that object at appropriate times during the download.

-<p />

-Because the DownloadService updates the DownloadInfo objects asynchronously from everything else (it uses a dedicated thread for that purpose), a lot of care has to be taken when upgrading the DownloadInfo object. In fact, only the DownloadService's updateThread function can update that object, and it should be considered read-only to every other bit of code. Even within the updateThread function, some care must be taken to ensure that the DownloadInfos don't get out of sync with the provider.

-<p />

-On the other hand, the DownloadService's updateThread function does upgrade the DownloadInfo when it spawns new DownloadThreads (and in a few more circumstances), and when it does that it must also update the DownloadProvider (or risk seeing its DownloadInfo data get overwritten).

-<p />

-Because of all that, all code outside of the DowloadService's updateThread must neither read from DownloadProvider nor write to the DownloadInfo objects under any circumstances. The DownloadService's updateFunction is responsible for copying data from the DownloadProvider to the DownloadInfo objects, and must ensure that the DownloadProvider remains in sync with the information it writes into the DownloadInfo objects.

-<li> <em>[DownloadProvider.java]</em> When upgrading the database, the numbering of ids should restart where it left off.

-</li>

-<li> <em>[DownloadProvider.java]</em> Handle errors when failing to start the service.

-</li>

-<li> <em>[DownloadProvider.java]</em> Explicitly populate all database columns that have documented default values, investigate whether that can be done at the SQL level.

-</li>

-<li> <em>[DownloadProvider.java]</em> It's possible that the last update time should be updated by the Sevice logic, not by the content provider.

-</li>

-<li> When relevant, combine logged messages on fewer lines.

-</li>

-<li> <em>[DownloadService.java]</em> Trim the database in the provider, not in the service. Notify application when trimming. Investigate why the row count seems off by one. Enforce on an ongoing basis.

-<li> Optimize database queries: use projections to reduce number of columns and get constant column numbers.

-</li>

-<li> Index last-mod date in DB, because of ordered searches. Investigate whether other columns need to be indexed (Hidden?)

-</li>

-<li> Deal with the fact that sqlite INTEGER matches java long (63-bit) .

-</li>

-<li> Use a single HTTP client for the entire download manager.

-</li>

-<li> Could use fewer alarms - currently setting new alarm each time database updated .

-</li>

-<li> Obsolete columns should be removed from the database .

-</li>

-<li> Assign relevant names to threads.

-</li>

-<li> Investigate and handle the different subclasses of IOException appropriately .

-</li>

-<li> There's potentially a race condition around read-modify-write cycles in the database, between the Service's updateFromProvider thread and the worker threads (and possibly more). Those should be synchronized appropriately, and the provider should be hardened to prevent asynchronous changes to sensitive data (or to synchronize when there's no other way, though I'd rather avoid that) .

-</li>

-<li> Temporary file leaks when downloads are deleted while the service isn't running .

-</li>

-<li> Increase priority of updaterThread while in the critical section (to avoid issues of priority inheritance with the main thread).

-</li>

-<li> Explicitly specify which interface to use for a given download (to get better sync with the connection manager).

-</li>

-<li> Cancel the requests on more kinds of errors instead of trusting the garbage collector.

-</li>

-<li> Issues with the fact that parseInt can throw exceptions on invalid server headers.