summaryrefslogtreecommitdiff
path: root/java/src/IceInternal/TcpTransceiver.java
blob: d1f0ea8d625c37fffeaa60a06bd71f4462999ea7 (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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
// **********************************************************************
//
// Copyright (c) 2003-2007 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 SocketStatus
    initialize(int timeout)
    {
        if(_state == StateNeedConnect && timeout == 0)
        {
            _state = StateConnectPending;
            return SocketStatus.NeedConnect;
        }
        else if(_state <= StateConnectPending)
        {
            try
            {
                Network.doFinishConnect(_fd, timeout);
                _state = StateConnected;
                _desc = Network.fdToString(_fd);
            }
            catch(Ice.LocalException ex)
            {
                if(_traceLevels.network >= 2)
                {
                    String s = "failed to establish tcp connection\n" + _desc + "\n" + ex;
                    _logger.trace(_traceLevels.networkCat, s);
                }
                throw ex;
            }

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

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

        synchronized(this)
        {
            assert(_fd != null);
            if(_readSelector != null)
            {
                try
                {
                    _readSelector.close();
                }
                catch(java.io.IOException ex)
                {
                    // Ignore.
                }
                _readSelector = null;
            }
            if(_writeSelector != null)
            {
                try
                {
                    _writeSelector.close();
                }
                catch(java.io.IOException ex)
                {
                    // Ignore.
                }
                _writeSelector = null;
            }
            try
            {
                _fd.close();
            }
            catch(java.io.IOException ex)
            {
                Ice.SocketException se = new Ice.SocketException();
                se.initCause(ex);
                throw se;
            }
            finally
            {
                _fd = null;
            }
        }
    }

    public void
    shutdownWrite()
    {
        if(_state < StateConnected)
        {
            return;
        }

        if(_traceLevels.network >= 2)
        {
            String s = "shutting down tcp connection for writing\n" + toString();
            _logger.trace(_traceLevels.networkCat, s);
        }

        assert(_fd != null);
        java.net.Socket socket = _fd.socket();
        try
        {
            socket.shutdownOutput(); // Shutdown socket for writing
        }
        catch(java.net.SocketException ex)
        {
            //
            // Ignore. We can't reliably figure out if the socket
            // exception is because the socket is not connected.
            //
            // if(!Network.notConnected(ex))
            // {
            //     Ice.SocketException se = new Ice.SocketException();
            //     se.initCause(ex);
            //     throw se;
            // }
        }
        catch(java.io.IOException ex)
        {
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
    }

    public void
    shutdownReadWrite()
    {
        if(_state < StateConnected)
        {
            return;
        }

        if(_traceLevels.network >= 2)
        {
            String s = "shutting down tcp connection for reading and writing\n" + toString();
            _logger.trace(_traceLevels.networkCat, s);
        }

        assert(_fd != null);
        java.net.Socket socket = _fd.socket();
        try
        {
            socket.shutdownInput(); // Shutdown socket for reading
            socket.shutdownOutput(); // Shutdown socket for writing
        }
        catch(java.net.SocketException ex)
        {
            //
            // Ignore. We can't reliably figure out if the socket
            // exception is because the socket is not connected.
            //
            // if(!Network.notConnected(ex))
            // {
            //     Ice.SocketException se = new Ice.SocketException();
            //     se.initCause(ex);
            //     throw se;
            // }
        }
        catch(java.io.IOException ex)
        {
            Ice.SocketException se = new Ice.SocketException();
            se.initCause(ex);
            throw se;
        }
    }

    public boolean
    write(Buffer buf, int timeout)
    {
        while(writeBuffer(buf.b))
        {
            //
            // There is more data to write but the socket would block; now we
            // must deal with timeouts.
            //
            assert(buf.b.hasRemaining());

            if(timeout == 0)
            {
                return false;
            }
                    
            try
            {
                if(_writeSelector == null)
                {
                    _writeSelector = java.nio.channels.Selector.open();
                    _fd.register(_writeSelector, java.nio.channels.SelectionKey.OP_WRITE, null);
                }
                
                try
                {
                    if(timeout > 0)
                    {
                        long start = IceInternal.Time.currentMonotonicTimeMillis();
                        int n = _writeSelector.select(timeout);
                        if(n == 0 && IceInternal.Time.currentMonotonicTimeMillis() >= start + timeout)
                        {
                            throw new Ice.TimeoutException();
                        }
                    }
                    else
                    {
                        _writeSelector.select();
                    }
                }
                catch(java.io.InterruptedIOException ex)
                {
                    // Ignore.
                }
            }
            catch(java.io.IOException ex)
            {
                Ice.SocketException se = new Ice.SocketException();
                se.initCause(ex);
                throw se;
            }
        }        
        return true;
    }

    public boolean
    read(Buffer buf, int timeout, Ice.BooleanHolder moreData)
    {
        int remaining = 0;
        if(_traceLevels.network >= 3)
        {
            remaining = 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)
                {
                    if(timeout == 0)
                    {
                        return false;
                    }

                    if(_readSelector == null)
                    {
                        _readSelector = java.nio.channels.Selector.open();
                        _fd.register(_readSelector, java.nio.channels.SelectionKey.OP_READ, null);
                    }
                    
                    try
                    {
                        if(timeout > 0)
                        {
                            long start = IceInternal.Time.currentMonotonicTimeMillis();
                            int n = _readSelector.select(timeout);
                            if(n == 0 && IceInternal.Time.currentMonotonicTimeMillis() >= start + timeout)
                            {
                                throw new Ice.TimeoutException();
                            }
                        }
                        else
                        {
                            _readSelector.select();
                        }
                    }
                    catch(java.io.InterruptedIOException ex)
                    {
                        // Ignore.
                    }

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

                    if(_stats != null)
                    {
                        _stats.bytesReceived(type(), ret);
                    }
                }
            }
            catch(java.io.InterruptedIOException ex)
            {
                continue;
            }
            catch(java.io.IOException ex)
            {
                if(Network.connectionLost(ex))
                {
                    Ice.ConnectionLostException se = new Ice.ConnectionLostException();
                    se.initCause(ex);
                    throw se;
                }
                
                Ice.SocketException se = new Ice.SocketException();
                se.initCause(ex);
                throw se;
            }
        }

        return true;
    }

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

    public String
    toString()
    {
        return _desc;
    }

    public void
    checkSendSize(Buffer buf, int messageSizeMax)
    {
        if(buf.size() > messageSizeMax)
        {
            throw new Ice.MemoryLimitException();
        }
    }

    //
    // Only for use by TcpConnector, TcpAcceptor
    //
    TcpTransceiver(Instance instance, java.nio.channels.SocketChannel fd, boolean connected)
    {
        _fd = fd;
        _traceLevels = instance.traceLevels();
        _logger = instance.initializationData().logger;
        _stats = instance.initializationData().stats;
        _state = connected ? StateConnected : StateNeedConnect;
        _desc = Network.fdToString(_fd);

        _maxPacketSize = 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.
            //
            _maxPacketSize = Network.getSendBufferSize(_fd) / 2;
            if(_maxPacketSize < 512)
            {
                _maxPacketSize = 0;
            }
        }
    }

    protected synchronized void
    finalize()
        throws Throwable
    {
        IceUtilInternal.Assert.FinalizerAssert(_fd == null);

        super.finalize();
    }

    private boolean
    writeBuffer(java.nio.ByteBuffer buf)
    {
        final int size = buf.limit();
        int packetSize = size - buf.position();
        if(_maxPacketSize > 0 && packetSize > _maxPacketSize)
        {
            packetSize = _maxPacketSize;
            buf.limit(buf.position() + packetSize);
        }

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

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

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

                if(_stats != null)
                {
                    _stats.bytesSent(type(), ret);
                }

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

        return false; // No more data to send.
    }

    private java.nio.channels.SocketChannel _fd;
    private TraceLevels _traceLevels;
    private Ice.Logger _logger;
    private Ice.Stats _stats;
    private String _desc;
    private int _state;
    private java.nio.channels.Selector _readSelector;
    private java.nio.channels.Selector _writeSelector;
    private int _maxPacketSize;
    
    private static final int StateNeedConnect = 0;
    private static final int StateConnectPending = 1;
    private static final int StateConnected = 2;
}