File: fake_sockets.cc

package info (click to toggle)
libtoxcore 0.2.22-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,992 kB
  • sloc: ansic: 70,235; cpp: 14,770; sh: 1,576; python: 649; makefile: 255; perl: 39
file content (659 lines) | stat: -rw-r--r-- 18,663 bytes parent folder | download
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
#include "fake_sockets.hh"

#include <algorithm>
#include <cerrno>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <mutex>
#include <vector>

#include "network_universe.hh"

namespace tox::test {

// --- FakeSocket ---

FakeSocket::FakeSocket(NetworkUniverse &universe, int type)
    : universe_(universe)
    , type_(type)
{
    ip_init(&ip_, false);
    ip_.ip.v4.uint32 = net_htonl(0x7F000001);
}

FakeSocket::~FakeSocket() = default;

int FakeSocket::close()
{
    // Override in subclasses to unbind
    return 0;
}

int FakeSocket::getsockopt(int level, int optname, void *_Nonnull optval, size_t *_Nonnull optlen)
{
    return 0;
}
int FakeSocket::setsockopt(int level, int optname, const void *_Nonnull optval, size_t optlen)
{
    return 0;
}
int FakeSocket::socket_nonblock(bool nonblock)
{
    nonblocking_ = nonblock;
    return 0;
}

// --- FakeUdpSocket ---

FakeUdpSocket::FakeUdpSocket(NetworkUniverse &universe)
    : FakeSocket(universe, SOCK_DGRAM)
{
}

FakeUdpSocket::~FakeUdpSocket() { close_impl(); }

int FakeUdpSocket::close()
{
    std::lock_guard<std::mutex> lock(mutex_);
    close_impl();
    return 0;
}

void FakeUdpSocket::close_impl()
{
    if (local_port_ != 0) {
        universe_.unbind_udp(ip_, local_port_);
        local_port_ = 0;
    }
}

int FakeUdpSocket::bind(const IP_Port *_Nonnull addr)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (local_port_ != 0)
        return -1;  // Already bound

    uint16_t port = addr->port;
    if (port == 0) {
        port = universe_.find_free_port(ip_);
    } else {
        port = net_ntohs(port);
    }

    if (universe_.bind_udp(ip_, port, this)) {
        local_port_ = port;
        return 0;
    }
    errno = EADDRINUSE;
    return -1;
}

int FakeUdpSocket::connect(const IP_Port *_Nonnull addr)
{
    // UDP connect just sets default dest.
    // Not strictly needed for toxcore UDP but good for completeness.
    return 0;
}

int FakeUdpSocket::listen(int backlog)
{
    errno = EOPNOTSUPP;
    return -1;
}
std::unique_ptr<FakeSocket> FakeUdpSocket::accept(IP_Port *_Nullable addr)
{
    errno = EOPNOTSUPP;
    return nullptr;
}
int FakeUdpSocket::send(const uint8_t *_Nonnull buf, size_t len)
{
    errno = EDESTADDRREQ;
    return -1;
}
int FakeUdpSocket::recv(uint8_t *_Nonnull buf, size_t len)
{
    errno = EOPNOTSUPP;
    return -1;
}

size_t FakeUdpSocket::recv_buffer_size()
{
    std::lock_guard<std::mutex> lock(mutex_);
    return recv_queue_.size();
}

int FakeUdpSocket::sendto(const uint8_t *_Nonnull buf, size_t len, const IP_Port *_Nonnull addr)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (local_port_ == 0) {
        // Implicit bind
        uint16_t p = universe_.find_free_port(ip_);
        if (universe_.bind_udp(ip_, p, this)) {
            local_port_ = p;
        } else {
            errno = EADDRINUSE;
            return -1;
        }
    }

    Packet p{};
    // Source
    p.from.ip = ip_;
    p.from.port = net_htons(local_port_);
    p.to = *addr;
    p.data.assign(buf, buf + len);
    p.is_tcp = false;

    universe_.send_packet(p);
    if (universe_.is_verbose()) {
        Ip_Ntoa ip_str;
        net_ip_ntoa(&addr->ip, &ip_str);
        std::cerr << "[FakeUdpSocket] sent " << len << " bytes from port " << local_port_ << " to "
                  << ip_str.buf << ":" << net_ntohs(addr->port) << std::endl;
    }
    return len;
}

