2 * Copyright (C) 2009 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.dumprendertree.forwarder;
19 import android.util.Log;
21 import java.io.IOException;
22 import java.net.ServerSocket;
23 import java.net.Socket;
24 import java.util.HashSet;
29 * A port forwarding server. Listens at specified local port and forward the tcp communications to
30 * external host/port via adb networking proxy.
33 public class ForwardServer {
35 private static final String LOGTAG = "ForwardServer";
37 private int remotePort;
38 private int remoteAddress;
39 private int localPort;
40 private ServerSocket serverSocket;
41 private boolean started;
43 private Set<Forwarder> forwarders;
45 public ForwardServer(int localPort, int remoteAddress, int remotePort) {
46 this.localPort = localPort;
47 this.remoteAddress = remoteAddress;
48 this.remotePort = remotePort;
50 forwarders = new HashSet<Forwarder>();
53 public synchronized void start() throws IOException {
55 serverSocket = new ServerSocket(localPort);
56 Thread serverThread = new Thread(new ServerRunner(serverSocket));
57 serverThread.setName(LOGTAG);
63 public synchronized void stop() {
65 synchronized (forwarders) {
66 for(Forwarder forwarder : forwarders)
72 } catch (IOException ioe) {
73 Log.v(LOGTAG, "exception while closing", ioe);
80 public synchronized boolean isRunning() {
84 private class ServerRunner implements Runnable {
86 private ServerSocket socket;
88 public ServerRunner(ServerSocket socket) {
95 Socket localSocket = socket.accept();
96 Socket remoteSocket = AdbUtils.getForwardedSocket(remoteAddress, remotePort);
97 if(remoteSocket == null) {
100 } catch (IOException ioe) {
101 Log.w(LOGTAG, "error while closing socket", ioe);
103 Log.w(LOGTAG, "failed to start forwarding from " + localSocket);
106 Forwarder forwarder = new Forwarder(localSocket, remoteSocket,
111 } catch (IOException ioe) {
117 public void register(Forwarder forwarder) {
118 synchronized (forwarders) {
119 if(!forwarders.contains(forwarder)) {
120 forwarders.add(forwarder);
125 public void unregister(Forwarder recyclable) {
126 synchronized (forwarders) {
127 if(forwarders.contains(recyclable)) {
129 forwarders.remove(recyclable);