summaryrefslogtreecommitdiffstats
path: root/src/lib/net/TCPSocket.cpp
blob: 09a8f17e0cfdc6e4cb30f6a767eb43179f781485 (plain) (blame)
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/*
 * barrier -- mouse and keyboard sharing utility
 * Copyright (C) 2012-2016 Symless Ltd.
 * Copyright (C) 2002 Chris Schoeneman
 * 
 * This package is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * found in the file LICENSE that should have accompanied this file.
 * 
 * This package is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "net/TCPSocket.h"

#include "net/NetworkAddress.h"
#include "net/SocketMultiplexer.h"
#include "net/TSocketMultiplexerMethodJob.h"
#include "net/XSocket.h"
#include "mt/Lock.h"
#include "arch/Arch.h"
#include "arch/XArch.h"
#include "base/Log.h"
#include "base/IEventQueue.h"
#include "base/IEventJob.h"

#include <cstring>
#include <cstdlib>
#include <memory>

//
// TCPSocket
//

TCPSocket::TCPSocket(IEventQueue* events, SocketMultiplexer* socketMultiplexer, IArchNetwork::EAddressFamily family) :
    IDataSocket(events),
    m_events(events),
    m_mutex(),
    m_flushed(&m_mutex, true),
    m_socketMultiplexer(socketMultiplexer)
{
    try {
        m_socket = ARCH->newSocket(family, IArchNetwork::kSTREAM);
    }
    catch (XArchNetwork& e) {
        throw XSocketCreate(e.what());
    }

    LOG((CLOG_DEBUG "Opening new socket: %08X", m_socket));

    init();
}

TCPSocket::TCPSocket(IEventQueue* events, SocketMultiplexer* socketMultiplexer, ArchSocket socket) :
    IDataSocket(events),
    m_events(events),
    m_mutex(),
    m_socket(socket),
    m_flushed(&m_mutex, true),
    m_socketMultiplexer(socketMultiplexer)
{
    assert(m_socket != NULL);

    LOG((CLOG_DEBUG "Opening new socket: %08X", m_socket));

    // socket starts in connected state
    init();
    onConnected();
    setJob(newJob());
}

TCPSocket::~TCPSocket()
{
    try {
        close();
    }
    catch (...) {
        // ignore
    }
}

void
TCPSocket::bind(const NetworkAddress& addr)
{
    try {
        ARCH->bindSocket(m_socket, addr.getAddress());
    }
    catch (XArchNetworkAddressInUse& e) {
        throw XSocketAddressInUse(e.what());
    }
    catch (XArchNetwork& e) {
        throw XSocketBind(e.what());
    }
}

void
TCPSocket::close()
{
    LOG((CLOG_DEBUG "Closing socket: %08X", m_socket));

    // remove ourself from the multiplexer
    setJob(NULL);

    Lock lock(&m_mutex);

    // clear buffers and enter disconnected state
    if (m_connected) {
        sendEvent(m_events->forISocket().disconnected());
    }
    onDisconnected();

    // close the socket
    if (m_socket != NULL) {
        ArchSocket socket = m_socket;
        m_socket = NULL;
        try {
            ARCH->closeSocket(socket);
        }
        catch (XArchNetwork& e) {
            // ignore, there's not much we can do
            LOG((CLOG_WARN "error closing socket: %s", e.what()));
        }
    }
}

void*
TCPSocket::getEventTarget() const
{
    return const_cast<void*>(static_cast<const void*>(this));
}

UInt32
TCPSocket::read(void* buffer, UInt32 n)
{
    // copy data directly from our input buffer
    Lock lock(&m_mutex);
    UInt32 size = m_inputBuffer.getSize();
    if (n > size) {
        n = size;
    }
    if (buffer != NULL && n != 0) {
        memcpy(buffer, m_inputBuffer.peek(n), n);
    }
    m_inputBuffer.pop(n);

    // if no more data and we cannot read or write then send disconnected
    if (n > 0 && m_inputBuffer.getSize() == 0 && !m_readable && !m_writable) {
        sendEvent(m_events->forISocket().disconnected());
        m_connected = false;
    }

    return n;
}

void
TCPSocket::write(const void* buffer, UInt32 n)
{
    bool wasEmpty;
    {
        Lock lock(&m_mutex);

        // must not have shutdown output
        if (!m_writable) {
            sendEvent(m_events->forIStream().outputError());
            return;
        }

        // ignore empty writes
        if (n == 0) {
            return;
        }

        // copy data to the output buffer
        wasEmpty = (m_outputBuffer.getSize() == 0);
        m_outputBuffer.write(buffer, n);

        // there's data to write
        m_flushed = false;
    }

    // make sure we're waiting to write
    if (wasEmpty) {
        setJob(newJob());
    }
}

void
TCPSocket::flush()
{
    Lock lock(&m_mutex);
    while (m_flushed == false) {
        m_flushed.wait();
    }
}

void
TCPSocket::shutdownInput()
{
    bool useNewJob = false;
    {
        Lock lock(&m_mutex);

        // shutdown socket for reading
        try {
            ARCH->closeSocketForRead(m_socket);
        }
        catch (XArchNetwork&) {
            // ignore
        }

        // shutdown buffer for reading
        if (m_readable) {
            sendEvent(m_events->forIStream().inputShutdown());
            onInputShutdown();
            useNewJob = true;
        }
    }
    if (useNewJob) {
        setJob(newJob());
    }
}

void
TCPSocket::shutdownOutput()
{
    bool useNewJob = false;
    {
        Lock lock(&m_mutex);

        // shutdown socket for writing
        try {
            ARCH->closeSocketForWrite(m_socket);
        }
        catch (XArchNetwork&) {
            // ignore
        }

        // shutdown buffer for writing
        if (m_writable) {
            sendEvent(m_events->forIStream().outputShutdown());
            onOutputShutdown();
            useNewJob = true;
        }
    }
    if (useNewJob) {
        setJob(newJob());
    }
}

bool
TCPSocket::isReady() const
{
    Lock lock(&m_mutex);
    return (m_inputBuffer.getSize() > 0);
}

bool
TCPSocket::isFatal() const
{
    // TCP sockets aren't ever left in a fatal state.
    LOG((CLOG_ERR "isFatal() not valid for non-secure connections"));
    return false;
}

UInt32
TCPSocket::getSize() const
{
    Lock lock(&m_mutex);
    return m_inputBuffer.getSize();
}

void
TCPSocket::connect(const NetworkAddress& addr)
{
    {
        Lock lock(&m_mutex);

        // fail on attempts to reconnect
        if (m_socket == NULL || m_connected) {
            sendConnectionFailedEvent("busy");
            return;
        }

        try {
            if (ARCH->connectSocket(m_socket, addr.getAddress())) {
                sendEvent(m_events->forIDataSocket().connected());
                onConnected();
            }
            else {
                // connection is in progress
                m_writable = true;
            }
        }
        catch (XArchNetwork& e) {
            throw XSocketConnect(e.what());
        }
    }
    setJob(newJob());
}

void
TCPSocket::init()
{
    // default state
    m_connected = false;
    m_readable  = false;
    m_writable  = false;

    try {
        // turn off Nagle algorithm.  we send lots of very short messages
        // that should be sent without (much) delay.  for example, the
        // mouse motion messages are much less useful if they're delayed.
        ARCH->setNoDelayOnSocket(m_socket, true);
    }
    catch (XArchNetwork& e) {
        try {
            ARCH->closeSocket(m_socket);
            m_socket = NULL;
        }
        catch (XArchNetwork&) {
            // ignore
        }
        throw XSocketCreate(e.what());
    }
}

TCPSocket::EJobResult
TCPSocket::doRead()
{
    UInt8 buffer[4096];
    memset(buffer, 0, sizeof(buffer));
    size_t bytesRead = 0;
    
    bytesRead = ARCH->readSocket(m_socket, buffer, sizeof(buffer));
    
    if (bytesRead > 0) {
        bool wasEmpty = (m_inputBuffer.getSize() == 0);
        
        // slurp up as much as possible
        do {
            m_inputBuffer.write(buffer, (UInt32)bytesRead);

            bytesRead = ARCH->readSocket(m_socket, buffer, sizeof(buffer));
        } while (bytesRead > 0);
        
        // send input ready if input buffer was empty
        if (wasEmpty) {
            sendEvent(m_events->forIStream().inputReady());
        }
    }
    else {
        // remote write end of stream hungup.  our input side
        // has therefore shutdown but don't flush our buffer
        // since there's still data to be read.
        sendEvent(m_events->forIStream().inputShutdown());
        if (!m_writable && m_inputBuffer.getSize() == 0) {
            sendEvent(m_events->forISocket().disconnected());
            m_connected = false;
        }
        m_readable = false;
        return kNew;
    }
    
    return kRetry;
}

TCPSocket::EJobResult
TCPSocket::doWrite()
{
    // write data
    UInt32 bufferSize = 0;
    int bytesWrote = 0;

    bufferSize = m_outputBuffer.getSize();
    const void* buffer = m_outputBuffer.peek(bufferSize);
    bytesWrote = (UInt32)ARCH->writeSocket(m_socket, buffer, bufferSize);

    if (bytesWrote > 0) {
        discardWrittenData(bytesWrote);
        return kNew;
    }
    
    return kRetry;
}

void TCPSocket::removeJob()
{
    // multiplexer will delete the old job
    m_socketMultiplexer->removeSocket(this);
}

void TCPSocket::setJob(std::unique_ptr<ISocketMultiplexerJob>&& job)
{
    if (job.get() == nullptr) {
        removeJob();
    } else {
        m_socketMultiplexer->addSocket(this, std::move(job));
    }
}

MultiplexerJobStatus TCPSocket::newJobOrStopServicing()
{
    auto new_job = newJob();
    if (new_job)
        return {true, std::move(new_job)};
    else
        return {false, {}};
}

std::unique_ptr<ISocketMultiplexerJob> TCPSocket::newJob()
{
    // note -- must have m_mutex locked on entry

    if (m_socket == NULL) {
        return {};
    }
    else if (!m_connected) {
        assert(!m_readable);
        if (!(m_readable || m_writable)) {
            return {};
        }
        return std::make_unique<TSocketMultiplexerMethodJob<TCPSocket>>(
                                this, &TCPSocket::serviceConnecting,
                                m_socket, m_readable, m_writable);
    }
    else {
        if (!(m_readable || (m_writable && (m_outputBuffer.getSize() > 0)))) {
            return {};
        }
        return std::make_unique<TSocketMultiplexerMethodJob<TCPSocket>>(
                                this, &TCPSocket::serviceConnected,
                                m_socket, m_readable,
                                m_writable && (m_outputBuffer.getSize() > 0));
    }
}

void
TCPSocket::sendConnectionFailedEvent(const char* msg)
{
    ConnectionFailedInfo* info = new ConnectionFailedInfo(msg);
    m_events->addEvent(Event(m_events->forIDataSocket().connectionFailed(),
                            getEventTarget(), info, Event::kDontFreeData));
}

void
TCPSocket::sendEvent(Event::Type type)
{
    m_events->addEvent(Event(type, getEventTarget(), NULL));
}

void
TCPSocket::discardWrittenData(int bytesWrote)
{
    m_outputBuffer.pop(bytesWrote);
    if (m_outputBuffer.getSize() == 0) {
        sendEvent(m_events->forIStream().outputFlushed());
        m_flushed = true;
        m_flushed.broadcast();
    }
}

void
TCPSocket::onConnected()
{
    m_connected = true;
    m_readable  = true;
    m_writable  = true;
}

void
TCPSocket::onInputShutdown()
{
    m_inputBuffer.pop(m_inputBuffer.getSize());
    m_readable = false;
}

void
TCPSocket::onOutputShutdown()
{
    m_outputBuffer.pop(m_outputBuffer.getSize());
    m_writable = false;

    // we're now flushed
    m_flushed = true;
    m_flushed.broadcast();
}

void
TCPSocket::onDisconnected()
{
    // disconnected
    onInputShutdown();
    onOutputShutdown();
    m_connected = false;
}

MultiplexerJobStatus TCPSocket::serviceConnecting(ISocketMultiplexerJob* job, bool, bool write, bool error)
{
    Lock lock(&m_mutex);

    // should only check for errors if error is true but checking a new
    // socket (and a socket that's connecting should be new) for errors
    // should be safe and Mac OS X appears to have a bug where a
    // non-blocking stream socket that fails to connect immediately is
    // reported by select as being writable (i.e. connected) even when
    // the connection has failed.  this is easily demonstrated on OS X
    // 10.3.4 by starting a barrier client and telling to connect to
    // another system that's not running a barrier server.  it will
    // claim to have connected then quickly disconnect (i guess because
    // read returns 0 bytes).  unfortunately, barrier attempts to
    // reconnect immediately, the process repeats and we end up
    // spinning the CPU.  luckily, OS X does set SO_ERROR on the
    // socket correctly when the connection has failed so checking for
    // errors works.  (curiously, sometimes OS X doesn't report
    // connection refused.  when that happens it at least doesn't
    // report the socket as being writable so barrier is able to time
    // out the attempt.)
    if (error || true) {
        try {
            // connection may have failed or succeeded
            ARCH->throwErrorOnSocket(m_socket);
        }
        catch (XArchNetwork& e) {
            sendConnectionFailedEvent(e.what());
            onDisconnected();
            return newJobOrStopServicing();
        }
    }

    if (write) {
        sendEvent(m_events->forIDataSocket().connected());
        onConnected();
        return newJobOrStopServicing();
    }

    return {true, {}};
}

MultiplexerJobStatus TCPSocket::serviceConnected(ISocketMultiplexerJob* job,
                                                 bool read, bool write, bool error)
{
    Lock lock(&m_mutex);

    if (error) {
        sendEvent(m_events->forISocket().disconnected());
        onDisconnected();
        return newJobOrStopServicing();
    }

    EJobResult writeResult = kRetry;
    EJobResult readResult = kRetry;
    if (write) {
        try {
            writeResult = doWrite();
        }
        catch (XArchNetworkShutdown&) {
            // remote read end of stream hungup.  our output side
            // has therefore shutdown.
            onOutputShutdown();
            sendEvent(m_events->forIStream().outputShutdown());
            if (!m_readable && m_inputBuffer.getSize() == 0) {
                sendEvent(m_events->forISocket().disconnected());
                m_connected = false;
            }
            writeResult = kNew;
        }
        catch (XArchNetworkDisconnected&) {
            // stream hungup
            onDisconnected();
            sendEvent(m_events->forISocket().disconnected());
            writeResult = kNew;
        }
        catch (XArchNetwork& e) {
            // other write error
            LOG((CLOG_WARN "error writing socket: %s", e.what()));
            onDisconnected();
            sendEvent(m_events->forIStream().outputError());
            sendEvent(m_events->forISocket().disconnected());
            writeResult = kNew;
        }
    }

    if (read && m_readable) {
        try {
            readResult = doRead();
        }
        catch (XArchNetworkDisconnected&) {
            // stream hungup
            sendEvent(m_events->forISocket().disconnected());
            onDisconnected();
            readResult = kNew;
        }
        catch (XArchNetwork& e) {
            // ignore other read error
            LOG((CLOG_WARN "error reading socket: %s", e.what()));
        }
    }

    if (writeResult == kBreak || readResult == kBreak) {
        return {false, {}};
    } else if (writeResult == kNew || readResult == kNew) {
        return newJobOrStopServicing();
    } else {
        return {true, {}};
    }
}