int FakeUdpSocket::recvfrom(uint8_t *_Nonnull buf, size_t len, IP_Port *_Nonnull addr)
{
    RecvObserver observer_copy;
    std::vector<uint8_t> data_copy;
    IP_Port from_copy;
    size_t copy_len = 0;

    {
        std::lock_guard<std::mutex> lock(mutex_);

        if (recv_queue_.empty() && packet_source_) {
            // NOTE: We call packet_source_ with lock held.
            // Be careful not to call back into socket methods from packet_source_.
            std::vector<uint8_t> data;
            IP_Port from;
            if (packet_source_(data, from)) {
                recv_queue_.push_back({std::move(data), from});
            }
        }

        if (recv_queue_.empty()) {
            errno = EWOULDBLOCK;
            return -1;
        }

        auto &p = recv_queue_.front();
        copy_len = std::min(len, p.data.size());
        std::memcpy(buf, p.data.data(), copy_len);
        *addr = p.from;

        if (recv_observer_) {
            observer_copy = recv_observer_;
            data_copy = p.data;
            from_copy = p.from;
        }

        recv_queue_.pop_front();
    }

    if (observer_copy) {
        observer_copy(data_copy, from_copy);
    }

    if (universe_.is_verbose()) {
        std::cerr << "[FakeUdpSocket] recv " << copy_len << " bytes at port " << local_port_
                  << " from port " << net_ntohs(addr->port) << std::endl;
    }

    return copy_len;
}

void FakeUdpSocket::push_packet(std::vector<uint8_t> data, IP_Port from)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (universe_.is_verbose()) {
        Ip_Ntoa local_ip_str, from_ip_str;
        net_ip_ntoa(&ip_, &local_ip_str);
        net_ip_ntoa(&from.ip, &from_ip_str);

        std::cerr << "[FakeUdpSocket] push " << data.size() << " bytes into queue for "
                  << local_ip_str.buf << ":" << local_port_ << " from " << from_ip_str.buf << ":"
                  << net_ntohs(from.port) << std::endl;
    }
    recv_queue_.push_back({std::move(data), from});
}

void FakeUdpSocket::set_packet_source(PacketSource source)
{
    std::lock_guard<std::mutex> lock(mutex_);
    packet_source_ = std::move(source);
}

void FakeUdpSocket::set_recv_observer(RecvObserver observer)
{
    std::lock_guard<std::mutex> lock(mutex_);
    recv_observer_ = std::move(observer);
}

// --- FakeTcpSocket ---

FakeTcpSocket::FakeTcpSocket(NetworkUniverse &universe)
    : FakeSocket(universe, SOCK_STREAM)
{
    ipport_reset(&remote_addr_);
}

FakeTcpSocket::~FakeTcpSocket() { close_impl(); }

int FakeTcpSocket::close()
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (state_ == ESTABLISHED || state_ == SYN_SENT || state_ == SYN_RECEIVED
        || state_ == CLOSE_WAIT) {
        // Send RST to peer
        Packet p{};
        p.from.ip = ip_;
        p.from.port = net_htons(local_port_);
        p.to = remote_addr_;
        p.is_tcp = true;
        p.tcp_flags = 0x04;  // RST
        universe_.send_packet(p);
    }
    close_impl();
    return 0;
}

void FakeTcpSocket::close_impl()
{
    if (local_port_ != 0) {
        universe_.unbind_tcp(ip_, local_port_, this);
        local_port_ = 0;
    }
    state_ = CLOSED;
}

int FakeTcpSocket::bind(const IP_Port *_Nonnull addr)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (local_port_ != 0)
        return -1;

    uint16_t port = addr->port;
    if (port == 0) {
        port = universe_.find_free_port(ip_);
    } else {
        port = net_ntohs(port);
    }

    if (universe_.bind_tcp(ip_, port, this)) {
        local_port_ = port;
        return 0;
    }
    errno = EADDRINUSE;
    return -1;
}

int FakeTcpSocket::listen(int backlog)
{
    std::lock_guard<std::mutex> lock(mutex_);
    state_ = LISTEN;
    backlog_ = backlog;
    return 0;
}

