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