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