int FakeTcpSocket::connect(const IP_Port *_Nonnull addr)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (universe_.is_verbose()) {
        Ip_Ntoa ip_str, dest_str;
        net_ip_ntoa(&ip_, &ip_str);
        net_ip_ntoa(&addr->ip, &dest_str);
        std::cerr << "[FakeTcpSocket] connect from " << ip_str.buf << " to " << dest_str.buf << ":"
                  << net_ntohs(addr->port) << std::endl;
    }

    if (local_port_ == 0) {
        // Implicit bind
        uint16_t p = universe_.find_free_port(ip_);
        if (universe_.bind_tcp(ip_, p, this)) {
            local_port_ = p;
            if (universe_.is_verbose()) {
                std::cerr << "[FakeTcpSocket] implicit bind to port " << local_port_ << std::endl;
            }
        } else {
            errno = EADDRINUSE;
            return -1;
        }
    }

    remote_addr_ = *addr;
    state_ = SYN_SENT;

    Packet p{};
    p.from.ip = ip_;
    p.from.port = net_htons(local_port_);
    p.to = *addr;
    p.is_tcp = true;
    p.tcp_flags = 0x02;  // SYN
    p.seq = next_seq_;

    universe_.send_packet(p);

    // Non-blocking connect not fully simulated (we return 0 but state is SYN_SENT).
    // Real connect() blocks or returns EINPROGRESS.
    // For simplicity, we assume the test will pump events until connected.
    errno = EINPROGRESS;
    return -1;
}

std::unique_ptr<FakeSocket> FakeTcpSocket::accept(IP_Port *_Nullable addr)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (state_ != LISTEN) {
        errno = EINVAL;
        return nullptr;
    }

    auto it = std::find_if(pending_connections_.begin(), pending_connections_.end(),
        [](const std::unique_ptr<FakeTcpSocket> &s) { return s->state() == ESTABLISHED; });

    if (it == pending_connections_.end()) {
        errno = EWOULDBLOCK;
        return nullptr;
    }

    auto client = std::move(*it);
    pending_connections_.erase(it);

    if (addr) {
        *addr = client->remote_addr();
    }
    return client;
}

int FakeTcpSocket::send(const uint8_t *_Nonnull buf, size_t len)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (state_ != ESTABLISHED) {
        if (universe_.is_verbose()) {
            std::cerr << "[FakeTcpSocket] send failed: state " << state_ << " port " << local_port_
                      << std::endl;
        }
        if (state_ == SYN_SENT || state_ == SYN_RECEIVED) {
            errno = EWOULDBLOCK;
        } else {
            errno = ENOTCONN;
        }
        return -1;
    }

    // Wrap as TCP packet
    Packet p{};
    // Source
    p.from.ip = ip_;
    p.from.port = net_htons(local_port_);
    p.to = remote_addr_;
    p.data.assign(buf, buf + len);
    p.is_tcp = true;
    p.tcp_flags = 0x10;  // ACK (Data packets usually have ACK)
    p.seq = next_seq_;
    p.ack = last_ack_;

    next_seq_ += len;
    universe_.send_packet(p);
    return len;
}

int FakeTcpSocket::recv(uint8_t *_Nonnull buf, size_t len)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (recv_buffer_.empty()) {
        if (state_ == CLOSED || state_ == CLOSE_WAIT)
            return 0;  // EOF
        errno = EWOULDBLOCK;
        return -1;
    }

    size_t actual = std::min(len, recv_buffer_.size());
    if (universe_.is_verbose() && actual > 0) {
        char remote_ip_str[TOX_INET_ADDRSTRLEN];
        ip_parse_addr(&remote_addr_.ip, remote_ip_str, sizeof(remote_ip_str));
        std::cerr << "[FakeTcpSocket] Port " << local_port_ << " (Peer: " << remote_ip_str << ":"
                  << net_ntohs(remote_addr_.port) << ") recv requested " << len << " got " << actual
                  << " (remaining " << recv_buffer_.size() - actual << ")" << std::endl;
    }
    for (size_t i = 0; i < actual; ++i) {
        buf[i] = recv_buffer_.front();
        recv_buffer_.pop_front();
    }
    return actual;
}

