File: UpdateService.java

package info (click to toggle)
wine-gecko-2.24 2.24%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 740,092 kB
  • ctags: 688,789
  • sloc: cpp: 3,160,639; ansic: 1,619,153; python: 164,084; java: 128,022; asm: 114,527; xml: 69,863; sh: 55,281; makefile: 49,648; perl: 20,454; objc: 2,344; yacc: 2,066; pascal: 995; lex: 982; exp: 449; php: 244; lisp: 228; awk: 211; sed: 61; csh: 21; ada: 16; ruby: 3
file content (598 lines) | stat: -rw-r--r-- 23,202 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.gecko.updater;

import org.mozilla.gecko.AppConstants;
import org.mozilla.gecko.R;

import org.mozilla.apache.commons.codec.binary.Hex;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class UpdateService extends IntentService {
    private static final int BUFSIZE = 8192;
    private static final int NOTIFICATION_ID = 0x3e40ddbd;

    private static final String LOGTAG = "UpdateService";

    private static final int INTERVAL_LONG = 86400000; // in milliseconds
    private static final int INTERVAL_SHORT = 14400000; // again, in milliseconds
    private static final int INTERVAL_RETRY = 3600000;

    private static final String PREFS_NAME = "UpdateService";
    private static final String KEY_LAST_BUILDID = "UpdateService.lastBuildID";
    private static final String KEY_LAST_HASH_FUNCTION = "UpdateService.lastHashFunction";
    private static final String KEY_LAST_HASH_VALUE = "UpdateService.lastHashValue";
    private static final String KEY_LAST_FILE_NAME = "UpdateService.lastFileName";
    private static final String KEY_LAST_ATTEMPT_DATE = "UpdateService.lastAttemptDate";
    private static final String KEY_AUTODOWNLOAD_POLICY = "UpdateService.autoDownloadPolicy";

    private SharedPreferences mPrefs;

    private NotificationManager mNotificationManager;
    private ConnectivityManager mConnectivityManager;

    private boolean mDownloading;
    private boolean mApplyImmediately;

    public UpdateService() {
        super("updater");
    }

    @Override
    public void onCreate () {
        super.onCreate();
        
        mPrefs = getSharedPreferences(PREFS_NAME, 0);
        mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        mConnectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    @Override
    public synchronized int onStartCommand (Intent intent, int flags, int startId) {
        // If we are busy doing a download, the new Intent here would normally be queued for
        // execution once that is done. In this case, however, we want to flip the boolean
        // while that is running, so handle that now.
        if (mDownloading && UpdateServiceHelper.ACTION_APPLY_UPDATE.equals(intent.getAction())) {
            Log.i(LOGTAG, "will apply update when download finished");

            mApplyImmediately = true;
            showDownloadNotification();
        } else {
            super.onStartCommand(intent, flags, startId);
        }

        return Service.START_REDELIVER_INTENT;
    }

    @Override
    protected void onHandleIntent (Intent intent) {
        if (UpdateServiceHelper.ACTION_REGISTER_FOR_UPDATES.equals(intent.getAction())) {
            int policy = intent.getIntExtra(UpdateServiceHelper.EXTRA_AUTODOWNLOAD_NAME, -1);
            if (policy >= 0) {
                setAutoDownloadPolicy(policy);
            }

            registerForUpdates(false);
        } else if (UpdateServiceHelper.ACTION_CHECK_FOR_UPDATE.equals(intent.getAction())) {
            startUpdate(intent.getIntExtra(UpdateServiceHelper.EXTRA_UPDATE_FLAGS_NAME, 0));
        } else if (UpdateServiceHelper.ACTION_DOWNLOAD_UPDATE.equals(intent.getAction())) {
            // We always want to do the download here
            startUpdate(UpdateServiceHelper.FLAG_FORCE_DOWNLOAD);
        } else if (UpdateServiceHelper.ACTION_APPLY_UPDATE.equals(intent.getAction())) {
            applyUpdate(intent.getStringExtra(UpdateServiceHelper.EXTRA_PACKAGE_PATH_NAME));
        }
    }

    private static boolean hasFlag(int flags, int flag) {
        return (flags & flag) == flag;
    }

    private void sendCheckUpdateResult(UpdateServiceHelper.CheckUpdateResult result) {
        Intent resultIntent = new Intent(UpdateServiceHelper.ACTION_CHECK_UPDATE_RESULT);
        resultIntent.putExtra("result", result.toString());
        sendBroadcast(resultIntent);
    }

    private int getUpdateInterval(boolean isRetry) {
        int interval;
        if (isRetry) {
            interval = INTERVAL_RETRY;
        } else if (AppConstants.MOZ_UPDATE_CHANNEL.equals("nightly") ||
                   AppConstants.MOZ_UPDATE_CHANNEL.equals("aurora")) {
            interval = INTERVAL_SHORT;
        } else {
            interval = INTERVAL_LONG;
        }

        return interval;
    }

    private void registerForUpdates(boolean isRetry) {
        Calendar lastAttempt = getLastAttemptDate();
        Calendar now = new GregorianCalendar(TimeZone.getTimeZone("GMT"));

        int interval = getUpdateInterval(isRetry);

        if (lastAttempt == null || (now.getTimeInMillis() - lastAttempt.getTimeInMillis()) > interval) {
            // We've either never attempted an update, or we are passed the desired
            // time. Start an update now.
            Log.i(LOGTAG, "no update has ever been attempted, checking now");
            startUpdate(0);
            return;
        }

        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        if (manager == null)
            return;

        PendingIntent pending = PendingIntent.getService(this, 0, new Intent(UpdateServiceHelper.ACTION_CHECK_FOR_UPDATE, null, this, UpdateService.class), PendingIntent.FLAG_UPDATE_CURRENT);
        manager.cancel(pending);

        lastAttempt.setTimeInMillis(lastAttempt.getTimeInMillis() + interval);
        Log.i(LOGTAG, "next update will be at: " + lastAttempt.getTime());

        manager.set(AlarmManager.RTC_WAKEUP, lastAttempt.getTimeInMillis(), pending);
    }

    private void startUpdate(int flags) {
        setLastAttemptDate();

        NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
        if (netInfo == null || !netInfo.isConnected()) {
            Log.i(LOGTAG, "not connected to the network");
            registerForUpdates(true);
            sendCheckUpdateResult(UpdateServiceHelper.CheckUpdateResult.NOT_AVAILABLE);
            return;
        }

        registerForUpdates(false);

        UpdateInfo info = findUpdate(hasFlag(flags, UpdateServiceHelper.FLAG_REINSTALL));
        boolean haveUpdate = (info != null);

        if (!haveUpdate) {
            Log.i(LOGTAG, "no update available");
            sendCheckUpdateResult(UpdateServiceHelper.CheckUpdateResult.NOT_AVAILABLE);
            return;
        }

        Log.i(LOGTAG, "update available, buildID = " + info.buildID);
        
        int connectionType = netInfo.getType();
        int autoDownloadPolicy = getAutoDownloadPolicy();


        /**
         * We only start a download automatically if one of following criteria are met:
         *
         * - We have a FORCE_DOWNLOAD flag passed in
         * - The preference is set to 'always'
         * - The preference is set to 'wifi' and we are actually using wifi (or regular ethernet)
         */
        boolean shouldStartDownload = hasFlag(flags, UpdateServiceHelper.FLAG_FORCE_DOWNLOAD) ||
            autoDownloadPolicy == UpdateServiceHelper.AUTODOWNLOAD_ENABLED ||
            (autoDownloadPolicy == UpdateServiceHelper.AUTODOWNLOAD_WIFI &&
             (connectionType == ConnectivityManager.TYPE_WIFI || connectionType == ConnectivityManager.TYPE_ETHERNET));

        if (!shouldStartDownload) {
            Log.i(LOGTAG, "not initiating automatic update download due to policy " + autoDownloadPolicy);
            sendCheckUpdateResult(UpdateServiceHelper.CheckUpdateResult.AVAILABLE);

            // We aren't autodownloading here, so prompt to start the update
            Notification notification = new Notification(R.drawable.ic_status_logo, null, System.currentTimeMillis());

            Intent notificationIntent = new Intent(UpdateServiceHelper.ACTION_DOWNLOAD_UPDATE);
            notificationIntent.setClass(this, UpdateService.class);

            PendingIntent contentIntent = PendingIntent.getService(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            notification.flags = Notification.FLAG_AUTO_CANCEL;

            notification.setLatestEventInfo(this, getResources().getString(R.string.updater_start_title),
                                            getResources().getString(R.string.updater_start_select),
                                            contentIntent);

            mNotificationManager.notify(NOTIFICATION_ID, notification);

            return;
        }

        File pkg = downloadUpdatePackage(info, hasFlag(flags, UpdateServiceHelper.FLAG_OVERWRITE_EXISTING));
        if (pkg == null) {
            sendCheckUpdateResult(UpdateServiceHelper.CheckUpdateResult.NOT_AVAILABLE);
            return;
        }

        Log.i(LOGTAG, "have update package at " + pkg);

        saveUpdateInfo(info, pkg);
        sendCheckUpdateResult(UpdateServiceHelper.CheckUpdateResult.DOWNLOADED);

        if (mApplyImmediately) {
            applyUpdate(pkg);
        } else {
            // Prompt to apply the update
            Notification notification = new Notification(R.drawable.ic_status_logo, null, System.currentTimeMillis());

            Intent notificationIntent = new Intent(UpdateServiceHelper.ACTION_APPLY_UPDATE);
            notificationIntent.setClass(this, UpdateService.class);
            notificationIntent.putExtra(UpdateServiceHelper.EXTRA_PACKAGE_PATH_NAME, pkg.getAbsolutePath());

            PendingIntent contentIntent = PendingIntent.getService(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            notification.flags = Notification.FLAG_AUTO_CANCEL;

            notification.setLatestEventInfo(this, getResources().getString(R.string.updater_apply_title),
                                            getResources().getString(R.string.updater_apply_select),
                                            contentIntent);

            mNotificationManager.notify(NOTIFICATION_ID, notification);
        }
    }

    private URLConnection openConnectionWithProxy(URL url) throws java.net.URISyntaxException, java.io.IOException {
        Log.i(LOGTAG, "openning connection with url: " + url);

        ProxySelector ps = ProxySelector.getDefault();
        Proxy proxy = Proxy.NO_PROXY;
        if (ps != null) {
            List<Proxy> proxies = ps.select(url.toURI());
            if (proxies != null && !proxies.isEmpty()) {
                proxy = proxies.get(0);
            }
        }

        return url.openConnection(proxy);
    }

    private UpdateInfo findUpdate(boolean force) {
        try {
            URL url = UpdateServiceHelper.getUpdateUrl(this, force);

            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document dom = builder.parse(openConnectionWithProxy(url).getInputStream());

            NodeList nodes = dom.getElementsByTagName("update");
            if (nodes == null || nodes.getLength() == 0)
                return null;

            Node updateNode = nodes.item(0);
            Node buildIdNode = updateNode.getAttributes().getNamedItem("buildID");
            if (buildIdNode == null)
                return null;

            nodes = dom.getElementsByTagName("patch");
            if (nodes == null || nodes.getLength() == 0)
                return null;

            Node patchNode = nodes.item(0);
            Node urlNode = patchNode.getAttributes().getNamedItem("URL");
            Node hashFunctionNode = patchNode.getAttributes().getNamedItem("hashFunction");
            Node hashValueNode = patchNode.getAttributes().getNamedItem("hashValue");
            Node sizeNode = patchNode.getAttributes().getNamedItem("size");

            if (urlNode == null || hashFunctionNode == null ||
                hashValueNode == null || sizeNode == null) {
                return null;
            }   

            // Fill in UpdateInfo from the XML data
            UpdateInfo info = new UpdateInfo();
            info.url = new URL(urlNode.getTextContent());
            info.buildID = buildIdNode.getTextContent();
            info.hashFunction = hashFunctionNode.getTextContent();
            info.hashValue = hashValueNode.getTextContent();

            try {
                info.size = Integer.parseInt(sizeNode.getTextContent());
            } catch (NumberFormatException e) {
                Log.e(LOGTAG, "Failed to find APK size: ", e);
                return null;
            }

            // Make sure we have all the stuff we need to apply the update
            if (!info.isValid()) {
                Log.e(LOGTAG, "missing some required update information, have: " + info);
                return null;
            }

            return info;
        } catch (Exception e) {
            Log.e(LOGTAG, "failed to check for update: ", e);
            return null;
        }
    }

    private MessageDigest createMessageDigest(String hashFunction) {
        String javaHashFunction = null;

        if ("sha512".equalsIgnoreCase(hashFunction)) {
            javaHashFunction = "SHA-512";
        } else {
            Log.e(LOGTAG, "Unhandled hash function: " + hashFunction);
            return null;
        }

        try {
            return MessageDigest.getInstance(javaHashFunction);
        } catch (java.security.NoSuchAlgorithmException e) {
            Log.e(LOGTAG, "Couldn't find algorithm " + javaHashFunction, e);
            return null;
        }
    }

    private void showDownloadNotification() {
        showDownloadNotification(null);
    }

    private void showDownloadNotification(File downloadFile) {
        Notification notification = new Notification(android.R.drawable.stat_sys_download, null, System.currentTimeMillis());

        Intent notificationIntent = new Intent(UpdateServiceHelper.ACTION_APPLY_UPDATE);
        notificationIntent.setClass(this, UpdateService.class);

        if (downloadFile != null)
            notificationIntent.putExtra(UpdateServiceHelper.EXTRA_PACKAGE_PATH_NAME, downloadFile.getAbsolutePath());

        PendingIntent contentIntent = PendingIntent.getService(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(this, getResources().getString(R.string.updater_downloading_title),
                                        mApplyImmediately ? "" : getResources().getString(R.string.updater_downloading_select),
                                        contentIntent);
        
        mNotificationManager.notify(NOTIFICATION_ID, notification);
    }

    private void showDownloadFailure() {
        Notification notification = new Notification(R.drawable.ic_status_logo, null, System.currentTimeMillis());

        Intent notificationIntent = new Intent(UpdateServiceHelper.ACTION_CHECK_FOR_UPDATE);
        notificationIntent.setClass(this, UpdateService.class);

        PendingIntent contentIntent = PendingIntent.getService(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(this, getResources().getString(R.string.updater_downloading_title_failed),
                                        getResources().getString(R.string.updater_downloading_retry),
                                        contentIntent);
        
        mNotificationManager.notify(NOTIFICATION_ID, notification);
    }

    private File downloadUpdatePackage(UpdateInfo info, boolean overwriteExisting) {
        File downloadFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), new File(info.url.getFile()).getName());

        if (!overwriteExisting && info.buildID.equals(getLastBuildID()) && downloadFile.exists()) {
            // The last saved buildID is the same as the one for the current update. We also have a file
            // already downloaded, so it's probably the package we want. Verify it to be sure and just
            // return that if it matches.

            if (verifyDownloadedPackage(downloadFile)) {
                Log.i(LOGTAG, "using existing update package");
                return downloadFile;
            } else {
                // Didn't match, so we're going to download a new one.
                downloadFile.delete();
            }
        }

        Log.i(LOGTAG, "downloading update package");
        sendCheckUpdateResult(UpdateServiceHelper.CheckUpdateResult.DOWNLOADING);

        OutputStream output = null;
        InputStream input = null;

        mDownloading = true;
        showDownloadNotification(downloadFile);

        try {
            URLConnection conn = openConnectionWithProxy(info.url);
            int length = conn.getContentLength();

            output = new BufferedOutputStream(new FileOutputStream(downloadFile));
            input = new BufferedInputStream(conn.getInputStream());

            byte[] buf = new byte[BUFSIZE];
            int len = 0;

            int bytesRead = 0;
            float lastPercent = 0.0f;

            while ((len = input.read(buf, 0, BUFSIZE)) > 0) {
                output.write(buf, 0, len);
                bytesRead += len;
            }

            Log.i(LOGTAG, "completed update download!");

            mNotificationManager.cancel(NOTIFICATION_ID);

            return downloadFile;
        } catch (Exception e) {
            downloadFile.delete();
            showDownloadFailure();

            Log.e(LOGTAG, "failed to download update: ", e);
            return null;
        } finally {
            try {
                if (input != null)
                    input.close();
            } catch (java.io.IOException e) {}

            try {
                if (output != null)
                    output.close();
            } catch (java.io.IOException e) {}

            mDownloading = false;
        }
    }

    private boolean verifyDownloadedPackage(File updateFile) {
        MessageDigest digest = createMessageDigest(getLastHashFunction());
        if (digest == null)
            return false;

        InputStream input = null;

        try {
            input = new BufferedInputStream(new FileInputStream(updateFile));

            byte[] buf = new byte[BUFSIZE];
            int len;
            while ((len = input.read(buf, 0, BUFSIZE)) > 0) {
                digest.update(buf, 0, len);
            }
        } catch (java.io.IOException e) {
            Log.e(LOGTAG, "Failed to verify update package: ", e);
            return false;
        } finally {
            try {
                if (input != null)
                    input.close();
            } catch(java.io.IOException e) {}
        }

        String hex = Hex.encodeHexString(digest.digest());
        if (!hex.equals(getLastHashValue())) {
            Log.e(LOGTAG, "Package hash does not match");
            return false;
        }

        return true;
    }

    private void applyUpdate(String updatePath) {
        if (updatePath == null) {
            updatePath = mPrefs.getString(KEY_LAST_FILE_NAME, null);
        }
        applyUpdate(new File(updatePath));
    }

    private void applyUpdate(File updateFile) {
        mApplyImmediately = false;

        if (!updateFile.exists())
            return;

        Log.i(LOGTAG, "Verifying package: " + updateFile);

        if (!verifyDownloadedPackage(updateFile)) {
            Log.e(LOGTAG, "Not installing update, failed verification");
            return;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(updateFile), "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    private String getLastBuildID() {
        return mPrefs.getString(KEY_LAST_BUILDID, null);
    }

    private String getLastHashFunction() {
        return mPrefs.getString(KEY_LAST_HASH_FUNCTION, null);
    }

    private String getLastHashValue() {
        return mPrefs.getString(KEY_LAST_HASH_VALUE, null);
    }

    private Calendar getLastAttemptDate() {
        long lastAttempt = mPrefs.getLong(KEY_LAST_ATTEMPT_DATE, -1);
        if (lastAttempt < 0)
            return null;

        GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
        cal.setTimeInMillis(lastAttempt);
        return cal;
    }

    private void setLastAttemptDate() {
        SharedPreferences.Editor editor = mPrefs.edit();
        editor.putLong(KEY_LAST_ATTEMPT_DATE, System.currentTimeMillis());
        editor.commit();
    }

    private int getAutoDownloadPolicy() {
        return mPrefs.getInt(KEY_AUTODOWNLOAD_POLICY, UpdateServiceHelper.AUTODOWNLOAD_WIFI);
    }

    private void setAutoDownloadPolicy(int policy) {
        SharedPreferences.Editor editor = mPrefs.edit();
        editor.putInt(KEY_AUTODOWNLOAD_POLICY, policy);
        editor.commit();
    }

    private void saveUpdateInfo(UpdateInfo info, File downloaded) {
        SharedPreferences.Editor editor = mPrefs.edit();
        editor.putString(KEY_LAST_BUILDID, info.buildID);
        editor.putString(KEY_LAST_HASH_FUNCTION, info.hashFunction);
        editor.putString(KEY_LAST_HASH_VALUE, info.hashValue);
        editor.putString(KEY_LAST_FILE_NAME, downloaded.toString());
        editor.commit();
    }

    private class UpdateInfo {
        public URL url;
        public String buildID;
        public String hashFunction;
        public String hashValue;
        public int size;

        private boolean isNonEmpty(String s) {
            return s != null && s.length() > 0;
        }

        public boolean isValid() {
            return url != null && isNonEmpty(buildID) &&
                isNonEmpty(hashFunction) && isNonEmpty(hashValue) && size > 0;
        }

        @Override
        public String toString() {
            return "url = " + url + ", buildID = " + buildID + ", hashFunction = " + hashFunction + ", hashValue = " + hashValue + ", size = " + size;
        }
    }
}