summaryrefslogtreecommitdiff
path: root/java/src/IceInternal/TcpTransceiver.java
blob: 7122f8ff7cff2136750daf33421ec9891c5a7cd6 (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
// **********************************************************************
//
// Copyright (c) 2003-2014 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

package IceInternal;

final class TcpTransceiver implements Transceiver
{
    public java.nio.channels.SelectableChannel
    fd()
    {
        assert(_fd != null);
        return _fd;
    }

    public int
    initialize(Buffer readBuffer, Buffer writeBuffer)
    {
        try
        {
            if(_state == StateNeedConnect)
            {
                _state = StateConnectPending;
                return SocketOperation.Connect;
            }
            else if(_state == StateConnectPending)
            {
                Network.doFinishConnect(_fd);
                _desc = Network.fdToString(_fd, _proxy, _addr);

                if(_proxy != null)
                {
                    //
                    // Prepare the read & write buffers in advance.
                    //
                    _proxy.beginWriteConnectRequest(_addr, writeBuffer);
                    _proxy.beginReadConnectRequestResponse(readBuffer);

                    //
                    // Write the proxy connection message.
                    //
                    if(write(writeBuffer))
                    {
                        //
                        // Write completed without blocking.
                        //
                        _proxy.endWriteConnectRequest(writeBuffer);

                        //
                        // Try to read the response.
                        //
                        Ice.BooleanHolder dummy = new Ice.BooleanHolder();
                        if(read(readBuffer, dummy))
                        {
                            //
                            // Read completed without blocking - fall through.
                            //
                            _proxy.endReadConnectRequestResponse(readBuffer);
                        }
                        else
                        {
                            //
                            // Return SocketOperationRead to indicate we need to complete the read.
                            //
                            _state = StateProxyConnectRequestPending; // Wait for proxy response
                            return SocketOperation.Read;
                        }
                    }
                    else
                    {
                        //
                        // Return SocketOperationWrite to indicate we need to complete the write.
                        //
                        _state = StateProxyConnectRequest; // Send proxy connect request
                        return SocketOperation.Write;
                    }
                }

                _state = StateConnected;
            }
            else if(_state == StateProxyConnectRequest)
            {
                //
                // Write completed.
                //
                _proxy.endWriteConnectRequest(writeBuffer);
                _state = StateProxyConnectRequestPending; // Wait for proxy response
                return SocketOperation.Read;
            }
            else if(_state == StateProxyConnectRequestPending)
            {
                //
                // Read completed.
                //
                _proxy.endReadConnectRequestResponse(readBuffer);
                _state = StateConnected;
            }
        }
        catch(Ice.LocalException ex)
        {
            if(_traceLevels.network >= 2)
            {
                StringBuilder s = new StringBuilder(128);
                s.append("failed to establish tcp connection\n");
                s.append(Network.fdToString(_fd, _proxy, _addr));
                _logger.trace(_traceLevels.networkCat, s.toString());
            }
            throw ex;
        }

        assert(_state == StateConnected);
        if(_traceLevels.network >= 1)
        {
            String s = "tcp connection established\n" + _desc;
            _logger.trace(_traceLevels.networkCat, s);
        }
        return SocketOperation.None;
    }

    public void
    close()
    {
        if(_state == StateConnected && _traceLevels.network >= 1)
        {
            String s = "closing tcp connection\n" + toString();
            _logger.trace(_traceLevels.networkCat, s);
        }

        assert(_fd != null);
        try
        {
            _fd.close();
        }
        catch(java.io.IOException ex)
        {
            throw new Ice.SocketException(ex);
        }
        finally
        {
            _fd = null;
        }
    }

    @SuppressWarnings("deprecation")
    public boolean
    write(Buffer buf)
    {
        //
        // We don't want write to be called on android main thread as this will cause
        // NetworkOnMainThreadException to be thrown. If that is the android main thread
        // we return false and this method will be later called from the thread pool.
        //
        if(Util.isAndroidMainThread(Thread.currentThread()))
        {
            return false;
        }

        final int size = buf.b.limit();
        int packetSize = size - buf.b.position();

        //
        // Limit packet size to avoid performance problems on WIN32
        //
        if(_maxSendPacketSize > 0 && packetSize > _maxSendPacketSize)
        {
            packetSize = _maxSendPacketSize;
            buf.b.limit(buf.b.position() + packetSize);
        }

        while(buf.b.hasRemaining())
        {
            try
            {
                assert(_fd != null);
                int ret = _fd.write(buf.b);

                if(ret == -1)
                {
                    throw new Ice.ConnectionLostException();
                }
                else if(ret == 0)
                {
                    //
                    // Writing would block, so we reset the limit (if necessary) and return false to indicate
                    // that more data must be sent.
                    //
                    if(packetSize == _maxSendPacketSize)
                    {
                        buf.b.limit(size);
                    }
                    return false;
                }

                if(_traceLevels.network >= 3)
                {
                    String s = "sent " + ret + " of " + packetSize + " bytes via tcp\n" + toString();
                    _logger.trace(_traceLevels.networkCat, s);
                }

                if(packetSize == _maxSendPacketSize)
                {
                    assert(buf.b.position() == buf.b.limit());
                    packetSize = size - buf.b.position();
                    if(packetSize > _maxSendPacketSize)
                    {
                        packetSize = _maxSendPacketSize;
                    }
                    buf.b.limit(buf.b.position() + packetSize);
                }
            }
            catch(java.io.InterruptedIOException ex)
            {
                continue;
            }
            catch(java.io.IOException ex)
            {
                throw new Ice.SocketException(ex);
            }
        }
        return true;
    }

    @SuppressWarnings("deprecation")
    public boolean
    read(Buffer buf, Ice.BooleanHolder moreData)
    {
        int packetSize = buf.b.remaining();
        moreData.value = false;

        while(buf.b.hasRemaining())
        {
            try
            {
                assert(_fd != null);
                int ret = _fd.read(buf.b);

                if(ret == -1)
                {
                    throw new Ice.ConnectionLostException();
                }

                if(ret == 0)
                {
                    return false;
                }

                if(ret > 0)
                {
                    if(_traceLevels.network >= 3)
                    {
                        String s = "received " + ret + " of " + packetSize + " bytes via tcp\n" + toString();
                        _logger.trace(_traceLevels.networkCat, s);
                    }
                }

                packetSize = buf.b.remaining();
            }
            catch(java.io.InterruptedIOException ex)
            {
                continue;
            }
            catch(java.io.IOException ex)
            {
                throw new Ice.ConnectionLostException(ex);
            }
        }

        return true;
    }

    public String
    type()
    {
        return "tcp";
    }

    public String
    toString()
    {
        return _desc;
    }

    public Ice.ConnectionInfo
    getInfo()
    {
        Ice.TCPConnectionInfo info = new Ice.TCPConnectionInfo();
        if(_fd != null)
        {
            java.net.Socket socket = _fd.socket();
            info.localAddress = socket.getLocalAddress().getHostAddress();
            info.localPort = socket.getLocalPort();
            if(socket.getInetAddress() != null)
            {
                info.remoteAddress = socket.getInetAddress().getHostAddress();
                info.remotePort = socket.getPort();
            }
        }
        return info;
    }

    public void
    checkSendSize(Buffer buf, int messageSizeMax)
    {
        if(buf.size() > messageSizeMax)
        {
            Ex.throwMemoryLimitException(buf.size(), messageSizeMax);
        }
    }

    @SuppressWarnings("deprecation")
    TcpTransceiver(Instance instance, java.nio.channels.SocketChannel fd, NetworkProxy proxy,
                   java.net.InetSocketAddress addr)
    {
        _fd = fd;
        _proxy = proxy;
        _addr = addr;
        _traceLevels = instance.traceLevels();
        _logger = instance.initializationData().logger;
        _state = StateNeedConnect;
        _desc = "";

        _maxSendPacketSize = 0;
        if(System.getProperty("os.name").startsWith("Windows"))
        {
            //
            // On Windows, limiting the buffer size is important to prevent
            // poor throughput performances when transfering large amount of
            // data. See Microsoft KB article KB823764.
            //
            _maxSendPacketSize = Network.getSendBufferSize(_fd) / 2;
            if(_maxSendPacketSize < 512)
            {
                _maxSendPacketSize = 0;
            }
        }
    }

    @SuppressWarnings("deprecation")
    TcpTransceiver(Instance instance, java.nio.channels.SocketChannel fd)
    {
        _fd = fd;
        _traceLevels = instance.traceLevels();
        _logger = instance.initializationData().logger;
        _state = StateConnected;
        _desc = Network.fdToString(_fd);

        _maxSendPacketSize = 0;
        if(System.getProperty("os.name").startsWith("Windows"))
        {
            //
            // On Windows, limiting the buffer size is important to prevent
            // poor throughput performances when transfering large amount of
            // data. See Microsoft KB article KB823764.
            //
            _maxSendPacketSize = Network.getSendBufferSize(_fd) / 2;
            if(_maxSendPacketSize < 512)
            {
                _maxSendPacketSize = 0;
            }
        }
    }

    protected synchronized void
    finalize()
        throws Throwable
    {
        try
        {
            IceUtilInternal.Assert.FinalizerAssert(_fd == null);
        }
        catch(java.lang.Exception ex)
        {
        }
        finally
        {
            super.finalize();
        }
    }

    private java.nio.channels.SocketChannel _fd;
    private NetworkProxy _proxy;
    private java.net.InetSocketAddress _addr;
    private TraceLevels _traceLevels;
    private Ice.Logger _logger;

    private String _desc;
    private int _state;
    private int _maxSendPacketSize;

    private static final int StateNeedConnect = 0;
    private static final int StateConnectPending = 1;
    private static final int StateProxyConnectRequest = 2;
    private static final int StateProxyConnectRequestPending = 3;
    private static final int StateConnected = 4;
}