Home | History | Annotate | Download | only in updates
      1 /*
      2  * Copyright (C) 2012 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.server.updates;
     18 
     19 import com.android.server.EventLogTags;
     20 import com.android.internal.util.HexDump;
     21 
     22 import android.content.BroadcastReceiver;
     23 import android.content.Context;
     24 import android.content.Intent;
     25 import android.net.Uri;
     26 import android.util.EventLog;
     27 import android.util.Slog;
     28 
     29 import java.io.File;
     30 import java.io.FileOutputStream;
     31 import java.io.IOException;
     32 import java.io.InputStream;
     33 import java.security.MessageDigest;
     34 import java.security.NoSuchAlgorithmException;
     35 
     36 import libcore.io.IoUtils;
     37 import libcore.io.Streams;
     38 
     39 public class ConfigUpdateInstallReceiver extends BroadcastReceiver {
     40 
     41     private static final String TAG = "ConfigUpdateInstallReceiver";
     42 
     43     private static final String EXTRA_REQUIRED_HASH = "REQUIRED_HASH";
     44     private static final String EXTRA_VERSION_NUMBER = "VERSION";
     45 
     46     protected final File updateDir;
     47     protected final File updateContent;
     48     protected final File updateVersion;
     49 
     50     public ConfigUpdateInstallReceiver(String updateDir, String updateContentPath,
     51                                        String updateMetadataPath, String updateVersionPath) {
     52         this.updateDir = new File(updateDir);
     53         this.updateContent = new File(updateDir, updateContentPath);
     54         File updateMetadataDir = new File(updateDir, updateMetadataPath);
     55         this.updateVersion = new File(updateMetadataDir, updateVersionPath);
     56     }
     57 
     58     @Override
     59     public void onReceive(final Context context, final Intent intent) {
     60         new Thread() {
     61             @Override
     62             public void run() {
     63                 try {
     64                     // get the content path from the extras
     65                     byte[] altContent = getAltContent(context, intent);
     66                     // get the version from the extras
     67                     int altVersion = getVersionFromIntent(intent);
     68                     // get the previous value from the extras
     69                     String altRequiredHash = getRequiredHashFromIntent(intent);
     70                     // get the version currently being used
     71                     int currentVersion = getCurrentVersion();
     72                     // get the hash of the currently used value
     73                     String currentHash = getCurrentHash(getCurrentContent());
     74                     if (!verifyVersion(currentVersion, altVersion)) {
     75                         Slog.i(TAG, "Not installing, new version is <= current version");
     76                     } else if (!verifyPreviousHash(currentHash, altRequiredHash)) {
     77                         EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED,
     78                                             "Current hash did not match required value");
     79                     } else {
     80                         // install the new content
     81                         Slog.i(TAG, "Found new update, installing...");
     82                         install(altContent, altVersion);
     83                         Slog.i(TAG, "Installation successful");
     84                         postInstall(context, intent);
     85                     }
     86                 } catch (Exception e) {
     87                     Slog.e(TAG, "Could not update content!", e);
     88                     // keep the error message <= 100 chars
     89                     String errMsg = e.toString();
     90                     if (errMsg.length() > 100) {
     91                         errMsg = errMsg.substring(0, 99);
     92                     }
     93                     EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED, errMsg);
     94                 }
     95             }
     96         }.start();
     97     }
     98 
     99     private Uri getContentFromIntent(Intent i) {
    100         Uri data = i.getData();
    101         if (data == null) {
    102             throw new IllegalStateException("Missing required content path, ignoring.");
    103         }
    104         return data;
    105     }
    106 
    107     private int getVersionFromIntent(Intent i) throws NumberFormatException {
    108         String extraValue = i.getStringExtra(EXTRA_VERSION_NUMBER);
    109         if (extraValue == null) {
    110             throw new IllegalStateException("Missing required version number, ignoring.");
    111         }
    112         return Integer.parseInt(extraValue.trim());
    113     }
    114 
    115     private String getRequiredHashFromIntent(Intent i) {
    116         String extraValue = i.getStringExtra(EXTRA_REQUIRED_HASH);
    117         if (extraValue == null) {
    118             throw new IllegalStateException("Missing required previous hash, ignoring.");
    119         }
    120         return extraValue.trim();
    121     }
    122 
    123     private int getCurrentVersion() throws NumberFormatException {
    124         try {
    125             String strVersion = IoUtils.readFileAsString(updateVersion.getCanonicalPath()).trim();
    126             return Integer.parseInt(strVersion);
    127         } catch (IOException e) {
    128             Slog.i(TAG, "Couldn't find current metadata, assuming first update");
    129             return 0;
    130         }
    131     }
    132 
    133     private byte[] getAltContent(Context c, Intent i) throws IOException {
    134         Uri content = getContentFromIntent(i);
    135         InputStream is = c.getContentResolver().openInputStream(content);
    136         try {
    137             return Streams.readFullyNoClose(is);
    138         } finally {
    139             is.close();
    140         }
    141     }
    142 
    143     private byte[] getCurrentContent() {
    144         try {
    145             return IoUtils.readFileAsByteArray(updateContent.getCanonicalPath());
    146         } catch (IOException e) {
    147             Slog.i(TAG, "Failed to read current content, assuming first update!");
    148             return null;
    149         }
    150     }
    151 
    152     private static String getCurrentHash(byte[] content) {
    153         if (content == null) {
    154             return "0";
    155         }
    156         try {
    157             MessageDigest dgst = MessageDigest.getInstance("SHA512");
    158             byte[] fingerprint = dgst.digest(content);
    159             return HexDump.toHexString(fingerprint, false);
    160         } catch (NoSuchAlgorithmException e) {
    161             throw new AssertionError(e);
    162         }
    163     }
    164 
    165     protected boolean verifyVersion(int current, int alternative) {
    166         return (current < alternative);
    167     }
    168 
    169     private boolean verifyPreviousHash(String current, String required) {
    170         // this is an optional value- if the required field is NONE then we ignore it
    171         if (required.equals("NONE")) {
    172             return true;
    173         }
    174         // otherwise, verify that we match correctly
    175         return current.equals(required);
    176     }
    177 
    178     protected void writeUpdate(File dir, File file, byte[] content) throws IOException {
    179         FileOutputStream out = null;
    180         File tmp = null;
    181         try {
    182             // create the parents for the destination file
    183             File parent = file.getParentFile();
    184             parent.mkdirs();
    185             // check that they were created correctly
    186             if (!parent.exists()) {
    187                 throw new IOException("Failed to create directory " + parent.getCanonicalPath());
    188             }
    189             // create the temporary file
    190             tmp = File.createTempFile("journal", "", dir);
    191             // mark tmp -rw-r--r--
    192             tmp.setReadable(true, false);
    193             // write to it
    194             out = new FileOutputStream(tmp);
    195             out.write(content);
    196             // sync to disk
    197             out.getFD().sync();
    198             // atomic rename
    199             if (!tmp.renameTo(file)) {
    200                 throw new IOException("Failed to atomically rename " + file.getCanonicalPath());
    201             }
    202         } finally {
    203             if (tmp != null) {
    204                 tmp.delete();
    205             }
    206             IoUtils.closeQuietly(out);
    207         }
    208     }
    209 
    210     protected void install(byte[] content, int version) throws IOException {
    211         writeUpdate(updateDir, updateContent, content);
    212         writeUpdate(updateDir, updateVersion, Long.toString(version).getBytes());
    213     }
    214 
    215     protected void postInstall(Context context, Intent intent) {
    216     }
    217 }
    218