size_t FakeTcpSocket::recv_buffer_size()
{
    std::lock_guard<std::mutex> lock(mutex_);
    return recv_buffer_.size();
}

bool FakeTcpSocket::is_readable()
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (state_ == LISTEN) {
        return std::any_of(pending_connections_.begin(), pending_connections_.end(),
            [](const std::unique_ptr<FakeTcpSocket> &s) { return s->state() == ESTABLISHED; });
    }
    return !recv_buffer_.empty() || state_ == CLOSED || state_ == CLOSE_WAIT;
}

bool FakeTcpSocket::is_writable()
{
    std::lock_guard<std::mutex> lock(mutex_);
    return state_ == ESTABLISHED;
}

int FakeTcpSocket::sendto(const uint8_t *_Nonnull buf, size_t len, const IP_Port *_Nonnull addr)
{
    errno = EOPNOTSUPP;
    return -1;
}
int FakeTcpSocket::recvfrom(uint8_t *_Nonnull buf, size_t len, IP_Port *_Nonnull addr)
{
    errno = EOPNOTSUPP;
    return -1;
}

int FakeTcpSocket::getsockopt(
    int level, int optname, void *_Nonnull optval, size_t *_Nonnull optlen)
{
    if (universe_.is_verbose()) {
        std::cerr << "[FakeTcpSocket] getsockopt level=" << level << " optname=" << optname
                  << " state=" << state_ << std::endl;
    }
    if (level == SOL_SOCKET && optname == SO_ERROR) {
        int error = 0;
        if (state_ == SYN_SENT || state_ == SYN_RECEIVED) {
            error = EINPROGRESS;
        } else if (state_ == CLOSED) {
            error = ECONNREFUSED;
        }

        if (*optlen >= sizeof(int)) {
            *static_cast<int *>(optval) = error;
            *optlen = sizeof(int);
        }
        if (universe_.is_verbose()) {
            std::cerr << "[FakeTcpSocket] getsockopt SO_ERROR returning error=" << error
                      << std::endl;
        }
        return 0;
    }
    return 0;
}

