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