1/* 2 * Copyright (C) 2010 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 17package com.android.dumprendertree2.forwarder; 18 19import android.util.Log; 20 21import java.io.IOException; 22import java.io.InputStream; 23import java.io.OutputStream; 24import java.net.Socket; 25 26/** 27 * The utility class that can setup a socket allowing the device to communicate with remote 28 * machines through the machine that the device is connected to via adb. 29 */ 30public class AdbUtils { 31 private static final String LOG_TAG = "AdbUtils"; 32 33 private static final String ADB_OK = "OKAY"; 34 private static final int ADB_PORT = 5037; 35 private static final String ADB_HOST = "127.0.0.1"; 36 private static final int ADB_RESPONSE_SIZE = 4; 37 38 /** 39 * Creates a new socket that can be configured to serve as a transparent proxy to a 40 * remote machine. This can be achieved by calling configureSocket() 41 * 42 * @return a socket that can be configured to link to remote machine 43 * @throws IOException 44 */ 45 public static Socket createSocket() throws IOException{ 46 return new Socket(ADB_HOST, ADB_PORT); 47 } 48 49 /** 50 * Configures the connection to serve as a transparent proxy to a remote machine. 51 * The given streams must belong to a socket created by createSocket(). 52 * 53 * @param inputStream inputStream of the socket we want to configure 54 * @param outputStream outputStream of the socket we want to configure 55 * @param remoteAddress address of the remote machine (as you would type in a browser 56 * in a machine that the device is connected to via adb) 57 * @param remotePort port on which to connect 58 * @return if the configuration suceeded 59 * @throws IOException 60 */ 61 public static boolean configureConnection(InputStream inputStream, OutputStream outputStream, 62 String remoteAddress, int remotePort) throws IOException { 63 String cmd = "tcp:" + remotePort + ":" + remoteAddress; 64 cmd = String.format("%04X", cmd.length()) + cmd; 65 66 byte[] buf = new byte[ADB_RESPONSE_SIZE]; 67 outputStream.write(cmd.getBytes()); 68 int read = inputStream.read(buf); 69 if (read != ADB_RESPONSE_SIZE || !ADB_OK.equals(new String(buf))) { 70 Log.w(LOG_TAG, "adb cmd failed."); 71 return false; 72 } 73 return true; 74 } 75} 76