1 /*
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 
11 #ifndef WEBRTC_P2P_BASE_PSEUDOTCP_H_
12 #define WEBRTC_P2P_BASE_PSEUDOTCP_H_
13 
14 #include <list>
15 
16 #include "webrtc/base/basictypes.h"
17 #include "webrtc/base/stream.h"
18 
19 namespace cricket {
20 
21 //////////////////////////////////////////////////////////////////////
22 // IPseudoTcpNotify
23 //////////////////////////////////////////////////////////////////////
24 
25 class PseudoTcp;
26 
27 class IPseudoTcpNotify {
28  public:
29   // Notification of tcp events
30   virtual void OnTcpOpen(PseudoTcp* tcp) = 0;
31   virtual void OnTcpReadable(PseudoTcp* tcp) = 0;
32   virtual void OnTcpWriteable(PseudoTcp* tcp) = 0;
33   virtual void OnTcpClosed(PseudoTcp* tcp, uint32 error) = 0;
34 
35   // Write the packet onto the network
36   enum WriteResult { WR_SUCCESS, WR_TOO_LARGE, WR_FAIL };
37   virtual WriteResult TcpWritePacket(PseudoTcp* tcp,
38                                      const char* buffer, size_t len) = 0;
39 
40  protected:
~IPseudoTcpNotify()41   virtual ~IPseudoTcpNotify() {}
42 };
43 
44 //////////////////////////////////////////////////////////////////////
45 // PseudoTcp
46 //////////////////////////////////////////////////////////////////////
47 
48 class PseudoTcp {
49  public:
50   static uint32 Now();
51 
52   PseudoTcp(IPseudoTcpNotify* notify, uint32 conv);
53   virtual ~PseudoTcp();
54 
55   int Connect();
56   int Recv(char* buffer, size_t len);
57   int Send(const char* buffer, size_t len);
58   void Close(bool force);
59   int GetError();
60 
61   enum TcpState {
62     TCP_LISTEN, TCP_SYN_SENT, TCP_SYN_RECEIVED, TCP_ESTABLISHED, TCP_CLOSED
63   };
State()64   TcpState State() const { return m_state; }
65 
66   // Call this when the PMTU changes.
67   void NotifyMTU(uint16 mtu);
68 
69   // Call this based on timeout value returned from GetNextClock.
70   // It's ok to call this too frequently.
71   void NotifyClock(uint32 now);
72 
73   // Call this whenever a packet arrives.
74   // Returns true if the packet was processed successfully.
75   bool NotifyPacket(const char * buffer, size_t len);
76 
77   // Call this to determine the next time NotifyClock should be called.
78   // Returns false if the socket is ready to be destroyed.
79   bool GetNextClock(uint32 now, long& timeout);
80 
81   // Call these to get/set option values to tailor this PseudoTcp
82   // instance's behaviour for the kind of data it will carry.
83   // If an unrecognized option is set or got, an assertion will fire.
84   //
85   // Setting options for OPT_RCVBUF or OPT_SNDBUF after Connect() is called
86   // will result in an assertion.
87   enum Option {
88     OPT_NODELAY,      // Whether to enable Nagle's algorithm (0 == off)
89     OPT_ACKDELAY,     // The Delayed ACK timeout (0 == off).
90     OPT_RCVBUF,       // Set the receive buffer size, in bytes.
91     OPT_SNDBUF,       // Set the send buffer size, in bytes.
92   };
93   void GetOption(Option opt, int* value);
94   void SetOption(Option opt, int value);
95 
96   // Returns current congestion window in bytes.
97   uint32 GetCongestionWindow() const;
98 
99   // Returns amount of data in bytes that has been sent, but haven't
100   // been acknowledged.
101   uint32 GetBytesInFlight() const;
102 
103   // Returns number of bytes that were written in buffer and haven't
104   // been sent.
105   uint32 GetBytesBufferedNotSent() const;
106 
107   // Returns current round-trip time estimate in milliseconds.
108   uint32 GetRoundTripTimeEstimateMs() const;
109 
110  protected:
111   enum SendFlags { sfNone, sfDelayedAck, sfImmediateAck };
112 
113   struct Segment {
114     uint32 conv, seq, ack;
115     uint8 flags;
116     uint16 wnd;
117     const char * data;
118     uint32 len;
119     uint32 tsval, tsecr;
120   };
121 
122   struct SSegment {
SSegmentSSegment123     SSegment(uint32 s, uint32 l, bool c)
124         : seq(s), len(l), /*tstamp(0),*/ xmit(0), bCtrl(c) {
125     }
126     uint32 seq, len;
127     //uint32 tstamp;
128     uint8 xmit;
129     bool bCtrl;
130   };
131   typedef std::list<SSegment> SList;
132 
133   struct RSegment {
134     uint32 seq, len;
135   };
136 
137   uint32 queue(const char* data, uint32 len, bool bCtrl);
138 
139   // Creates a packet and submits it to the network. This method can either
140   // send payload or just an ACK packet.
141   //
142   // |seq| is the sequence number of this packet.
143   // |flags| is the flags for sending this packet.
144   // |offset| is the offset to read from |m_sbuf|.
145   // |len| is the number of bytes to read from |m_sbuf| as payload. If this
146   // value is 0 then this is an ACK packet, otherwise this packet has payload.
147   IPseudoTcpNotify::WriteResult packet(uint32 seq, uint8 flags,
148                                        uint32 offset, uint32 len);
149   bool parse(const uint8* buffer, uint32 size);
150 
151   void attemptSend(SendFlags sflags = sfNone);
152 
153   void closedown(uint32 err = 0);
154 
155   bool clock_check(uint32 now, long& nTimeout);
156 
157   bool process(Segment& seg);
158   bool transmit(const SList::iterator& seg, uint32 now);
159 
160   void adjustMTU();
161 
162  protected:
163   // This method is used in test only to query receive buffer state.
164   bool isReceiveBufferFull() const;
165 
166   // This method is only used in tests, to disable window scaling
167   // support for testing backward compatibility.
168   void disableWindowScale();
169 
170  private:
171   // Queue the connect message with TCP options.
172   void queueConnectMessage();
173 
174   // Parse TCP options in the header.
175   void parseOptions(const char* data, uint32 len);
176 
177   // Apply a TCP option that has been read from the header.
178   void applyOption(char kind, const char* data, uint32 len);
179 
180   // Apply window scale option.
181   void applyWindowScaleOption(uint8 scale_factor);
182 
183   // Resize the send buffer with |new_size| in bytes.
184   void resizeSendBuffer(uint32 new_size);
185 
186   // Resize the receive buffer with |new_size| in bytes. This call adjusts
187   // window scale factor |m_swnd_scale| accordingly.
188   void resizeReceiveBuffer(uint32 new_size);
189 
190   IPseudoTcpNotify* m_notify;
191   enum Shutdown { SD_NONE, SD_GRACEFUL, SD_FORCEFUL } m_shutdown;
192   int m_error;
193 
194   // TCB data
195   TcpState m_state;
196   uint32 m_conv;
197   bool m_bReadEnable, m_bWriteEnable, m_bOutgoing;
198   uint32 m_lasttraffic;
199 
200   // Incoming data
201   typedef std::list<RSegment> RList;
202   RList m_rlist;
203   uint32 m_rbuf_len, m_rcv_nxt, m_rcv_wnd, m_lastrecv;
204   uint8 m_rwnd_scale;  // Window scale factor.
205   rtc::FifoBuffer m_rbuf;
206 
207   // Outgoing data
208   SList m_slist;
209   uint32 m_sbuf_len, m_snd_nxt, m_snd_wnd, m_lastsend, m_snd_una;
210   uint8 m_swnd_scale;  // Window scale factor.
211   rtc::FifoBuffer m_sbuf;
212 
213   // Maximum segment size, estimated protocol level, largest segment sent
214   uint32 m_mss, m_msslevel, m_largest, m_mtu_advise;
215   // Retransmit timer
216   uint32 m_rto_base;
217 
218   // Timestamp tracking
219   uint32 m_ts_recent, m_ts_lastack;
220 
221   // Round-trip calculation
222   uint32 m_rx_rttvar, m_rx_srtt, m_rx_rto;
223 
224   // Congestion avoidance, Fast retransmit/recovery, Delayed ACKs
225   uint32 m_ssthresh, m_cwnd;
226   uint8 m_dup_acks;
227   uint32 m_recover;
228   uint32 m_t_ack;
229 
230   // Configuration options
231   bool m_use_nagling;
232   uint32 m_ack_delay;
233 
234   // This is used by unit tests to test backward compatibility of
235   // PseudoTcp implementations that don't support window scaling.
236   bool m_support_wnd_scale;
237 };
238 
239 }  // namespace cricket
240 
241 #endif  // WEBRTC_P2P_BASE_PSEUDOTCP_H_
242