summaryrefslogtreecommitdiff
path: root/jdwp/src/test/java/org/apache/harmony/jpda/tests/framework/jdwp/SocketTransportWrapper.java
blob: 17879211041c73e3a31302574f1be6efc38b514d (plain)
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
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * @author Ivan G. Popov
 */

/**
 * Created on 05.23.2004
 */
package org.apache.harmony.jpda.tests.framework.jdwp;


import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.IOException;

import org.apache.harmony.jpda.tests.framework.jdwp.Packet;

/**
 * This class provides TransportWrapper for row TCP/IP socket connection.
 *
 */
public class SocketTransportWrapper implements TransportWrapper {

    public static final String HANDSHAKE_STRING = "JDWP-Handshake";

    private ServerSocket serverSocket;
    private Socket transportSocket;
    private InputStream input;
    private OutputStream output;

    /**
     * Starts listening for connection on given or default address.
     *
     * @param address
     *            address to listen to or null for default address,
     *            parsed as "hostname:port" or "port", if it contains
     *            no semi-colon.
     * @return string representation of listening address
     */
    public String startListening(String address) throws IOException {
        String hostName = null;
        InetAddress hostAddr = null;
        int port = 0;
        if (address != null) {
            String portName = null;
            int i = address.indexOf(':');
            if (i < 0) {
                portName = address;
            } else {
                hostName = address.substring(0, i);
                portName = address.substring(i+1);
            }
            try {
                port = Integer.parseInt(portName);
            } catch (NumberFormatException e) {
                throw new IOException("Illegal port number in socket address: " + address);
            }
        }

        if (hostName != null) {
            hostAddr = InetAddress.getByName(hostName);
            serverSocket = new ServerSocket(port, 0, hostAddr);
        } else {
            serverSocket = new ServerSocket(port);
        }

        // use as workaround for unspecified behaviour of isAnyLocalAddress()
        InetAddress iAddress = null;
        if (hostName != null) {
            iAddress = serverSocket.getInetAddress();
        } else {
            iAddress = InetAddress.getLocalHost();
        }

        address = iAddress.getHostName() + ":" + serverSocket.getLocalPort();
        return address;
    }

    /**
     * Stops listening for connection on current address.
     */
    public void stopListening() throws IOException {
        if (serverSocket != null) {
            serverSocket.close();
        }
    }

    /**
     * Accepts transport connection for currently listened address and performs handshaking 
     * for specified timeout.
     * 
     * @param acceptTimeout timeout for accepting in milliseconds
     * @param handshakeTimeout timeout for handshaking in milliseconds
     */
    public void accept(long acceptTimeout, long handshakeTimeout) throws IOException {
        synchronized (serverSocket) {
            serverSocket.setSoTimeout((int) acceptTimeout);
            try {
                transportSocket = serverSocket.accept();
            } finally {
                serverSocket.setSoTimeout(0);
            }
        }
        createStreams();
        handshake(handshakeTimeout);
    }
    
    /**
     * Attaches transport connection to given address and performs handshaking 
     * for specified timeout.
     * 
     * @param address address for attaching
     * @param attachTimeout timeout for attaching in milliseconds
     * @param handshakeTimeout timeout for handshaking in milliseconds
     */
    public void attach(String address, long attachTimeout, long handshakeTimeout) throws IOException {
        if (address == null) {
            throw new IOException("Illegal socket address: " + address);
        }

        String hostName = null;
        int port = 0;
        {
            String portName = null;
            int i = address.indexOf(':');
            if (i < 0) {
                throw new IOException("Illegal socket address: " + address);
            } else {
                hostName = address.substring(0, i);
                portName = address.substring(i+1);
            }
            try {
                port = Integer.parseInt(portName);
            } catch (NumberFormatException e) {
                throw new IOException("Illegal port number in socket address: " + address);
            }
        }

        long finishTime = System.currentTimeMillis() + attachTimeout;
        long sleepTime = 4 * 1000; // milliseconds
        IOException exception = null;
        try {
            do {
                try {
                    transportSocket = new Socket(hostName, port);
                    break;
                } catch (IOException e) {
                    Thread.sleep(sleepTime);
                }
            } while (attachTimeout == 0 || System.currentTimeMillis() < finishTime);
        } catch (InterruptedException e) {
            throw new InterruptedIOException("Interruption in attaching to " + address);
        }
        
        if (transportSocket == null) {
            if (exception != null) {
                throw exception;
            } else {
                throw new SocketTimeoutException("Timeout exceeded in attaching to " + address);
            }
        }
        
        createStreams();
        handshake(handshakeTimeout);
    }

