connection.go 11 KB

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