1 /* 2 * Copyright (C) 2017 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.backup.utils; 18 19 import static com.android.server.backup.BackupManagerService.TAG; 20 21 import android.os.ParcelFileDescriptor; 22 import android.util.Slog; 23 24 import java.io.DataInputStream; 25 import java.io.EOFException; 26 import java.io.FileInputStream; 27 import java.io.IOException; 28 import java.io.OutputStream; 29 30 /** 31 * Low-level utility methods for full backup. 32 */ 33 public class FullBackupUtils { 34 /** 35 * Reads data from pipe and writes it to the stream in chunks of up to 32KB. 36 * 37 * @param inPipe - pipe to read the data from. 38 * @param out - stream to write the data to. 39 * @throws IOException - in case of an error. 40 */ routeSocketDataToOutput(ParcelFileDescriptor inPipe, OutputStream out)41 public static void routeSocketDataToOutput(ParcelFileDescriptor inPipe, OutputStream out) 42 throws IOException { 43 // We do not take close() responsibility for the pipe FD 44 FileInputStream raw = new FileInputStream(inPipe.getFileDescriptor()); 45 DataInputStream in = new DataInputStream(raw); 46 47 byte[] buffer = new byte[32 * 1024]; 48 int chunkTotal; 49 while ((chunkTotal = in.readInt()) > 0) { 50 while (chunkTotal > 0) { 51 int toRead = (chunkTotal > buffer.length) ? buffer.length : chunkTotal; 52 int nRead = in.read(buffer, 0, toRead); 53 if (nRead < 0) { 54 Slog.e(TAG, "Unexpectedly reached end of file while reading data"); 55 throw new EOFException(); 56 } 57 out.write(buffer, 0, nRead); 58 chunkTotal -= nRead; 59 } 60 } 61 } 62 } 63