connection.go 11 KB

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