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