You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1296 lines
37 KiB

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