bool FakeTcpSocket::handle_packet(const Packet &p)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (universe_.is_verbose()) {
        char remote_ip_str[TOX_INET_ADDRSTRLEN];
        ip_parse_addr(&remote_addr_.ip, remote_ip_str, sizeof(remote_ip_str));
        std::cerr << "Handle Packet: Port " << local_port_ << " (Peer: " << remote_ip_str << ":"
                  << net_ntohs(remote_addr_.port) << ") Flags " << TcpFlags{p.tcp_flags}
                  << " State " << state_ << " From " << net_ntohs(p.from.port) << std::endl;
    }

    if (state_ != LISTEN) {
        // Filter packets not from our peer
        bool port_match = net_ntohs(p.from.port) == net_ntohs(remote_addr_.port);
        bool ip_match = ip_equal(&p.from.ip, &remote_addr_.ip)
            || (is_loopback(p.from.ip) && ip_equal(&remote_addr_.ip, &ip_))
            || (is_loopback(remote_addr_.ip) && ip_equal(&p.from.ip, &ip_));

        if (!port_match || !ip_match) {
            return false;
        }

        if (p.tcp_flags & 0x04) {  // RST
            state_ = CLOSED;
            if (local_port_ != 0) {
                universe_.unbind_tcp(ip_, local_port_, this);
                local_port_ = 0;
            }
            return true;
        }
    }

    if (state_ == LISTEN) {
        if (p.tcp_flags & 0x02) {  // SYN
            // Check for duplicate SYN from same peer
            for (const auto &pending : pending_connections_) {
                if (ipport_equal(&p.from, &pending->remote_addr_)) {
                    return true;
                }
            }

            // Create new socket for connection
            auto new_sock = std::make_unique<FakeTcpSocket>(universe_);

            new_sock->state_ = SYN_RECEIVED;
            new_sock->remote_addr_ = p.from;
            new_sock->local_port_ = local_port_;
            new_sock->set_ip(ip_);  // Inherit IP from listening socket
            new_sock->last_ack_ = p.seq + 1;
            new_sock->next_seq_ = 1000;  // Random ISN

            universe_.bind_tcp(ip_, local_port_, new_sock.get());

            // Send SYN-ACK
            Packet resp{};
            resp.from = p.to;
            resp.to = p.from;
            resp.is_tcp = true;
            resp.tcp_flags = 0x12;  // SYN | ACK
            resp.seq = new_sock->next_seq_++;
            resp.ack = new_sock->last_ack_;

            universe_.send_packet(resp);

            // Add to pending, but it's still SYN_RECEIVED
            pending_connections_.push_back(std::move(new_sock));
            return true;
        }
    } else if (state_ == SYN_SENT) {
        if ((p.tcp_flags & 0x12) == 0x12) {  // SYN | ACK
            state_ = ESTABLISHED;
            last_ack_ = p.seq + 1;
            next_seq_++;  // Consumer SYN

            // Send ACK
            Packet ack{};
            ack.from = p.to;
            ack.to = p.from;
            ack.is_tcp = true;
            ack.tcp_flags = 0x10;  // ACK
            ack.seq = next_seq_;
            ack.ack = last_ack_;
            universe_.send_packet(ack);
            return true;
        } else if (p.tcp_flags & 0x02) {  // SYN (Simultaneous Open)
            state_ = SYN_RECEIVED;
            last_ack_ = p.seq + 1;

            // Send SYN-ACK
            Packet resp{};
            resp.from = p.to;
            resp.to = p.from;
            resp.is_tcp = true;
            resp.tcp_flags = 0x12;  // SYN | ACK
            resp.seq = next_seq_++;
            resp.ack = last_ack_;
            universe_.send_packet(resp);
            return true;
        }
    } else if (state_ == SYN_RECEIVED) {
        if (p.tcp_flags & 0x10) {  // ACK
            state_ = ESTABLISHED;
        } else {
            return false;
        }
    }

    if (state_ == ESTABLISHED) {
        if (p.tcp_flags & 0x01) {  // FIN
            state_ = CLOSE_WAIT;
            // Send ACK
            Packet ack{};
            ack.from = p.to;
            ack.to = p.from;
            ack.is_tcp = true;
            ack.tcp_flags = 0x10;  // ACK
            ack.seq = next_seq_;
            ack.ack = p.seq + 1;  // Consume FIN
            universe_.send_packet(ack);
            return true;
        } else {
            if (!p.data.empty()) {
                if (universe_.is_verbose()) {
                    char remote_ip_str[TOX_INET_ADDRSTRLEN];
                    ip_parse_addr(&remote_addr_.ip, remote_ip_str, sizeof(remote_ip_str));
                    std::cerr << "[FakeTcpSocket] Port " << local_port_
                              << " (Peer: " << remote_ip_str << ":" << net_ntohs(remote_addr_.port)
                              << ") adding " << p.data.size() << " bytes to buffer (currently "
                              << recv_buffer_.size() << ")" << std::endl;
                }
                recv_buffer_.insert(recv_buffer_.end(), p.data.begin(), p.data.end());
            }
            return true;
        }
    }
    return false;
}

std::unique_ptr<FakeTcpSocket> FakeTcpSocket::create_connected(
    NetworkUniverse &universe, const IP_Port &remote, uint16_t local_port)
{
    auto s = std::make_unique<FakeTcpSocket>(universe);
    s->state_ = ESTABLISHED;
    s->remote_addr_ = remote;
    s->local_port_ = local_port;
    return s;
}

std::ostream &operator<<(std::ostream &os, FakeTcpSocket::State state)
{
    switch (state) {
    case FakeTcpSocket::CLOSED:
        return os << "CLOSED";
    case FakeTcpSocket::LISTEN:
        return os << "LISTEN";
    case FakeTcpSocket::SYN_SENT:
        return os << "SYN_SENT";
    case FakeTcpSocket::SYN_RECEIVED:
        return os << "SYN_RECEIVED";
    case FakeTcpSocket::ESTABLISHED:
        return os << "ESTABLISHED";
    case FakeTcpSocket::CLOSE_WAIT:
        return os << "CLOSE_WAIT";
    }
    return os << "UNKNOWN(" << static_cast<int>(state) << ")";
}

}  // namespace tox::test