1 /* 2 * Copyright 2006-2010, Haiku, Inc. All Rights Reserved. 3 * Distributed under the terms of the MIT License. 4 * 5 * Authors: 6 * Andrew Galante, haiku.galante@gmail.com 7 * Axel Dörfler, axeld@pinc-software.de 8 * Hugo Santos, hugosantos@gmail.com 9 */ 10 11 12 #include "TCPEndpoint.h" 13 14 #include <netinet/in.h> 15 #include <netinet/ip.h> 16 #include <netinet/tcp.h> 17 #include <new> 18 #include <signal.h> 19 #include <stdlib.h> 20 #include <string.h> 21 #include <stdint.h> 22 23 #include <KernelExport.h> 24 #include <Select.h> 25 26 #include <net_buffer.h> 27 #include <net_datalink.h> 28 #include <net_stat.h> 29 #include <NetBufferUtilities.h> 30 #include <NetUtilities.h> 31 32 #include <lock.h> 33 #include <tracing.h> 34 #include <util/AutoLock.h> 35 #include <util/list.h> 36 37 #include "EndpointManager.h" 38 39 40 // References: 41 // - RFC 793 - Transmission Control Protocol 42 // - RFC 813 - Window and Acknowledgement Strategy in TCP 43 // - RFC 1337 - TIME_WAIT Assassination Hazards in TCP 44 // 45 // Things incomplete in this implementation: 46 // - TCP Extensions for High Performance, RFC 1323 - RTTM, PAWS 47 // - Congestion Control, RFC 5681 48 // - Limited Transit, RFC 3042 49 // - SACK, Selective Acknowledgment; RFC 2018, RFC 2883, RFC 6675 50 // - NewReno Modification to TCP's Fast Recovery, RFC 2582 51 // 52 // Things this implementation currently doesn't implement: 53 // - Explicit Congestion Notification (ECN), RFC 3168 54 // - SYN-Cache 55 // - Forward RTO-Recovery, RFC 4138 56 // - Time-Wait hash instead of keeping sockets alive 57 58 #define PrintAddress(address) \ 59 AddressString(Domain(), address, true).Data() 60 61 //#define TRACE_TCP 62 //#define PROBE_TCP 63 64 #ifdef TRACE_TCP 65 // the space before ', ##args' is important in order for this to work with cpp 2.95 66 # define TRACE(format, args...) dprintf("%" B_PRId32 ": TCP [%" \ 67 B_PRIdBIGTIME "] %p (%12s) " format "\n", find_thread(NULL), \ 68 system_time(), this, name_for_state(fState) , ##args) 69 #else 70 # define TRACE(args...) do { } while (0) 71 #endif 72 73 #ifdef PROBE_TCP 74 # define PROBE(buffer, window) \ 75 dprintf("TCP PROBE %" B_PRIdBIGTIME " %s %s %" B_PRIu32 " snxt %" B_PRIu32 \ 76 " suna %" B_PRIu32 " cw %" B_PRIu32 " sst %" B_PRIu32 " win %" \ 77 B_PRIu32 " swin %" B_PRIu32 " smax-suna %" B_PRIu32 " savail %" \ 78 B_PRIuSIZE " sqused %" B_PRIuSIZE " rto %" B_PRIdBIGTIME "\n", \ 79 system_time(), PrintAddress(buffer->source), \ 80 PrintAddress(buffer->destination), buffer->size, fSendNext.Number(), \ 81 fSendUnacknowledged.Number(), fCongestionWindow, fSlowStartThreshold, \ 82 window, fSendWindow, (fSendMax - fSendUnacknowledged).Number(), \ 83 fSendQueue.Available(fSendNext), fSendQueue.Used(), fRetransmitTimeout) 84 #else 85 # define PROBE(buffer, window) do { } while (0) 86 #endif 87 88 #if TCP_TRACING 89 namespace TCPTracing { 90 91 class Receive : public AbstractTraceEntry { 92 public: 93 Receive(TCPEndpoint* endpoint, tcp_segment_header& segment, uint32 window, 94 net_buffer* buffer) 95 : 96 fEndpoint(endpoint), 97 fBuffer(buffer), 98 fBufferSize(buffer->size), 99 fSequence(segment.sequence), 100 fAcknowledge(segment.acknowledge), 101 fWindow(window), 102 fState(endpoint->State()), 103 fFlags(segment.flags) 104 { 105 Initialized(); 106 } 107 108 virtual void AddDump(TraceOutput& out) 109 { 110 out.Print("tcp:%p (%12s) receive buffer %p (%" B_PRIu32 " bytes), " 111 "flags %#" B_PRIx8 ", seq %" B_PRIu32 ", ack %" B_PRIu32 112 ", wnd %" B_PRIu32, fEndpoint, name_for_state(fState), fBuffer, 113 fBufferSize, fFlags, fSequence, fAcknowledge, fWindow); 114 } 115 116 protected: 117 TCPEndpoint* fEndpoint; 118 net_buffer* fBuffer; 119 uint32 fBufferSize; 120 uint32 fSequence; 121 uint32 fAcknowledge; 122 uint32 fWindow; 123 tcp_state fState; 124 uint8 fFlags; 125 }; 126 127 class Send : public AbstractTraceEntry { 128 public: 129 Send(TCPEndpoint* endpoint, tcp_segment_header& segment, net_buffer* buffer, 130 tcp_sequence firstSequence, tcp_sequence lastSequence) 131 : 132 fEndpoint(endpoint), 133 fBuffer(buffer), 134 fBufferSize(buffer->size), 135 fSequence(segment.sequence), 136 fAcknowledge(segment.acknowledge), 137 fFirstSequence(firstSequence.Number()), 138 fLastSequence(lastSequence.Number()), 139 fState(endpoint->State()), 140 fFlags(segment.flags) 141 { 142 Initialized(); 143 } 144 145 virtual void AddDump(TraceOutput& out) 146 { 147 out.Print("tcp:%p (%12s) send buffer %p (%" B_PRIu32 " bytes), " 148 "flags %#" B_PRIx8 ", seq %" B_PRIu32 ", ack %" B_PRIu32 149 ", first %" B_PRIu32 ", last %" B_PRIu32, fEndpoint, 150 name_for_state(fState), fBuffer, fBufferSize, fFlags, fSequence, 151 fAcknowledge, fFirstSequence, fLastSequence); 152 } 153 154 protected: 155 TCPEndpoint* fEndpoint; 156 net_buffer* fBuffer; 157 uint32 fBufferSize; 158 uint32 fSequence; 159 uint32 fAcknowledge; 160 uint32 fFirstSequence; 161 uint32 fLastSequence; 162 tcp_state fState; 163 uint8 fFlags; 164 }; 165 166 class State : public AbstractTraceEntry { 167 public: 168 State(TCPEndpoint* endpoint) 169 : 170 fEndpoint(endpoint), 171 fState(endpoint->State()) 172 { 173 Initialized(); 174 } 175 176 virtual void AddDump(TraceOutput& out) 177 { 178 out.Print("tcp:%p (%12s) state change", fEndpoint, 179 name_for_state(fState)); 180 } 181 182 protected: 183 TCPEndpoint* fEndpoint; 184 tcp_state fState; 185 }; 186 187 class Spawn : public AbstractTraceEntry { 188 public: 189 Spawn(TCPEndpoint* listeningEndpoint, TCPEndpoint* spawnedEndpoint) 190 : 191 fListeningEndpoint(listeningEndpoint), 192 fSpawnedEndpoint(spawnedEndpoint) 193 { 194 Initialized(); 195 } 196 197 virtual void AddDump(TraceOutput& out) 198 { 199 out.Print("tcp:%p spawns %p", fListeningEndpoint, fSpawnedEndpoint); 200 } 201 202 protected: 203 TCPEndpoint* fListeningEndpoint; 204 TCPEndpoint* fSpawnedEndpoint; 205 }; 206 207 class Error : public AbstractTraceEntry { 208 public: 209 Error(TCPEndpoint* endpoint, const char* error, int32 line) 210 : 211 fEndpoint(endpoint), 212 fLine(line), 213 fError(error), 214 fState(endpoint->State()) 215 { 216 Initialized(); 217 } 218 219 virtual void AddDump(TraceOutput& out) 220 { 221 out.Print("tcp:%p (%12s) error at line %" B_PRId32 ": %s", fEndpoint, 222 name_for_state(fState), fLine, fError); 223 } 224 225 protected: 226 TCPEndpoint* fEndpoint; 227 int32 fLine; 228 const char* fError; 229 tcp_state fState; 230 }; 231 232 class TimerSet : public AbstractTraceEntry { 233 public: 234 TimerSet(TCPEndpoint* endpoint, const char* which, bigtime_t timeout) 235 : 236 fEndpoint(endpoint), 237 fWhich(which), 238 fTimeout(timeout), 239 fState(endpoint->State()) 240 { 241 Initialized(); 242 } 243 244 virtual void AddDump(TraceOutput& out) 245 { 246 out.Print("tcp:%p (%12s) %s timer set to %" B_PRIdBIGTIME, fEndpoint, 247 name_for_state(fState), fWhich, fTimeout); 248 } 249 250 protected: 251 TCPEndpoint* fEndpoint; 252 const char* fWhich; 253 bigtime_t fTimeout; 254 tcp_state fState; 255 }; 256 257 class TimerTriggered : public AbstractTraceEntry { 258 public: 259 TimerTriggered(TCPEndpoint* endpoint, const char* which) 260 : 261 fEndpoint(endpoint), 262 fWhich(which), 263 fState(endpoint->State()) 264 { 265 Initialized(); 266 } 267 268 virtual void AddDump(TraceOutput& out) 269 { 270 out.Print("tcp:%p (%12s) %s timer triggered", fEndpoint, 271 name_for_state(fState), fWhich); 272 } 273 274 protected: 275 TCPEndpoint* fEndpoint; 276 const char* fWhich; 277 tcp_state fState; 278 }; 279 280 class APICall : public AbstractTraceEntry { 281 public: 282 APICall(TCPEndpoint* endpoint, const char* which) 283 : 284 fEndpoint(endpoint), 285 fWhich(which), 286 fState(endpoint->State()) 287 { 288 Initialized(); 289 } 290 291 virtual void AddDump(TraceOutput& out) 292 { 293 out.Print("tcp:%p (%12s) api call: %s", fEndpoint, 294 name_for_state(fState), fWhich); 295 } 296 297 protected: 298 TCPEndpoint* fEndpoint; 299 const char* fWhich; 300 tcp_state fState; 301 }; 302 303 } // namespace TCPTracing 304 305 # define T(x) new(std::nothrow) TCPTracing::x 306 #else 307 # define T(x) 308 #endif // TCP_TRACING 309 310 311 // constants for the fFlags field 312 enum { 313 FLAG_OPTION_WINDOW_SCALE = 0x01, 314 FLAG_OPTION_TIMESTAMP = 0x02, 315 // TODO: Should FLAG_NO_RECEIVE apply as well to received connections? 316 // That is, what is expected from accept() after a shutdown() 317 // is performed on a listen()ing socket. 318 FLAG_NO_RECEIVE = 0x04, 319 FLAG_CLOSED = 0x08, 320 FLAG_DELETE_ON_CLOSE = 0x10, 321 FLAG_LOCAL = 0x20, 322 FLAG_RECOVERY = 0x40, 323 FLAG_OPTION_SACK_PERMITTED = 0x80, 324 }; 325 326 327 static const int kTimestampFactor = 1000; 328 // conversion factor between usec system time and msec tcp time 329 330 331 static inline bigtime_t 332 absolute_timeout(bigtime_t timeout) 333 { 334 if (timeout == 0 || timeout == B_INFINITE_TIMEOUT) 335 return timeout; 336 337 return timeout + system_time(); 338 } 339 340 341 static inline status_t 342 posix_error(status_t error) 343 { 344 if (error == B_TIMED_OUT) 345 return B_WOULD_BLOCK; 346 347 return error; 348 } 349 350 351 static inline bool 352 in_window(const tcp_sequence& sequence, const tcp_sequence& receiveNext, 353 uint32 receiveWindow) 354 { 355 return sequence >= receiveNext && sequence < (receiveNext + receiveWindow); 356 } 357 358 359 static inline bool 360 segment_in_sequence(const tcp_segment_header& segment, int size, 361 const tcp_sequence& receiveNext, uint32 receiveWindow) 362 { 363 tcp_sequence sequence(segment.sequence); 364 if (size == 0) { 365 if (receiveWindow == 0) 366 return sequence == receiveNext; 367 return in_window(sequence, receiveNext, receiveWindow); 368 } else { 369 if (receiveWindow == 0) 370 return false; 371 return in_window(sequence, receiveNext, receiveWindow) 372 || in_window(sequence + size - 1, receiveNext, receiveWindow); 373 } 374 } 375 376 377 static inline bool 378 is_writable(tcp_state state) 379 { 380 return state == ESTABLISHED || state == FINISH_RECEIVED; 381 } 382 383 384 static inline bool 385 is_establishing(tcp_state state) 386 { 387 return state == SYNCHRONIZE_SENT || state == SYNCHRONIZE_RECEIVED; 388 } 389 390 391 static inline uint32 tcp_now() 392 { 393 return system_time() / kTimestampFactor; 394 } 395 396 397 static inline uint32 tcp_diff_timestamp(uint32 base) 398 { 399 uint32 now = tcp_now(); 400 401 if (now > base) 402 return now - base; 403 404 return now + UINT_MAX - base; 405 } 406 407 408 static inline bool 409 state_needs_finish(int32 state) 410 { 411 return state == WAIT_FOR_FINISH_ACKNOWLEDGE 412 || state == FINISH_SENT || state == CLOSING; 413 } 414 415 416 // #pragma mark - 417 418 419 TCPEndpoint::TCPEndpoint(net_socket* socket) 420 : 421 ProtocolSocket(socket), 422 fManager(NULL), 423 fOptions(0), 424 fSendWindowShift(0), 425 fReceiveWindowShift(0), 426 fSendUnacknowledged(0), 427 fSendNext(0), 428 fSendMax(0), 429 fSendUrgentOffset(0), 430 fSendWindow(0), 431 fSendMaxWindow(0), 432 fSendMaxSegmentSize(TCP_DEFAULT_MAX_SEGMENT_SIZE), 433 fSendMaxSegments(0), 434 fSendQueue(socket->send.buffer_size), 435 fInitialSendSequence(0), 436 fPreviousHighestAcknowledge(0), 437 fDuplicateAcknowledgeCount(0), 438 fPreviousFlightSize(0), 439 fRecover(0), 440 fRoute(NULL), 441 fReceiveNext(0), 442 fReceiveMaxAdvertised(0), 443 fReceiveWindow(socket->receive.buffer_size), 444 fReceiveMaxSegmentSize(TCP_DEFAULT_MAX_SEGMENT_SIZE), 445 fReceiveQueue(socket->receive.buffer_size), 446 fSmoothedRoundTripTime(0), 447 fRoundTripVariation(0), 448 fSendTime(0), 449 fRoundTripStartSequence(0), 450 fRetransmitTimeout(TCP_INITIAL_RTT), 451 fReceivedTimestamp(0), 452 fCongestionWindow(0), 453 fSlowStartThreshold(0), 454 fState(CLOSED), 455 fFlags(FLAG_OPTION_WINDOW_SCALE | FLAG_OPTION_TIMESTAMP | FLAG_OPTION_SACK_PERMITTED) 456 { 457 // TODO: to be replaced with a real read/write locking strategy! 458 mutex_init(&fLock, "tcp lock"); 459 460 fReceiveCondition.Init(this, "tcp receive"); 461 fSendCondition.Init(this, "tcp send"); 462 463 gStackModule->init_timer(&fPersistTimer, TCPEndpoint::_PersistTimer, this); 464 gStackModule->init_timer(&fRetransmitTimer, TCPEndpoint::_RetransmitTimer, 465 this); 466 gStackModule->init_timer(&fDelayedAcknowledgeTimer, 467 TCPEndpoint::_DelayedAcknowledgeTimer, this); 468 gStackModule->init_timer(&fTimeWaitTimer, TCPEndpoint::_TimeWaitTimer, 469 this); 470 471 T(APICall(this, "constructor")); 472 } 473 474 475 TCPEndpoint::~TCPEndpoint() 476 { 477 mutex_lock(&fLock); 478 479 T(APICall(this, "destructor")); 480 481 _CancelConnectionTimers(); 482 gStackModule->cancel_timer(&fTimeWaitTimer); 483 T(TimerSet(this, "time-wait", -1)); 484 485 if (fManager != NULL) { 486 fManager->Unbind(this); 487 put_endpoint_manager(fManager); 488 } 489 490 mutex_destroy(&fLock); 491 492 // we need to wait for all timers to return 493 gStackModule->wait_for_timer(&fRetransmitTimer); 494 gStackModule->wait_for_timer(&fPersistTimer); 495 gStackModule->wait_for_timer(&fDelayedAcknowledgeTimer); 496 gStackModule->wait_for_timer(&fTimeWaitTimer); 497 498 gDatalinkModule->put_route(Domain(), fRoute); 499 } 500 501 502 status_t 503 TCPEndpoint::InitCheck() const 504 { 505 return B_OK; 506 } 507 508 509 // #pragma mark - protocol API 510 511 512 status_t 513 TCPEndpoint::Open() 514 { 515 TRACE("Open()"); 516 T(APICall(this, "open")); 517 518 status_t status = ProtocolSocket::Open(); 519 if (status < B_OK) 520 return status; 521 522 fManager = get_endpoint_manager(Domain()); 523 if (fManager == NULL) 524 return EAFNOSUPPORT; 525 526 return B_OK; 527 } 528 529 530 status_t 531 TCPEndpoint::Close() 532 { 533 MutexLocker locker(fLock); 534 535 TRACE("Close()"); 536 T(APICall(this, "close")); 537 538 if (fState == LISTEN) 539 delete_sem(fAcceptSemaphore); 540 541 if (fState == SYNCHRONIZE_SENT || fState == LISTEN) { 542 // TODO: what about linger in case of SYNCHRONIZE_SENT? 543 fState = CLOSED; 544 T(State(this)); 545 return B_OK; 546 } 547 548 // handle linger with zero timeout 549 if ((socket->options & SO_LINGER) != 0 && socket->linger == 0) { 550 fState = CLOSED; 551 T(State(this)); 552 return _SendQueued(true); 553 } 554 555 status_t status = _Disconnect(true); 556 if (status != B_OK) 557 return status; 558 559 if ((socket->options & SO_LINGER) != 0) { 560 TRACE("Close(): Lingering for %i secs", socket->linger); 561 562 bigtime_t maximum = absolute_timeout(socket->linger * 1000000LL); 563 564 while (fSendQueue.Used() > 0) { 565 status = _WaitForCondition(fSendCondition, locker, maximum); 566 if (status == B_TIMED_OUT || status == B_WOULD_BLOCK) 567 break; 568 else if (status < B_OK) 569 return status; 570 } 571 572 TRACE("Close(): after waiting, the SendQ was left with %" B_PRIuSIZE 573 " bytes.", fSendQueue.Used()); 574 } 575 return B_OK; 576 } 577 578 579 void 580 TCPEndpoint::Free() 581 { 582 MutexLocker _(fLock); 583 584 TRACE("Free()"); 585 T(APICall(this, "free")); 586 587 if (fState <= SYNCHRONIZE_SENT) 588 return; 589 590 // we are only interested in the timer, not in changing state 591 _EnterTimeWait(); 592 593 fFlags |= FLAG_CLOSED; 594 if ((fFlags & FLAG_DELETE_ON_CLOSE) == 0) { 595 // we'll be freed later when the 2MSL timer expires 596 gSocketModule->acquire_socket(socket); 597 } 598 } 599 600 601 /*! Creates and sends a synchronize packet to /a address, and then waits 602 until the connection has been established or refused. 603 */ 604 status_t 605 TCPEndpoint::Connect(const sockaddr* address) 606 { 607 if (!AddressModule()->is_same_family(address)) 608 return EAFNOSUPPORT; 609 610 MutexLocker locker(fLock); 611 612 TRACE("Connect() on address %s", PrintAddress(address)); 613 T(APICall(this, "connect")); 614 615 if (gStackModule->is_restarted_syscall()) { 616 bigtime_t timeout = gStackModule->restore_syscall_restart_timeout(); 617 status_t status = _WaitForEstablished(locker, timeout); 618 TRACE(" Connect(): Connection complete: %s (timeout was %" 619 B_PRIdBIGTIME ")", strerror(status), timeout); 620 return posix_error(status); 621 } 622 623 // Can only call connect() from CLOSED or LISTEN states 624 // otherwise endpoint is considered already connected 625 if (fState == LISTEN) { 626 // this socket is about to connect; remove pending connections in the backlog 627 gSocketModule->set_max_backlog(socket, 0); 628 } else if (fState == ESTABLISHED) { 629 return EISCONN; 630 } else if (fState != CLOSED) 631 return EALREADY; 632 633 // consider destination address INADDR_ANY as INADDR_LOOPBACK 634 sockaddr_storage _address; 635 if (AddressModule()->is_empty_address(address, false)) { 636 AddressModule()->get_loopback_address((sockaddr *)&_address); 637 // for IPv4 and IPv6 the port is at the same offset 638 ((sockaddr_in &)_address).sin_port = ((sockaddr_in *)address)->sin_port; 639 address = (sockaddr *)&_address; 640 } 641 642 status_t status = _PrepareSendPath(address); 643 if (status < B_OK) 644 return status; 645 646 TRACE(" Connect(): starting 3-way handshake..."); 647 648 fState = SYNCHRONIZE_SENT; 649 T(State(this)); 650 651 // send SYN 652 status = _SendAcknowledge(); 653 if (status != B_OK) { 654 _Close(); 655 return status; 656 } 657 658 // If we are running over Loopback, after _SendQueued() returns we 659 // may be in ESTABLISHED already. 660 if (fState == ESTABLISHED) { 661 TRACE(" Connect() completed after _SendQueued()"); 662 return B_OK; 663 } 664 665 // wait until 3-way handshake is complete (if needed) 666 bigtime_t timeout = min_c(socket->send.timeout, TCP_CONNECTION_TIMEOUT); 667 if (timeout == 0) { 668 // we're a non-blocking socket 669 TRACE(" Connect() delayed, return EINPROGRESS"); 670 return EINPROGRESS; 671 } 672 673 bigtime_t absoluteTimeout = absolute_timeout(timeout); 674 gStackModule->store_syscall_restart_timeout(absoluteTimeout); 675 676 status = _WaitForEstablished(locker, absoluteTimeout); 677 TRACE(" Connect(): Connection complete: %s (timeout was %" B_PRIdBIGTIME 678 ")", strerror(status), timeout); 679 return posix_error(status); 680 } 681 682 683 status_t 684 TCPEndpoint::Accept(struct net_socket** _acceptedSocket) 685 { 686 MutexLocker locker(fLock); 687 688 TRACE("Accept()"); 689 T(APICall(this, "accept")); 690 691 status_t status; 692 bigtime_t timeout = absolute_timeout(socket->receive.timeout); 693 if (gStackModule->is_restarted_syscall()) 694 timeout = gStackModule->restore_syscall_restart_timeout(); 695 else 696 gStackModule->store_syscall_restart_timeout(timeout); 697 698 do { 699 locker.Unlock(); 700 701 status = acquire_sem_etc(fAcceptSemaphore, 1, B_ABSOLUTE_TIMEOUT 702 | B_CAN_INTERRUPT, timeout); 703 if (status != B_OK) { 704 if (status == B_TIMED_OUT && socket->receive.timeout == 0) 705 return B_WOULD_BLOCK; 706 707 return status; 708 } 709 710 locker.Lock(); 711 status = gSocketModule->dequeue_connected(socket, _acceptedSocket); 712 #ifdef TRACE_TCP 713 if (status == B_OK) 714 TRACE(" Accept() returning %p", (*_acceptedSocket)->first_protocol); 715 #endif 716 } while (status != B_OK); 717 718 return status; 719 } 720 721 722 status_t 723 TCPEndpoint::Bind(const sockaddr *address) 724 { 725 if (address == NULL) 726 return B_BAD_VALUE; 727 728 MutexLocker lock(fLock); 729 730 TRACE("Bind() on address %s", PrintAddress(address)); 731 T(APICall(this, "bind")); 732 733 if (fState != CLOSED) 734 return EISCONN; 735 736 return fManager->Bind(this, address); 737 } 738 739 740 status_t 741 TCPEndpoint::Unbind(struct sockaddr *address) 742 { 743 MutexLocker _(fLock); 744 745 TRACE("Unbind()"); 746 T(APICall(this, "unbind")); 747 748 return fManager->Unbind(this); 749 } 750 751 752 status_t 753 TCPEndpoint::Listen(int count) 754 { 755 MutexLocker _(fLock); 756 757 TRACE("Listen()"); 758 T(APICall(this, "listen")); 759 760 if (fState != CLOSED && fState != LISTEN) 761 return B_BAD_VALUE; 762 763 if (fState == CLOSED) { 764 fAcceptSemaphore = create_sem(0, "tcp accept"); 765 if (fAcceptSemaphore < B_OK) 766 return ENOBUFS; 767 768 status_t status = fManager->SetPassive(this); 769 if (status != B_OK) { 770 delete_sem(fAcceptSemaphore); 771 fAcceptSemaphore = -1; 772 return status; 773 } 774 } 775 776 gSocketModule->set_max_backlog(socket, count); 777 778 fState = LISTEN; 779 T(State(this)); 780 return B_OK; 781 } 782 783 784 status_t 785 TCPEndpoint::Shutdown(int direction) 786 { 787 MutexLocker lock(fLock); 788 789 TRACE("Shutdown(%i)", direction); 790 T(APICall(this, "shutdown")); 791 792 if (direction == SHUT_RD || direction == SHUT_RDWR) 793 fFlags |= FLAG_NO_RECEIVE; 794 795 if (direction == SHUT_WR || direction == SHUT_RDWR) { 796 // TODO: That's not correct. After read/write shutting down the socket 797 // one should still be able to read previously arrived data. 798 _Disconnect(false); 799 } 800 801 return B_OK; 802 } 803 804 805 /*! Puts data contained in \a buffer into send buffer */ 806 status_t 807 TCPEndpoint::SendData(net_buffer *buffer) 808 { 809 MutexLocker lock(fLock); 810 811 TRACE("SendData(buffer %p, size %" B_PRIu32 ", flags %#" B_PRIx32 812 ") [total %" B_PRIuSIZE " bytes, has %" B_PRIuSIZE "]", buffer, 813 buffer->size, buffer->flags, fSendQueue.Size(), fSendQueue.Free()); 814 T(APICall(this, "senddata")); 815 816 const uint32 flags = buffer->flags; 817 if ((flags & ~(MSG_DONTWAIT | MSG_OOB | MSG_EOF)) != 0) 818 return EOPNOTSUPP; 819 820 if (fState == CLOSED) 821 return ENOTCONN; 822 if (fState == LISTEN) 823 return EDESTADDRREQ; 824 if (!is_writable(fState) && !is_establishing(fState)) 825 return EPIPE; 826 827 size_t left = buffer->size; 828 829 bigtime_t timeout = 0; 830 if ((flags & MSG_DONTWAIT) == 0) { 831 timeout = absolute_timeout(socket->send.timeout); 832 if (gStackModule->is_restarted_syscall()) 833 timeout = gStackModule->restore_syscall_restart_timeout(); 834 else 835 gStackModule->store_syscall_restart_timeout(timeout); 836 } 837 838 while (left > 0) { 839 while (fSendQueue.Free() < socket->send.low_water_mark) { 840 // initiate a send before waiting 841 _SendQueued(); 842 843 // wait until enough space is available 844 status_t status = _WaitForCondition(fSendCondition, lock, timeout); 845 if (status < B_OK) { 846 TRACE(" SendData() returning %s (%d)", 847 strerror(posix_error(status)), (int)posix_error(status)); 848 return posix_error(status); 849 } 850 851 if (!is_writable(fState) && !is_establishing(fState)) 852 return EPIPE; 853 } 854 855 size_t size = fSendQueue.Free(); 856 if (size < left) { 857 // we need to split the original buffer 858 net_buffer* clone = gBufferModule->clone(buffer, false); 859 // TODO: add offset/size parameter to net_buffer::clone() or 860 // even a move_data() function, as this is a bit inefficient 861 if (clone == NULL) 862 return ENOBUFS; 863 864 status_t status = gBufferModule->trim(clone, size); 865 if (status != B_OK) { 866 gBufferModule->free(clone); 867 return status; 868 } 869 870 gBufferModule->remove_header(buffer, size); 871 left -= size; 872 fSendQueue.Add(clone); 873 } else { 874 left -= buffer->size; 875 fSendQueue.Add(buffer); 876 } 877 } 878 879 TRACE(" SendData(): %" B_PRIuSIZE " bytes used.", fSendQueue.Used()); 880 881 bool force = false; 882 if ((flags & MSG_OOB) != 0) { 883 fSendUrgentOffset = fSendQueue.LastSequence(); 884 // RFC 961 specifies that the urgent offset points to the last 885 // byte of urgent data. However, this is commonly implemented as 886 // here, ie. it points to the first byte after the urgent data. 887 force = true; 888 } 889 if ((flags & MSG_EOF) != 0) 890 _Disconnect(false); 891 892 _SendQueued(force); 893 894 return B_OK; 895 } 896 897 898 ssize_t 899 TCPEndpoint::SendAvailable() 900 { 901 MutexLocker locker(fLock); 902 903 ssize_t available; 904 905 if (is_writable(fState)) 906 available = fSendQueue.Free(); 907 else if (is_establishing(fState)) 908 available = 0; 909 else 910 available = EPIPE; 911 912 TRACE("SendAvailable(): %" B_PRIdSSIZE, available); 913 T(APICall(this, "sendavailable")); 914 return available; 915 } 916 917 918 status_t 919 TCPEndpoint::FillStat(net_stat *stat) 920 { 921 MutexLocker _(fLock); 922 923 strlcpy(stat->state, name_for_state(fState), sizeof(stat->state)); 924 stat->receive_queue_size = fReceiveQueue.Available(); 925 stat->send_queue_size = fSendQueue.Used(); 926 927 return B_OK; 928 } 929 930 931 status_t 932 TCPEndpoint::ReadData(size_t numBytes, uint32 flags, net_buffer** _buffer) 933 { 934 if ((flags & ~(MSG_DONTWAIT | MSG_WAITALL | MSG_PEEK)) != 0) 935 return EOPNOTSUPP; 936 937 MutexLocker locker(fLock); 938 939 TRACE("ReadData(%" B_PRIuSIZE " bytes, flags %#" B_PRIx32 ")", numBytes, 940 flags); 941 T(APICall(this, "readdata")); 942 943 *_buffer = NULL; 944 945 if (fState == CLOSED) { 946 if (socket->error != B_OK) 947 return socket->error; 948 return ENOTCONN; 949 } 950 951 bigtime_t timeout = 0; 952 if ((flags & MSG_DONTWAIT) == 0) { 953 timeout = absolute_timeout(socket->receive.timeout); 954 if (gStackModule->is_restarted_syscall()) 955 timeout = gStackModule->restore_syscall_restart_timeout(); 956 else 957 gStackModule->store_syscall_restart_timeout(timeout); 958 } 959 960 if (fState == SYNCHRONIZE_SENT || fState == SYNCHRONIZE_RECEIVED) { 961 if (flags & MSG_DONTWAIT) 962 return B_WOULD_BLOCK; 963 964 status_t status = _WaitForEstablished(locker, timeout); 965 if (status < B_OK) 966 return posix_error(status); 967 } 968 969 size_t dataNeeded = socket->receive.low_water_mark; 970 971 // When MSG_WAITALL is set then the function should block 972 // until the full amount of data can be returned. 973 if (flags & MSG_WAITALL) 974 dataNeeded = numBytes; 975 976 // TODO: add support for urgent data (MSG_OOB) 977 978 while (true) { 979 if (fState == CLOSING || fState == WAIT_FOR_FINISH_ACKNOWLEDGE 980 || fState == TIME_WAIT) { 981 // ``Connection closing''. 982 if (fReceiveQueue.Available() > 0) 983 break; 984 return B_OK; 985 } 986 987 if (fReceiveQueue.Available() > 0) { 988 if (fReceiveQueue.Available() >= dataNeeded 989 || (fReceiveQueue.PushedData() > 0 990 && fReceiveQueue.PushedData() >= fReceiveQueue.Available())) 991 break; 992 } else if (fState == FINISH_RECEIVED) { 993 // ``If no text is awaiting delivery, the RECEIVE will 994 // get a Connection closing''. 995 return B_OK; 996 } 997 998 if (timeout == 0) 999 return B_WOULD_BLOCK; 1000 1001 if ((fFlags & FLAG_NO_RECEIVE) != 0) 1002 return B_OK; 1003 1004 status_t status = _WaitForCondition(fReceiveCondition, locker, timeout); 1005 if (status < B_OK) { 1006 // The Open Group base specification mentions that EINTR should be 1007 // returned if the recv() is interrupted before _any data_ is 1008 // available. So we actually check if there is data, and if so, 1009 // push it to the user. 1010 if ((status == B_TIMED_OUT || status == B_INTERRUPTED) 1011 && fReceiveQueue.Available() > 0) 1012 break; 1013 1014 return posix_error(status); 1015 } 1016 } 1017 1018 TRACE(" ReadData(): %" B_PRIuSIZE " are available.", 1019 fReceiveQueue.Available()); 1020 1021 if (numBytes < fReceiveQueue.Available()) 1022 fReceiveCondition.NotifyAll(); 1023 1024 bool clone = (flags & MSG_PEEK) != 0; 1025 1026 ssize_t receivedBytes = fReceiveQueue.Get(numBytes, !clone, _buffer); 1027 1028 TRACE(" ReadData(): %" B_PRIuSIZE " bytes kept.", 1029 fReceiveQueue.Available()); 1030 1031 if (fReceiveQueue.Available() == 0 && fState == FINISH_RECEIVED) 1032 socket->receive.low_water_mark = 0; 1033 1034 // if we are opening the window, check if we should send an ACK 1035 if (!clone) 1036 _SendAcknowledge(); 1037 1038 return receivedBytes; 1039 } 1040 1041 1042 ssize_t 1043 TCPEndpoint::ReadAvailable() 1044 { 1045 MutexLocker locker(fLock); 1046 1047 TRACE("ReadAvailable(): %" B_PRIdSSIZE, _AvailableData()); 1048 T(APICall(this, "readavailable")); 1049 1050 return _AvailableData(); 1051 } 1052 1053 1054 status_t 1055 TCPEndpoint::SetSendBufferSize(size_t length) 1056 { 1057 MutexLocker _(fLock); 1058 fSendQueue.SetMaxBytes(length); 1059 return B_OK; 1060 } 1061 1062 1063 status_t 1064 TCPEndpoint::SetReceiveBufferSize(size_t length) 1065 { 1066 MutexLocker _(fLock); 1067 fReceiveQueue.SetMaxBytes(length); 1068 return B_OK; 1069 } 1070 1071 1072 status_t 1073 TCPEndpoint::GetOption(int option, void* _value, int* _length) 1074 { 1075 if (*_length != sizeof(int)) 1076 return B_BAD_VALUE; 1077 1078 int* value = (int*)_value; 1079 1080 switch (option) { 1081 case TCP_NODELAY: 1082 if ((fOptions & TCP_NODELAY) != 0) 1083 *value = 1; 1084 else 1085 *value = 0; 1086 return B_OK; 1087 1088 case TCP_MAXSEG: 1089 *value = fReceiveMaxSegmentSize; 1090 return B_OK; 1091 1092 default: 1093 return B_BAD_VALUE; 1094 } 1095 } 1096 1097 1098 status_t 1099 TCPEndpoint::SetOption(int option, const void* _value, int length) 1100 { 1101 if (option != TCP_NODELAY) 1102 return B_BAD_VALUE; 1103 1104 if (length != sizeof(int)) 1105 return B_BAD_VALUE; 1106 1107 const int* value = (const int*)_value; 1108 1109 MutexLocker _(fLock); 1110 if (*value) 1111 fOptions |= TCP_NODELAY; 1112 else 1113 fOptions &= ~TCP_NODELAY; 1114 1115 return B_OK; 1116 } 1117 1118 1119 // #pragma mark - misc 1120 1121 1122 bool 1123 TCPEndpoint::IsBound() const 1124 { 1125 return !LocalAddress().IsEmpty(true); 1126 } 1127 1128 1129 bool 1130 TCPEndpoint::IsLocal() const 1131 { 1132 return (fFlags & FLAG_LOCAL) != 0; 1133 } 1134 1135 1136 status_t 1137 TCPEndpoint::DelayedAcknowledge() 1138 { 1139 // ACKs "MUST" be generated within 500ms of the first unACKed packet, and 1140 // "SHOULD" be for at least every second full-size segment. (RFC 5681 § 4.2) 1141 1142 bigtime_t delay = TCP_DELAYED_ACKNOWLEDGE_TIMEOUT; 1143 if ((fReceiveNext - fLastAcknowledgeSent) >= (fReceiveMaxSegmentSize * 2)) { 1144 // Trigger an immediate timeout rather than invoking Send directly, 1145 // allowing multiple invocations to be coalesced. 1146 delay = 0; 1147 } else if (gStackModule->is_timer_active(&fDelayedAcknowledgeTimer)) { 1148 return B_OK; 1149 } 1150 1151 gStackModule->set_timer(&fDelayedAcknowledgeTimer, delay); 1152 T(TimerSet(this, "delayed ack", TCP_DELAYED_ACKNOWLEDGE_TIMEOUT)); 1153 return B_OK; 1154 } 1155 1156 1157 void 1158 TCPEndpoint::_StartPersistTimer() 1159 { 1160 gStackModule->set_timer(&fPersistTimer, TCP_PERSIST_TIMEOUT); 1161 T(TimerSet(this, "persist", TCP_PERSIST_TIMEOUT)); 1162 } 1163 1164 1165 void 1166 TCPEndpoint::_EnterTimeWait() 1167 { 1168 TRACE("_EnterTimeWait()"); 1169 1170 if (fState == TIME_WAIT) { 1171 _CancelConnectionTimers(); 1172 } 1173 1174 _UpdateTimeWait(); 1175 } 1176 1177 1178 void 1179 TCPEndpoint::_UpdateTimeWait() 1180 { 1181 gStackModule->set_timer(&fTimeWaitTimer, TCP_MAX_SEGMENT_LIFETIME << 1); 1182 T(TimerSet(this, "time-wait", TCP_MAX_SEGMENT_LIFETIME << 1)); 1183 } 1184 1185 1186 void 1187 TCPEndpoint::_CancelConnectionTimers() 1188 { 1189 gStackModule->cancel_timer(&fRetransmitTimer); 1190 T(TimerSet(this, "retransmit", -1)); 1191 gStackModule->cancel_timer(&fPersistTimer); 1192 T(TimerSet(this, "persist", -1)); 1193 gStackModule->cancel_timer(&fDelayedAcknowledgeTimer); 1194 T(TimerSet(this, "delayed ack", -1)); 1195 } 1196 1197 1198 /*! Sends the FIN flag to the peer when the connection is still open. 1199 Moves the endpoint to the next state depending on where it was. 1200 */ 1201 status_t 1202 TCPEndpoint::_Disconnect(bool closing) 1203 { 1204 tcp_state previousState = fState; 1205 1206 if (fState == SYNCHRONIZE_RECEIVED || fState == ESTABLISHED) 1207 fState = FINISH_SENT; 1208 else if (fState == FINISH_RECEIVED) 1209 fState = WAIT_FOR_FINISH_ACKNOWLEDGE; 1210 else 1211 return B_OK; 1212 1213 T(State(this)); 1214 1215 status_t status = _SendQueued(); 1216 if (status != B_OK) { 1217 fState = previousState; 1218 T(State(this)); 1219 return status; 1220 } 1221 1222 return B_OK; 1223 } 1224 1225 1226 void 1227 TCPEndpoint::_MarkEstablished() 1228 { 1229 fState = ESTABLISHED; 1230 T(State(this)); 1231 1232 gSocketModule->set_connected(socket); 1233 if (gSocketModule->has_parent(socket)) 1234 release_sem_etc(fAcceptSemaphore, 1, B_DO_NOT_RESCHEDULE); 1235 1236 fSendCondition.NotifyAll(); 1237 gSocketModule->notify(socket, B_SELECT_WRITE, fSendQueue.Free()); 1238 } 1239 1240 1241 status_t 1242 TCPEndpoint::_WaitForEstablished(MutexLocker &locker, bigtime_t timeout) 1243 { 1244 // TODO: Checking for CLOSED seems correct, but breaks several neon tests. 1245 // When investigating this, also have a look at _Close() and _HandleReset(). 1246 while (fState < ESTABLISHED/* && fState != CLOSED*/) { 1247 if (socket->error != B_OK) 1248 return socket->error; 1249 1250 status_t status = _WaitForCondition(fSendCondition, locker, timeout); 1251 if (status < B_OK) 1252 return status; 1253 } 1254 1255 return B_OK; 1256 } 1257 1258 1259 // #pragma mark - receive 1260 1261 1262 void 1263 TCPEndpoint::_Close() 1264 { 1265 _CancelConnectionTimers(); 1266 fState = CLOSED; 1267 T(State(this)); 1268 1269 fFlags |= FLAG_DELETE_ON_CLOSE; 1270 1271 fSendCondition.NotifyAll(); 1272 _NotifyReader(); 1273 1274 if (gSocketModule->has_parent(socket)) { 1275 // We still have a parent - obviously, we haven't been accepted yet, 1276 // so no one could ever close us. 1277 _CancelConnectionTimers(); 1278 gSocketModule->set_aborted(socket); 1279 } 1280 } 1281 1282 1283 void 1284 TCPEndpoint::_HandleReset(status_t error) 1285 { 1286 socket->error = error; 1287 _Close(); 1288 1289 gSocketModule->notify(socket, B_SELECT_WRITE, error); 1290 gSocketModule->notify(socket, B_SELECT_ERROR, error); 1291 } 1292 1293 1294 void 1295 TCPEndpoint::_DuplicateAcknowledge(tcp_segment_header &segment) 1296 { 1297 if (fDuplicateAcknowledgeCount == 0) 1298 fPreviousFlightSize = (fSendMax - fSendUnacknowledged).Number(); 1299 1300 if (++fDuplicateAcknowledgeCount < 3) { 1301 if (fSendQueue.Available(fSendMax) != 0 && fSendWindow != 0) { 1302 fSendNext = fSendMax; 1303 fCongestionWindow += fDuplicateAcknowledgeCount * fSendMaxSegmentSize; 1304 _SendQueued(); 1305 TRACE("_DuplicateAcknowledge(): packet sent under limited transmit on receipt of dup ack"); 1306 fCongestionWindow -= fDuplicateAcknowledgeCount * fSendMaxSegmentSize; 1307 } 1308 } 1309 1310 if (fDuplicateAcknowledgeCount == 3) { 1311 if ((segment.acknowledge - 1) > fRecover || (fCongestionWindow > fSendMaxSegmentSize && 1312 (fSendUnacknowledged - fPreviousHighestAcknowledge) <= 4 * fSendMaxSegmentSize)) { 1313 fFlags |= FLAG_RECOVERY; 1314 fRecover = fSendMax.Number() - 1; 1315 fSlowStartThreshold = max_c(fPreviousFlightSize / 2, 2 * fSendMaxSegmentSize); 1316 fCongestionWindow = fSlowStartThreshold + 3 * fSendMaxSegmentSize; 1317 fSendNext = segment.acknowledge; 1318 _SendQueued(); 1319 TRACE("_DuplicateAcknowledge(): packet sent under fast restransmit on the receipt of 3rd dup ack"); 1320 } 1321 } else if (fDuplicateAcknowledgeCount > 3) { 1322 uint32 flightSize = (fSendMax - fSendUnacknowledged).Number(); 1323 if ((fDuplicateAcknowledgeCount - 3) * fSendMaxSegmentSize <= flightSize) 1324 fCongestionWindow += fSendMaxSegmentSize; 1325 if (fSendQueue.Available(fSendMax) != 0) { 1326 fSendNext = fSendMax; 1327 _SendQueued(); 1328 } 1329 } 1330 } 1331 1332 1333 void 1334 TCPEndpoint::_UpdateTimestamps(tcp_segment_header& segment, 1335 size_t segmentLength) 1336 { 1337 if (fFlags & FLAG_OPTION_TIMESTAMP) { 1338 tcp_sequence sequence(segment.sequence); 1339 1340 if (fLastAcknowledgeSent >= sequence 1341 && fLastAcknowledgeSent < (sequence + segmentLength)) 1342 fReceivedTimestamp = segment.timestamp_value; 1343 } 1344 } 1345 1346 1347 ssize_t 1348 TCPEndpoint::_AvailableData() const 1349 { 1350 // TODO: Refer to the FLAG_NO_RECEIVE comment above regarding 1351 // the application of FLAG_NO_RECEIVE in listen()ing 1352 // sockets. 1353 if (fState == LISTEN) 1354 return gSocketModule->count_connected(socket); 1355 if (fState == SYNCHRONIZE_SENT) 1356 return 0; 1357 1358 ssize_t availableData = fReceiveQueue.Available(); 1359 1360 if (availableData == 0 && !_ShouldReceive()) 1361 return ENOTCONN; 1362 if (availableData == 0 && (fState == FINISH_RECEIVED || fState == WAIT_FOR_FINISH_ACKNOWLEDGE)) 1363 return ESHUTDOWN; 1364 return availableData; 1365 } 1366 1367 1368 void 1369 TCPEndpoint::_NotifyReader() 1370 { 1371 fReceiveCondition.NotifyAll(); 1372 gSocketModule->notify(socket, B_SELECT_READ, _AvailableData()); 1373 } 1374 1375 1376 bool 1377 TCPEndpoint::_AddData(tcp_segment_header& segment, net_buffer* buffer) 1378 { 1379 if ((segment.flags & TCP_FLAG_FINISH) != 0) { 1380 // Remember the position of the finish received flag 1381 fFinishReceived = true; 1382 fFinishReceivedAt = segment.sequence + buffer->size; 1383 } 1384 1385 fReceiveQueue.Add(buffer, segment.sequence); 1386 fReceiveNext = fReceiveQueue.NextSequence(); 1387 1388 if (fFinishReceived) { 1389 // Set or reset the finish flag on the current segment 1390 if (fReceiveNext < fFinishReceivedAt) 1391 segment.flags &= ~TCP_FLAG_FINISH; 1392 else 1393 segment.flags |= TCP_FLAG_FINISH; 1394 } 1395 1396 TRACE(" _AddData(): adding data, receive next = %" B_PRIu32 ". Now have %" 1397 B_PRIuSIZE " bytes.", fReceiveNext.Number(), fReceiveQueue.Available()); 1398 1399 if ((segment.flags & TCP_FLAG_PUSH) != 0) 1400 fReceiveQueue.SetPushPointer(); 1401 1402 return fReceiveQueue.Available() > 0; 1403 } 1404 1405 1406 void 1407 TCPEndpoint::_PrepareReceivePath(tcp_segment_header& segment) 1408 { 1409 fInitialReceiveSequence = segment.sequence; 1410 fFinishReceived = false; 1411 1412 // count the received SYN 1413 segment.sequence++; 1414 1415 fReceiveNext = segment.sequence; 1416 fReceiveQueue.SetInitialSequence(segment.sequence); 1417 1418 if ((fOptions & TCP_NOOPT) == 0) { 1419 if (segment.max_segment_size > 0) { 1420 // The maximum size of a segment that a TCP endpoint really sends, 1421 // the "effective send MSS", MUST be the smaller of the send MSS and 1422 // the largest transmission size permitted by the IP layer: 1423 fSendMaxSegmentSize = min_c(segment.max_segment_size, 1424 _MaxSegmentSize(*PeerAddress())); 1425 } 1426 1427 if (segment.options & TCP_HAS_WINDOW_SCALE) { 1428 fFlags |= FLAG_OPTION_WINDOW_SCALE; 1429 fSendWindowShift = segment.window_shift; 1430 } else { 1431 fFlags &= ~FLAG_OPTION_WINDOW_SCALE; 1432 fReceiveWindowShift = 0; 1433 } 1434 1435 if (segment.options & TCP_HAS_TIMESTAMPS) { 1436 fFlags |= FLAG_OPTION_TIMESTAMP; 1437 fReceivedTimestamp = segment.timestamp_value; 1438 } else 1439 fFlags &= ~FLAG_OPTION_TIMESTAMP; 1440 1441 if ((segment.options & TCP_SACK_PERMITTED) == 0) 1442 fFlags &= ~FLAG_OPTION_SACK_PERMITTED; 1443 } 1444 1445 if (fSendMaxSegmentSize > 2190) 1446 fCongestionWindow = 2 * fSendMaxSegmentSize; 1447 else if (fSendMaxSegmentSize > 1095) 1448 fCongestionWindow = 3 * fSendMaxSegmentSize; 1449 else 1450 fCongestionWindow = 4 * fSendMaxSegmentSize; 1451 1452 fSendMaxSegments = fCongestionWindow / fSendMaxSegmentSize; 1453 fSlowStartThreshold = (uint32)segment.advertised_window << fSendWindowShift; 1454 } 1455 1456 1457 bool 1458 TCPEndpoint::_ShouldReceive() const 1459 { 1460 if ((fFlags & FLAG_NO_RECEIVE) != 0) 1461 return false; 1462 1463 return fState == ESTABLISHED || fState == FINISH_SENT 1464 || fState == FINISH_ACKNOWLEDGED || fState == FINISH_RECEIVED; 1465 } 1466 1467 1468 int32 1469 TCPEndpoint::_Spawn(TCPEndpoint* parent, tcp_segment_header& segment, 1470 net_buffer* buffer) 1471 { 1472 MutexLocker _(fLock); 1473 1474 // TODO error checking 1475 ProtocolSocket::Open(); 1476 1477 fState = SYNCHRONIZE_RECEIVED; 1478 T(Spawn(parent, this)); 1479 1480 fManager = parent->fManager; 1481 1482 LocalAddress().SetTo(buffer->destination); 1483 PeerAddress().SetTo(buffer->source); 1484 1485 TRACE("Spawn()"); 1486 1487 // TODO: proper error handling! 1488 if (fManager->BindChild(this) != B_OK) { 1489 T(Error(this, "binding failed", __LINE__)); 1490 return DROP; 1491 } 1492 if (_PrepareSendPath(*PeerAddress()) != B_OK) { 1493 T(Error(this, "prepare send faild", __LINE__)); 1494 return DROP; 1495 } 1496 1497 fOptions = parent->fOptions; 1498 fAcceptSemaphore = parent->fAcceptSemaphore; 1499 1500 _PrepareReceivePath(segment); 1501 1502 // send SYN+ACK 1503 if (_SendAcknowledge() != B_OK) { 1504 T(Error(this, "sending failed", __LINE__)); 1505 return DROP; 1506 } 1507 1508 segment.flags &= ~TCP_FLAG_SYNCHRONIZE; 1509 // we handled this flag now, it must not be set for further processing 1510 1511 return _Receive(segment, buffer); 1512 } 1513 1514 1515 int32 1516 TCPEndpoint::_ListenReceive(tcp_segment_header& segment, net_buffer* buffer) 1517 { 1518 TRACE("ListenReceive()"); 1519 1520 // Essentially, we accept only TCP_FLAG_SYNCHRONIZE in this state, 1521 // but the error behaviour differs 1522 if (segment.flags & TCP_FLAG_RESET) 1523 return DROP; 1524 if (segment.flags & TCP_FLAG_ACKNOWLEDGE) 1525 return DROP | RESET; 1526 if ((segment.flags & TCP_FLAG_SYNCHRONIZE) == 0) 1527 return DROP; 1528 1529 // TODO: drop broadcast/multicast 1530 1531 // spawn new endpoint for accept() 1532 net_socket* newSocket; 1533 if (gSocketModule->spawn_pending_socket(socket, &newSocket) < B_OK) { 1534 T(Error(this, "spawning failed", __LINE__)); 1535 return DROP; 1536 } 1537 1538 return ((TCPEndpoint *)newSocket->first_protocol)->_Spawn(this, 1539 segment, buffer); 1540 } 1541 1542 1543 int32 1544 TCPEndpoint::_SynchronizeSentReceive(tcp_segment_header &segment, 1545 net_buffer *buffer) 1546 { 1547 TRACE("_SynchronizeSentReceive()"); 1548 1549 if ((segment.flags & TCP_FLAG_ACKNOWLEDGE) != 0 1550 && (fInitialSendSequence >= segment.acknowledge 1551 || fSendMax < segment.acknowledge)) 1552 return DROP | RESET; 1553 1554 if (segment.flags & TCP_FLAG_RESET) { 1555 _HandleReset(ECONNREFUSED); 1556 return DROP; 1557 } 1558 1559 if ((segment.flags & TCP_FLAG_SYNCHRONIZE) == 0) 1560 return DROP; 1561 1562 fSendUnacknowledged = segment.acknowledge; 1563 _PrepareReceivePath(segment); 1564 1565 if (segment.flags & TCP_FLAG_ACKNOWLEDGE) { 1566 _MarkEstablished(); 1567 } else { 1568 // simultaneous open 1569 fState = SYNCHRONIZE_RECEIVED; 1570 T(State(this)); 1571 } 1572 1573 segment.flags &= ~TCP_FLAG_SYNCHRONIZE; 1574 // we handled this flag now, it must not be set for further processing 1575 1576 return _Receive(segment, buffer) | IMMEDIATE_ACKNOWLEDGE; 1577 } 1578 1579 1580 int32 1581 TCPEndpoint::_Receive(tcp_segment_header& segment, net_buffer* buffer) 1582 { 1583 // PAWS processing takes precedence over regular TCP acceptability check 1584 if ((fFlags & FLAG_OPTION_TIMESTAMP) != 0 && (segment.flags & TCP_FLAG_RESET) == 0) { 1585 if ((segment.options & TCP_HAS_TIMESTAMPS) == 0) 1586 return DROP; 1587 if ((int32)(fReceivedTimestamp - segment.timestamp_value) > 0 1588 && (fReceivedTimestamp - segment.timestamp_value) <= INT32_MAX) 1589 return DROP | IMMEDIATE_ACKNOWLEDGE; 1590 } 1591 1592 uint32 advertisedWindow = segment.AdvertisedWindow(fSendWindowShift); 1593 size_t segmentLength = buffer->size; 1594 1595 // First, handle the most common case for uni-directional data transfer 1596 // (known as header prediction - the segment must not change the window, 1597 // and must be the expected sequence, and contain no control flags) 1598 1599 if (fState == ESTABLISHED 1600 && segment.AcknowledgeOnly() 1601 && fReceiveNext == segment.sequence 1602 && advertisedWindow > 0 && advertisedWindow == fSendWindow 1603 && fSendNext == fSendMax) { 1604 _UpdateTimestamps(segment, segmentLength); 1605 1606 if (segmentLength == 0) { 1607 // this is a pure acknowledge segment - we're on the sending end 1608 if (fSendUnacknowledged < segment.acknowledge 1609 && fSendMax >= segment.acknowledge) { 1610 _Acknowledged(segment); 1611 return DROP; 1612 } 1613 } else if (segment.acknowledge == fSendUnacknowledged 1614 && fReceiveQueue.IsContiguous() 1615 && fReceiveQueue.Free() >= segmentLength 1616 && (fFlags & FLAG_NO_RECEIVE) == 0) { 1617 if (_AddData(segment, buffer)) 1618 _NotifyReader(); 1619 1620 return KEEP | ((segment.flags & TCP_FLAG_PUSH) != 0 1621 ? IMMEDIATE_ACKNOWLEDGE : ACKNOWLEDGE); 1622 } 1623 } 1624 1625 // The fast path was not applicable, so we continue with the standard 1626 // processing of the incoming segment 1627 1628 ASSERT(fState != SYNCHRONIZE_SENT && fState != LISTEN); 1629 1630 if (fState != CLOSED && fState != TIME_WAIT) { 1631 // Check sequence number 1632 if (!segment_in_sequence(segment, segmentLength, fReceiveNext, 1633 fReceiveWindow)) { 1634 TRACE(" Receive(): segment out of window, next: %" B_PRIu32 1635 " wnd: %" B_PRIu32, fReceiveNext.Number(), fReceiveWindow); 1636 if ((segment.flags & TCP_FLAG_RESET) != 0) { 1637 // TODO: this doesn't look right - review! 1638 return DROP; 1639 } 1640 return DROP | IMMEDIATE_ACKNOWLEDGE; 1641 } 1642 } 1643 1644 if ((segment.flags & TCP_FLAG_RESET) != 0) { 1645 // Is this a valid reset? 1646 // We generally ignore resets in time wait state (see RFC 1337) 1647 if (fLastAcknowledgeSent <= segment.sequence 1648 && tcp_sequence(segment.sequence) < (fLastAcknowledgeSent 1649 + fReceiveWindow) 1650 && fState != TIME_WAIT) { 1651 status_t error; 1652 if (fState == SYNCHRONIZE_RECEIVED) 1653 error = ECONNREFUSED; 1654 else if (fState == CLOSING || fState == WAIT_FOR_FINISH_ACKNOWLEDGE) 1655 error = ENOTCONN; 1656 else 1657 error = ECONNRESET; 1658 1659 _HandleReset(error); 1660 } 1661 1662 return DROP; 1663 } 1664 1665 if ((segment.flags & TCP_FLAG_SYNCHRONIZE) != 0 1666 || (fState == SYNCHRONIZE_RECEIVED 1667 && (fInitialReceiveSequence > segment.sequence 1668 || ((segment.flags & TCP_FLAG_ACKNOWLEDGE) != 0 1669 && (fSendUnacknowledged > segment.acknowledge 1670 || fSendMax < segment.acknowledge))))) { 1671 // reset the connection - either the initial SYN was faulty, or we 1672 // received a SYN within the data stream 1673 return DROP | RESET; 1674 } 1675 1676 // TODO: Check this! Why do we advertize a window outside of what we should 1677 // buffer? 1678 fReceiveWindow = max_c(fReceiveQueue.Free(), fReceiveWindow); 1679 // the window must not shrink 1680 1681 // trim buffer to be within the receive window 1682 int32 drop = (int32)(fReceiveNext - segment.sequence).Number(); 1683 if (drop > 0) { 1684 if ((uint32)drop > buffer->size 1685 || ((uint32)drop == buffer->size 1686 && (segment.flags & TCP_FLAG_FINISH) == 0)) { 1687 // don't accidently remove a FIN we shouldn't remove 1688 segment.flags &= ~TCP_FLAG_FINISH; 1689 drop = buffer->size; 1690 } 1691 1692 // remove duplicate data at the start 1693 TRACE("* remove %" B_PRId32 " bytes from the start", drop); 1694 gBufferModule->remove_header(buffer, drop); 1695 segment.sequence += drop; 1696 } 1697 1698 int32 action = KEEP; 1699 1700 // immediately acknowledge out-of-order segment to trigger fast-retransmit at the sender 1701 if (drop != 0) 1702 action |= IMMEDIATE_ACKNOWLEDGE; 1703 1704 drop = (int32)(segment.sequence + buffer->size 1705 - (fReceiveNext + fReceiveWindow)).Number(); 1706 if (drop > 0) { 1707 // remove data exceeding our window 1708 if ((uint32)drop >= buffer->size) { 1709 // if we can accept data, or the segment is not what we'd expect, 1710 // drop the segment (an immediate acknowledge is always triggered) 1711 if (fReceiveWindow != 0 || segment.sequence != fReceiveNext) 1712 return DROP | IMMEDIATE_ACKNOWLEDGE; 1713 1714 action |= IMMEDIATE_ACKNOWLEDGE; 1715 } 1716 1717 if ((segment.flags & TCP_FLAG_FINISH) != 0) { 1718 // we need to remove the finish, too, as part of the data 1719 drop--; 1720 } 1721 1722 segment.flags &= ~(TCP_FLAG_FINISH | TCP_FLAG_PUSH); 1723 TRACE("* remove %" B_PRId32 " bytes from the end", drop); 1724 gBufferModule->remove_trailer(buffer, drop); 1725 } 1726 1727 #ifdef TRACE_TCP 1728 if (advertisedWindow > fSendWindow) { 1729 TRACE(" Receive(): Window update %" B_PRIu32 " -> %" B_PRIu32, 1730 fSendWindow, advertisedWindow); 1731 } 1732 #endif 1733 1734 if (fSendWindow < fSendMaxSegmentSize 1735 && advertisedWindow >= fSendMaxSegmentSize) { 1736 // Our current send window is less than a segment wide, and the new one 1737 // is larger, so trigger a send in case there's anything to be sent. 1738 action |= SEND_QUEUED; 1739 } 1740 1741 fSendWindow = advertisedWindow; 1742 if (advertisedWindow > fSendMaxWindow) 1743 fSendMaxWindow = advertisedWindow; 1744 1745 // Then look at the acknowledgement for any updates 1746 1747 if ((segment.flags & TCP_FLAG_ACKNOWLEDGE) != 0) { 1748 // process acknowledged data 1749 if (fState == SYNCHRONIZE_RECEIVED) 1750 _MarkEstablished(); 1751 1752 if (fSendMax < segment.acknowledge) 1753 return DROP | IMMEDIATE_ACKNOWLEDGE; 1754 1755 if (segment.acknowledge == fSendUnacknowledged) { 1756 if (buffer->size == 0 && advertisedWindow == fSendWindow 1757 && (segment.flags & TCP_FLAG_FINISH) == 0 && fSendUnacknowledged != fSendMax) { 1758 TRACE("Receive(): duplicate ack!"); 1759 _DuplicateAcknowledge(segment); 1760 } 1761 } else if (segment.acknowledge < fSendUnacknowledged) { 1762 return DROP; 1763 } else { 1764 // this segment acknowledges in flight data 1765 1766 if (fDuplicateAcknowledgeCount >= 3) { 1767 // deflate the window. 1768 if (segment.acknowledge > fRecover) { 1769 uint32 flightSize = (fSendMax - fSendUnacknowledged).Number(); 1770 fCongestionWindow = min_c(fSlowStartThreshold, 1771 max_c(flightSize, fSendMaxSegmentSize) + fSendMaxSegmentSize); 1772 fFlags &= ~FLAG_RECOVERY; 1773 } 1774 } 1775 1776 if (fSendMax == segment.acknowledge) 1777 TRACE("Receive(): all inflight data ack'd!"); 1778 1779 if (segment.acknowledge > fSendQueue.LastSequence() 1780 && fState > ESTABLISHED) { 1781 TRACE("Receive(): FIN has been acknowledged!"); 1782 1783 switch (fState) { 1784 case FINISH_SENT: 1785 fState = FINISH_ACKNOWLEDGED; 1786 T(State(this)); 1787 break; 1788 case CLOSING: 1789 fState = TIME_WAIT; 1790 T(State(this)); 1791 _EnterTimeWait(); 1792 return DROP; 1793 case WAIT_FOR_FINISH_ACKNOWLEDGE: 1794 _Close(); 1795 break; 1796 1797 default: 1798 break; 1799 } 1800 } 1801 1802 if (fState != CLOSED) { 1803 tcp_sequence last = fLastAcknowledgeSent; 1804 _Acknowledged(segment); 1805 // we just sent an acknowledge, remove from action 1806 if (last < fLastAcknowledgeSent) 1807 action &= ~IMMEDIATE_ACKNOWLEDGE; 1808 } 1809 } 1810 } 1811 1812 if (segment.flags & TCP_FLAG_URGENT) { 1813 if (fState == ESTABLISHED || fState == FINISH_SENT 1814 || fState == FINISH_ACKNOWLEDGED) { 1815 // TODO: Handle urgent data: 1816 // - RCV.UP <- max(RCV.UP, SEG.UP) 1817 // - signal the user that urgent data is available (SIGURG) 1818 } 1819 } 1820 1821 bool notify = false; 1822 1823 // The buffer may be freed if its data is added to the queue, so cache 1824 // the size as we still need it later. 1825 const uint32 bufferSize = buffer->size; 1826 1827 if ((bufferSize > 0 || (segment.flags & TCP_FLAG_FINISH) != 0) 1828 && _ShouldReceive()) 1829 notify = _AddData(segment, buffer); 1830 else { 1831 if ((fFlags & FLAG_NO_RECEIVE) != 0) 1832 fReceiveNext += buffer->size; 1833 1834 action = (action & ~KEEP) | DROP; 1835 } 1836 1837 if ((segment.flags & TCP_FLAG_FINISH) != 0) { 1838 segmentLength++; 1839 if (fState != CLOSED && fState != LISTEN && fState != SYNCHRONIZE_SENT) { 1840 TRACE("Receive(): peer is finishing connection!"); 1841 fReceiveNext++; 1842 notify = true; 1843 1844 // FIN implies PUSH 1845 fReceiveQueue.SetPushPointer(); 1846 1847 // we'll reply immediately to the FIN if we are not 1848 // transitioning to TIME WAIT so we immediatly ACK it. 1849 action |= IMMEDIATE_ACKNOWLEDGE; 1850 1851 // other side is closing connection; change states 1852 switch (fState) { 1853 case ESTABLISHED: 1854 case SYNCHRONIZE_RECEIVED: 1855 fState = FINISH_RECEIVED; 1856 T(State(this)); 1857 break; 1858 case FINISH_SENT: 1859 // simultaneous close 1860 fState = CLOSING; 1861 T(State(this)); 1862 break; 1863 case FINISH_ACKNOWLEDGED: 1864 fState = TIME_WAIT; 1865 T(State(this)); 1866 _EnterTimeWait(); 1867 break; 1868 case TIME_WAIT: 1869 _UpdateTimeWait(); 1870 break; 1871 1872 default: 1873 break; 1874 } 1875 } 1876 } 1877 1878 if (notify) 1879 _NotifyReader(); 1880 1881 if (bufferSize > 0 || (segment.flags & TCP_FLAG_SYNCHRONIZE) != 0) 1882 action |= ACKNOWLEDGE; 1883 1884 _UpdateTimestamps(segment, segmentLength); 1885 1886 TRACE("Receive() Action %" B_PRId32, action); 1887 1888 return action; 1889 } 1890 1891 1892 int32 1893 TCPEndpoint::SegmentReceived(tcp_segment_header& segment, net_buffer* buffer) 1894 { 1895 MutexLocker locker(fLock); 1896 1897 TRACE("SegmentReceived(): buffer %p (%" B_PRIu32 " bytes) address %s " 1898 "to %s flags %#" B_PRIx8 ", seq %" B_PRIu32 ", ack %" B_PRIu32 1899 ", wnd %" B_PRIu32, buffer, buffer->size, PrintAddress(buffer->source), 1900 PrintAddress(buffer->destination), segment.flags, segment.sequence, 1901 segment.acknowledge, 1902 (uint32)segment.advertised_window << fSendWindowShift); 1903 T(Receive(this, segment, 1904 (uint32)segment.advertised_window << fSendWindowShift, buffer)); 1905 int32 segmentAction = DROP; 1906 1907 switch (fState) { 1908 case LISTEN: 1909 segmentAction = _ListenReceive(segment, buffer); 1910 break; 1911 1912 case SYNCHRONIZE_SENT: 1913 segmentAction = _SynchronizeSentReceive(segment, buffer); 1914 break; 1915 1916 case SYNCHRONIZE_RECEIVED: 1917 case ESTABLISHED: 1918 case FINISH_RECEIVED: 1919 case WAIT_FOR_FINISH_ACKNOWLEDGE: 1920 case FINISH_SENT: 1921 case FINISH_ACKNOWLEDGED: 1922 case CLOSING: 1923 case TIME_WAIT: 1924 case CLOSED: 1925 segmentAction = _Receive(segment, buffer); 1926 break; 1927 } 1928 1929 // process acknowledge action as asked for by the *Receive() method 1930 if (segmentAction & IMMEDIATE_ACKNOWLEDGE) 1931 _SendAcknowledge(true); 1932 else if (segmentAction & ACKNOWLEDGE) 1933 DelayedAcknowledge(); 1934 1935 if (segmentAction & SEND_QUEUED) 1936 _SendQueued(); 1937 1938 if ((fFlags & (FLAG_CLOSED | FLAG_DELETE_ON_CLOSE)) 1939 == (FLAG_CLOSED | FLAG_DELETE_ON_CLOSE)) { 1940 1941 locker.Unlock(); 1942 if (gSocketModule->release_socket(socket)) 1943 segmentAction |= DELETED_ENDPOINT; 1944 } 1945 1946 return segmentAction; 1947 } 1948 1949 1950 // #pragma mark - send 1951 1952 1953 tcp_segment_header 1954 TCPEndpoint::_PrepareSendSegment() 1955 { 1956 // we don't set FLAG_FINISH here, instead we do it 1957 // conditionally below depending if we are sending 1958 // the last bytes of the send queue. 1959 1960 uint8 flags = 0; 1961 switch (fState) { 1962 case CLOSED: 1963 flags = TCP_FLAG_RESET | TCP_FLAG_ACKNOWLEDGE; 1964 break; 1965 1966 case SYNCHRONIZE_SENT: 1967 flags = TCP_FLAG_SYNCHRONIZE; 1968 break; 1969 1970 case SYNCHRONIZE_RECEIVED: 1971 flags = TCP_FLAG_SYNCHRONIZE | TCP_FLAG_ACKNOWLEDGE; 1972 break; 1973 1974 case ESTABLISHED: 1975 case FINISH_RECEIVED: 1976 case FINISH_ACKNOWLEDGED: 1977 case TIME_WAIT: 1978 case WAIT_FOR_FINISH_ACKNOWLEDGE: 1979 case FINISH_SENT: 1980 case CLOSING: 1981 flags = TCP_FLAG_ACKNOWLEDGE; 1982 1983 default: 1984 break; 1985 } 1986 1987 tcp_segment_header segment(flags); 1988 1989 if ((fOptions & TCP_NOOPT) == 0) { 1990 if ((fFlags & FLAG_OPTION_TIMESTAMP) != 0) { 1991 segment.options |= TCP_HAS_TIMESTAMPS; 1992 segment.timestamp_reply = fReceivedTimestamp; 1993 segment.timestamp_value = tcp_now(); 1994 } 1995 1996 if ((segment.flags & TCP_FLAG_SYNCHRONIZE) != 0 1997 && fSendNext == fInitialSendSequence) { 1998 // add connection establishment options 1999 segment.max_segment_size = fReceiveMaxSegmentSize; 2000 if (fFlags & FLAG_OPTION_WINDOW_SCALE) { 2001 segment.options |= TCP_HAS_WINDOW_SCALE; 2002 segment.window_shift = fReceiveWindowShift; 2003 } 2004 if ((fFlags & FLAG_OPTION_SACK_PERMITTED) != 0) 2005 segment.options |= TCP_SACK_PERMITTED; 2006 } 2007 2008 if (!fReceiveQueue.IsContiguous() 2009 && (fFlags & FLAG_OPTION_SACK_PERMITTED) != 0) { 2010 segment.options |= TCP_HAS_SACK; 2011 int maxSackCount = MAX_SACK_BLKS 2012 - ((fFlags & FLAG_OPTION_TIMESTAMP) != 0) ? 1 : 0; 2013 memset(segment.sacks, 0, sizeof(segment.sacks)); 2014 segment.sackCount = fReceiveQueue.PopulateSackInfo(fReceiveNext, 2015 maxSackCount, segment.sacks); 2016 } 2017 } 2018 2019 size_t availableBytes = fReceiveQueue.Free(); 2020 // window size must remain same for duplicate acknowledgements 2021 if (!fReceiveQueue.IsContiguous()) 2022 availableBytes = (fReceiveMaxAdvertised - fReceiveNext).Number(); 2023 segment.SetAdvertisedWindow(availableBytes, fReceiveWindowShift); 2024 2025 segment.acknowledge = fReceiveNext.Number(); 2026 2027 // Process urgent data 2028 if (fSendUrgentOffset > fSendNext) { 2029 segment.flags |= TCP_FLAG_URGENT; 2030 segment.urgent_offset = (fSendUrgentOffset - fSendNext).Number(); 2031 } else { 2032 fSendUrgentOffset = fSendUnacknowledged.Number(); 2033 // Keep urgent offset updated, so that it doesn't reach into our 2034 // send window on overlap 2035 segment.urgent_offset = 0; 2036 } 2037 2038 return segment; 2039 } 2040 2041 2042 status_t 2043 TCPEndpoint::_PrepareAndSend(tcp_segment_header& segment, net_buffer* buffer, 2044 bool isRetransmit) 2045 { 2046 LocalAddress().CopyTo(buffer->source); 2047 PeerAddress().CopyTo(buffer->destination); 2048 2049 uint32 size = buffer->size, segmentLength = size; 2050 segment.sequence = fSendNext.Number(); 2051 2052 TRACE("_PrepareAndSend(): buffer %p (%" B_PRIu32 " bytes) address %s to " 2053 "%s flags %#" B_PRIx8 ", seq %" B_PRIu32 ", ack %" B_PRIu32 2054 ", rwnd %" B_PRIu16 ", cwnd %" B_PRIu32 ", ssthresh %" B_PRIu32 2055 ", len %" B_PRIu32 ", first %" B_PRIu32 ", last %" B_PRIu32, 2056 buffer, buffer->size, PrintAddress(buffer->source), 2057 PrintAddress(buffer->destination), segment.flags, segment.sequence, 2058 segment.acknowledge, segment.advertised_window, 2059 fCongestionWindow, fSlowStartThreshold, segmentLength, 2060 fSendQueue.FirstSequence().Number(), 2061 fSendQueue.LastSequence().Number()); 2062 T(Send(this, segment, buffer, fSendQueue.FirstSequence(), 2063 fSendQueue.LastSequence())); 2064 2065 PROBE(buffer, sendWindow); 2066 2067 status_t status = add_tcp_header(AddressModule(), segment, buffer); 2068 if (status != B_OK) { 2069 gBufferModule->free(buffer); 2070 return status; 2071 } 2072 2073 if (segment.flags & TCP_FLAG_SYNCHRONIZE) { 2074 segment.options &= ~TCP_HAS_WINDOW_SCALE; 2075 segment.max_segment_size = 0; 2076 size++; 2077 } 2078 2079 if (segment.flags & TCP_FLAG_FINISH) 2080 size++; 2081 2082 status = next->module->send_routed_data(next, fRoute, buffer); 2083 if (status < B_OK) { 2084 gBufferModule->free(buffer); 2085 return status; 2086 } 2087 2088 fSendNext += size; 2089 if (fSendMax < fSendNext) 2090 fSendMax = fSendNext; 2091 2092 fReceiveMaxAdvertised = fReceiveNext + segment.AdvertisedWindow(fReceiveWindowShift); 2093 2094 if (segmentLength != 0 && fState == ESTABLISHED) 2095 --fSendMaxSegments; 2096 2097 if (fSendTime == 0 && !isRetransmit 2098 && (segmentLength != 0 || (segment.flags & TCP_FLAG_SYNCHRONIZE) != 0)) { 2099 fSendTime = tcp_now(); 2100 fRoundTripStartSequence = segment.sequence; 2101 } 2102 2103 if (segment.flags & TCP_FLAG_ACKNOWLEDGE) { 2104 fLastAcknowledgeSent = segment.acknowledge; 2105 gStackModule->cancel_timer(&fDelayedAcknowledgeTimer); 2106 } 2107 2108 return B_OK; 2109 } 2110 2111 2112 inline bool 2113 TCPEndpoint::_ShouldSendSegment(tcp_segment_header& segment, uint32 length, 2114 uint32 segmentMaxSize, uint32 flightSize) 2115 { 2116 if (fState == ESTABLISHED && fSendMaxSegments == 0) 2117 return false; 2118 2119 if (length > 0) { 2120 // Avoid the silly window syndrome - we only send a segment in case: 2121 // - we have a full segment to send, or 2122 // - we're at the end of our buffer queue, or 2123 // - the buffer is at least larger than half of the maximum send window, 2124 // or 2125 // - we're retransmitting data 2126 if (length == segmentMaxSize 2127 || (fOptions & TCP_NODELAY) != 0 2128 || tcp_sequence(fSendNext + length) == fSendQueue.LastSequence() 2129 || (fSendMaxWindow > 0 && length >= fSendMaxWindow / 2)) 2130 return true; 2131 } 2132 2133 // check if we need to send a window update to the peer 2134 if (segment.advertised_window > 0) { 2135 // correct the window to take into account what already has been advertised 2136 uint32 window = segment.AdvertisedWindow(fReceiveWindowShift) 2137 - (fReceiveMaxAdvertised - fReceiveNext).Number(); 2138 2139 // if we can advertise a window larger than twice the maximum segment 2140 // size, or half the maximum buffer size we send a window update 2141 if (window >= (fReceiveMaxSegmentSize << 1) 2142 || window >= (socket->receive.buffer_size >> 1)) 2143 return true; 2144 } 2145 2146 if ((segment.flags & (TCP_FLAG_SYNCHRONIZE | TCP_FLAG_FINISH 2147 | TCP_FLAG_RESET)) != 0) 2148 return true; 2149 2150 // We do have urgent data pending 2151 if (fSendUrgentOffset > fSendNext) 2152 return true; 2153 2154 // there is no reason to send a segment just now 2155 return false; 2156 } 2157 2158 2159 status_t 2160 TCPEndpoint::_SendAcknowledge(bool force) 2161 { 2162 if (fRoute == NULL || fState == LISTEN) 2163 return B_ERROR; 2164 2165 tcp_segment_header segment = _PrepareSendSegment(); 2166 2167 // Is there actually anything to do? 2168 if (!force && fState == ESTABLISHED 2169 && fLastAcknowledgeSent == fReceiveNext 2170 && fReceiveQueue.IsContiguous() 2171 && !_ShouldSendSegment(segment, 0, 0, 0)) 2172 return B_OK; 2173 2174 net_buffer* buffer = gBufferModule->create(256); 2175 if (buffer == NULL) 2176 return B_NO_MEMORY; 2177 2178 return _PrepareAndSend(segment, buffer, false); 2179 } 2180 2181 2182 /*! Sends one or more TCP segments with the data waiting in the queue. */ 2183 status_t 2184 TCPEndpoint::_SendQueued(bool force) 2185 { 2186 if (fRoute == NULL || fState < ESTABLISHED) 2187 return B_ERROR; 2188 2189 tcp_segment_header segment = _PrepareSendSegment(); 2190 2191 uint32 sendWindow = fSendWindow; 2192 if (fCongestionWindow > 0 && fCongestionWindow < sendWindow) 2193 sendWindow = fCongestionWindow; 2194 2195 // fSendUnacknowledged 2196 // | fSendNext fSendMax 2197 // | | | 2198 // v v v 2199 // ----------------------------------- 2200 // | effective window | 2201 // ----------------------------------- 2202 2203 // Flight size represents the window of data which is currently in the 2204 // ether. We should never send data such as the flight size becomes larger 2205 // than the effective window. Note however that the effective window may be 2206 // reduced (by congestion for instance), so at some point in time flight 2207 // size may be larger than the currently calculated window. 2208 2209 uint32 flightSize = (fSendMax - fSendUnacknowledged).Number(); 2210 uint32 consumedWindow = (fSendNext - fSendUnacknowledged).Number(); 2211 2212 if (consumedWindow > sendWindow) { 2213 sendWindow = 0; 2214 // TODO: enter persist state? try to get a window update. 2215 } else 2216 sendWindow -= consumedWindow; 2217 2218 uint32 length = min_c(fSendQueue.Available(fSendNext), sendWindow); 2219 if (length == 0) { 2220 // Nothing to send. 2221 return B_OK; 2222 } 2223 2224 bool shouldStartRetransmitTimer = fSendNext == fSendUnacknowledged; 2225 bool retransmit = fSendNext < fSendMax; 2226 2227 if (fDuplicateAcknowledgeCount != 0) { 2228 // send at most 1 SMSS of data when under limited transmit, fast transmit/recovery 2229 length = min_c(length, fSendMaxSegmentSize); 2230 } 2231 2232 do { 2233 uint32 segmentMaxSize = fSendMaxSegmentSize 2234 - tcp_options_length(segment); 2235 uint32 segmentLength = min_c(length, segmentMaxSize); 2236 2237 if ((fSendNext + segmentLength) == fSendQueue.LastSequence() && !force) { 2238 if (state_needs_finish(fState)) 2239 segment.flags |= TCP_FLAG_FINISH; 2240 if (length > 0) 2241 segment.flags |= TCP_FLAG_PUSH; 2242 } 2243 2244 // Determine if we should really send this segment 2245 if (!force && !retransmit && !_ShouldSendSegment(segment, segmentLength, 2246 segmentMaxSize, flightSize)) { 2247 if (fSendQueue.Available() 2248 && !gStackModule->is_timer_active(&fPersistTimer) 2249 && !gStackModule->is_timer_active(&fRetransmitTimer)) 2250 _StartPersistTimer(); 2251 break; 2252 } 2253 2254 net_buffer *buffer = gBufferModule->create(256); 2255 if (buffer == NULL) 2256 return B_NO_MEMORY; 2257 2258 status_t status = B_OK; 2259 if (segmentLength > 0) 2260 status = fSendQueue.Get(buffer, fSendNext, segmentLength); 2261 if (status < B_OK) { 2262 gBufferModule->free(buffer); 2263 return status; 2264 } 2265 2266 sendWindow -= buffer->size; 2267 2268 status = _PrepareAndSend(segment, buffer, retransmit); 2269 if (status != B_OK) 2270 return status; 2271 2272 if (shouldStartRetransmitTimer) { 2273 TRACE("starting initial retransmit timer of: %" B_PRIdBIGTIME, 2274 fRetransmitTimeout); 2275 gStackModule->set_timer(&fRetransmitTimer, fRetransmitTimeout); 2276 T(TimerSet(this, "retransmit", fRetransmitTimeout)); 2277 shouldStartRetransmitTimer = false; 2278 } 2279 2280 length -= segmentLength; 2281 segment.flags &= ~(TCP_FLAG_SYNCHRONIZE | TCP_FLAG_RESET 2282 | TCP_FLAG_FINISH); 2283 2284 if (retransmit) 2285 break; 2286 2287 } while (length > 0); 2288 2289 return B_OK; 2290 } 2291 2292 2293 int 2294 TCPEndpoint::_MaxSegmentSize(const sockaddr* address) const 2295 { 2296 return next->module->get_mtu(next, address) - sizeof(tcp_header); 2297 } 2298 2299 2300 status_t 2301 TCPEndpoint::_PrepareSendPath(const sockaddr* peer) 2302 { 2303 if (fRoute == NULL) { 2304 fRoute = gDatalinkModule->get_route(Domain(), peer); 2305 if (fRoute == NULL) 2306 return ENETUNREACH; 2307 2308 if ((fRoute->flags & RTF_LOCAL) != 0) 2309 fFlags |= FLAG_LOCAL; 2310 } 2311 2312 // make sure connection does not already exist 2313 status_t status = fManager->SetConnection(this, *LocalAddress(), peer, 2314 fRoute->interface_address->local); 2315 if (status < B_OK) 2316 return status; 2317 2318 fInitialSendSequence = system_time() >> 4; 2319 fSendNext = fInitialSendSequence; 2320 fSendUnacknowledged = fInitialSendSequence; 2321 fSendMax = fInitialSendSequence; 2322 fSendUrgentOffset = fInitialSendSequence; 2323 fRecover = fInitialSendSequence.Number(); 2324 2325 // we are counting the SYN here 2326 fSendQueue.SetInitialSequence(fSendNext + 1); 2327 2328 fReceiveMaxSegmentSize = _MaxSegmentSize(peer); 2329 2330 // Compute the window shift we advertise to our peer - if it doesn't support 2331 // this option, this will be reset to 0 (when its SYN is received) 2332 fReceiveWindowShift = 0; 2333 while (fReceiveWindowShift < TCP_MAX_WINDOW_SHIFT 2334 && (0xffffUL << fReceiveWindowShift) < socket->receive.buffer_size) { 2335 fReceiveWindowShift++; 2336 } 2337 2338 return B_OK; 2339 } 2340 2341 2342 void 2343 TCPEndpoint::_Acknowledged(tcp_segment_header& segment) 2344 { 2345 TRACE("_Acknowledged(): ack %" B_PRIu32 "; uack %" B_PRIu32 "; next %" 2346 B_PRIu32 "; max %" B_PRIu32, segment.acknowledge, 2347 fSendUnacknowledged.Number(), fSendNext.Number(), fSendMax.Number()); 2348 2349 ASSERT(fSendUnacknowledged <= segment.acknowledge); 2350 2351 if (fSendUnacknowledged < segment.acknowledge) { 2352 fSendQueue.RemoveUntil(segment.acknowledge); 2353 2354 uint32 bytesAcknowledged = segment.acknowledge - fSendUnacknowledged.Number(); 2355 fPreviousHighestAcknowledge = fSendUnacknowledged; 2356 fSendUnacknowledged = segment.acknowledge; 2357 uint32 flightSize = (fSendMax - fSendUnacknowledged).Number(); 2358 int32 expectedSamples = flightSize / (fSendMaxSegmentSize << 1); 2359 2360 if (fPreviousHighestAcknowledge > fSendUnacknowledged) { 2361 // need to update the recover variable upon a sequence wraparound 2362 fRecover = segment.acknowledge - 1; 2363 } 2364 2365 // the acknowledgment of the SYN/ACK MUST NOT increase the size of the congestion window 2366 if (fSendUnacknowledged != fInitialSendSequence) { 2367 if (fCongestionWindow < fSlowStartThreshold) 2368 fCongestionWindow += min_c(bytesAcknowledged, fSendMaxSegmentSize); 2369 else { 2370 uint32 increment = fSendMaxSegmentSize * fSendMaxSegmentSize; 2371 2372 if (increment < fCongestionWindow) 2373 increment = 1; 2374 else 2375 increment /= fCongestionWindow; 2376 2377 fCongestionWindow += increment; 2378 } 2379 2380 fSendMaxSegments = UINT32_MAX; 2381 } 2382 2383 if ((fFlags & FLAG_RECOVERY) != 0) { 2384 fSendNext = fSendUnacknowledged; 2385 _SendQueued(); 2386 fCongestionWindow -= bytesAcknowledged; 2387 2388 if (bytesAcknowledged > fSendMaxSegmentSize) 2389 fCongestionWindow += fSendMaxSegmentSize; 2390 2391 fSendNext = fSendMax; 2392 } else 2393 fDuplicateAcknowledgeCount = 0; 2394 2395 if (fSendNext < fSendUnacknowledged) 2396 fSendNext = fSendUnacknowledged; 2397 2398 if (fFlags & FLAG_OPTION_TIMESTAMP) { 2399 _UpdateRoundTripTime(tcp_diff_timestamp(segment.timestamp_reply), 2400 expectedSamples > 0 ? expectedSamples : 1); 2401 } else if (fSendTime != 0 && fRoundTripStartSequence < segment.acknowledge) { 2402 _UpdateRoundTripTime(tcp_diff_timestamp(fSendTime), 1); 2403 fSendTime = 0; 2404 } 2405 2406 if (fSendUnacknowledged == fSendMax) { 2407 TRACE("all acknowledged, cancelling retransmission timer."); 2408 gStackModule->cancel_timer(&fRetransmitTimer); 2409 T(TimerSet(this, "retransmit", -1)); 2410 } else { 2411 TRACE("data acknowledged, resetting retransmission timer to: %" 2412 B_PRIdBIGTIME, fRetransmitTimeout); 2413 gStackModule->set_timer(&fRetransmitTimer, fRetransmitTimeout); 2414 T(TimerSet(this, "retransmit", fRetransmitTimeout)); 2415 } 2416 2417 if (is_writable(fState)) { 2418 // notify threads waiting on the socket to become writable again 2419 fSendCondition.NotifyAll(); 2420 gSocketModule->notify(socket, B_SELECT_WRITE, fSendQueue.Free()); 2421 } 2422 } 2423 2424 // if there is data left to be sent, send it now 2425 if (fSendQueue.Used() > 0) 2426 _SendQueued(); 2427 } 2428 2429 2430 void 2431 TCPEndpoint::_Retransmit() 2432 { 2433 TRACE("Retransmit()"); 2434 2435 if (fState < ESTABLISHED) { 2436 fRetransmitTimeout = TCP_SYN_RETRANSMIT_TIMEOUT; 2437 fCongestionWindow = fSendMaxSegmentSize; 2438 } else { 2439 _ResetSlowStart(); 2440 fDuplicateAcknowledgeCount = 0; 2441 // Do exponential back off of the retransmit timeout 2442 fRetransmitTimeout *= 2; 2443 if (fRetransmitTimeout > TCP_MAX_RETRANSMIT_TIMEOUT) 2444 fRetransmitTimeout = TCP_MAX_RETRANSMIT_TIMEOUT; 2445 } 2446 2447 fSendNext = fSendUnacknowledged; 2448 _SendQueued(); 2449 2450 fRecover = fSendNext.Number() - 1; 2451 if ((fFlags & FLAG_RECOVERY) != 0) 2452 fFlags &= ~FLAG_RECOVERY; 2453 } 2454 2455 2456 void 2457 TCPEndpoint::_UpdateRoundTripTime(int32 roundTripTime, int32 expectedSamples) 2458 { 2459 if (fSmoothedRoundTripTime == 0) { 2460 fSmoothedRoundTripTime = roundTripTime; 2461 fRoundTripVariation = roundTripTime / 2; 2462 fRetransmitTimeout = (fSmoothedRoundTripTime + max_c(100, fRoundTripVariation * 4)) 2463 * kTimestampFactor; 2464 } else { 2465 int32 delta = fSmoothedRoundTripTime - roundTripTime; 2466 if (delta < 0) 2467 delta = -delta; 2468 fRoundTripVariation += (delta - fRoundTripVariation) / (expectedSamples * 4); 2469 fSmoothedRoundTripTime += (roundTripTime - fSmoothedRoundTripTime) / (expectedSamples * 8); 2470 fRetransmitTimeout = (fSmoothedRoundTripTime + max_c(100, fRoundTripVariation * 4)) 2471 * kTimestampFactor; 2472 } 2473 2474 if (fRetransmitTimeout > TCP_MAX_RETRANSMIT_TIMEOUT) 2475 fRetransmitTimeout = TCP_MAX_RETRANSMIT_TIMEOUT; 2476 2477 if (fRetransmitTimeout < TCP_MIN_RETRANSMIT_TIMEOUT) 2478 fRetransmitTimeout = TCP_MIN_RETRANSMIT_TIMEOUT; 2479 2480 TRACE(" RTO is now %" B_PRIdBIGTIME " (after rtt %" B_PRId32 "ms)", 2481 fRetransmitTimeout, roundTripTime); 2482 } 2483 2484 2485 void 2486 TCPEndpoint::_ResetSlowStart() 2487 { 2488 fSlowStartThreshold = max_c((fSendMax - fSendUnacknowledged).Number() / 2, 2489 2 * fSendMaxSegmentSize); 2490 fCongestionWindow = fSendMaxSegmentSize; 2491 } 2492 2493 2494 // #pragma mark - timer 2495 2496 2497 /*static*/ void 2498 TCPEndpoint::_RetransmitTimer(net_timer* timer, void* _endpoint) 2499 { 2500 TCPEndpoint* endpoint = (TCPEndpoint*)_endpoint; 2501 T(TimerTriggered(endpoint, "retransmit")); 2502 2503 MutexLocker locker(endpoint->fLock); 2504 if (!locker.IsLocked() || gStackModule->is_timer_active(timer)) 2505 return; 2506 2507 endpoint->_Retransmit(); 2508 } 2509 2510 2511 /*static*/ void 2512 TCPEndpoint::_PersistTimer(net_timer* timer, void* _endpoint) 2513 { 2514 TCPEndpoint* endpoint = (TCPEndpoint*)_endpoint; 2515 T(TimerTriggered(endpoint, "persist")); 2516 2517 MutexLocker locker(endpoint->fLock); 2518 if (!locker.IsLocked()) 2519 return; 2520 2521 // the timer might not have been canceled early enough 2522 if (endpoint->State() == CLOSED) 2523 return; 2524 2525 endpoint->_SendQueued(true); 2526 } 2527 2528 2529 /*static*/ void 2530 TCPEndpoint::_DelayedAcknowledgeTimer(net_timer* timer, void* _endpoint) 2531 { 2532 TCPEndpoint* endpoint = (TCPEndpoint*)_endpoint; 2533 T(TimerTriggered(endpoint, "delayed ack")); 2534 2535 MutexLocker locker(endpoint->fLock); 2536 if (!locker.IsLocked()) 2537 return; 2538 2539 // the timer might not have been canceled early enough 2540 if (endpoint->State() == CLOSED) 2541 return; 2542 2543 endpoint->_SendAcknowledge(); 2544 } 2545 2546 2547 /*static*/ void 2548 TCPEndpoint::_TimeWaitTimer(net_timer* timer, void* _endpoint) 2549 { 2550 TCPEndpoint* endpoint = (TCPEndpoint*)_endpoint; 2551 T(TimerTriggered(endpoint, "time-wait")); 2552 2553 MutexLocker locker(endpoint->fLock); 2554 if (!locker.IsLocked()) 2555 return; 2556 2557 if ((endpoint->fFlags & FLAG_CLOSED) == 0) { 2558 endpoint->fFlags |= FLAG_DELETE_ON_CLOSE; 2559 return; 2560 } 2561 2562 locker.Unlock(); 2563 2564 gSocketModule->release_socket(endpoint->socket); 2565 } 2566 2567 2568 /*static*/ status_t 2569 TCPEndpoint::_WaitForCondition(ConditionVariable& condition, 2570 MutexLocker& locker, bigtime_t timeout) 2571 { 2572 ConditionVariableEntry entry; 2573 condition.Add(&entry); 2574 2575 locker.Unlock(); 2576 status_t result = entry.Wait(B_ABSOLUTE_TIMEOUT | B_CAN_INTERRUPT, timeout); 2577 locker.Lock(); 2578 2579 return result; 2580 } 2581 2582 2583 // #pragma mark - 2584 2585 2586 void 2587 TCPEndpoint::Dump() const 2588 { 2589 kprintf("TCP endpoint %p\n", this); 2590 kprintf(" state: %s\n", name_for_state(fState)); 2591 kprintf(" flags: 0x%" B_PRIx32 "\n", fFlags); 2592 #if KDEBUG 2593 kprintf(" lock: { %p, holder: %" B_PRId32 " }\n", &fLock, fLock.holder); 2594 #endif 2595 kprintf(" accept sem: %" B_PRId32 "\n", fAcceptSemaphore); 2596 kprintf(" options: 0x%" B_PRIx32 "\n", (uint32)fOptions); 2597 kprintf(" send\n"); 2598 kprintf(" window shift: %" B_PRIu8 "\n", fSendWindowShift); 2599 kprintf(" unacknowledged: %" B_PRIu32 "\n", 2600 fSendUnacknowledged.Number()); 2601 kprintf(" next: %" B_PRIu32 "\n", fSendNext.Number()); 2602 kprintf(" max: %" B_PRIu32 "\n", fSendMax.Number()); 2603 kprintf(" urgent offset: %" B_PRIu32 "\n", fSendUrgentOffset.Number()); 2604 kprintf(" window: %" B_PRIu32 "\n", fSendWindow); 2605 kprintf(" max window: %" B_PRIu32 "\n", fSendMaxWindow); 2606 kprintf(" max segment size: %" B_PRIu32 "\n", fSendMaxSegmentSize); 2607 kprintf(" queue: %" B_PRIuSIZE " / %" B_PRIuSIZE "\n", fSendQueue.Used(), 2608 fSendQueue.Size()); 2609 #if DEBUG_TCP_BUFFER_QUEUE 2610 fSendQueue.Dump(); 2611 #endif 2612 kprintf(" last acknowledge sent: %" B_PRIu32 "\n", 2613 fLastAcknowledgeSent.Number()); 2614 kprintf(" initial sequence: %" B_PRIu32 "\n", 2615 fInitialSendSequence.Number()); 2616 kprintf(" receive\n"); 2617 kprintf(" window shift: %" B_PRIu8 "\n", fReceiveWindowShift); 2618 kprintf(" next: %" B_PRIu32 "\n", fReceiveNext.Number()); 2619 kprintf(" max advertised: %" B_PRIu32 "\n", 2620 fReceiveMaxAdvertised.Number()); 2621 kprintf(" window: %" B_PRIu32 "\n", fReceiveWindow); 2622 kprintf(" max segment size: %" B_PRIu32 "\n", fReceiveMaxSegmentSize); 2623 kprintf(" queue: %" B_PRIuSIZE " / %" B_PRIuSIZE "\n", 2624 fReceiveQueue.Available(), fReceiveQueue.Size()); 2625 #if DEBUG_TCP_BUFFER_QUEUE 2626 fReceiveQueue.Dump(); 2627 #endif 2628 kprintf(" initial sequence: %" B_PRIu32 "\n", 2629 fInitialReceiveSequence.Number()); 2630 kprintf(" duplicate acknowledge count: %" B_PRIu32 "\n", 2631 fDuplicateAcknowledgeCount); 2632 kprintf(" smoothed round trip time: %" B_PRId32 " (deviation %" B_PRId32 ")\n", 2633 fSmoothedRoundTripTime, fRoundTripVariation); 2634 kprintf(" retransmit timeout: %" B_PRId64 "\n", fRetransmitTimeout); 2635 kprintf(" congestion window: %" B_PRIu32 "\n", fCongestionWindow); 2636 kprintf(" slow start threshold: %" B_PRIu32 "\n", fSlowStartThreshold); 2637 } 2638 2639