    /**
     * Closes transport connection.
     */
    public void close() throws IOException {
        if (input != null) {
            input.close();
        }
        if (output != null) {
            output.close();
        }
        
        if (transportSocket != null && input == null && output == null && !transportSocket.isClosed()) {
            transportSocket.close();
        }
        if (serverSocket != null) {
            serverSocket.close();
        }
    }

    /**
     * Checks if transport connection is open.
     * 
     * @return true if transport connection is open
     */
    public boolean isOpen() {
        return (transportSocket != null 
                    && transportSocket.isConnected() 
                    && !transportSocket.isClosed());
    }

    /**
     * Reads packet bytes from transport connection.
     * 
     * @return packet as byte array or null or empty packet if connection was closed
     */
    public byte[] readPacket() throws IOException {

        // read packet header
        byte[] header = new byte[Packet.HEADER_SIZE];
        int off = 0;

        while (off < Packet.HEADER_SIZE) {
            try {
                int bytesRead = input.read(header, off, Packet.HEADER_SIZE - off);
                if (bytesRead < 0) {
                    break;
                }
                off += bytesRead;
            } catch (IOException e) {
                // workaround for "Socket Closed" exception if connection was closed
                break;
            }
        }

        if (off == 0) {
            return null;
        }
        if (off < Packet.HEADER_SIZE) {
            throw new IOException("Connection closed in reading packet header");
        }

        // extract packet length
        int len = Packet.getPacketLength(header);
        if (len < Packet.HEADER_SIZE) {
            throw new IOException("Wrong packet size detected: " + len);
        }
        
        // allocate packet bytes and store header there 
        byte[] bytes = new byte[len];
        System.arraycopy(header, 0, bytes, 0, Packet.HEADER_SIZE);

        // read packet data
        while (off < len) {
            int bytesRead = input.read(bytes, off, len - off);
            if (bytesRead < 0) {
                break;
            }
            off += bytesRead;
        }
        if (off < len) {
            throw new IOException("Connection closed in reading packet data");
        }

        return bytes;
    }

    /**
     * Writes packet bytes to transport connection.
     * 
     * @param packet
     *            packet as byte array
     */
    public void writePacket(byte[] packet) throws IOException {
        output.write(packet);
        output.flush();
    }

    /**
     * Performs handshaking for given timeout.
     * 
     * @param handshakeTimeout timeout for handshaking in milliseconds
     */
    protected void handshake(long handshakeTimeout) throws IOException {
        transportSocket.setSoTimeout((int) handshakeTimeout);
        
        try {
            output.write(HANDSHAKE_STRING.getBytes());
            output.flush();
            int len = HANDSHAKE_STRING.length();
            byte[] bytes = new byte[len];
            int off = 0;
            while (off < len) {
                int bytesRead = input.read(bytes, off, len - off);
                if (bytesRead < 0) {
                    break;
                }
                off += bytesRead;
            }
            String response = new String(bytes, 0, off);
            if (!response.equals(HANDSHAKE_STRING)) {
                throw new IOException("Unexpected handshake response: " + response);
            }
        } finally {
            transportSocket.setSoTimeout(0);
        }
    }

    /**
     * Creates input/output streams for connection socket.
     */
    protected void createStreams() throws IOException {
        input = transportSocket.getInputStream();
        output = transportSocket.getOutputStream();
    }
}