blob: 0dfe7d829894484281216472f86cf14a85c04d19 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
pthatcher@webrtc.orge9db7fe2014-12-13 01:56:39 +000011#include "webrtc/p2p/base/pseudotcp.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000012
13#include <stdio.h>
14#include <stdlib.h>
15
16#include <set>
17
18#include "webrtc/base/basictypes.h"
19#include "webrtc/base/bytebuffer.h"
20#include "webrtc/base/byteorder.h"
21#include "webrtc/base/common.h"
22#include "webrtc/base/logging.h"
23#include "webrtc/base/scoped_ptr.h"
24#include "webrtc/base/socket.h"
25#include "webrtc/base/stringutils.h"
26#include "webrtc/base/timeutils.h"
27
28// The following logging is for detailed (packet-level) analysis only.
29#define _DBG_NONE 0
30#define _DBG_NORMAL 1
31#define _DBG_VERBOSE 2
32#define _DEBUGMSG _DBG_NONE
33
34namespace cricket {
35
36//////////////////////////////////////////////////////////////////////
37// Network Constants
38//////////////////////////////////////////////////////////////////////
39
40// Standard MTUs
41const uint16 PACKET_MAXIMUMS[] = {
42 65535, // Theoretical maximum, Hyperchannel
43 32000, // Nothing
44 17914, // 16Mb IBM Token Ring
45 8166, // IEEE 802.4
46 //4464, // IEEE 802.5 (4Mb max)
47 4352, // FDDI
48 //2048, // Wideband Network
49 2002, // IEEE 802.5 (4Mb recommended)
50 //1536, // Expermental Ethernet Networks
51 //1500, // Ethernet, Point-to-Point (default)
52 1492, // IEEE 802.3
53 1006, // SLIP, ARPANET
54 //576, // X.25 Networks
55 //544, // DEC IP Portal
56 //512, // NETBIOS
57 508, // IEEE 802/Source-Rt Bridge, ARCNET
58 296, // Point-to-Point (low delay)
59 //68, // Official minimum
60 0, // End of list marker
61};
62
63const uint32 MAX_PACKET = 65535;
64// Note: we removed lowest level because packet overhead was larger!
65const uint32 MIN_PACKET = 296;
66
67const uint32 IP_HEADER_SIZE = 20; // (+ up to 40 bytes of options?)
68const uint32 UDP_HEADER_SIZE = 8;
69// TODO: Make JINGLE_HEADER_SIZE transparent to this code?
70const uint32 JINGLE_HEADER_SIZE = 64; // when relay framing is in use
71
72// Default size for receive and send buffer.
73const uint32 DEFAULT_RCV_BUF_SIZE = 60 * 1024;
74const uint32 DEFAULT_SND_BUF_SIZE = 90 * 1024;
75
76//////////////////////////////////////////////////////////////////////
77// Global Constants and Functions
78//////////////////////////////////////////////////////////////////////
79//
80// 0 1 2 3
81// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
82// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
83// 0 | Conversation Number |
84// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
85// 4 | Sequence Number |
86// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
87// 8 | Acknowledgment Number |
88// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
89// | | |U|A|P|R|S|F| |
90// 12 | Control | |R|C|S|S|Y|I| Window |
91// | | |G|K|H|T|N|N| |
92// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
93// 16 | Timestamp sending |
94// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
95// 20 | Timestamp receiving |
96// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
97// 24 | data |
98// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
99//
100//////////////////////////////////////////////////////////////////////
101
102#define PSEUDO_KEEPALIVE 0
103
104const uint32 HEADER_SIZE = 24;
105const uint32 PACKET_OVERHEAD = HEADER_SIZE + UDP_HEADER_SIZE + IP_HEADER_SIZE + JINGLE_HEADER_SIZE;
106
107const uint32 MIN_RTO = 250; // 250 ms (RFC1122, Sec 4.2.3.1 "fractions of a second")
108const uint32 DEF_RTO = 3000; // 3 seconds (RFC1122, Sec 4.2.3.1)
109const uint32 MAX_RTO = 60000; // 60 seconds
110const uint32 DEF_ACK_DELAY = 100; // 100 milliseconds
111
112const uint8 FLAG_CTL = 0x02;
113const uint8 FLAG_RST = 0x04;
114
115const uint8 CTL_CONNECT = 0;
116
117// TCP options.
118const uint8 TCP_OPT_EOL = 0; // End of list.
119const uint8 TCP_OPT_NOOP = 1; // No-op.
120const uint8 TCP_OPT_MSS = 2; // Maximum segment size.
121const uint8 TCP_OPT_WND_SCALE = 3; // Window scale factor.
122
123const long DEFAULT_TIMEOUT = 4000; // If there are no pending clocks, wake up every 4 seconds
124const long CLOSED_TIMEOUT = 60 * 1000; // If the connection is closed, once per minute
125
126#if PSEUDO_KEEPALIVE
127// !?! Rethink these times
128const uint32 IDLE_PING = 20 * 1000; // 20 seconds (note: WinXP SP2 firewall udp timeout is 90 seconds)
129const uint32 IDLE_TIMEOUT = 90 * 1000; // 90 seconds;
130#endif // PSEUDO_KEEPALIVE
131
132//////////////////////////////////////////////////////////////////////
133// Helper Functions
134//////////////////////////////////////////////////////////////////////
135
136inline void long_to_bytes(uint32 val, void* buf) {
137 *static_cast<uint32*>(buf) = rtc::HostToNetwork32(val);
138}
139
140inline void short_to_bytes(uint16 val, void* buf) {
141 *static_cast<uint16*>(buf) = rtc::HostToNetwork16(val);
142}
143
144inline uint32 bytes_to_long(const void* buf) {
145 return rtc::NetworkToHost32(*static_cast<const uint32*>(buf));
146}
147
148inline uint16 bytes_to_short(const void* buf) {
149 return rtc::NetworkToHost16(*static_cast<const uint16*>(buf));
150}
151
152uint32 bound(uint32 lower, uint32 middle, uint32 upper) {
153 return rtc::_min(rtc::_max(lower, middle), upper);
154}
155
156//////////////////////////////////////////////////////////////////////
157// Debugging Statistics
158//////////////////////////////////////////////////////////////////////
159
160#if 0 // Not used yet
161
162enum Stat {
163 S_SENT_PACKET, // All packet sends
164 S_RESENT_PACKET, // All packet sends that are retransmits
165 S_RECV_PACKET, // All packet receives
166 S_RECV_NEW, // All packet receives that are too new
167 S_RECV_OLD, // All packet receives that are too old
168 S_NUM_STATS
169};
170
171const char* const STAT_NAMES[S_NUM_STATS] = {
172 "snt",
173 "snt-r",
174 "rcv"
175 "rcv-n",
176 "rcv-o"
177};
178
179int g_stats[S_NUM_STATS];
180inline void Incr(Stat s) { ++g_stats[s]; }
181void ReportStats() {
182 char buffer[256];
183 size_t len = 0;
184 for (int i = 0; i < S_NUM_STATS; ++i) {
185 len += rtc::sprintfn(buffer, ARRAY_SIZE(buffer), "%s%s:%d",
186 (i == 0) ? "" : ",", STAT_NAMES[i], g_stats[i]);
187 g_stats[i] = 0;
188 }
189 LOG(LS_INFO) << "Stats[" << buffer << "]";
190}
191
192#endif
193
194//////////////////////////////////////////////////////////////////////
195// PseudoTcp
196//////////////////////////////////////////////////////////////////////
197
198uint32 PseudoTcp::Now() {
199#if 0 // Use this to synchronize timers with logging timestamps (easier debug)
200 return rtc::TimeSince(StartTime());
201#else
202 return rtc::Time();
203#endif
204}
205
206PseudoTcp::PseudoTcp(IPseudoTcpNotify* notify, uint32 conv)
207 : m_notify(notify),
208 m_shutdown(SD_NONE),
209 m_error(0),
210 m_rbuf_len(DEFAULT_RCV_BUF_SIZE),
211 m_rbuf(m_rbuf_len),
212 m_sbuf_len(DEFAULT_SND_BUF_SIZE),
213 m_sbuf(m_sbuf_len) {
214
215 // Sanity check on buffer sizes (needed for OnTcpWriteable notification logic)
216 ASSERT(m_rbuf_len + MIN_PACKET < m_sbuf_len);
217
218 uint32 now = Now();
219
220 m_state = TCP_LISTEN;
221 m_conv = conv;
222 m_rcv_wnd = m_rbuf_len;
223 m_rwnd_scale = m_swnd_scale = 0;
224 m_snd_nxt = 0;
225 m_snd_wnd = 1;
226 m_snd_una = m_rcv_nxt = 0;
227 m_bReadEnable = true;
228 m_bWriteEnable = false;
229 m_t_ack = 0;
230
231 m_msslevel = 0;
232 m_largest = 0;
233 ASSERT(MIN_PACKET > PACKET_OVERHEAD);
234 m_mss = MIN_PACKET - PACKET_OVERHEAD;
235 m_mtu_advise = MAX_PACKET;
236
237 m_rto_base = 0;
238
239 m_cwnd = 2 * m_mss;
240 m_ssthresh = m_rbuf_len;
241 m_lastrecv = m_lastsend = m_lasttraffic = now;
242 m_bOutgoing = false;
243
244 m_dup_acks = 0;
245 m_recover = 0;
246
247 m_ts_recent = m_ts_lastack = 0;
248
249 m_rx_rto = DEF_RTO;
250 m_rx_srtt = m_rx_rttvar = 0;
251
252 m_use_nagling = true;
253 m_ack_delay = DEF_ACK_DELAY;
254 m_support_wnd_scale = true;
255}
256
257PseudoTcp::~PseudoTcp() {
258}
259
260int PseudoTcp::Connect() {
261 if (m_state != TCP_LISTEN) {
262 m_error = EINVAL;
263 return -1;
264 }
265
266 m_state = TCP_SYN_SENT;
267 LOG(LS_INFO) << "State: TCP_SYN_SENT";
268
269 queueConnectMessage();
270 attemptSend();
271
272 return 0;
273}
274
275void PseudoTcp::NotifyMTU(uint16 mtu) {
276 m_mtu_advise = mtu;
277 if (m_state == TCP_ESTABLISHED) {
278 adjustMTU();
279 }
280}
281
282void PseudoTcp::NotifyClock(uint32 now) {
283 if (m_state == TCP_CLOSED)
284 return;
285
286 // Check if it's time to retransmit a segment
287 if (m_rto_base && (rtc::TimeDiff(m_rto_base + m_rx_rto, now) <= 0)) {
288 if (m_slist.empty()) {
289 ASSERT(false);
290 } else {
291 // Note: (m_slist.front().xmit == 0)) {
292 // retransmit segments
293#if _DEBUGMSG >= _DBG_NORMAL
294 LOG(LS_INFO) << "timeout retransmit (rto: " << m_rx_rto
295 << ") (rto_base: " << m_rto_base
296 << ") (now: " << now
297 << ") (dup_acks: " << static_cast<unsigned>(m_dup_acks)
298 << ")";
299#endif // _DEBUGMSG
300 if (!transmit(m_slist.begin(), now)) {
301 closedown(ECONNABORTED);
302 return;
303 }
304
305 uint32 nInFlight = m_snd_nxt - m_snd_una;
306 m_ssthresh = rtc::_max(nInFlight / 2, 2 * m_mss);
307 //LOG(LS_INFO) << "m_ssthresh: " << m_ssthresh << " nInFlight: " << nInFlight << " m_mss: " << m_mss;
308 m_cwnd = m_mss;
309
310 // Back off retransmit timer. Note: the limit is lower when connecting.
311 uint32 rto_limit = (m_state < TCP_ESTABLISHED) ? DEF_RTO : MAX_RTO;
312 m_rx_rto = rtc::_min(rto_limit, m_rx_rto * 2);
313 m_rto_base = now;
314 }
315 }
316
317 // Check if it's time to probe closed windows
318 if ((m_snd_wnd == 0)
319 && (rtc::TimeDiff(m_lastsend + m_rx_rto, now) <= 0)) {
320 if (rtc::TimeDiff(now, m_lastrecv) >= 15000) {
321 closedown(ECONNABORTED);
322 return;
323 }
324
325 // probe the window
326 packet(m_snd_nxt - 1, 0, 0, 0);
327 m_lastsend = now;
328
329 // back off retransmit timer
330 m_rx_rto = rtc::_min(MAX_RTO, m_rx_rto * 2);
331 }
332
333 // Check if it's time to send delayed acks
334 if (m_t_ack && (rtc::TimeDiff(m_t_ack + m_ack_delay, now) <= 0)) {
335 packet(m_snd_nxt, 0, 0, 0);
336 }
337
338#if PSEUDO_KEEPALIVE
339 // Check for idle timeout
340 if ((m_state == TCP_ESTABLISHED) && (TimeDiff(m_lastrecv + IDLE_TIMEOUT, now) <= 0)) {
341 closedown(ECONNABORTED);
342 return;
343 }
344
345 // Check for ping timeout (to keep udp mapping open)
346 if ((m_state == TCP_ESTABLISHED) && (TimeDiff(m_lasttraffic + (m_bOutgoing ? IDLE_PING * 3/2 : IDLE_PING), now) <= 0)) {
347 packet(m_snd_nxt, 0, 0, 0);
348 }
349#endif // PSEUDO_KEEPALIVE
350}
351
352bool PseudoTcp::NotifyPacket(const char* buffer, size_t len) {
353 if (len > MAX_PACKET) {
354 LOG_F(WARNING) << "packet too large";
355 return false;
356 }
357 return parse(reinterpret_cast<const uint8 *>(buffer), uint32(len));
358}
359
360bool PseudoTcp::GetNextClock(uint32 now, long& timeout) {
361 return clock_check(now, timeout);
362}
363
364void PseudoTcp::GetOption(Option opt, int* value) {
365 if (opt == OPT_NODELAY) {
366 *value = m_use_nagling ? 0 : 1;
367 } else if (opt == OPT_ACKDELAY) {
368 *value = m_ack_delay;
369 } else if (opt == OPT_SNDBUF) {
370 *value = m_sbuf_len;
371 } else if (opt == OPT_RCVBUF) {
372 *value = m_rbuf_len;
373 } else {
374 ASSERT(false);
375 }
376}
377void PseudoTcp::SetOption(Option opt, int value) {
378 if (opt == OPT_NODELAY) {
379 m_use_nagling = value == 0;
380 } else if (opt == OPT_ACKDELAY) {
381 m_ack_delay = value;
382 } else if (opt == OPT_SNDBUF) {
383 ASSERT(m_state == TCP_LISTEN);
384 resizeSendBuffer(value);
385 } else if (opt == OPT_RCVBUF) {
386 ASSERT(m_state == TCP_LISTEN);
387 resizeReceiveBuffer(value);
388 } else {
389 ASSERT(false);
390 }
391}
392
393uint32 PseudoTcp::GetCongestionWindow() const {
394 return m_cwnd;
395}
396
397uint32 PseudoTcp::GetBytesInFlight() const {
398 return m_snd_nxt - m_snd_una;
399}
400
401uint32 PseudoTcp::GetBytesBufferedNotSent() const {
402 size_t buffered_bytes = 0;
403 m_sbuf.GetBuffered(&buffered_bytes);
404 return static_cast<uint32>(m_snd_una + buffered_bytes - m_snd_nxt);
405}
406
407uint32 PseudoTcp::GetRoundTripTimeEstimateMs() const {
408 return m_rx_srtt;
409}
410
411//
412// IPStream Implementation
413//
414
415int PseudoTcp::Recv(char* buffer, size_t len) {
416 if (m_state != TCP_ESTABLISHED) {
417 m_error = ENOTCONN;
418 return SOCKET_ERROR;
419 }
420
421 size_t read = 0;
422 rtc::StreamResult result = m_rbuf.Read(buffer, len, &read, NULL);
423
424 // If there's no data in |m_rbuf|.
425 if (result == rtc::SR_BLOCK) {
426 m_bReadEnable = true;
427 m_error = EWOULDBLOCK;
428 return SOCKET_ERROR;
429 }
430 ASSERT(result == rtc::SR_SUCCESS);
431
432 size_t available_space = 0;
433 m_rbuf.GetWriteRemaining(&available_space);
434
435 if (uint32(available_space) - m_rcv_wnd >=
436 rtc::_min<uint32>(m_rbuf_len / 2, m_mss)) {
437 // TODO(jbeda): !?! Not sure about this was closed business
438 bool bWasClosed = (m_rcv_wnd == 0);
439 m_rcv_wnd = static_cast<uint32>(available_space);
440
441 if (bWasClosed) {
442 attemptSend(sfImmediateAck);
443 }
444 }
445
446 return static_cast<int>(read);
447}
448
449int PseudoTcp::Send(const char* buffer, size_t len) {
450 if (m_state != TCP_ESTABLISHED) {
451 m_error = ENOTCONN;
452 return SOCKET_ERROR;
453 }
454
455 size_t available_space = 0;
456 m_sbuf.GetWriteRemaining(&available_space);
457
458 if (!available_space) {
459 m_bWriteEnable = true;
460 m_error = EWOULDBLOCK;
461 return SOCKET_ERROR;
462 }
463
464 int written = queue(buffer, uint32(len), false);
465 attemptSend();
466 return written;
467}
468
469void PseudoTcp::Close(bool force) {
470 LOG_F(LS_VERBOSE) << "(" << (force ? "true" : "false") << ")";
471 m_shutdown = force ? SD_FORCEFUL : SD_GRACEFUL;
472}
473
474int PseudoTcp::GetError() {
475 return m_error;
476}
477
478//
479// Internal Implementation
480//
481
482uint32 PseudoTcp::queue(const char* data, uint32 len, bool bCtrl) {
483 size_t available_space = 0;
484 m_sbuf.GetWriteRemaining(&available_space);
485
486 if (len > static_cast<uint32>(available_space)) {
487 ASSERT(!bCtrl);
488 len = static_cast<uint32>(available_space);
489 }
490
491 // We can concatenate data if the last segment is the same type
492 // (control v. regular data), and has not been transmitted yet
493 if (!m_slist.empty() && (m_slist.back().bCtrl == bCtrl) &&
494 (m_slist.back().xmit == 0)) {
495 m_slist.back().len += len;
496 } else {
497 size_t snd_buffered = 0;
498 m_sbuf.GetBuffered(&snd_buffered);
499 SSegment sseg(static_cast<uint32>(m_snd_una + snd_buffered), len, bCtrl);
500 m_slist.push_back(sseg);
501 }
502
503 size_t written = 0;
504 m_sbuf.Write(data, len, &written, NULL);
505 return static_cast<uint32>(written);
506}
507
508IPseudoTcpNotify::WriteResult PseudoTcp::packet(uint32 seq, uint8 flags,
509 uint32 offset, uint32 len) {
510 ASSERT(HEADER_SIZE + len <= MAX_PACKET);
511
512 uint32 now = Now();
513
514 rtc::scoped_ptr<uint8[]> buffer(new uint8[MAX_PACKET]);
515 long_to_bytes(m_conv, buffer.get());
516 long_to_bytes(seq, buffer.get() + 4);
517 long_to_bytes(m_rcv_nxt, buffer.get() + 8);
518 buffer[12] = 0;
519 buffer[13] = flags;
520 short_to_bytes(
521 static_cast<uint16>(m_rcv_wnd >> m_rwnd_scale), buffer.get() + 14);
522
523 // Timestamp computations
524 long_to_bytes(now, buffer.get() + 16);
525 long_to_bytes(m_ts_recent, buffer.get() + 20);
526 m_ts_lastack = m_rcv_nxt;
527
528 if (len) {
529 size_t bytes_read = 0;
530 rtc::StreamResult result = m_sbuf.ReadOffset(
531 buffer.get() + HEADER_SIZE, len, offset, &bytes_read);
532 RTC_UNUSED(result);
533 ASSERT(result == rtc::SR_SUCCESS);
534 ASSERT(static_cast<uint32>(bytes_read) == len);
535 }
536
537#if _DEBUGMSG >= _DBG_VERBOSE
538 LOG(LS_INFO) << "<-- <CONV=" << m_conv
539 << "><FLG=" << static_cast<unsigned>(flags)
540 << "><SEQ=" << seq << ":" << seq + len
541 << "><ACK=" << m_rcv_nxt
542 << "><WND=" << m_rcv_wnd
543 << "><TS=" << (now % 10000)
544 << "><TSR=" << (m_ts_recent % 10000)
545 << "><LEN=" << len << ">";
546#endif // _DEBUGMSG
547
548 IPseudoTcpNotify::WriteResult wres = m_notify->TcpWritePacket(
549 this, reinterpret_cast<char *>(buffer.get()), len + HEADER_SIZE);
550 // Note: When len is 0, this is an ACK packet. We don't read the return value for those,
551 // and thus we won't retry. So go ahead and treat the packet as a success (basically simulate
552 // as if it were dropped), which will prevent our timers from being messed up.
553 if ((wres != IPseudoTcpNotify::WR_SUCCESS) && (0 != len))
554 return wres;
555
556 m_t_ack = 0;
557 if (len > 0) {
558 m_lastsend = now;
559 }
560 m_lasttraffic = now;
561 m_bOutgoing = true;
562
563 return IPseudoTcpNotify::WR_SUCCESS;
564}
565
566bool PseudoTcp::parse(const uint8* buffer, uint32 size) {
567 if (size < 12)
568 return false;
569
570 Segment seg;
571 seg.conv = bytes_to_long(buffer);
572 seg.seq = bytes_to_long(buffer + 4);
573 seg.ack = bytes_to_long(buffer + 8);
574 seg.flags = buffer[13];
575 seg.wnd = bytes_to_short(buffer + 14);
576
577 seg.tsval = bytes_to_long(buffer + 16);
578 seg.tsecr = bytes_to_long(buffer + 20);
579
580 seg.data = reinterpret_cast<const char *>(buffer) + HEADER_SIZE;
581 seg.len = size - HEADER_SIZE;
582
583#if _DEBUGMSG >= _DBG_VERBOSE
584 LOG(LS_INFO) << "--> <CONV=" << seg.conv
585 << "><FLG=" << static_cast<unsigned>(seg.flags)
586 << "><SEQ=" << seg.seq << ":" << seg.seq + seg.len
587 << "><ACK=" << seg.ack
588 << "><WND=" << seg.wnd
589 << "><TS=" << (seg.tsval % 10000)
590 << "><TSR=" << (seg.tsecr % 10000)
591 << "><LEN=" << seg.len << ">";
592#endif // _DEBUGMSG
593
594 return process(seg);
595}
596
597bool PseudoTcp::clock_check(uint32 now, long& nTimeout) {
598 if (m_shutdown == SD_FORCEFUL)
599 return false;
600
601 size_t snd_buffered = 0;
602 m_sbuf.GetBuffered(&snd_buffered);
603 if ((m_shutdown == SD_GRACEFUL)
604 && ((m_state != TCP_ESTABLISHED)
605 || ((snd_buffered == 0) && (m_t_ack == 0)))) {
606 return false;
607 }
608
609 if (m_state == TCP_CLOSED) {
610 nTimeout = CLOSED_TIMEOUT;
611 return true;
612 }
613
614 nTimeout = DEFAULT_TIMEOUT;
615
616 if (m_t_ack) {
617 nTimeout = rtc::_min<int32>(nTimeout,
618 rtc::TimeDiff(m_t_ack + m_ack_delay, now));
619 }
620 if (m_rto_base) {
621 nTimeout = rtc::_min<int32>(nTimeout,
622 rtc::TimeDiff(m_rto_base + m_rx_rto, now));
623 }
624 if (m_snd_wnd == 0) {
625 nTimeout = rtc::_min<int32>(nTimeout, rtc::TimeDiff(m_lastsend + m_rx_rto, now));
626 }
627#if PSEUDO_KEEPALIVE
628 if (m_state == TCP_ESTABLISHED) {
629 nTimeout = rtc::_min<int32>(nTimeout,
630 rtc::TimeDiff(m_lasttraffic + (m_bOutgoing ? IDLE_PING * 3/2 : IDLE_PING), now));
631 }
632#endif // PSEUDO_KEEPALIVE
633 return true;
634}
635
636bool PseudoTcp::process(Segment& seg) {
637 // If this is the wrong conversation, send a reset!?! (with the correct conversation?)
638 if (seg.conv != m_conv) {
639 //if ((seg.flags & FLAG_RST) == 0) {
640 // packet(tcb, seg.ack, 0, FLAG_RST, 0, 0);
641 //}
642 LOG_F(LS_ERROR) << "wrong conversation";
643 return false;
644 }
645
646 uint32 now = Now();
647 m_lasttraffic = m_lastrecv = now;
648 m_bOutgoing = false;
649
650 if (m_state == TCP_CLOSED) {
651 // !?! send reset?
652 LOG_F(LS_ERROR) << "closed";
653 return false;
654 }
655
656 // Check if this is a reset segment
657 if (seg.flags & FLAG_RST) {
658 closedown(ECONNRESET);
659 return false;
660 }
661
662 // Check for control data
663 bool bConnect = false;
664 if (seg.flags & FLAG_CTL) {
665 if (seg.len == 0) {
666 LOG_F(LS_ERROR) << "Missing control code";
667 return false;
668 } else if (seg.data[0] == CTL_CONNECT) {
669 bConnect = true;
670
671 // TCP options are in the remainder of the payload after CTL_CONNECT.
672 parseOptions(&seg.data[1], seg.len - 1);
673
674 if (m_state == TCP_LISTEN) {
675 m_state = TCP_SYN_RECEIVED;
676 LOG(LS_INFO) << "State: TCP_SYN_RECEIVED";
677 //m_notify->associate(addr);
678 queueConnectMessage();
679 } else if (m_state == TCP_SYN_SENT) {
680 m_state = TCP_ESTABLISHED;
681 LOG(LS_INFO) << "State: TCP_ESTABLISHED";
682 adjustMTU();
683 if (m_notify) {
684 m_notify->OnTcpOpen(this);
685 }
686 //notify(evOpen);
687 }
688 } else {
689 LOG_F(LS_WARNING) << "Unknown control code: " << seg.data[0];
690 return false;
691 }
692 }
693
694 // Update timestamp
695 if ((seg.seq <= m_ts_lastack) && (m_ts_lastack < seg.seq + seg.len)) {
696 m_ts_recent = seg.tsval;
697 }
698
699 // Check if this is a valuable ack
700 if ((seg.ack > m_snd_una) && (seg.ack <= m_snd_nxt)) {
701 // Calculate round-trip time
702 if (seg.tsecr) {
703 int32 rtt = rtc::TimeDiff(now, seg.tsecr);
704 if (rtt >= 0) {
705 if (m_rx_srtt == 0) {
706 m_rx_srtt = rtt;
707 m_rx_rttvar = rtt / 2;
708 } else {
709 uint32 unsigned_rtt = static_cast<uint32>(rtt);
710 uint32 abs_err = unsigned_rtt > m_rx_srtt ? unsigned_rtt - m_rx_srtt
711 : m_rx_srtt - unsigned_rtt;
712 m_rx_rttvar = (3 * m_rx_rttvar + abs_err) / 4;
713 m_rx_srtt = (7 * m_rx_srtt + rtt) / 8;
714 }
715 m_rx_rto = bound(MIN_RTO, m_rx_srtt +
716 rtc::_max<uint32>(1, 4 * m_rx_rttvar), MAX_RTO);
717#if _DEBUGMSG >= _DBG_VERBOSE
718 LOG(LS_INFO) << "rtt: " << rtt
719 << " srtt: " << m_rx_srtt
720 << " rto: " << m_rx_rto;
721#endif // _DEBUGMSG
722 } else {
723 ASSERT(false);
724 }
725 }
726
727 m_snd_wnd = static_cast<uint32>(seg.wnd) << m_swnd_scale;
728
729 uint32 nAcked = seg.ack - m_snd_una;
730 m_snd_una = seg.ack;
731
732 m_rto_base = (m_snd_una == m_snd_nxt) ? 0 : now;
733
734 m_sbuf.ConsumeReadData(nAcked);
735
736 for (uint32 nFree = nAcked; nFree > 0; ) {
737 ASSERT(!m_slist.empty());
738 if (nFree < m_slist.front().len) {
739 m_slist.front().len -= nFree;
740 nFree = 0;
741 } else {
742 if (m_slist.front().len > m_largest) {
743 m_largest = m_slist.front().len;
744 }
745 nFree -= m_slist.front().len;
746 m_slist.pop_front();
747 }
748 }
749
750 if (m_dup_acks >= 3) {
751 if (m_snd_una >= m_recover) { // NewReno
752 uint32 nInFlight = m_snd_nxt - m_snd_una;
753 m_cwnd = rtc::_min(m_ssthresh, nInFlight + m_mss); // (Fast Retransmit)
754#if _DEBUGMSG >= _DBG_NORMAL
755 LOG(LS_INFO) << "exit recovery";
756#endif // _DEBUGMSG
757 m_dup_acks = 0;
758 } else {
759#if _DEBUGMSG >= _DBG_NORMAL
760 LOG(LS_INFO) << "recovery retransmit";
761#endif // _DEBUGMSG
762 if (!transmit(m_slist.begin(), now)) {
763 closedown(ECONNABORTED);
764 return false;
765 }
766 m_cwnd += m_mss - rtc::_min(nAcked, m_cwnd);
767 }
768 } else {
769 m_dup_acks = 0;
770 // Slow start, congestion avoidance
771 if (m_cwnd < m_ssthresh) {
772 m_cwnd += m_mss;
773 } else {
774 m_cwnd += rtc::_max<uint32>(1, m_mss * m_mss / m_cwnd);
775 }
776 }
777 } else if (seg.ack == m_snd_una) {
778 // !?! Note, tcp says don't do this... but otherwise how does a closed window become open?
779 m_snd_wnd = static_cast<uint32>(seg.wnd) << m_swnd_scale;
780
781 // Check duplicate acks
782 if (seg.len > 0) {
783 // it's a dup ack, but with a data payload, so don't modify m_dup_acks
784 } else if (m_snd_una != m_snd_nxt) {
785 m_dup_acks += 1;
786 if (m_dup_acks == 3) { // (Fast Retransmit)
787#if _DEBUGMSG >= _DBG_NORMAL
788 LOG(LS_INFO) << "enter recovery";
789 LOG(LS_INFO) << "recovery retransmit";
790#endif // _DEBUGMSG
791 if (!transmit(m_slist.begin(), now)) {
792 closedown(ECONNABORTED);
793 return false;
794 }
795 m_recover = m_snd_nxt;
796 uint32 nInFlight = m_snd_nxt - m_snd_una;
797 m_ssthresh = rtc::_max(nInFlight / 2, 2 * m_mss);
798 //LOG(LS_INFO) << "m_ssthresh: " << m_ssthresh << " nInFlight: " << nInFlight << " m_mss: " << m_mss;
799 m_cwnd = m_ssthresh + 3 * m_mss;
800 } else if (m_dup_acks > 3) {
801 m_cwnd += m_mss;
802 }
803 } else {
804 m_dup_acks = 0;
805 }
806 }
807
808 // !?! A bit hacky
809 if ((m_state == TCP_SYN_RECEIVED) && !bConnect) {
810 m_state = TCP_ESTABLISHED;
811 LOG(LS_INFO) << "State: TCP_ESTABLISHED";
812 adjustMTU();
813 if (m_notify) {
814 m_notify->OnTcpOpen(this);
815 }
816 //notify(evOpen);
817 }
818
819 // If we make room in the send queue, notify the user
820 // The goal it to make sure we always have at least enough data to fill the
821 // window. We'd like to notify the app when we are halfway to that point.
822 const uint32 kIdealRefillSize = (m_sbuf_len + m_rbuf_len) / 2;
823 size_t snd_buffered = 0;
824 m_sbuf.GetBuffered(&snd_buffered);
825 if (m_bWriteEnable && static_cast<uint32>(snd_buffered) < kIdealRefillSize) {
826 m_bWriteEnable = false;
827 if (m_notify) {
828 m_notify->OnTcpWriteable(this);
829 }
830 //notify(evWrite);
831 }
832
833 // Conditions were acks must be sent:
834 // 1) Segment is too old (they missed an ACK) (immediately)
835 // 2) Segment is too new (we missed a segment) (immediately)
836 // 3) Segment has data (so we need to ACK!) (delayed)
837 // ... so the only time we don't need to ACK, is an empty segment that points to rcv_nxt!
838
839 SendFlags sflags = sfNone;
840 if (seg.seq != m_rcv_nxt) {
841 sflags = sfImmediateAck; // (Fast Recovery)
842 } else if (seg.len != 0) {
843 if (m_ack_delay == 0) {
844 sflags = sfImmediateAck;
845 } else {
846 sflags = sfDelayedAck;
847 }
848 }
849#if _DEBUGMSG >= _DBG_NORMAL
850 if (sflags == sfImmediateAck) {
851 if (seg.seq > m_rcv_nxt) {
852 LOG_F(LS_INFO) << "too new";
853 } else if (seg.seq + seg.len <= m_rcv_nxt) {
854 LOG_F(LS_INFO) << "too old";
855 }
856 }
857#endif // _DEBUGMSG
858
859 // Adjust the incoming segment to fit our receive buffer
860 if (seg.seq < m_rcv_nxt) {
861 uint32 nAdjust = m_rcv_nxt - seg.seq;
862 if (nAdjust < seg.len) {
863 seg.seq += nAdjust;
864 seg.data += nAdjust;
865 seg.len -= nAdjust;
866 } else {
867 seg.len = 0;
868 }
869 }
870
871 size_t available_space = 0;
872 m_rbuf.GetWriteRemaining(&available_space);
873
874 if ((seg.seq + seg.len - m_rcv_nxt) > static_cast<uint32>(available_space)) {
875 uint32 nAdjust = seg.seq + seg.len - m_rcv_nxt - static_cast<uint32>(available_space);
876 if (nAdjust < seg.len) {
877 seg.len -= nAdjust;
878 } else {
879 seg.len = 0;
880 }
881 }
882
883 bool bIgnoreData = (seg.flags & FLAG_CTL) || (m_shutdown != SD_NONE);
884 bool bNewData = false;
885
886 if (seg.len > 0) {
887 if (bIgnoreData) {
888 if (seg.seq == m_rcv_nxt) {
889 m_rcv_nxt += seg.len;
890 }
891 } else {
892 uint32 nOffset = seg.seq - m_rcv_nxt;
893
894 rtc::StreamResult result = m_rbuf.WriteOffset(seg.data, seg.len,
895 nOffset, NULL);
896 ASSERT(result == rtc::SR_SUCCESS);
897 RTC_UNUSED(result);
898
899 if (seg.seq == m_rcv_nxt) {
900 m_rbuf.ConsumeWriteBuffer(seg.len);
901 m_rcv_nxt += seg.len;
902 m_rcv_wnd -= seg.len;
903 bNewData = true;
904
905 RList::iterator it = m_rlist.begin();
906 while ((it != m_rlist.end()) && (it->seq <= m_rcv_nxt)) {
907 if (it->seq + it->len > m_rcv_nxt) {
908 sflags = sfImmediateAck; // (Fast Recovery)
909 uint32 nAdjust = (it->seq + it->len) - m_rcv_nxt;
910#if _DEBUGMSG >= _DBG_NORMAL
911 LOG(LS_INFO) << "Recovered " << nAdjust << " bytes (" << m_rcv_nxt << " -> " << m_rcv_nxt + nAdjust << ")";
912#endif // _DEBUGMSG
913 m_rbuf.ConsumeWriteBuffer(nAdjust);
914 m_rcv_nxt += nAdjust;
915 m_rcv_wnd -= nAdjust;
916 }
917 it = m_rlist.erase(it);
918 }
919 } else {
920#if _DEBUGMSG >= _DBG_NORMAL
921 LOG(LS_INFO) << "Saving " << seg.len << " bytes (" << seg.seq << " -> " << seg.seq + seg.len << ")";
922#endif // _DEBUGMSG
923 RSegment rseg;
924 rseg.seq = seg.seq;
925 rseg.len = seg.len;
926 RList::iterator it = m_rlist.begin();
927 while ((it != m_rlist.end()) && (it->seq < rseg.seq)) {
928 ++it;
929 }
930 m_rlist.insert(it, rseg);
931 }
932 }
933 }
934
935 attemptSend(sflags);
936
937 // If we have new data, notify the user
938 if (bNewData && m_bReadEnable) {
939 m_bReadEnable = false;
940 if (m_notify) {
941 m_notify->OnTcpReadable(this);
942 }
943 //notify(evRead);
944 }
945
946 return true;
947}
948
949bool PseudoTcp::transmit(const SList::iterator& seg, uint32 now) {
950 if (seg->xmit >= ((m_state == TCP_ESTABLISHED) ? 15 : 30)) {
951 LOG_F(LS_VERBOSE) << "too many retransmits";
952 return false;
953 }
954
955 uint32 nTransmit = rtc::_min(seg->len, m_mss);
956
957 while (true) {
958 uint32 seq = seg->seq;
959 uint8 flags = (seg->bCtrl ? FLAG_CTL : 0);
960 IPseudoTcpNotify::WriteResult wres = packet(seq,
961 flags,
962 seg->seq - m_snd_una,
963 nTransmit);
964
965 if (wres == IPseudoTcpNotify::WR_SUCCESS)
966 break;
967
968 if (wres == IPseudoTcpNotify::WR_FAIL) {
969 LOG_F(LS_VERBOSE) << "packet failed";
970 return false;
971 }
972
973 ASSERT(wres == IPseudoTcpNotify::WR_TOO_LARGE);
974
975 while (true) {
976 if (PACKET_MAXIMUMS[m_msslevel + 1] == 0) {
977 LOG_F(LS_VERBOSE) << "MTU too small";
978 return false;
979 }
980 // !?! We need to break up all outstanding and pending packets and then retransmit!?!
981
982 m_mss = PACKET_MAXIMUMS[++m_msslevel] - PACKET_OVERHEAD;
983 m_cwnd = 2 * m_mss; // I added this... haven't researched actual formula
984 if (m_mss < nTransmit) {
985 nTransmit = m_mss;
986 break;
987 }
988 }
989#if _DEBUGMSG >= _DBG_NORMAL
990 LOG(LS_INFO) << "Adjusting mss to " << m_mss << " bytes";
991#endif // _DEBUGMSG
992 }
993
994 if (nTransmit < seg->len) {
995 LOG_F(LS_VERBOSE) << "mss reduced to " << m_mss;
996
997 SSegment subseg(seg->seq + nTransmit, seg->len - nTransmit, seg->bCtrl);
998 //subseg.tstamp = seg->tstamp;
999 subseg.xmit = seg->xmit;
1000 seg->len = nTransmit;
1001
1002 SList::iterator next = seg;
1003 m_slist.insert(++next, subseg);
1004 }
1005
1006 if (seg->xmit == 0) {
1007 m_snd_nxt += seg->len;
1008 }
1009 seg->xmit += 1;
1010 //seg->tstamp = now;
1011 if (m_rto_base == 0) {
1012 m_rto_base = now;
1013 }
1014
1015 return true;
1016}
1017
1018void PseudoTcp::attemptSend(SendFlags sflags) {
1019 uint32 now = Now();
1020
1021 if (rtc::TimeDiff(now, m_lastsend) > static_cast<long>(m_rx_rto)) {
1022 m_cwnd = m_mss;
1023 }
1024
1025#if _DEBUGMSG
1026 bool bFirst = true;
1027 RTC_UNUSED(bFirst);
1028#endif // _DEBUGMSG
1029
1030 while (true) {
1031 uint32 cwnd = m_cwnd;
1032 if ((m_dup_acks == 1) || (m_dup_acks == 2)) { // Limited Transmit
1033 cwnd += m_dup_acks * m_mss;
1034 }
1035 uint32 nWindow = rtc::_min(m_snd_wnd, cwnd);
1036 uint32 nInFlight = m_snd_nxt - m_snd_una;
1037 uint32 nUseable = (nInFlight < nWindow) ? (nWindow - nInFlight) : 0;
1038
1039 size_t snd_buffered = 0;
1040 m_sbuf.GetBuffered(&snd_buffered);
1041 uint32 nAvailable =
1042 rtc::_min(static_cast<uint32>(snd_buffered) - nInFlight, m_mss);
1043
1044 if (nAvailable > nUseable) {
1045 if (nUseable * 4 < nWindow) {
1046 // RFC 813 - avoid SWS
1047 nAvailable = 0;
1048 } else {
1049 nAvailable = nUseable;
1050 }
1051 }
1052
1053#if _DEBUGMSG >= _DBG_VERBOSE
1054 if (bFirst) {
1055 size_t available_space = 0;
1056 m_sbuf.GetWriteRemaining(&available_space);
1057
1058 bFirst = false;
1059 LOG(LS_INFO) << "[cwnd: " << m_cwnd
1060 << " nWindow: " << nWindow
1061 << " nInFlight: " << nInFlight
1062 << " nAvailable: " << nAvailable
1063 << " nQueued: " << snd_buffered
1064 << " nEmpty: " << available_space
1065 << " ssthresh: " << m_ssthresh << "]";
1066 }
1067#endif // _DEBUGMSG
1068
1069 if (nAvailable == 0) {
1070 if (sflags == sfNone)
1071 return;
1072
1073 // If this is an immediate ack, or the second delayed ack
1074 if ((sflags == sfImmediateAck) || m_t_ack) {
1075 packet(m_snd_nxt, 0, 0, 0);
1076 } else {
1077 m_t_ack = Now();
1078 }
1079 return;
1080 }
1081
1082 // Nagle's algorithm.
1083 // If there is data already in-flight, and we haven't a full segment of
1084 // data ready to send then hold off until we get more to send, or the
1085 // in-flight data is acknowledged.
1086 if (m_use_nagling && (m_snd_nxt > m_snd_una) && (nAvailable < m_mss)) {
1087 return;
1088 }
1089
1090 // Find the next segment to transmit
1091 SList::iterator it = m_slist.begin();
1092 while (it->xmit > 0) {
1093 ++it;
1094 ASSERT(it != m_slist.end());
1095 }
1096 SList::iterator seg = it;
1097
1098 // If the segment is too large, break it into two
1099 if (seg->len > nAvailable) {
1100 SSegment subseg(seg->seq + nAvailable, seg->len - nAvailable, seg->bCtrl);
1101 seg->len = nAvailable;
1102 m_slist.insert(++it, subseg);
1103 }
1104
1105 if (!transmit(seg, now)) {
1106 LOG_F(LS_VERBOSE) << "transmit failed";
1107 // TODO: consider closing socket
1108 return;
1109 }
1110
1111 sflags = sfNone;
1112 }
1113}
1114
1115void
1116PseudoTcp::closedown(uint32 err) {
1117 LOG(LS_INFO) << "State: TCP_CLOSED";
1118 m_state = TCP_CLOSED;
1119 if (m_notify) {
1120 m_notify->OnTcpClosed(this, err);
1121 }
1122 //notify(evClose, err);
1123}
1124
1125void
1126PseudoTcp::adjustMTU() {
1127 // Determine our current mss level, so that we can adjust appropriately later
1128 for (m_msslevel = 0; PACKET_MAXIMUMS[m_msslevel + 1] > 0; ++m_msslevel) {
1129 if (static_cast<uint16>(PACKET_MAXIMUMS[m_msslevel]) <= m_mtu_advise) {
1130 break;
1131 }
1132 }
1133 m_mss = m_mtu_advise - PACKET_OVERHEAD;
1134 // !?! Should we reset m_largest here?
1135#if _DEBUGMSG >= _DBG_NORMAL
1136 LOG(LS_INFO) << "Adjusting mss to " << m_mss << " bytes";
1137#endif // _DEBUGMSG
1138 // Enforce minimums on ssthresh and cwnd
1139 m_ssthresh = rtc::_max(m_ssthresh, 2 * m_mss);
1140 m_cwnd = rtc::_max(m_cwnd, m_mss);
1141}
1142
1143bool
1144PseudoTcp::isReceiveBufferFull() const {
1145 size_t available_space = 0;
1146 m_rbuf.GetWriteRemaining(&available_space);
1147 return !available_space;
1148}
1149
1150void
1151PseudoTcp::disableWindowScale() {
1152 m_support_wnd_scale = false;
1153}
1154
1155void
1156PseudoTcp::queueConnectMessage() {
1157 rtc::ByteBuffer buf(rtc::ByteBuffer::ORDER_NETWORK);
1158
1159 buf.WriteUInt8(CTL_CONNECT);
1160 if (m_support_wnd_scale) {
1161 buf.WriteUInt8(TCP_OPT_WND_SCALE);
1162 buf.WriteUInt8(1);
1163 buf.WriteUInt8(m_rwnd_scale);
1164 }
1165 m_snd_wnd = static_cast<uint32>(buf.Length());
1166 queue(buf.Data(), static_cast<uint32>(buf.Length()), true);
1167}
1168
1169void
1170PseudoTcp::parseOptions(const char* data, uint32 len) {
1171 std::set<uint8> options_specified;
1172
1173 // See http://www.freesoft.org/CIE/Course/Section4/8.htm for
1174 // parsing the options list.
1175 rtc::ByteBuffer buf(data, len);
1176 while (buf.Length()) {
1177 uint8 kind = TCP_OPT_EOL;
1178 buf.ReadUInt8(&kind);
1179
1180 if (kind == TCP_OPT_EOL) {
1181 // End of option list.
1182 break;
1183 } else if (kind == TCP_OPT_NOOP) {
1184 // No op.
1185 continue;
1186 }
1187
1188 // Length of this option.
1189 ASSERT(len != 0);
1190 RTC_UNUSED(len);
1191 uint8 opt_len = 0;
1192 buf.ReadUInt8(&opt_len);
1193
1194 // Content of this option.
1195 if (opt_len <= buf.Length()) {
1196 applyOption(kind, buf.Data(), opt_len);
1197 buf.Consume(opt_len);
1198 } else {
1199 LOG(LS_ERROR) << "Invalid option length received.";
1200 return;
1201 }
1202 options_specified.insert(kind);
1203 }
1204
1205 if (options_specified.find(TCP_OPT_WND_SCALE) == options_specified.end()) {
1206 LOG(LS_WARNING) << "Peer doesn't support window scaling";
1207
1208 if (m_rwnd_scale > 0) {
1209 // Peer doesn't support TCP options and window scaling.
1210 // Revert receive buffer size to default value.
1211 resizeReceiveBuffer(DEFAULT_RCV_BUF_SIZE);
1212 m_swnd_scale = 0;
1213 }
1214 }
1215}
1216
1217void
1218PseudoTcp::applyOption(char kind, const char* data, uint32 len) {
1219 if (kind == TCP_OPT_MSS) {
1220 LOG(LS_WARNING) << "Peer specified MSS option which is not supported.";
1221 // TODO: Implement.
1222 } else if (kind == TCP_OPT_WND_SCALE) {
1223 // Window scale factor.
1224 // http://www.ietf.org/rfc/rfc1323.txt
1225 if (len != 1) {
1226 LOG_F(WARNING) << "Invalid window scale option received.";
1227 return;
1228 }
1229 applyWindowScaleOption(data[0]);
1230 }
1231}
1232
1233void
1234PseudoTcp::applyWindowScaleOption(uint8 scale_factor) {
1235 m_swnd_scale = scale_factor;
1236}
1237
1238void
1239PseudoTcp::resizeSendBuffer(uint32 new_size) {
1240 m_sbuf_len = new_size;
1241 m_sbuf.SetCapacity(new_size);
1242}
1243
1244void
1245PseudoTcp::resizeReceiveBuffer(uint32 new_size) {
1246 uint8 scale_factor = 0;
1247
1248 // Determine the scale factor such that the scaled window size can fit
1249 // in a 16-bit unsigned integer.
1250 while (new_size > 0xFFFF) {
1251 ++scale_factor;
1252 new_size >>= 1;
1253 }
1254
1255 // Determine the proper size of the buffer.
1256 new_size <<= scale_factor;
1257 bool result = m_rbuf.SetCapacity(new_size);
1258
1259 // Make sure the new buffer is large enough to contain data in the old
1260 // buffer. This should always be true because this method is called either
1261 // before connection is established or when peers are exchanging connect
1262 // messages.
1263 ASSERT(result);
1264 RTC_UNUSED(result);
1265 m_rbuf_len = new_size;
1266 m_rwnd_scale = scale_factor;
1267 m_ssthresh = new_size;
1268
1269 size_t available_space = 0;
1270 m_rbuf.GetWriteRemaining(&available_space);
1271 m_rcv_wnd = static_cast<uint32>(available_space);
1272}
1273
1274} // namespace cricket