connection.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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.Debug("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() && this.rd.Before(time.Now()) {
  154. timer = time.AfterFunc(this.rd.Sub(time.Now()), this.dataInputCond.Signal)
  155. }
  156. this.dataInputCond.L.Lock()
  157. this.dataInputCond.Wait()
  158. this.dataInputCond.L.Unlock()
  159. if timer != nil {
  160. timer.Stop()
  161. }
  162. if !this.rd.IsZero() && this.rd.Before(time.Now()) {
  163. return 0, errTimeout
  164. }
  165. }
  166. }
  167. // Write implements the Conn Write method.
  168. func (this *Connection) Write(b []byte) (int, error) {
  169. if this == nil || this.State() != StateActive {
  170. return 0, io.ErrClosedPipe
  171. }
  172. totalWritten := 0
  173. for {
  174. if this == nil || this.State() != StateActive {
  175. return totalWritten, io.ErrClosedPipe
  176. }
  177. nBytes := this.sendingWorker.Push(b[totalWritten:])
  178. if nBytes > 0 {
  179. totalWritten += nBytes
  180. if totalWritten == len(b) {
  181. return totalWritten, nil
  182. }
  183. }
  184. if !this.wd.IsZero() && this.wd.Before(time.Now()) {
  185. return totalWritten, errTimeout
  186. }
  187. // Sending windows is 1024 for the moment. This amount is not gonna sent in 1 sec.
  188. time.Sleep(time.Second)
  189. }
  190. }
  191. func (this *Connection) SetState(state State) {
  192. atomic.StoreInt32((*int32)(&this.state), int32(state))
  193. atomic.StoreUint32(&this.stateBeginTime, this.Elapsed())
  194. switch state {
  195. case StateReadyToClose:
  196. this.receivingWorker.CloseRead()
  197. case StatePeerClosed:
  198. this.sendingWorker.CloseWrite()
  199. case StateTerminating:
  200. this.receivingWorker.CloseRead()
  201. this.sendingWorker.CloseWrite()
  202. case StateTerminated:
  203. this.receivingWorker.CloseRead()
  204. this.sendingWorker.CloseWrite()
  205. }
  206. }
  207. // Close closes the connection.
  208. func (this *Connection) Close() error {
  209. if this == nil {
  210. return errClosedConnection
  211. }
  212. this.dataInputCond.Broadcast()
  213. state := this.State()
  214. if state == StateReadyToClose ||
  215. state == StateTerminating ||
  216. state == StateTerminated {
  217. return errClosedConnection
  218. }
  219. log.Debug("KCP|Connection: Closing connection to ", this.remote)
  220. if state == StateActive {
  221. this.SetState(StateReadyToClose)
  222. }
  223. if state == StatePeerClosed {
  224. this.SetState(StateTerminating)
  225. }
  226. return nil
  227. }
  228. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  229. func (this *Connection) LocalAddr() net.Addr {
  230. if this == nil {
  231. return nil
  232. }
  233. return this.local
  234. }
  235. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  236. func (this *Connection) RemoteAddr() net.Addr {
  237. if this == nil {
  238. return nil
  239. }
  240. return this.remote
  241. }
  242. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  243. func (this *Connection) SetDeadline(t time.Time) error {
  244. if err := this.SetReadDeadline(t); err != nil {
  245. return err
  246. }
  247. if err := this.SetWriteDeadline(t); err != nil {
  248. return err
  249. }
  250. return nil
  251. }
  252. // SetReadDeadline implements the Conn SetReadDeadline method.
  253. func (this *Connection) SetReadDeadline(t time.Time) error {
  254. if this == nil || this.State() != StateActive {
  255. return errClosedConnection
  256. }
  257. this.rd = t
  258. return nil
  259. }
  260. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  261. func (this *Connection) SetWriteDeadline(t time.Time) error {
  262. if this == nil || this.State() != StateActive {
  263. return errClosedConnection
  264. }
  265. this.wd = t
  266. return nil
  267. }
  268. // kcp update, input loop
  269. func (this *Connection) updateTask() {
  270. for this.State() != StateTerminated {
  271. this.flush()
  272. interval := time.Duration(effectiveConfig.Tti) * time.Millisecond
  273. if this.State() == StateTerminating {
  274. interval = time.Second
  275. }
  276. time.Sleep(interval)
  277. }
  278. this.Terminate()
  279. }
  280. func (this *Connection) FetchInputFrom(conn net.Conn) {
  281. go func() {
  282. for {
  283. payload := alloc.NewBuffer()
  284. nBytes, err := conn.Read(payload.Value)
  285. if err != nil {
  286. payload.Release()
  287. return
  288. }
  289. payload.Slice(0, nBytes)
  290. if this.block.Open(payload) {
  291. this.Input(payload.Value)
  292. } else {
  293. log.Info("KCP|Connection: Invalid response from ", conn.RemoteAddr())
  294. }
  295. payload.Release()
  296. }
  297. }()
  298. }
  299. func (this *Connection) Reusable() bool {
  300. return false
  301. }
  302. func (this *Connection) SetReusable(b bool) {}
  303. func (this *Connection) Terminate() {
  304. if this == nil || this.writer == nil {
  305. return
  306. }
  307. log.Info("Terminating connection to ", this.RemoteAddr())
  308. this.writer.Close()
  309. }
  310. func (this *Connection) HandleOption(opt SegmentOption) {
  311. if (opt & SegmentOptionClose) == SegmentOptionClose {
  312. this.OnPeerClosed()
  313. }
  314. }
  315. func (this *Connection) OnPeerClosed() {
  316. state := this.State()
  317. if state == StateReadyToClose {
  318. this.SetState(StateTerminating)
  319. }
  320. if state == StateActive {
  321. this.SetState(StatePeerClosed)
  322. }
  323. }
  324. // Input when you received a low level packet (eg. UDP packet), call it
  325. func (this *Connection) Input(data []byte) int {
  326. current := this.Elapsed()
  327. atomic.StoreUint32(&this.lastIncomingTime, current)
  328. var seg Segment
  329. for {
  330. seg, data = ReadSegment(data)
  331. if seg == nil {
  332. break
  333. }
  334. switch seg := seg.(type) {
  335. case *DataSegment:
  336. this.HandleOption(seg.Opt)
  337. this.receivingWorker.ProcessSegment(seg)
  338. atomic.StoreUint32(&this.lastPayloadTime, current)
  339. this.dataInputCond.Signal()
  340. case *AckSegment:
  341. this.HandleOption(seg.Opt)
  342. this.sendingWorker.ProcessSegment(current, seg)
  343. atomic.StoreUint32(&this.lastPayloadTime, current)
  344. case *CmdOnlySegment:
  345. this.HandleOption(seg.Opt)
  346. if seg.Cmd == SegmentCommandTerminated {
  347. state := this.State()
  348. if state == StateActive ||
  349. state == StateReadyToClose ||
  350. state == StatePeerClosed {
  351. this.SetState(StateTerminating)
  352. } else if state == StateTerminating {
  353. this.SetState(StateTerminated)
  354. }
  355. }
  356. this.sendingWorker.ProcessReceivingNext(seg.ReceivinNext)
  357. this.receivingWorker.ProcessSendingNext(seg.SendingNext)
  358. default:
  359. }
  360. }
  361. return 0
  362. }
  363. func (this *Connection) flush() {
  364. current := this.Elapsed()
  365. if this.State() == StateTerminated {
  366. return
  367. }
  368. if this.State() == StateActive && current-this.lastPayloadTime >= 30000 {
  369. this.Close()
  370. }
  371. if this.State() == StateTerminating {
  372. this.output.Write(&CmdOnlySegment{
  373. Conv: this.conv,
  374. Cmd: SegmentCommandTerminated,
  375. })
  376. this.output.Flush()
  377. if current-this.stateBeginTime > 8000 {
  378. this.SetState(StateTerminated)
  379. }
  380. return
  381. }
  382. if this.State() == StateReadyToClose && current-this.stateBeginTime > 15000 {
  383. this.SetState(StateTerminating)
  384. }
  385. // flush acknowledges
  386. this.receivingWorker.Flush(current)
  387. this.sendingWorker.Flush(current)
  388. if this.sendingWorker.PingNecessary() || this.receivingWorker.PingNecessary() || current-this.lastPingTime >= 5000 {
  389. seg := NewCmdOnlySegment()
  390. seg.Conv = this.conv
  391. seg.Cmd = SegmentCommandPing
  392. seg.ReceivinNext = this.receivingWorker.nextNumber
  393. seg.SendingNext = this.sendingWorker.firstUnacknowledged
  394. if this.State() == StateReadyToClose {
  395. seg.Opt = SegmentOptionClose
  396. }
  397. this.output.Write(seg)
  398. this.lastPingTime = current
  399. this.sendingUpdated = false
  400. seg.Release()
  401. }
  402. // flash remain segments
  403. this.output.Flush()
  404. }
  405. func (this *Connection) State() State {
  406. return State(atomic.LoadInt32((*int32)(&this.state)))
  407. }