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 = _SendQueued(); 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 // wait until enough space is available 841 status_t status = _WaitForCondition(fSendCondition, lock, timeout); 842 if (status < B_OK) { 843 TRACE(" SendData() returning %s (%d)", 844 strerror(posix_error(status)), (int)posix_error(status)); 845 return posix_error(status); 846 } 847 848 if (!is_writable(fState) && !is_establishing(fState)) 849 return EPIPE; 850 } 851 852 size_t size = fSendQueue.Free(); 853 if (size < left) { 854 // we need to split the original buffer 855 net_buffer* clone = gBufferModule->clone(buffer, false); 856 // TODO: add offset/size parameter to net_buffer::clone() or 857 // even a move_data() function, as this is a bit inefficient 858 if (clone == NULL) 859 return ENOBUFS; 860 861 status_t status = gBufferModule->trim(clone, size); 862 if (status != B_OK) { 863 gBufferModule->free(clone); 864 return status; 865 } 866 867 gBufferModule->remove_header(buffer, size); 868 left -= size; 869 fSendQueue.Add(clone); 870 } else { 871 left -= buffer->size; 872 fSendQueue.Add(buffer); 873 } 874 } 875 876 TRACE(" SendData(): %" B_PRIuSIZE " bytes used.", fSendQueue.Used()); 877 878 bool force = false; 879 if ((flags & MSG_OOB) != 0) { 880 fSendUrgentOffset = fSendQueue.LastSequence(); 881 // RFC 961 specifies that the urgent offset points to the last 882 // byte of urgent data. However, this is commonly implemented as 883 // here, ie. it points to the first byte after the urgent data. 884 force = true; 885 } 886 if ((flags & MSG_EOF) != 0) 887 _Disconnect(false); 888 889 if (fState == ESTABLISHED || fState == FINISH_RECEIVED) 890 _SendQueued(force); 891 892 return B_OK; 893 } 894 895 896 ssize_t 897 TCPEndpoint::SendAvailable() 898 { 899 MutexLocker locker(fLock); 900 901 ssize_t available; 902 903 if (is_writable(fState)) 904 available = fSendQueue.Free(); 905 else if (is_establishing(fState)) 906 available = 0; 907 else 908 available = EPIPE; 909 910 TRACE("SendAvailable(): %" B_PRIdSSIZE, available); 911 T(APICall(this, "sendavailable")); 912 return available; 913 } 914 915 916 status_t 917 TCPEndpoint::FillStat(net_stat *stat) 918 { 919 MutexLocker _(fLock); 920 921 strlcpy(stat->state, name_for_state(fState), sizeof(stat->state)); 922 stat->receive_queue_size = fReceiveQueue.Available(); 923 stat->send_queue_size = fSendQueue.Used(); 924 925 return B_OK; 926 } 927 928 929 status_t 930 TCPEndpoint::ReadData(size_t numBytes, uint32 flags, net_buffer** _buffer) 931 { 932 if ((flags & ~(MSG_DONTWAIT | MSG_WAITALL | MSG_PEEK)) != 0) 933 return EOPNOTSUPP; 934 935 MutexLocker locker(fLock); 936 937 TRACE("ReadData(%" B_PRIuSIZE " bytes, flags %#" B_PRIx32 ")", numBytes, 938 flags); 939 T(APICall(this, "readdata")); 940 941 *_buffer = NULL; 942 943 if (fState == CLOSED) { 944 if (socket->error != B_OK) 945 return socket->error; 946 return ENOTCONN; 947 } 948 949 bigtime_t timeout = 0; 950 if ((flags & MSG_DONTWAIT) == 0) { 951 timeout = absolute_timeout(socket->receive.timeout); 952 if (gStackModule->is_restarted_syscall()) 953 timeout = gStackModule->restore_syscall_restart_timeout(); 954 else 955 gStackModule->store_syscall_restart_timeout(timeout); 956 } 957 958 if (fState == SYNCHRONIZE_SENT || fState == SYNCHRONIZE_RECEIVED) { 959 if (flags & MSG_DONTWAIT) 960 return B_WOULD_BLOCK; 961 962 status_t status = _WaitForEstablished(locker, timeout); 963 if (status < B_OK) 964 return posix_error(status); 965 } 966 967 size_t dataNeeded = socket->receive.low_water_mark; 968 969 // When MSG_WAITALL is set then the function should block 970 // until the full amount of data can be returned. 971 if (flags & MSG_WAITALL) 972 dataNeeded = numBytes; 973 974 // TODO: add support for urgent data (MSG_OOB) 975 976 while (true) { 977 if (fState == CLOSING || fState == WAIT_FOR_FINISH_ACKNOWLEDGE 978 || fState == TIME_WAIT) { 979 // ``Connection closing''. 980 if (fReceiveQueue.Available() > 0) 981 break; 982 return B_OK; 983 } 984 985 if (fReceiveQueue.Available() > 0) { 986 if (fReceiveQueue.Available() >= dataNeeded 987 || (fReceiveQueue.PushedData() > 0 988 && fReceiveQueue.PushedData() >= fReceiveQueue.Available())) 989 break; 990 } else if (fState == FINISH_RECEIVED) { 991 // ``If no text is awaiting delivery, the RECEIVE will 992 // get a Connection closing''. 993 return B_OK; 994 } 995 996 if (timeout == 0) 997 return B_WOULD_BLOCK; 998 999 if ((fFlags & FLAG_NO_RECEIVE) != 0) 1000 return B_OK; 1001 1002 status_t status = _WaitForCondition(fReceiveCondition, locker, timeout); 1003 if (status < B_OK) { 1004 // The Open Group base specification mentions that EINTR should be 1005 // returned if the recv() is interrupted before _any data_ is 1006 // available. So we actually check if there is data, and if so, 1007 // push it to the user. 1008 if ((status == B_TIMED_OUT || status == B_INTERRUPTED) 1009 && fReceiveQueue.Available() > 0) 1010 break; 1011 1012 return posix_error(status); 1013 } 1014 } 1015 1016 TRACE(" ReadData(): %" B_PRIuSIZE " are available.", 1017 fReceiveQueue.Available()); 1018 1019 if (numBytes < fReceiveQueue.Available()) 1020 fReceiveCondition.NotifyAll(); 1021 1022 bool clone = (flags & MSG_PEEK) != 0; 1023 1024 ssize_t receivedBytes = fReceiveQueue.Get(numBytes, !clone, _buffer); 1025 1026 TRACE(" ReadData(): %" B_PRIuSIZE " bytes kept.", 1027 fReceiveQueue.Available()); 1028 1029 if (fReceiveQueue.Available() == 0 && fState == FINISH_RECEIVED) 1030 socket->receive.low_water_mark = 0; 1031 1032 // if we are opening the window, check if we should send an ACK 1033 if (!clone) 1034 SendAcknowledge(false); 1035 1036 return receivedBytes; 1037 } 1038 1039 1040 ssize_t 1041 TCPEndpoint::ReadAvailable() 1042 { 1043 MutexLocker locker(fLock); 1044 1045 TRACE("ReadAvailable(): %" B_PRIdSSIZE, _AvailableData()); 1046 T(APICall(this, "readavailable")); 1047 1048 return _AvailableData(); 1049 } 1050 1051 1052 status_t 1053 TCPEndpoint::SetSendBufferSize(size_t length) 1054 { 1055 MutexLocker _(fLock); 1056 fSendQueue.SetMaxBytes(length); 1057 return B_OK; 1058 } 1059 1060 1061 status_t 1062 TCPEndpoint::SetReceiveBufferSize(size_t length) 1063 { 1064 MutexLocker _(fLock); 1065 fReceiveQueue.SetMaxBytes(length); 1066 return B_OK; 1067 } 1068 1069 1070 status_t 1071 TCPEndpoint::GetOption(int option, void* _value, int* _length) 1072 { 1073 if (*_length != sizeof(int)) 1074 return B_BAD_VALUE; 1075 1076 int* value = (int*)_value; 1077 1078 switch (option) { 1079 case TCP_NODELAY: 1080 if ((fOptions & TCP_NODELAY) != 0) 1081 *value = 1; 1082 else 1083 *value = 0; 1084 return B_OK; 1085 1086 case TCP_MAXSEG: 1087 *value = fReceiveMaxSegmentSize; 1088 return B_OK; 1089 1090 default: 1091 return B_BAD_VALUE; 1092 } 1093 } 1094 1095 1096 status_t 1097 TCPEndpoint::SetOption(int option, const void* _value, int length) 1098 { 1099 if (option != TCP_NODELAY) 1100 return B_BAD_VALUE; 1101 1102 if (length != sizeof(int)) 1103 return B_BAD_VALUE; 1104 1105 const int* value = (const int*)_value; 1106 1107 MutexLocker _(fLock); 1108 if (*value) 1109 fOptions |= TCP_NODELAY; 1110 else 1111 fOptions &= ~TCP_NODELAY; 1112 1113 return B_OK; 1114 } 1115 1116 1117 // #pragma mark - misc 1118 1119 1120 bool 1121 TCPEndpoint::IsBound() const 1122 { 1123 return !LocalAddress().IsEmpty(true); 1124 } 1125 1126 1127 bool 1128 TCPEndpoint::IsLocal() const 1129 { 1130 return (fFlags & FLAG_LOCAL) != 0; 1131 } 1132 1133 1134 status_t 1135 TCPEndpoint::DelayedAcknowledge() 1136 { 1137 // ACKs "MUST" be generated within 500ms of the first unACKed packet, and 1138 // "SHOULD" be for at least every second full-size segment. (RFC 5681 § 4.2) 1139 1140 bigtime_t delay = TCP_DELAYED_ACKNOWLEDGE_TIMEOUT; 1141 if ((fReceiveNext - fLastAcknowledgeSent) >= (fReceiveMaxSegmentSize * 2)) { 1142 // Trigger an immediate timeout rather than invoking Send directly, 1143 // allowing multiple invocations to be coalesced. 1144 delay = 0; 1145 } else if (gStackModule->is_timer_active(&fDelayedAcknowledgeTimer)) { 1146 return B_OK; 1147 } 1148 1149 gStackModule->set_timer(&fDelayedAcknowledgeTimer, delay); 1150 T(TimerSet(this, "delayed ack", TCP_DELAYED_ACKNOWLEDGE_TIMEOUT)); 1151 return B_OK; 1152 } 1153 1154 1155 status_t 1156 TCPEndpoint::SendAcknowledge(bool force) 1157 { 1158 return _SendQueued(force, 0); 1159 } 1160 1161 1162 void 1163 TCPEndpoint::_StartPersistTimer() 1164 { 1165 gStackModule->set_timer(&fPersistTimer, TCP_PERSIST_TIMEOUT); 1166 T(TimerSet(this, "persist", TCP_PERSIST_TIMEOUT)); 1167 } 1168 1169 1170 void 1171 TCPEndpoint::_EnterTimeWait() 1172 { 1173 TRACE("_EnterTimeWait()"); 1174 1175 if (fState == TIME_WAIT) { 1176 _CancelConnectionTimers(); 1177 } 1178 1179 _UpdateTimeWait(); 1180 } 1181 1182 1183 void 1184 TCPEndpoint::_UpdateTimeWait() 1185 { 1186 gStackModule->set_timer(&fTimeWaitTimer, TCP_MAX_SEGMENT_LIFETIME << 1); 1187 T(TimerSet(this, "time-wait", TCP_MAX_SEGMENT_LIFETIME << 1)); 1188 } 1189 1190 1191 void 1192 TCPEndpoint::_CancelConnectionTimers() 1193 { 1194 gStackModule->cancel_timer(&fRetransmitTimer); 1195 T(TimerSet(this, "retransmit", -1)); 1196 gStackModule->cancel_timer(&fPersistTimer); 1197 T(TimerSet(this, "persist", -1)); 1198 gStackModule->cancel_timer(&fDelayedAcknowledgeTimer); 1199 T(TimerSet(this, "delayed ack", -1)); 1200 } 1201 1202 1203 /*! Sends the FIN flag to the peer when the connection is still open. 1204 Moves the endpoint to the next state depending on where it was. 1205 */ 1206 status_t 1207 TCPEndpoint::_Disconnect(bool closing) 1208 { 1209 tcp_state previousState = fState; 1210 1211 if (fState == SYNCHRONIZE_RECEIVED || fState == ESTABLISHED) 1212 fState = FINISH_SENT; 1213 else if (fState == FINISH_RECEIVED) 1214 fState = WAIT_FOR_FINISH_ACKNOWLEDGE; 1215 else 1216 return B_OK; 1217 1218 T(State(this)); 1219 1220 status_t status = _SendQueued(); 1221 if (status != B_OK) { 1222 fState = previousState; 1223 T(State(this)); 1224 return status; 1225 } 1226 1227 return B_OK; 1228 } 1229 1230 1231 void 1232 TCPEndpoint::_MarkEstablished() 1233 { 1234 fState = ESTABLISHED; 1235 T(State(this)); 1236 1237 gSocketModule->set_connected(socket); 1238 if (gSocketModule->has_parent(socket)) 1239 release_sem_etc(fAcceptSemaphore, 1, B_DO_NOT_RESCHEDULE); 1240 1241 fSendCondition.NotifyAll(); 1242 gSocketModule->notify(socket, B_SELECT_WRITE, fSendQueue.Free()); 1243 } 1244 1245 1246 status_t 1247 TCPEndpoint::_WaitForEstablished(MutexLocker &locker, bigtime_t timeout) 1248 { 1249 // TODO: Checking for CLOSED seems correct, but breaks several neon tests. 1250 // When investigating this, also have a look at _Close() and _HandleReset(). 1251 while (fState < ESTABLISHED/* && fState != CLOSED*/) { 1252 if (socket->error != B_OK) 1253 return socket->error; 1254 1255 status_t status = _WaitForCondition(fSendCondition, locker, timeout); 1256 if (status < B_OK) 1257 return status; 1258 } 1259 1260 return B_OK; 1261 } 1262 1263 1264 // #pragma mark - receive 1265 1266 1267 void 1268 TCPEndpoint::_Close() 1269 { 1270 _CancelConnectionTimers(); 1271 fState = CLOSED; 1272 T(State(this)); 1273 1274 fFlags |= FLAG_DELETE_ON_CLOSE; 1275 1276 fSendCondition.NotifyAll(); 1277 _NotifyReader(); 1278 1279 if (gSocketModule->has_parent(socket)) { 1280 // We still have a parent - obviously, we haven't been accepted yet, 1281 // so no one could ever close us. 1282 _CancelConnectionTimers(); 1283 gSocketModule->set_aborted(socket); 1284 } 1285 } 1286 1287 1288 void 1289 TCPEndpoint::_HandleReset(status_t error) 1290 { 1291 socket->error = error; 1292 _Close(); 1293 1294 gSocketModule->notify(socket, B_SELECT_WRITE, error); 1295 gSocketModule->notify(socket, B_SELECT_ERROR, error); 1296 } 1297 1298 1299 void 1300 TCPEndpoint::_DuplicateAcknowledge(tcp_segment_header &segment) 1301 { 1302 if (fDuplicateAcknowledgeCount == 0) 1303 fPreviousFlightSize = (fSendMax - fSendUnacknowledged).Number(); 1304 1305 if (++fDuplicateAcknowledgeCount < 3) { 1306 if (fSendQueue.Available(fSendMax) != 0 && fSendWindow != 0) { 1307 fSendNext = fSendMax; 1308 fCongestionWindow += fDuplicateAcknowledgeCount * fSendMaxSegmentSize; 1309 _SendQueued(); 1310 TRACE("_DuplicateAcknowledge(): packet sent under limited transmit on receipt of dup ack"); 1311 fCongestionWindow -= fDuplicateAcknowledgeCount * fSendMaxSegmentSize; 1312 } 1313 } 1314 1315 if (fDuplicateAcknowledgeCount == 3) { 1316 if ((segment.acknowledge - 1) > fRecover || (fCongestionWindow > fSendMaxSegmentSize && 1317 (fSendUnacknowledged - fPreviousHighestAcknowledge) <= 4 * fSendMaxSegmentSize)) { 1318 fFlags |= FLAG_RECOVERY; 1319 fRecover = fSendMax.Number() - 1; 1320 fSlowStartThreshold = max_c(fPreviousFlightSize / 2, 2 * fSendMaxSegmentSize); 1321 fCongestionWindow = fSlowStartThreshold + 3 * fSendMaxSegmentSize; 1322 fSendNext = segment.acknowledge; 1323 _SendQueued(); 1324 TRACE("_DuplicateAcknowledge(): packet sent under fast restransmit on the receipt of 3rd dup ack"); 1325 } 1326 } else if (fDuplicateAcknowledgeCount > 3) { 1327 uint32 flightSize = (fSendMax - fSendUnacknowledged).Number(); 1328 if ((fDuplicateAcknowledgeCount - 3) * fSendMaxSegmentSize <= flightSize) 1329 fCongestionWindow += fSendMaxSegmentSize; 1330 if (fSendQueue.Available(fSendMax) != 0) { 1331 fSendNext = fSendMax; 1332 _SendQueued(); 1333 } 1334 } 1335 } 1336 1337 1338 void 1339 TCPEndpoint::_UpdateTimestamps(tcp_segment_header& segment, 1340 size_t segmentLength) 1341 { 1342 if (fFlags & FLAG_OPTION_TIMESTAMP) { 1343 tcp_sequence sequence(segment.sequence); 1344 1345 if (fLastAcknowledgeSent >= sequence 1346 && fLastAcknowledgeSent < (sequence + segmentLength)) 1347 fReceivedTimestamp = segment.timestamp_value; 1348 } 1349 } 1350 1351 1352 ssize_t 1353 TCPEndpoint::_AvailableData() const 1354 { 1355 // TODO: Refer to the FLAG_NO_RECEIVE comment above regarding 1356 // the application of FLAG_NO_RECEIVE in listen()ing 1357 // sockets. 1358 if (fState == LISTEN) 1359 return gSocketModule->count_connected(socket); 1360 if (fState == SYNCHRONIZE_SENT) 1361 return 0; 1362 1363 ssize_t availableData = fReceiveQueue.Available(); 1364 1365 if (availableData == 0 && !_ShouldReceive()) 1366 return ENOTCONN; 1367 if (availableData == 0 && (fState == FINISH_RECEIVED || fState == WAIT_FOR_FINISH_ACKNOWLEDGE)) 1368 return ESHUTDOWN; 1369 return availableData; 1370 } 1371 1372 1373 void 1374 TCPEndpoint::_NotifyReader() 1375 { 1376 fReceiveCondition.NotifyAll(); 1377 gSocketModule->notify(socket, B_SELECT_READ, _AvailableData()); 1378 } 1379 1380 1381 bool 1382 TCPEndpoint::_AddData(tcp_segment_header& segment, net_buffer* buffer) 1383 { 1384 if ((segment.flags & TCP_FLAG_FINISH) != 0) { 1385 // Remember the position of the finish received flag 1386 fFinishReceived = true; 1387 fFinishReceivedAt = segment.sequence + buffer->size; 1388 } 1389 1390 fReceiveQueue.Add(buffer, segment.sequence); 1391 fReceiveNext = fReceiveQueue.NextSequence(); 1392 1393 if (fFinishReceived) { 1394 // Set or reset the finish flag on the current segment 1395 if (fReceiveNext < fFinishReceivedAt) 1396 segment.flags &= ~TCP_FLAG_FINISH; 1397 else 1398 segment.flags |= TCP_FLAG_FINISH; 1399 } 1400 1401 TRACE(" _AddData(): adding data, receive next = %" B_PRIu32 ". Now have %" 1402 B_PRIuSIZE " bytes.", fReceiveNext.Number(), fReceiveQueue.Available()); 1403 1404 if ((segment.flags & TCP_FLAG_PUSH) != 0) 1405 fReceiveQueue.SetPushPointer(); 1406 1407 return fReceiveQueue.Available() > 0; 1408 } 1409 1410 1411 void 1412 TCPEndpoint::_PrepareReceivePath(tcp_segment_header& segment) 1413 { 1414 fInitialReceiveSequence = segment.sequence; 1415 fFinishReceived = false; 1416 1417 // count the received SYN 1418 segment.sequence++; 1419 1420 fReceiveNext = segment.sequence; 1421 fReceiveQueue.SetInitialSequence(segment.sequence); 1422 1423 if ((fOptions & TCP_NOOPT) == 0) { 1424 if (segment.max_segment_size > 0) { 1425 // The maximum size of a segment that a TCP endpoint really sends, 1426 // the "effective send MSS", MUST be the smaller of the send MSS and 1427 // the largest transmission size permitted by the IP layer: 1428 fSendMaxSegmentSize = min_c(segment.max_segment_size, 1429 _MaxSegmentSize(*PeerAddress())); 1430 } 1431 1432 if (segment.options & TCP_HAS_WINDOW_SCALE) { 1433 fFlags |= FLAG_OPTION_WINDOW_SCALE; 1434 fSendWindowShift = segment.window_shift; 1435 } else { 1436 fFlags &= ~FLAG_OPTION_WINDOW_SCALE; 1437 fReceiveWindowShift = 0; 1438 } 1439 1440 if (segment.options & TCP_HAS_TIMESTAMPS) { 1441 fFlags |= FLAG_OPTION_TIMESTAMP; 1442 fReceivedTimestamp = segment.timestamp_value; 1443 } else 1444 fFlags &= ~FLAG_OPTION_TIMESTAMP; 1445 1446 if ((segment.options & TCP_SACK_PERMITTED) == 0) 1447 fFlags &= ~FLAG_OPTION_SACK_PERMITTED; 1448 } 1449 1450 if (fSendMaxSegmentSize > 2190) 1451 fCongestionWindow = 2 * fSendMaxSegmentSize; 1452 else if (fSendMaxSegmentSize > 1095) 1453 fCongestionWindow = 3 * fSendMaxSegmentSize; 1454 else 1455 fCongestionWindow = 4 * fSendMaxSegmentSize; 1456 1457 fSendMaxSegments = fCongestionWindow / fSendMaxSegmentSize; 1458 fSlowStartThreshold = (uint32)segment.advertised_window << fSendWindowShift; 1459 } 1460 1461 1462 bool 1463 TCPEndpoint::_ShouldReceive() const 1464 { 1465 if ((fFlags & FLAG_NO_RECEIVE) != 0) 1466 return false; 1467 1468 return fState == ESTABLISHED || fState == FINISH_SENT 1469 || fState == FINISH_ACKNOWLEDGED || fState == FINISH_RECEIVED; 1470 } 1471 1472 1473 int32 1474 TCPEndpoint::_Spawn(TCPEndpoint* parent, tcp_segment_header& segment, 1475 net_buffer* buffer) 1476 { 1477 MutexLocker _(fLock); 1478 1479 // TODO error checking 1480 ProtocolSocket::Open(); 1481 1482 fState = SYNCHRONIZE_RECEIVED; 1483 T(Spawn(parent, this)); 1484 1485 fManager = parent->fManager; 1486 1487 LocalAddress().SetTo(buffer->destination); 1488 PeerAddress().SetTo(buffer->source); 1489 1490 TRACE("Spawn()"); 1491 1492 // TODO: proper error handling! 1493 if (fManager->BindChild(this) != B_OK) { 1494 T(Error(this, "binding failed", __LINE__)); 1495 return DROP; 1496 } 1497 if (_PrepareSendPath(*PeerAddress()) != B_OK) { 1498 T(Error(this, "prepare send faild", __LINE__)); 1499 return DROP; 1500 } 1501 1502 fOptions = parent->fOptions; 1503 fAcceptSemaphore = parent->fAcceptSemaphore; 1504 1505 _PrepareReceivePath(segment); 1506 1507 // send SYN+ACK 1508 if (_SendQueued() != B_OK) { 1509 T(Error(this, "sending failed", __LINE__)); 1510 return DROP; 1511 } 1512 1513 segment.flags &= ~TCP_FLAG_SYNCHRONIZE; 1514 // we handled this flag now, it must not be set for further processing 1515 1516 return _Receive(segment, buffer); 1517 } 1518 1519 1520 int32 1521 TCPEndpoint::_ListenReceive(tcp_segment_header& segment, net_buffer* buffer) 1522 { 1523 TRACE("ListenReceive()"); 1524 1525 // Essentially, we accept only TCP_FLAG_SYNCHRONIZE in this state, 1526 // but the error behaviour differs 1527 if (segment.flags & TCP_FLAG_RESET) 1528 return DROP; 1529 if (segment.flags & TCP_FLAG_ACKNOWLEDGE) 1530 return DROP | RESET; 1531 if ((segment.flags & TCP_FLAG_SYNCHRONIZE) == 0) 1532 return DROP; 1533 1534 // TODO: drop broadcast/multicast 1535 1536 // spawn new endpoint for accept() 1537 net_socket* newSocket; 1538 if (gSocketModule->spawn_pending_socket(socket, &newSocket) < B_OK) { 1539 T(Error(this, "spawning failed", __LINE__)); 1540 return DROP; 1541 } 1542 1543 return ((TCPEndpoint *)newSocket->first_protocol)->_Spawn(this, 1544 segment, buffer); 1545 } 1546 1547 1548 int32 1549 TCPEndpoint::_SynchronizeSentReceive(tcp_segment_header &segment, 1550 net_buffer *buffer) 1551 { 1552 TRACE("_SynchronizeSentReceive()"); 1553 1554 if ((segment.flags & TCP_FLAG_ACKNOWLEDGE) != 0 1555 && (fInitialSendSequence >= segment.acknowledge 1556 || fSendMax < segment.acknowledge)) 1557 return DROP | RESET; 1558 1559 if (segment.flags & TCP_FLAG_RESET) { 1560 _HandleReset(ECONNREFUSED); 1561 return DROP; 1562 } 1563 1564 if ((segment.flags & TCP_FLAG_SYNCHRONIZE) == 0) 1565 return DROP; 1566 1567 fSendUnacknowledged = segment.acknowledge; 1568 _PrepareReceivePath(segment); 1569 1570 if (segment.flags & TCP_FLAG_ACKNOWLEDGE) { 1571 _MarkEstablished(); 1572 } else { 1573 // simultaneous open 1574 fState = SYNCHRONIZE_RECEIVED; 1575 T(State(this)); 1576 } 1577 1578 segment.flags &= ~TCP_FLAG_SYNCHRONIZE; 1579 // we handled this flag now, it must not be set for further processing 1580 1581 return _Receive(segment, buffer) | IMMEDIATE_ACKNOWLEDGE; 1582 } 1583 1584 1585 int32 1586 TCPEndpoint::_Receive(tcp_segment_header& segment, net_buffer* buffer) 1587 { 1588 // PAWS processing takes precedence over regular TCP acceptability check 1589 if ((fFlags & FLAG_OPTION_TIMESTAMP) != 0 && (segment.flags & TCP_FLAG_RESET) == 0) { 1590 if ((segment.options & TCP_HAS_TIMESTAMPS) == 0) 1591 return DROP; 1592 if ((int32)(fReceivedTimestamp - segment.timestamp_value) > 0 1593 && (fReceivedTimestamp - segment.timestamp_value) <= INT32_MAX) 1594 return DROP | IMMEDIATE_ACKNOWLEDGE; 1595 } 1596 1597 uint32 advertisedWindow = (uint32)segment.advertised_window 1598 << fSendWindowShift; 1599 size_t segmentLength = buffer->size; 1600 1601 // First, handle the most common case for uni-directional data transfer 1602 // (known as header prediction - the segment must not change the window, 1603 // and must be the expected sequence, and contain no control flags) 1604 1605 if (fState == ESTABLISHED 1606 && segment.AcknowledgeOnly() 1607 && fReceiveNext == segment.sequence 1608 && advertisedWindow > 0 && advertisedWindow == fSendWindow 1609 && fSendNext == fSendMax) { 1610 _UpdateTimestamps(segment, segmentLength); 1611 1612 if (segmentLength == 0) { 1613 // this is a pure acknowledge segment - we're on the sending end 1614 if (fSendUnacknowledged < segment.acknowledge 1615 && fSendMax >= segment.acknowledge) { 1616 _Acknowledged(segment); 1617 return DROP; 1618 } 1619 } else if (segment.acknowledge == fSendUnacknowledged 1620 && fReceiveQueue.IsContiguous() 1621 && fReceiveQueue.Free() >= segmentLength 1622 && (fFlags & FLAG_NO_RECEIVE) == 0) { 1623 if (_AddData(segment, buffer)) 1624 _NotifyReader(); 1625 1626 return KEEP | ((segment.flags & TCP_FLAG_PUSH) != 0 1627 ? IMMEDIATE_ACKNOWLEDGE : ACKNOWLEDGE); 1628 } 1629 } 1630 1631 // The fast path was not applicable, so we continue with the standard 1632 // processing of the incoming segment 1633 1634 ASSERT(fState != SYNCHRONIZE_SENT && fState != LISTEN); 1635 1636 if (fState != CLOSED && fState != TIME_WAIT) { 1637 // Check sequence number 1638 if (!segment_in_sequence(segment, segmentLength, fReceiveNext, 1639 fReceiveWindow)) { 1640 TRACE(" Receive(): segment out of window, next: %" B_PRIu32 1641 " wnd: %" B_PRIu32, fReceiveNext.Number(), fReceiveWindow); 1642 if ((segment.flags & TCP_FLAG_RESET) != 0) { 1643 // TODO: this doesn't look right - review! 1644 return DROP; 1645 } 1646 return DROP | IMMEDIATE_ACKNOWLEDGE; 1647 } 1648 } 1649 1650 if ((segment.flags & TCP_FLAG_RESET) != 0) { 1651 // Is this a valid reset? 1652 // We generally ignore resets in time wait state (see RFC 1337) 1653 if (fLastAcknowledgeSent <= segment.sequence 1654 && tcp_sequence(segment.sequence) < (fLastAcknowledgeSent 1655 + fReceiveWindow) 1656 && fState != TIME_WAIT) { 1657 status_t error; 1658 if (fState == SYNCHRONIZE_RECEIVED) 1659 error = ECONNREFUSED; 1660 else if (fState == CLOSING || fState == WAIT_FOR_FINISH_ACKNOWLEDGE) 1661 error = ENOTCONN; 1662 else 1663 error = ECONNRESET; 1664 1665 _HandleReset(error); 1666 } 1667 1668 return DROP; 1669 } 1670 1671 if ((segment.flags & TCP_FLAG_SYNCHRONIZE) != 0 1672 || (fState == SYNCHRONIZE_RECEIVED 1673 && (fInitialReceiveSequence > segment.sequence 1674 || ((segment.flags & TCP_FLAG_ACKNOWLEDGE) != 0 1675 && (fSendUnacknowledged > segment.acknowledge 1676 || fSendMax < segment.acknowledge))))) { 1677 // reset the connection - either the initial SYN was faulty, or we 1678 // received a SYN within the data stream 1679 return DROP | RESET; 1680 } 1681 1682 // TODO: Check this! Why do we advertize a window outside of what we should 1683 // buffer? 1684 fReceiveWindow = max_c(fReceiveQueue.Free(), fReceiveWindow); 1685 // the window must not shrink 1686 1687 // trim buffer to be within the receive window 1688 int32 drop = (int32)(fReceiveNext - segment.sequence).Number(); 1689 if (drop > 0) { 1690 if ((uint32)drop > buffer->size 1691 || ((uint32)drop == buffer->size 1692 && (segment.flags & TCP_FLAG_FINISH) == 0)) { 1693 // don't accidently remove a FIN we shouldn't remove 1694 segment.flags &= ~TCP_FLAG_FINISH; 1695 drop = buffer->size; 1696 } 1697 1698 // remove duplicate data at the start 1699 TRACE("* remove %" B_PRId32 " bytes from the start", drop); 1700 gBufferModule->remove_header(buffer, drop); 1701 segment.sequence += drop; 1702 } 1703 1704 int32 action = KEEP; 1705 1706 // immediately acknowledge out-of-order segment to trigger fast-retransmit at the sender 1707 if (drop != 0) 1708 action |= IMMEDIATE_ACKNOWLEDGE; 1709 1710 drop = (int32)(segment.sequence + buffer->size 1711 - (fReceiveNext + fReceiveWindow)).Number(); 1712 if (drop > 0) { 1713 // remove data exceeding our window 1714 if ((uint32)drop >= buffer->size) { 1715 // if we can accept data, or the segment is not what we'd expect, 1716 // drop the segment (an immediate acknowledge is always triggered) 1717 if (fReceiveWindow != 0 || segment.sequence != fReceiveNext) 1718 return DROP | IMMEDIATE_ACKNOWLEDGE; 1719 1720 action |= IMMEDIATE_ACKNOWLEDGE; 1721 } 1722 1723 if ((segment.flags & TCP_FLAG_FINISH) != 0) { 1724 // we need to remove the finish, too, as part of the data 1725 drop--; 1726 } 1727 1728 segment.flags &= ~(TCP_FLAG_FINISH | TCP_FLAG_PUSH); 1729 TRACE("* remove %" B_PRId32 " bytes from the end", drop); 1730 gBufferModule->remove_trailer(buffer, drop); 1731 } 1732 1733 #ifdef TRACE_TCP 1734 if (advertisedWindow > fSendWindow) { 1735 TRACE(" Receive(): Window update %" B_PRIu32 " -> %" B_PRIu32, 1736 fSendWindow, advertisedWindow); 1737 } 1738 #endif 1739 1740 if (fSendWindow < fSendMaxSegmentSize 1741 && advertisedWindow >= fSendMaxSegmentSize) { 1742 // Our current send window is less than a segment wide, and the new one 1743 // is larger, so trigger a send in case there's anything to be sent. 1744 action |= SEND_QUEUED; 1745 } 1746 1747 fSendWindow = advertisedWindow; 1748 if (advertisedWindow > fSendMaxWindow) 1749 fSendMaxWindow = advertisedWindow; 1750 1751 // Then look at the acknowledgement for any updates 1752 1753 if ((segment.flags & TCP_FLAG_ACKNOWLEDGE) != 0) { 1754 // process acknowledged data 1755 if (fState == SYNCHRONIZE_RECEIVED) 1756 _MarkEstablished(); 1757 1758 if (fSendMax < segment.acknowledge) 1759 return DROP | IMMEDIATE_ACKNOWLEDGE; 1760 1761 if (segment.acknowledge == fSendUnacknowledged) { 1762 if (buffer->size == 0 && advertisedWindow == fSendWindow 1763 && (segment.flags & TCP_FLAG_FINISH) == 0 && fSendUnacknowledged != fSendMax) { 1764 TRACE("Receive(): duplicate ack!"); 1765 _DuplicateAcknowledge(segment); 1766 } 1767 } else if (segment.acknowledge < fSendUnacknowledged) { 1768 return DROP; 1769 } else { 1770 // this segment acknowledges in flight data 1771 1772 if (fDuplicateAcknowledgeCount >= 3) { 1773 // deflate the window. 1774 if (segment.acknowledge > fRecover) { 1775 uint32 flightSize = (fSendMax - fSendUnacknowledged).Number(); 1776 fCongestionWindow = min_c(fSlowStartThreshold, 1777 max_c(flightSize, fSendMaxSegmentSize) + fSendMaxSegmentSize); 1778 fFlags &= ~FLAG_RECOVERY; 1779 } 1780 } 1781 1782 if (fSendMax == segment.acknowledge) 1783 TRACE("Receive(): all inflight data ack'd!"); 1784 1785 if (segment.acknowledge > fSendQueue.LastSequence() 1786 && fState > ESTABLISHED) { 1787 TRACE("Receive(): FIN has been acknowledged!"); 1788 1789 switch (fState) { 1790 case FINISH_SENT: 1791 fState = FINISH_ACKNOWLEDGED; 1792 T(State(this)); 1793 break; 1794 case CLOSING: 1795 fState = TIME_WAIT; 1796 T(State(this)); 1797 _EnterTimeWait(); 1798 return DROP; 1799 case WAIT_FOR_FINISH_ACKNOWLEDGE: 1800 _Close(); 1801 break; 1802 1803 default: 1804 break; 1805 } 1806 } 1807 1808 if (fState != CLOSED) { 1809 tcp_sequence last = fLastAcknowledgeSent; 1810 _Acknowledged(segment); 1811 // we just sent an acknowledge, remove from action 1812 if (last < fLastAcknowledgeSent) 1813 action &= ~IMMEDIATE_ACKNOWLEDGE; 1814 } 1815 } 1816 } 1817 1818 if (segment.flags & TCP_FLAG_URGENT) { 1819 if (fState == ESTABLISHED || fState == FINISH_SENT 1820 || fState == FINISH_ACKNOWLEDGED) { 1821 // TODO: Handle urgent data: 1822 // - RCV.UP <- max(RCV.UP, SEG.UP) 1823 // - signal the user that urgent data is available (SIGURG) 1824 } 1825 } 1826 1827 bool notify = false; 1828 1829 // The buffer may be freed if its data is added to the queue, so cache 1830 // the size as we still need it later. 1831 const uint32 bufferSize = buffer->size; 1832 1833 if ((bufferSize > 0 || (segment.flags & TCP_FLAG_FINISH) != 0) 1834 && _ShouldReceive()) 1835 notify = _AddData(segment, buffer); 1836 else { 1837 if ((fFlags & FLAG_NO_RECEIVE) != 0) 1838 fReceiveNext += buffer->size; 1839 1840 action = (action & ~KEEP) | DROP; 1841 } 1842 1843 if ((segment.flags & TCP_FLAG_FINISH) != 0) { 1844 segmentLength++; 1845 if (fState != CLOSED && fState != LISTEN && fState != SYNCHRONIZE_SENT) { 1846 TRACE("Receive(): peer is finishing connection!"); 1847 fReceiveNext++; 1848 notify = true; 1849 1850 // FIN implies PUSH 1851 fReceiveQueue.SetPushPointer(); 1852 1853 // we'll reply immediately to the FIN if we are not 1854 // transitioning to TIME WAIT so we immediatly ACK it. 1855 action |= IMMEDIATE_ACKNOWLEDGE; 1856 1857 // other side is closing connection; change states 1858 switch (fState) { 1859 case ESTABLISHED: 1860 case SYNCHRONIZE_RECEIVED: 1861 fState = FINISH_RECEIVED; 1862 T(State(this)); 1863 break; 1864 case FINISH_SENT: 1865 // simultaneous close 1866 fState = CLOSING; 1867 T(State(this)); 1868 break; 1869 case FINISH_ACKNOWLEDGED: 1870 fState = TIME_WAIT; 1871 T(State(this)); 1872 _EnterTimeWait(); 1873 break; 1874 case TIME_WAIT: 1875 _UpdateTimeWait(); 1876 break; 1877 1878 default: 1879 break; 1880 } 1881 } 1882 } 1883 1884 if (notify) 1885 _NotifyReader(); 1886 1887 if (bufferSize > 0 || (segment.flags & TCP_FLAG_SYNCHRONIZE) != 0) 1888 action |= ACKNOWLEDGE; 1889 1890 _UpdateTimestamps(segment, segmentLength); 1891 1892 TRACE("Receive() Action %" B_PRId32, action); 1893 1894 return action; 1895 } 1896 1897 1898 int32 1899 TCPEndpoint::SegmentReceived(tcp_segment_header& segment, net_buffer* buffer) 1900 { 1901 MutexLocker locker(fLock); 1902 1903 TRACE("SegmentReceived(): buffer %p (%" B_PRIu32 " bytes) address %s " 1904 "to %s flags %#" B_PRIx8 ", seq %" B_PRIu32 ", ack %" B_PRIu32 1905 ", wnd %" B_PRIu32, buffer, buffer->size, PrintAddress(buffer->source), 1906 PrintAddress(buffer->destination), segment.flags, segment.sequence, 1907 segment.acknowledge, 1908 (uint32)segment.advertised_window << fSendWindowShift); 1909 T(Receive(this, segment, 1910 (uint32)segment.advertised_window << fSendWindowShift, buffer)); 1911 int32 segmentAction = DROP; 1912 1913 switch (fState) { 1914 case LISTEN: 1915 segmentAction = _ListenReceive(segment, buffer); 1916 break; 1917 1918 case SYNCHRONIZE_SENT: 1919 segmentAction = _SynchronizeSentReceive(segment, buffer); 1920 break; 1921 1922 case SYNCHRONIZE_RECEIVED: 1923 case ESTABLISHED: 1924 case FINISH_RECEIVED: 1925 case WAIT_FOR_FINISH_ACKNOWLEDGE: 1926 case FINISH_SENT: 1927 case FINISH_ACKNOWLEDGED: 1928 case CLOSING: 1929 case TIME_WAIT: 1930 case CLOSED: 1931 segmentAction = _Receive(segment, buffer); 1932 break; 1933 } 1934 1935 // process acknowledge action as asked for by the *Receive() method 1936 if (segmentAction & IMMEDIATE_ACKNOWLEDGE) 1937 SendAcknowledge(true); 1938 else if (segmentAction & ACKNOWLEDGE) 1939 DelayedAcknowledge(); 1940 1941 if (segmentAction & SEND_QUEUED) 1942 _SendQueued(); 1943 1944 if ((fFlags & (FLAG_CLOSED | FLAG_DELETE_ON_CLOSE)) 1945 == (FLAG_CLOSED | FLAG_DELETE_ON_CLOSE)) { 1946 1947 locker.Unlock(); 1948 if (gSocketModule->release_socket(socket)) 1949 segmentAction |= DELETED_ENDPOINT; 1950 } 1951 1952 return segmentAction; 1953 } 1954 1955 1956 // #pragma mark - send 1957 1958 1959 inline uint8 1960 TCPEndpoint::_CurrentFlags() 1961 { 1962 // we don't set FLAG_FINISH here, instead we do it 1963 // conditionally below depending if we are sending 1964 // the last bytes of the send queue. 1965 1966 switch (fState) { 1967 case CLOSED: 1968 return TCP_FLAG_RESET | TCP_FLAG_ACKNOWLEDGE; 1969 1970 case SYNCHRONIZE_SENT: 1971 return TCP_FLAG_SYNCHRONIZE; 1972 case SYNCHRONIZE_RECEIVED: 1973 return TCP_FLAG_SYNCHRONIZE | TCP_FLAG_ACKNOWLEDGE; 1974 1975 case ESTABLISHED: 1976 case FINISH_RECEIVED: 1977 case FINISH_ACKNOWLEDGED: 1978 case TIME_WAIT: 1979 case WAIT_FOR_FINISH_ACKNOWLEDGE: 1980 case FINISH_SENT: 1981 case CLOSING: 1982 return TCP_FLAG_ACKNOWLEDGE; 1983 1984 default: 1985 return 0; 1986 } 1987 } 1988 1989 1990 inline bool 1991 TCPEndpoint::_ShouldSendSegment(tcp_segment_header& segment, uint32 length, 1992 uint32 segmentMaxSize, uint32 flightSize) 1993 { 1994 if (fState == ESTABLISHED && fSendMaxSegments == 0) 1995 return false; 1996 1997 if (length > 0) { 1998 // Avoid the silly window syndrome - we only send a segment in case: 1999 // - we have a full segment to send, or 2000 // - we're at the end of our buffer queue, or 2001 // - the buffer is at least larger than half of the maximum send window, 2002 // or 2003 // - we're retransmitting data 2004 if (length == segmentMaxSize 2005 || (fOptions & TCP_NODELAY) != 0 2006 || tcp_sequence(fSendNext + length) == fSendQueue.LastSequence() 2007 || (fSendMaxWindow > 0 && length >= fSendMaxWindow / 2)) 2008 return true; 2009 } 2010 2011 // check if we need to send a window update to the peer 2012 if (segment.advertised_window > 0) { 2013 // correct the window to take into account what already has been advertised 2014 uint32 window = (segment.advertised_window << fReceiveWindowShift) 2015 - (fReceiveMaxAdvertised - fReceiveNext).Number(); 2016 2017 // if we can advertise a window larger than twice the maximum segment 2018 // size, or half the maximum buffer size we send a window update 2019 if (window >= (fReceiveMaxSegmentSize << 1) 2020 || window >= (socket->receive.buffer_size >> 1)) 2021 return true; 2022 } 2023 2024 if ((segment.flags & (TCP_FLAG_SYNCHRONIZE | TCP_FLAG_FINISH 2025 | TCP_FLAG_RESET)) != 0) 2026 return true; 2027 2028 // We do have urgent data pending 2029 if (fSendUrgentOffset > fSendNext) 2030 return true; 2031 2032 // there is no reason to send a segment just now 2033 return false; 2034 } 2035 2036 2037 status_t 2038 TCPEndpoint::_SendQueued(bool force) 2039 { 2040 return _SendQueued(force, fSendWindow); 2041 } 2042 2043 2044 /*! Sends one or more TCP segments with the data waiting in the queue, or some 2045 specific flags that need to be sent. 2046 */ 2047 status_t 2048 TCPEndpoint::_SendQueued(bool force, uint32 sendWindow) 2049 { 2050 if (fRoute == NULL) 2051 return B_ERROR; 2052 2053 // in passive state? 2054 if (fState == LISTEN) 2055 return B_ERROR; 2056 2057 tcp_segment_header segment(_CurrentFlags()); 2058 2059 if ((fOptions & TCP_NOOPT) == 0) { 2060 if ((fFlags & FLAG_OPTION_TIMESTAMP) != 0) { 2061 segment.options |= TCP_HAS_TIMESTAMPS; 2062 segment.timestamp_reply = fReceivedTimestamp; 2063 segment.timestamp_value = tcp_now(); 2064 } 2065 2066 // SACK information is embedded with duplicate acknowledgements 2067 if (!fReceiveQueue.IsContiguous() 2068 && fLastAcknowledgeSent <= fReceiveNext 2069 && (fFlags & FLAG_OPTION_SACK_PERMITTED) != 0) { 2070 segment.options |= TCP_HAS_SACK; 2071 int maxSackCount = MAX_SACK_BLKS 2072 - ((fFlags & FLAG_OPTION_TIMESTAMP) != 0); 2073 memset(segment.sacks, 0, sizeof(segment.sacks)); 2074 segment.sackCount = fReceiveQueue.PopulateSackInfo(fReceiveNext, 2075 maxSackCount, segment.sacks); 2076 } 2077 2078 if ((segment.flags & TCP_FLAG_SYNCHRONIZE) != 0 2079 && fSendNext == fInitialSendSequence) { 2080 // add connection establishment options 2081 segment.max_segment_size = fReceiveMaxSegmentSize; 2082 if (fFlags & FLAG_OPTION_WINDOW_SCALE) { 2083 segment.options |= TCP_HAS_WINDOW_SCALE; 2084 segment.window_shift = fReceiveWindowShift; 2085 } 2086 if ((fFlags & FLAG_OPTION_SACK_PERMITTED) != 0) 2087 segment.options |= TCP_SACK_PERMITTED; 2088 } 2089 } 2090 2091 size_t availableBytes = fReceiveQueue.Free(); 2092 // window size must remain same for duplicate acknowledgements 2093 if (!fReceiveQueue.IsContiguous()) 2094 availableBytes = (fReceiveMaxAdvertised - fReceiveNext).Number(); 2095 2096 if (fFlags & FLAG_OPTION_WINDOW_SCALE) 2097 availableBytes >>= fReceiveWindowShift; 2098 segment.advertised_window = min_c(TCP_MAX_WINDOW, availableBytes); 2099 2100 segment.acknowledge = fReceiveNext.Number(); 2101 2102 // Process urgent data 2103 if (fSendUrgentOffset > fSendNext) { 2104 segment.flags |= TCP_FLAG_URGENT; 2105 segment.urgent_offset = (fSendUrgentOffset - fSendNext).Number(); 2106 } else { 2107 fSendUrgentOffset = fSendUnacknowledged.Number(); 2108 // Keep urgent offset updated, so that it doesn't reach into our 2109 // send window on overlap 2110 segment.urgent_offset = 0; 2111 } 2112 2113 if (fCongestionWindow > 0 && fCongestionWindow < sendWindow) 2114 sendWindow = fCongestionWindow; 2115 2116 // fSendUnacknowledged 2117 // | fSendNext fSendMax 2118 // | | | 2119 // v v v 2120 // ----------------------------------- 2121 // | effective window | 2122 // ----------------------------------- 2123 2124 // Flight size represents the window of data which is currently in the 2125 // ether. We should never send data such as the flight size becomes larger 2126 // than the effective window. Note however that the effective window may be 2127 // reduced (by congestion for instance), so at some point in time flight 2128 // size may be larger than the currently calculated window. 2129 2130 uint32 flightSize = (fSendMax - fSendUnacknowledged).Number(); 2131 uint32 consumedWindow = (fSendNext - fSendUnacknowledged).Number(); 2132 2133 if (consumedWindow > sendWindow) { 2134 sendWindow = 0; 2135 // TODO: enter persist state? try to get a window update. 2136 } else 2137 sendWindow -= consumedWindow; 2138 2139 uint32 length = min_c(fSendQueue.Available(fSendNext), sendWindow); 2140 bool shouldStartRetransmitTimer = fSendNext == fSendUnacknowledged; 2141 bool retransmit = fSendNext < fSendMax; 2142 2143 if (fDuplicateAcknowledgeCount != 0) { 2144 // send at most 1 SMSS of data when under limited transmit, fast transmit/recovery 2145 length = min_c(length, fSendMaxSegmentSize); 2146 } 2147 2148 do { 2149 uint32 segmentMaxSize = fSendMaxSegmentSize 2150 - tcp_options_length(segment); 2151 uint32 segmentLength = min_c(length, segmentMaxSize); 2152 2153 if (fSendNext + segmentLength == fSendQueue.LastSequence() && !force) { 2154 if (state_needs_finish(fState)) 2155 segment.flags |= TCP_FLAG_FINISH; 2156 if (length > 0) 2157 segment.flags |= TCP_FLAG_PUSH; 2158 } 2159 2160 // Determine if we should really send this segment 2161 if (!force && !retransmit && !_ShouldSendSegment(segment, segmentLength, 2162 segmentMaxSize, flightSize)) { 2163 if (fSendQueue.Available() 2164 && !gStackModule->is_timer_active(&fPersistTimer) 2165 && !gStackModule->is_timer_active(&fRetransmitTimer)) 2166 _StartPersistTimer(); 2167 break; 2168 } 2169 2170 net_buffer *buffer = gBufferModule->create(256); 2171 if (buffer == NULL) 2172 return B_NO_MEMORY; 2173 2174 status_t status = B_OK; 2175 if (segmentLength > 0) 2176 status = fSendQueue.Get(buffer, fSendNext, segmentLength); 2177 if (status < B_OK) { 2178 gBufferModule->free(buffer); 2179 return status; 2180 } 2181 2182 LocalAddress().CopyTo(buffer->source); 2183 PeerAddress().CopyTo(buffer->destination); 2184 2185 uint32 size = buffer->size; 2186 segment.sequence = fSendNext.Number(); 2187 2188 TRACE("SendQueued(): buffer %p (%" B_PRIu32 " bytes) address %s to " 2189 "%s flags %#" B_PRIx8 ", seq %" B_PRIu32 ", ack %" B_PRIu32 2190 ", rwnd %" B_PRIu16 ", cwnd %" B_PRIu32 ", ssthresh %" B_PRIu32 2191 ", len %" B_PRIu32 ", first %" B_PRIu32 ", last %" B_PRIu32, 2192 buffer, buffer->size, PrintAddress(buffer->source), 2193 PrintAddress(buffer->destination), segment.flags, segment.sequence, 2194 segment.acknowledge, segment.advertised_window, 2195 fCongestionWindow, fSlowStartThreshold, segmentLength, 2196 fSendQueue.FirstSequence().Number(), 2197 fSendQueue.LastSequence().Number()); 2198 T(Send(this, segment, buffer, fSendQueue.FirstSequence(), 2199 fSendQueue.LastSequence())); 2200 2201 PROBE(buffer, sendWindow); 2202 sendWindow -= buffer->size; 2203 2204 status = add_tcp_header(AddressModule(), segment, buffer); 2205 if (status != B_OK) { 2206 gBufferModule->free(buffer); 2207 return status; 2208 } 2209 2210 // Update send status - we need to do this before we send the data 2211 // for local connections as the answer is directly handled 2212 2213 if (segment.flags & TCP_FLAG_SYNCHRONIZE) { 2214 segment.options &= ~TCP_HAS_WINDOW_SCALE; 2215 segment.max_segment_size = 0; 2216 size++; 2217 } 2218 2219 if (segment.flags & TCP_FLAG_FINISH) 2220 size++; 2221 2222 uint32 sendMax = fSendMax.Number(); 2223 fSendNext += size; 2224 if (fSendMax < fSendNext) 2225 fSendMax = fSendNext; 2226 2227 fReceiveMaxAdvertised = fReceiveNext 2228 + ((uint32)segment.advertised_window << fReceiveWindowShift); 2229 2230 if (segmentLength != 0 && fState == ESTABLISHED) 2231 --fSendMaxSegments; 2232 2233 status = next->module->send_routed_data(next, fRoute, buffer); 2234 if (status < B_OK) { 2235 gBufferModule->free(buffer); 2236 2237 fSendNext = segment.sequence; 2238 fSendMax = sendMax; 2239 // restore send status 2240 return status; 2241 } 2242 2243 if (fSendTime == 0 && !retransmit 2244 && (segmentLength != 0 || (segment.flags & TCP_FLAG_SYNCHRONIZE) !=0)) { 2245 fSendTime = tcp_now(); 2246 fRoundTripStartSequence = segment.sequence; 2247 } 2248 2249 if (shouldStartRetransmitTimer && size > 0) { 2250 TRACE("starting initial retransmit timer of: %" B_PRIdBIGTIME, 2251 fRetransmitTimeout); 2252 gStackModule->set_timer(&fRetransmitTimer, fRetransmitTimeout); 2253 T(TimerSet(this, "retransmit", fRetransmitTimeout)); 2254 shouldStartRetransmitTimer = false; 2255 } 2256 2257 if (segment.flags & TCP_FLAG_ACKNOWLEDGE) { 2258 fLastAcknowledgeSent = segment.acknowledge; 2259 gStackModule->cancel_timer(&fDelayedAcknowledgeTimer); 2260 } 2261 2262 length -= segmentLength; 2263 segment.flags &= ~(TCP_FLAG_SYNCHRONIZE | TCP_FLAG_RESET 2264 | TCP_FLAG_FINISH); 2265 2266 if (retransmit) 2267 break; 2268 2269 } while (length > 0); 2270 2271 return B_OK; 2272 } 2273 2274 2275 int 2276 TCPEndpoint::_MaxSegmentSize(const sockaddr* address) const 2277 { 2278 return next->module->get_mtu(next, address) - sizeof(tcp_header); 2279 } 2280 2281 2282 status_t 2283 TCPEndpoint::_PrepareSendPath(const sockaddr* peer) 2284 { 2285 if (fRoute == NULL) { 2286 fRoute = gDatalinkModule->get_route(Domain(), peer); 2287 if (fRoute == NULL) 2288 return ENETUNREACH; 2289 2290 if ((fRoute->flags & RTF_LOCAL) != 0) 2291 fFlags |= FLAG_LOCAL; 2292 } 2293 2294 // make sure connection does not already exist 2295 status_t status = fManager->SetConnection(this, *LocalAddress(), peer, 2296 fRoute->interface_address->local); 2297 if (status < B_OK) 2298 return status; 2299 2300 fInitialSendSequence = system_time() >> 4; 2301 fSendNext = fInitialSendSequence; 2302 fSendUnacknowledged = fInitialSendSequence; 2303 fSendMax = fInitialSendSequence; 2304 fSendUrgentOffset = fInitialSendSequence; 2305 fRecover = fInitialSendSequence.Number(); 2306 2307 // we are counting the SYN here 2308 fSendQueue.SetInitialSequence(fSendNext + 1); 2309 2310 fReceiveMaxSegmentSize = _MaxSegmentSize(peer); 2311 2312 // Compute the window shift we advertise to our peer - if it doesn't support 2313 // this option, this will be reset to 0 (when its SYN is received) 2314 fReceiveWindowShift = 0; 2315 while (fReceiveWindowShift < TCP_MAX_WINDOW_SHIFT 2316 && (0xffffUL << fReceiveWindowShift) < socket->receive.buffer_size) { 2317 fReceiveWindowShift++; 2318 } 2319 2320 return B_OK; 2321 } 2322 2323 2324 void 2325 TCPEndpoint::_Acknowledged(tcp_segment_header& segment) 2326 { 2327 TRACE("_Acknowledged(): ack %" B_PRIu32 "; uack %" B_PRIu32 "; next %" 2328 B_PRIu32 "; max %" B_PRIu32, segment.acknowledge, 2329 fSendUnacknowledged.Number(), fSendNext.Number(), fSendMax.Number()); 2330 2331 ASSERT(fSendUnacknowledged <= segment.acknowledge); 2332 2333 if (fSendUnacknowledged < segment.acknowledge) { 2334 fSendQueue.RemoveUntil(segment.acknowledge); 2335 2336 uint32 bytesAcknowledged = segment.acknowledge - fSendUnacknowledged.Number(); 2337 fPreviousHighestAcknowledge = fSendUnacknowledged; 2338 fSendUnacknowledged = segment.acknowledge; 2339 uint32 flightSize = (fSendMax - fSendUnacknowledged).Number(); 2340 int32 expectedSamples = flightSize / (fSendMaxSegmentSize << 1); 2341 2342 if (fPreviousHighestAcknowledge > fSendUnacknowledged) { 2343 // need to update the recover variable upon a sequence wraparound 2344 fRecover = segment.acknowledge - 1; 2345 } 2346 2347 // the acknowledgment of the SYN/ACK MUST NOT increase the size of the congestion window 2348 if (fSendUnacknowledged != fInitialSendSequence) { 2349 if (fCongestionWindow < fSlowStartThreshold) 2350 fCongestionWindow += min_c(bytesAcknowledged, fSendMaxSegmentSize); 2351 else { 2352 uint32 increment = fSendMaxSegmentSize * fSendMaxSegmentSize; 2353 2354 if (increment < fCongestionWindow) 2355 increment = 1; 2356 else 2357 increment /= fCongestionWindow; 2358 2359 fCongestionWindow += increment; 2360 } 2361 2362 fSendMaxSegments = UINT32_MAX; 2363 } 2364 2365 if ((fFlags & FLAG_RECOVERY) != 0) { 2366 fSendNext = fSendUnacknowledged; 2367 _SendQueued(); 2368 fCongestionWindow -= bytesAcknowledged; 2369 2370 if (bytesAcknowledged > fSendMaxSegmentSize) 2371 fCongestionWindow += fSendMaxSegmentSize; 2372 2373 fSendNext = fSendMax; 2374 } else 2375 fDuplicateAcknowledgeCount = 0; 2376 2377 if (fSendNext < fSendUnacknowledged) 2378 fSendNext = fSendUnacknowledged; 2379 2380 if (fFlags & FLAG_OPTION_TIMESTAMP) { 2381 _UpdateRoundTripTime(tcp_diff_timestamp(segment.timestamp_reply), 2382 expectedSamples > 0 ? expectedSamples : 1); 2383 } else if (fSendTime != 0 && fRoundTripStartSequence < segment.acknowledge) { 2384 _UpdateRoundTripTime(tcp_diff_timestamp(fSendTime), 1); 2385 fSendTime = 0; 2386 } 2387 2388 if (fSendUnacknowledged == fSendMax) { 2389 TRACE("all acknowledged, cancelling retransmission timer."); 2390 gStackModule->cancel_timer(&fRetransmitTimer); 2391 T(TimerSet(this, "retransmit", -1)); 2392 } else { 2393 TRACE("data acknowledged, resetting retransmission timer to: %" 2394 B_PRIdBIGTIME, fRetransmitTimeout); 2395 gStackModule->set_timer(&fRetransmitTimer, fRetransmitTimeout); 2396 T(TimerSet(this, "retransmit", fRetransmitTimeout)); 2397 } 2398 2399 if (is_writable(fState)) { 2400 // notify threads waiting on the socket to become writable again 2401 fSendCondition.NotifyAll(); 2402 gSocketModule->notify(socket, B_SELECT_WRITE, fSendQueue.Free()); 2403 } 2404 } 2405 2406 // if there is data left to be sent, send it now 2407 if (fSendQueue.Used() > 0) 2408 _SendQueued(); 2409 } 2410 2411 2412 void 2413 TCPEndpoint::_Retransmit() 2414 { 2415 TRACE("Retransmit()"); 2416 2417 if (fState < ESTABLISHED) { 2418 fRetransmitTimeout = TCP_SYN_RETRANSMIT_TIMEOUT; 2419 fCongestionWindow = fSendMaxSegmentSize; 2420 } else { 2421 _ResetSlowStart(); 2422 fDuplicateAcknowledgeCount = 0; 2423 // Do exponential back off of the retransmit timeout 2424 fRetransmitTimeout *= 2; 2425 if (fRetransmitTimeout > TCP_MAX_RETRANSMIT_TIMEOUT) 2426 fRetransmitTimeout = TCP_MAX_RETRANSMIT_TIMEOUT; 2427 } 2428 2429 fSendNext = fSendUnacknowledged; 2430 _SendQueued(); 2431 2432 fRecover = fSendNext.Number() - 1; 2433 if ((fFlags & FLAG_RECOVERY) != 0) 2434 fFlags &= ~FLAG_RECOVERY; 2435 } 2436 2437 2438 void 2439 TCPEndpoint::_UpdateRoundTripTime(int32 roundTripTime, int32 expectedSamples) 2440 { 2441 if (fSmoothedRoundTripTime == 0) { 2442 fSmoothedRoundTripTime = roundTripTime; 2443 fRoundTripVariation = roundTripTime / 2; 2444 fRetransmitTimeout = (fSmoothedRoundTripTime + max_c(100, fRoundTripVariation * 4)) 2445 * kTimestampFactor; 2446 } else { 2447 int32 delta = fSmoothedRoundTripTime - roundTripTime; 2448 if (delta < 0) 2449 delta = -delta; 2450 fRoundTripVariation += (delta - fRoundTripVariation) / (expectedSamples * 4); 2451 fSmoothedRoundTripTime += (roundTripTime - fSmoothedRoundTripTime) / (expectedSamples * 8); 2452 fRetransmitTimeout = (fSmoothedRoundTripTime + max_c(100, fRoundTripVariation * 4)) 2453 * kTimestampFactor; 2454 } 2455 2456 if (fRetransmitTimeout > TCP_MAX_RETRANSMIT_TIMEOUT) 2457 fRetransmitTimeout = TCP_MAX_RETRANSMIT_TIMEOUT; 2458 2459 if (fRetransmitTimeout < TCP_MIN_RETRANSMIT_TIMEOUT) 2460 fRetransmitTimeout = TCP_MIN_RETRANSMIT_TIMEOUT; 2461 2462 TRACE(" RTO is now %" B_PRIdBIGTIME " (after rtt %" B_PRId32 "ms)", 2463 fRetransmitTimeout, roundTripTime); 2464 } 2465 2466 2467 void 2468 TCPEndpoint::_ResetSlowStart() 2469 { 2470 fSlowStartThreshold = max_c((fSendMax - fSendUnacknowledged).Number() / 2, 2471 2 * fSendMaxSegmentSize); 2472 fCongestionWindow = fSendMaxSegmentSize; 2473 } 2474 2475 2476 // #pragma mark - timer 2477 2478 2479 /*static*/ void 2480 TCPEndpoint::_RetransmitTimer(net_timer* timer, void* _endpoint) 2481 { 2482 TCPEndpoint* endpoint = (TCPEndpoint*)_endpoint; 2483 T(TimerTriggered(endpoint, "retransmit")); 2484 2485 MutexLocker locker(endpoint->fLock); 2486 if (!locker.IsLocked() || gStackModule->is_timer_active(timer)) 2487 return; 2488 2489 endpoint->_Retransmit(); 2490 } 2491 2492 2493 /*static*/ void 2494 TCPEndpoint::_PersistTimer(net_timer* timer, void* _endpoint) 2495 { 2496 TCPEndpoint* endpoint = (TCPEndpoint*)_endpoint; 2497 T(TimerTriggered(endpoint, "persist")); 2498 2499 MutexLocker locker(endpoint->fLock); 2500 if (!locker.IsLocked()) 2501 return; 2502 2503 // the timer might not have been canceled early enough 2504 if (endpoint->State() == CLOSED) 2505 return; 2506 if (endpoint->fSendQueue.Available(endpoint->fSendNext) == 0) 2507 return; 2508 2509 endpoint->_SendQueued(true); 2510 } 2511 2512 2513 /*static*/ void 2514 TCPEndpoint::_DelayedAcknowledgeTimer(net_timer* timer, void* _endpoint) 2515 { 2516 TCPEndpoint* endpoint = (TCPEndpoint*)_endpoint; 2517 T(TimerTriggered(endpoint, "delayed ack")); 2518 2519 MutexLocker locker(endpoint->fLock); 2520 if (!locker.IsLocked()) 2521 return; 2522 2523 // the timer might not have been canceled early enough 2524 if (endpoint->State() == CLOSED) 2525 return; 2526 if (endpoint->fLastAcknowledgeSent == endpoint->fReceiveNext) 2527 return; 2528 2529 endpoint->SendAcknowledge(true); 2530 } 2531 2532 2533 /*static*/ void 2534 TCPEndpoint::_TimeWaitTimer(net_timer* timer, void* _endpoint) 2535 { 2536 TCPEndpoint* endpoint = (TCPEndpoint*)_endpoint; 2537 T(TimerTriggered(endpoint, "time-wait")); 2538 2539 MutexLocker locker(endpoint->fLock); 2540 if (!locker.IsLocked()) 2541 return; 2542 2543 if ((endpoint->fFlags & FLAG_CLOSED) == 0) { 2544 endpoint->fFlags |= FLAG_DELETE_ON_CLOSE; 2545 return; 2546 } 2547 2548 locker.Unlock(); 2549 2550 gSocketModule->release_socket(endpoint->socket); 2551 } 2552 2553 2554 /*static*/ status_t 2555 TCPEndpoint::_WaitForCondition(ConditionVariable& condition, 2556 MutexLocker& locker, bigtime_t timeout) 2557 { 2558 ConditionVariableEntry entry; 2559 condition.Add(&entry); 2560 2561 locker.Unlock(); 2562 status_t result = entry.Wait(B_ABSOLUTE_TIMEOUT | B_CAN_INTERRUPT, timeout); 2563 locker.Lock(); 2564 2565 return result; 2566 } 2567 2568 2569 // #pragma mark - 2570 2571 2572 void 2573 TCPEndpoint::Dump() const 2574 { 2575 kprintf("TCP endpoint %p\n", this); 2576 kprintf(" state: %s\n", name_for_state(fState)); 2577 kprintf(" flags: 0x%" B_PRIx32 "\n", fFlags); 2578 #if KDEBUG 2579 kprintf(" lock: { %p, holder: %" B_PRId32 " }\n", &fLock, fLock.holder); 2580 #endif 2581 kprintf(" accept sem: %" B_PRId32 "\n", fAcceptSemaphore); 2582 kprintf(" options: 0x%" B_PRIx32 "\n", (uint32)fOptions); 2583 kprintf(" send\n"); 2584 kprintf(" window shift: %" B_PRIu8 "\n", fSendWindowShift); 2585 kprintf(" unacknowledged: %" B_PRIu32 "\n", 2586 fSendUnacknowledged.Number()); 2587 kprintf(" next: %" B_PRIu32 "\n", fSendNext.Number()); 2588 kprintf(" max: %" B_PRIu32 "\n", fSendMax.Number()); 2589 kprintf(" urgent offset: %" B_PRIu32 "\n", fSendUrgentOffset.Number()); 2590 kprintf(" window: %" B_PRIu32 "\n", fSendWindow); 2591 kprintf(" max window: %" B_PRIu32 "\n", fSendMaxWindow); 2592 kprintf(" max segment size: %" B_PRIu32 "\n", fSendMaxSegmentSize); 2593 kprintf(" queue: %" B_PRIuSIZE " / %" B_PRIuSIZE "\n", fSendQueue.Used(), 2594 fSendQueue.Size()); 2595 #if DEBUG_TCP_BUFFER_QUEUE 2596 fSendQueue.Dump(); 2597 #endif 2598 kprintf(" last acknowledge sent: %" B_PRIu32 "\n", 2599 fLastAcknowledgeSent.Number()); 2600 kprintf(" initial sequence: %" B_PRIu32 "\n", 2601 fInitialSendSequence.Number()); 2602 kprintf(" receive\n"); 2603 kprintf(" window shift: %" B_PRIu8 "\n", fReceiveWindowShift); 2604 kprintf(" next: %" B_PRIu32 "\n", fReceiveNext.Number()); 2605 kprintf(" max advertised: %" B_PRIu32 "\n", 2606 fReceiveMaxAdvertised.Number()); 2607 kprintf(" window: %" B_PRIu32 "\n", fReceiveWindow); 2608 kprintf(" max segment size: %" B_PRIu32 "\n", fReceiveMaxSegmentSize); 2609 kprintf(" queue: %" B_PRIuSIZE " / %" B_PRIuSIZE "\n", 2610 fReceiveQueue.Available(), fReceiveQueue.Size()); 2611 #if DEBUG_TCP_BUFFER_QUEUE 2612 fReceiveQueue.Dump(); 2613 #endif 2614 kprintf(" initial sequence: %" B_PRIu32 "\n", 2615 fInitialReceiveSequence.Number()); 2616 kprintf(" duplicate acknowledge count: %" B_PRIu32 "\n", 2617 fDuplicateAcknowledgeCount); 2618 kprintf(" smoothed round trip time: %" B_PRId32 " (deviation %" B_PRId32 ")\n", 2619 fSmoothedRoundTripTime, fRoundTripVariation); 2620 kprintf(" retransmit timeout: %" B_PRId64 "\n", fRetransmitTimeout); 2621 kprintf(" congestion window: %" B_PRIu32 "\n", fCongestionWindow); 2622 kprintf(" slow start threshold: %" B_PRIu32 "\n", fSlowStartThreshold); 2623 } 2624 2625