summaryrefslogtreecommitdiffstats
blob: ba696b70a703ec2a1f388a6a70f7722c0b739632 (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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
/*  Copyright (c) 2016, Isode Limited, London, England.
 *  All rights reserved.
 *
 *  Acquisition and use of this software and related materials for any
 *  purpose requires a written license agreement from Isode Limited,
 *  or a written license from an organisation licensed by Isode Limited
 *  to grant such a license.
 *
 */
package com.isode.stroke.filetransfer;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;

import org.junit.Before;
import org.junit.Test;

import com.isode.stroke.base.ByteArray;
import com.isode.stroke.base.SafeByteArray;
import com.isode.stroke.crypto.CryptoProvider;
import com.isode.stroke.crypto.JavaCryptoProvider;
import com.isode.stroke.eventloop.DummyEventLoop;
import com.isode.stroke.eventloop.Event.Callback;
import com.isode.stroke.eventloop.EventLoop;
import com.isode.stroke.eventloop.EventOwner;
import com.isode.stroke.network.Connection;
import com.isode.stroke.network.DummyTimerFactory;
import com.isode.stroke.network.HostAddress;
import com.isode.stroke.network.HostAddressPort;
import com.isode.stroke.signals.Signal1;
import com.isode.stroke.signals.Slot1;

/**
 * Tests for {@link SOCKS5BytestreamClientSession}
 */
public class SOCKS5BytestreamClientSessionTest {

    private static final Random rng = new Random();
    
    private final HostAddressPort destinationAddressPort = new HostAddressPort(new HostAddress("127.0.0.1"), 8888);
    private final CryptoProvider crypto = new JavaCryptoProvider();
    private final String destination = "092a44d859d19c9eed676b551ee80025903351c2";
    private final DummyEventLoop eventLoop = new DummyEventLoop();
    private final DummyTimerFactory timerFactory = new DummyTimerFactory();
    private final List<HostAddressPort> failingPorts = new ArrayList<HostAddressPort>();
    private final MockeryConnection connection = 
            new MockeryConnection(failingPorts, true, eventLoop);
    
    @Before
    public void setUp() {
        rng.setSeed(System.currentTimeMillis());
    }
    
    @Test
    public void testForSessionReady() {
        final TestHelper helper = new TestHelper();
        connection.onDataSent.connect(new Slot1<SafeByteArray>() {
            
            @Override
            public void call(SafeByteArray data) {
                helper.handleConnectionDataWritten(data);
            }
            
        });
        
        SOCKS5BytestreamClientSession clientSession = new SOCKS5BytestreamClientSession(connection, destinationAddressPort, destination, timerFactory);
        clientSession.onSessionReady.connect(new Slot1<Boolean>() {

            @Override
            public void call(Boolean hasError) {
                helper.handleSessionRead(hasError.booleanValue());
            }
            
        });
        
        clientSession.start();
        eventLoop.processEvents();
        assertEquals(new ByteArray(new byte[] {0x05,0x01,0x00}),helper.unprocessedInput);
        
        helper.unprocessedInput.clear();
        serverRespondHelloOK();
        eventLoop.processEvents();
        ByteArray expected = new ByteArray(new byte[] {0x05,0x01,0x00,0x03});
        expected.append((byte)destination.length());
        expected.append(destination);
        expected.append((byte)0x00);
        ByteArray results = getSubArray(helper.unprocessedInput, expected.getSize());
        assertEquals(expected,results);
        
        helper.unprocessedInput.clear();
        serverRespondRequestOK();
        eventLoop.processEvents();
        assertTrue(helper.sessionReadyCalled);
        assertFalse(helper.sessionReadyError);
    }
    
    @Test
    public void testErrorHandlingHello() {
        final TestHelper helper = new TestHelper();
        connection.onDataSent.connect(new Slot1<SafeByteArray>() {
            
            @Override
            public void call(SafeByteArray data) {
                helper.handleConnectionDataWritten(data);
            }
            
        });
        
        SOCKS5BytestreamClientSession clientSession = new SOCKS5BytestreamClientSession(connection, destinationAddressPort, destination, timerFactory);
        clientSession.onSessionReady.connect(new Slot1<Boolean>() {

            @Override
            public void call(Boolean hasError) {
                helper.handleSessionRead(hasError.booleanValue());
            }
            
        });
        
        clientSession.start();
        eventLoop.processEvents();
        assertEquals(new ByteArray(new byte[] {0x05,0x01,0x00}),helper.unprocessedInput);
        
        helper.unprocessedInput.clear();
        serverRespondHelloAuthFail();
        eventLoop.processEvents();
        
        assertTrue(helper.sessionReadyCalled);
        assertTrue(helper.sessionReadyError);
        assertTrue(connection.disconnectCalled);
    }
    
    @Test
    public void testErrorHandlingRequest() {
        final TestHelper helper = new TestHelper();
        connection.onDataSent.connect(new Slot1<SafeByteArray>() {
            
            @Override
            public void call(SafeByteArray data) {
                helper.handleConnectionDataWritten(data);
            }
            
        });
        
        SOCKS5BytestreamClientSession clientSession = new SOCKS5BytestreamClientSession(connection, destinationAddressPort, destination, timerFactory);
        clientSession.onSessionReady.connect(new Slot1<Boolean>() {

            @Override
            public void call(Boolean hasError) {
                helper.handleSessionRead(hasError.booleanValue());
            }
            
        });
        
        clientSession.start();
        eventLoop.processEvents();
        assertEquals(new ByteArray(new byte[] {0x05,0x01,0x00}),helper.unprocessedInput);
        
        helper.unprocessedInput.clear();
        serverRespondHelloOK();
        eventLoop.processEvents();
        ByteArray expected = new ByteArray(new byte[] {0x05,0x01,0x00,0x03});
        expected.append((byte)destination.length());
        expected.append(destination);
        expected.append((byte)0x00);
        ByteArray results = getSubArray(helper.unprocessedInput, expected.getSize());
        assertEquals(expected,results);
        
        helper.unprocessedInput.clear();
        serverRespondRequestFail();
        eventLoop.processEvents();
        assertTrue(helper.sessionReadyCalled);
        assertTrue(helper.sessionReadyError);
        assertTrue(connection.disconnectCalled);
    }
    
    @Test
    public void testWriteBytestream() {
        final TestHelper helper = new TestHelper();
        connection.onDataSent.connect(new Slot1<SafeByteArray>() {
            
            @Override
            public void call(SafeByteArray data) {
                helper.handleConnectionDataWritten(data);
            }
            
        });
        
        SOCKS5BytestreamClientSession clientSession = new SOCKS5BytestreamClientSession(connection, destinationAddressPort, destination, timerFactory);
        clientSession.onSessionReady.connect(new Slot1<Boolean>() {

            @Override
            public void call(Boolean hasError) {
                helper.handleSessionRead(hasError.booleanValue());
            }
            
        });
        
        clientSession.start();
        eventLoop.processEvents();
        
        helper.unprocessedInput.clear();
        serverRespondHelloOK();
        eventLoop.processEvents();
        
        helper.unprocessedInput.clear();
        serverRespondRequestOK();
        eventLoop.processEvents();
        assertTrue(helper.sessionReadyCalled);
        assertFalse(helper.sessionReadyError);
        
        ByteArrayWriteBytestream output = new ByteArrayWriteBytestream();
        clientSession.startReceiving(output);
        
        ByteArray transferData = generateRandomByteArray(1024);
        connection.onDataRead.emit(new SafeByteArray(transferData));
        assertEquals(transferData,output.getData());
    }
    
    @Test
    public void testReadBytestream() {
        final TestHelper helper = new TestHelper();
        connection.onDataSent.connect(new Slot1<SafeByteArray>() {

            @Override
            public void call(SafeByteArray data) {
                helper.handleConnectionDataWritten(data);
            }
            
        });
        
        SOCKS5BytestreamClientSession clientSession = new SOCKS5BytestreamClientSession(connection, destinationAddressPort, destination, timerFactory);
        clientSession.onSessionReady.connect(new Slot1<Boolean>() {

            @Override
            public void call(Boolean hasError) {
                helper.handleSessionRead(hasError.booleanValue());
            }
            
        });
        
        clientSession.start();
        eventLoop.processEvents();
        
        helper.unprocessedInput.clear();
        serverRespondHelloOK();
        eventLoop.processEvents();
        
        helper.unprocessedInput.clear();
        serverRespondRequestOK();
        eventLoop.processEvents();
        assertTrue(helper.sessionReadyCalled);
        assertFalse(helper.sessionReadyError);
        
        helper.unprocessedInput.clear();
        ByteArray transferData = generateRandomByteArray(1024);
        ByteArrayReadBytestream input = new ByteArrayReadBytestream(transferData);
        clientSession.startSending(input);
        eventLoop.processEvents();
        
        assertEquals(transferData,helper.unprocessedInput);
    }
    
    private static ByteArray generateRandomByteArray(int len) {
        byte[] randomBytes = new byte[len];
        rng.nextBytes(randomBytes);
        return new ByteArray(randomBytes);
    }
    
    private void serverRespondHelloOK() {
        connection.onDataRead.emit(new SafeByteArray(new byte[] {0x05,0x00}));
    }
    
    private void serverRespondHelloAuthFail() {
        connection.onDataRead.emit(new SafeByteArray(new byte[] {0x05,(byte) 0xFF}));
    }
    
    private void serverRespondRequestOK() {
        SafeByteArray dataToSend = new SafeByteArray(new byte[] {0x05,0x00,0x00,0x03});
        dataToSend.append((byte)destination.length());
        dataToSend.append(destination);
        dataToSend.append((byte)0x00);
        connection.onDataRead.emit(dataToSend);
    }
    
    private void serverRespondRequestFail() {
        SafeByteArray correctData = new SafeByteArray(new byte[] {0x05,0x00,0x00,0x03});
        correctData.append((byte)destination.length());
        correctData.append(destination);
        correctData.append((byte)0x00);
        SafeByteArray dataToSend;
        do {
            ByteArray rndArray = generateRandomByteArray(correctData.getSize());
            dataToSend = new SafeByteArray(rndArray);
        } while (dataToSend.equals(correctData));
        connection.onDataRead.emit(dataToSend);
    }
    
    /**
     * Gets the sub {@link ByteArray} consisting of the first n bytes of
     * a given {@link ByteArray}
     * @param array A {@link ByteArray} should not be {@code null} and should
     * be at least n characters long.
     * @param n the number of bytes of the {@link ByteArray} to return as a new
     * {@link ByteArray}
     * @return The first n characters of the given {@link ByteArray} as a new
     * {@link ByteArray}.  Will not be {@code null}
     */
    private ByteArray getSubArray(ByteArray array,int n) {
        byte[] arrayData = array.getData();
        byte[] newArrayData = Arrays.copyOfRange(arrayData, 0, n);
        return new ByteArray(newArrayData);
    }

    private static final class TestHelper {
        
        private ByteArray unprocessedInput = new ByteArray();
        private boolean sessionReadyCalled = false;
        private boolean sessionReadyError = false;
        
        public TestHelper() {
            // Empty Constructor 
        }
        
        public void handleConnectionDataWritten(SafeByteArray data) {
            unprocessedInput.append(data);
        }
        
        public void handleSessionRead(boolean error) {
            sessionReadyCalled = true;
            sessionReadyError = error;
        }
        
    }
    
    
    private static final class MockeryConnection extends Connection implements EventOwner {

        private EventLoop eventLoop;
        private HostAddressPort hostAddressPort;
        private final List<HostAddressPort> failingPorts;
        private boolean isResponsive;
        private boolean disconnectCalled;
        
        private final Signal1<SafeByteArray> onDataSent = new Signal1<SafeByteArray>();

        public MockeryConnection(Collection<HostAddressPort> failingPorts,
                boolean isResponsive,EventLoop eventLoop) {
            this.eventLoop = eventLoop;
            this.failingPorts = new ArrayList<HostAddressPort>(failingPorts);
            this.isResponsive = isResponsive;
            this.disconnectCalled = false;
        }
        
        @Override
        public void listen() {
            fail();
        }

        /* (non-Javadoc)
         * @see com.isode.stroke.network.Connection#connect(com.isode.stroke.network.HostAddressPort)
         */
        @Override
        public void connect(HostAddressPort address) {
            hostAddressPort = address;
            if (isResponsive) {
                final boolean fail = failingPorts.contains(address);
                eventLoop.postEvent(new Callback() {
                    
                    @Override
                    public void run() {
                        onConnectFinished.emit(fail);
                    }
                    
                });
            }
        }

        /* (non-Javadoc)
         * @see com.isode.stroke.network.Connection#disconnect()
         */
        @Override
        public void disconnect() {
            disconnectCalled = true;
        }

        /* (non-Javadoc)
         * @see com.isode.stroke.network.Connection#write(com.isode.stroke.base.SafeByteArray)
         */
        @Override
        public void write(SafeByteArray data) {
            eventLoop.postEvent(new Callback() {
                
                @Override
                public void run() {
                    onDataWritten.emit();
                }
                
            });
            onDataSent.emit(data);
        }
        
        

        /* (non-Javadoc)
         * @see com.isode.stroke.network.Connection#getLocalAddress()
         */
        @Override
        public HostAddressPort getLocalAddress() {
            return new HostAddressPort();
        }
        
        public HostAddressPort getRemoteAddress() {
            return new HostAddressPort();
        }
        
    }

}