connection.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. package kcp
  2. import (
  3. "errors"
  4. "io"
  5. "net"
  6. "sync"
  7. "sync/atomic"
  8. "time"
  9. "github.com/v2ray/v2ray-core/common/alloc"
  10. "github.com/v2ray/v2ray-core/common/log"
  11. )
  12. var (
  13. errTimeout = errors.New("i/o timeout")
  14. errBrokenPipe = errors.New("broken pipe")
  15. errClosedListener = errors.New("Listener closed.")
  16. errClosedConnection = errors.New("Connection closed.")
  17. )
  18. type State int32
  19. const (
  20. StateActive State = 0
  21. StateReadyToClose State = 1
  22. StatePeerClosed State = 2
  23. StateTerminating State = 3
  24. StateTerminated State = 4
  25. )
  26. const (
  27. headerSize uint32 = 2
  28. )
  29. func nowMillisec() int64 {
  30. now := time.Now()
  31. return now.Unix()*1000 + int64(now.Nanosecond()/1000000)
  32. }
  33. type RountTripInfo struct {
  34. sync.RWMutex
  35. variation uint32
  36. srtt uint32
  37. rto uint32
  38. minRtt uint32
  39. }
  40. func (this *RountTripInfo) Update(rtt uint32) {
  41. if rtt > 0x7FFFFFFF {
  42. return
  43. }
  44. this.Lock()
  45. defer this.Unlock()
  46. // https://tools.ietf.org/html/rfc6298
  47. if this.srtt == 0 {
  48. this.srtt = rtt
  49. this.variation = rtt / 2
  50. } else {
  51. delta := rtt - this.srtt
  52. if this.srtt > rtt {
  53. delta = this.srtt - rtt
  54. }
  55. this.variation = (3*this.variation + delta) / 4
  56. this.srtt = (7*this.srtt + rtt) / 8
  57. if this.srtt < this.minRtt {
  58. this.srtt = this.minRtt
  59. }
  60. }
  61. var rto uint32
  62. if this.minRtt < 4*this.variation {
  63. rto = this.srtt + 4*this.variation
  64. } else {
  65. rto = this.srtt + this.variation
  66. }
  67. if rto > 10000 {
  68. rto = 10000
  69. }
  70. this.rto = rto * 3 / 2
  71. }
  72. func (this *RountTripInfo) Timeout() uint32 {
  73. this.RLock()
  74. defer this.RUnlock()
  75. return this.rto
  76. }
  77. func (this *RountTripInfo) SmoothedTime() uint32 {
  78. this.RLock()
  79. defer this.RUnlock()
  80. return this.srtt
  81. }
  82. // Connection is a KCP connection over UDP.
  83. type Connection struct {
  84. block Authenticator
  85. local, remote net.Addr
  86. rd time.Time
  87. wd time.Time // write deadline
  88. writer io.WriteCloser
  89. since int64
  90. dataInputCond *sync.Cond
  91. conv uint16
  92. state State
  93. stateBeginTime uint32
  94. lastIncomingTime uint32
  95. lastPayloadTime uint32
  96. sendingUpdated bool
  97. lastPingTime uint32
  98. mss uint32
  99. roundTrip *RountTripInfo
  100. interval uint32
  101. receivingWorker *ReceivingWorker
  102. sendingWorker *SendingWorker
  103. fastresend uint32
  104. congestionControl bool
  105. output *BufferedSegmentWriter
  106. }
  107. // NewConnection create a new KCP connection between local and remote.
  108. func NewConnection(conv uint16, writerCloser io.WriteCloser, local *net.UDPAddr, remote *net.UDPAddr, block Authenticator) *Connection {
  109. log.Info("KCP|Connection: creating connection ", conv)
  110. conn := new(Connection)
  111. conn.local = local
  112. conn.remote = remote
  113. conn.block = block
  114. conn.writer = writerCloser
  115. conn.since = nowMillisec()
  116. conn.dataInputCond = sync.NewCond(new(sync.Mutex))
  117. authWriter := &AuthenticationWriter{
  118. Authenticator: block,
  119. Writer: writerCloser,
  120. }
  121. conn.conv = conv
  122. conn.output = NewSegmentWriter(authWriter)
  123. conn.mss = authWriter.Mtu() - DataSegmentOverhead
  124. conn.roundTrip = &RountTripInfo{
  125. rto: 100,
  126. minRtt: effectiveConfig.Tti,
  127. }
  128. conn.interval = effectiveConfig.Tti
  129. conn.receivingWorker = NewReceivingWorker(conn)
  130. conn.fastresend = 2
  131. conn.congestionControl = effectiveConfig.Congestion
  132. conn.sendingWorker = NewSendingWorker(conn)
  133. go conn.updateTask()
  134. return conn
  135. }
  136. func (this *Connection) Elapsed() uint32 {
  137. return uint32(nowMillisec() - this.since)
  138. }
  139. // Read implements the Conn Read method.
  140. func (this *Connection) Read(b []byte) (int, error) {
  141. if this == nil {
  142. return 0, io.EOF
  143. }
  144. for {
  145. if this.State() == StateReadyToClose || this.State() == StateTerminating || this.State() == StateTerminated {
  146. return 0, io.EOF
  147. }
  148. nBytes := this.receivingWorker.Read(b)
  149. if nBytes > 0 {
  150. return nBytes, nil
  151. }
  152. var timer *time.Timer
  153. if !this.rd.IsZero() {
  154. duration := this.rd.Sub(time.Now())
  155. if duration <= 0 {
  156. return 0, errTimeout
  157. }
  158. timer = time.AfterFunc(duration, this.dataInputCond.Signal)
  159. }
  160. this.dataInputCond.L.Lock()
  161. this.dataInputCond.Wait()
  162. this.dataInputCond.L.Unlock()
  163. if timer != nil {
  164. timer.Stop()
  165. }
  166. if !this.rd.IsZero() && this.rd.Before(time.Now()) {
  167. return 0, errTimeout
  168. }
  169. }
  170. }
  171. // Write implements the Conn Write method.
  172. func (this *Connection) Write(b []byte) (int, error) {
  173. if this == nil || this.State() != StateActive {
  174. return 0, io.ErrClosedPipe
  175. }
  176. totalWritten := 0
  177. for {
  178. if this == nil || this.State() != StateActive {
  179. return totalWritten, io.ErrClosedPipe
  180. }
  181. nBytes := this.sendingWorker.Push(b[totalWritten:])
  182. if nBytes > 0 {
  183. totalWritten += nBytes
  184. if totalWritten == len(b) {
  185. return totalWritten, nil
  186. }
  187. }
  188. if !this.wd.IsZero() && this.wd.Before(time.Now()) {
  189. return totalWritten, errTimeout
  190. }
  191. // Sending windows is 1024 for the moment. This amount is not gonna sent in 1 sec.
  192. time.Sleep(time.Second)
  193. }
  194. }
  195. func (this *Connection) SetState(state State) {
  196. current := this.Elapsed()
  197. atomic.StoreInt32((*int32)(&this.state), int32(state))
  198. atomic.StoreUint32(&this.stateBeginTime, current)
  199. log.Info("KCP|Connection: Entering state ", state, " at ", current)
  200. switch state {
  201. case StateReadyToClose:
  202. this.receivingWorker.CloseRead()
  203. case StatePeerClosed:
  204. this.sendingWorker.CloseWrite()
  205. case StateTerminating:
  206. this.receivingWorker.CloseRead()
  207. this.sendingWorker.CloseWrite()
  208. case StateTerminated:
  209. this.receivingWorker.CloseRead()
  210. this.sendingWorker.CloseWrite()
  211. }
  212. }
  213. // Close closes the connection.
  214. func (this *Connection) Close() error {
  215. if this == nil {
  216. return errClosedConnection
  217. }
  218. this.dataInputCond.Broadcast()
  219. state := this.State()
  220. if state == StateReadyToClose ||
  221. state == StateTerminating ||
  222. state == StateTerminated {
  223. return errClosedConnection
  224. }
  225. log.Info("KCP|Connection: Closing connection to ", this.remote)
  226. if state == StateActive {
  227. this.SetState(StateReadyToClose)
  228. }
  229. if state == StatePeerClosed {
  230. this.SetState(StateTerminating)
  231. }
  232. return nil
  233. }
  234. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  235. func (this *Connection) LocalAddr() net.Addr {
  236. if this == nil {
  237. return nil
  238. }
  239. return this.local
  240. }
  241. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  242. func (this *Connection) RemoteAddr() net.Addr {
  243. if this == nil {
  244. return nil
  245. }
  246. return this.remote
  247. }
  248. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  249. func (this *Connection) SetDeadline(t time.Time) error {
  250. if err := this.SetReadDeadline(t); err != nil {
  251. return err
  252. }
  253. if err := this.SetWriteDeadline(t); err != nil {
  254. return err
  255. }
  256. return nil
  257. }
  258. // SetReadDeadline implements the Conn SetReadDeadline method.
  259. func (this *Connection) SetReadDeadline(t time.Time) error {
  260. if this == nil || this.State() != StateActive {
  261. return errClosedConnection
  262. }
  263. this.rd = t
  264. return nil
  265. }
  266. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  267. func (this *Connection) SetWriteDeadline(t time.Time) error {
  268. if this == nil || this.State() != StateActive {
  269. return errClosedConnection
  270. }
  271. this.wd = t
  272. return nil
  273. }
  274. // kcp update, input loop
  275. func (this *Connection) updateTask() {
  276. for this.State() != StateTerminated {
  277. this.flush()
  278. interval := time.Duration(effectiveConfig.Tti) * time.Millisecond
  279. if this.State() == StateTerminating {
  280. interval = time.Second
  281. }
  282. time.Sleep(interval)
  283. }
  284. this.Terminate()
  285. }
  286. func (this *Connection) FetchInputFrom(conn net.Conn) {
  287. go func() {
  288. for {
  289. payload := alloc.NewBuffer()
  290. nBytes, err := conn.Read(payload.Value)
  291. if err != nil {
  292. payload.Release()
  293. return
  294. }
  295. payload.Slice(0, nBytes)
  296. if this.block.Open(payload) {
  297. this.Input(payload.Value)
  298. } else {
  299. log.Info("KCP|Connection: Invalid response from ", conn.RemoteAddr())
  300. }
  301. payload.Release()
  302. }
  303. }()
  304. }
  305. func (this *Connection) Reusable() bool {
  306. return false
  307. }
  308. func (this *Connection) SetReusable(b bool) {}
  309. func (this *Connection) Terminate() {
  310. if this == nil || this.writer == nil {
  311. return
  312. }
  313. log.Info("KCP|Connection: Terminating connection to ", this.RemoteAddr())
  314. this.writer.Close()
  315. }
  316. func (this *Connection) HandleOption(opt SegmentOption) {
  317. if (opt & SegmentOptionClose) == SegmentOptionClose {
  318. this.OnPeerClosed()
  319. }
  320. }
  321. func (this *Connection) OnPeerClosed() {
  322. state := this.State()
  323. if state == StateReadyToClose {
  324. this.SetState(StateTerminating)
  325. }
  326. if state == StateActive {
  327. this.SetState(StatePeerClosed)
  328. }
  329. }
  330. // Input when you received a low level packet (eg. UDP packet), call it
  331. func (this *Connection) Input(data []byte) int {
  332. current := this.Elapsed()
  333. atomic.StoreUint32(&this.lastIncomingTime, current)
  334. var seg Segment
  335. for {
  336. seg, data = ReadSegment(data)
  337. if seg == nil {
  338. break
  339. }
  340. switch seg := seg.(type) {
  341. case *DataSegment:
  342. this.HandleOption(seg.Opt)
  343. this.receivingWorker.ProcessSegment(seg)
  344. atomic.StoreUint32(&this.lastPayloadTime, current)
  345. this.dataInputCond.Signal()
  346. case *AckSegment:
  347. this.HandleOption(seg.Opt)
  348. this.sendingWorker.ProcessSegment(current, seg)
  349. atomic.StoreUint32(&this.lastPayloadTime, current)
  350. case *CmdOnlySegment:
  351. this.HandleOption(seg.Opt)
  352. if seg.Cmd == SegmentCommandTerminated {
  353. state := this.State()
  354. if state == StateActive ||
  355. state == StateReadyToClose ||
  356. state == StatePeerClosed {
  357. this.SetState(StateTerminating)
  358. } else if state == StateTerminating {
  359. this.SetState(StateTerminated)
  360. }
  361. }
  362. this.sendingWorker.ProcessReceivingNext(seg.ReceivinNext)
  363. this.receivingWorker.ProcessSendingNext(seg.SendingNext)
  364. default:
  365. }
  366. }
  367. return 0
  368. }
  369. func (this *Connection) flush() {
  370. current := this.Elapsed()
  371. if this.State() == StateTerminated {
  372. return
  373. }
  374. if this.State() == StateActive && current-this.lastPayloadTime >= 30000 {
  375. this.Close()
  376. }
  377. if this.State() == StateTerminating {
  378. this.output.Write(&CmdOnlySegment{
  379. Conv: this.conv,
  380. Cmd: SegmentCommandTerminated,
  381. })
  382. this.output.Flush()
  383. if current-this.stateBeginTime > 8000 {
  384. this.SetState(StateTerminated)
  385. }
  386. return
  387. }
  388. if this.State() == StateReadyToClose && current-this.stateBeginTime > 15000 {
  389. this.SetState(StateTerminating)
  390. }
  391. // flush acknowledges
  392. this.receivingWorker.Flush(current)
  393. this.sendingWorker.Flush(current)
  394. if this.sendingWorker.PingNecessary() || this.receivingWorker.PingNecessary() || current-this.lastPingTime >= 5000 {
  395. seg := NewCmdOnlySegment()
  396. seg.Conv = this.conv
  397. seg.Cmd = SegmentCommandPing
  398. seg.ReceivinNext = this.receivingWorker.nextNumber
  399. seg.SendingNext = this.sendingWorker.firstUnacknowledged
  400. if this.State() == StateReadyToClose {
  401. seg.Opt = SegmentOptionClose
  402. }
  403. this.output.Write(seg)
  404. this.lastPingTime = current
  405. this.sendingUpdated = false
  406. seg.Release()
  407. }
  408. // flash remain segments
  409. this.output.Flush()
  410. }
  411. func (this *Connection) State() State {
  412. return State(atomic.LoadInt32((*int32)(&this.state)))
  413. }