connection.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. lastPingTime uint32
  96. mss uint32
  97. roundTrip *RountTripInfo
  98. interval uint32
  99. receivingWorker *ReceivingWorker
  100. sendingWorker *SendingWorker
  101. fastresend uint32
  102. congestionControl bool
  103. output *BufferedSegmentWriter
  104. }
  105. // NewConnection create a new KCP connection between local and remote.
  106. func NewConnection(conv uint16, writerCloser io.WriteCloser, local *net.UDPAddr, remote *net.UDPAddr, block Authenticator) *Connection {
  107. log.Info("KCP|Connection: creating connection ", conv)
  108. conn := new(Connection)
  109. conn.local = local
  110. conn.remote = remote
  111. conn.block = block
  112. conn.writer = writerCloser
  113. conn.since = nowMillisec()
  114. conn.dataInputCond = sync.NewCond(new(sync.Mutex))
  115. authWriter := &AuthenticationWriter{
  116. Authenticator: block,
  117. Writer: writerCloser,
  118. }
  119. conn.conv = conv
  120. conn.output = NewSegmentWriter(authWriter)
  121. conn.mss = authWriter.Mtu() - DataSegmentOverhead
  122. conn.roundTrip = &RountTripInfo{
  123. rto: 100,
  124. minRtt: effectiveConfig.Tti,
  125. }
  126. conn.interval = effectiveConfig.Tti
  127. conn.receivingWorker = NewReceivingWorker(conn)
  128. conn.fastresend = 2
  129. conn.congestionControl = effectiveConfig.Congestion
  130. conn.sendingWorker = NewSendingWorker(conn)
  131. go conn.updateTask()
  132. return conn
  133. }
  134. func (this *Connection) Elapsed() uint32 {
  135. return uint32(nowMillisec() - this.since)
  136. }
  137. // Read implements the Conn Read method.
  138. func (this *Connection) Read(b []byte) (int, error) {
  139. if this == nil {
  140. return 0, io.EOF
  141. }
  142. for {
  143. if this.State() == StateReadyToClose || this.State() == StateTerminating || this.State() == StateTerminated {
  144. return 0, io.EOF
  145. }
  146. nBytes := this.receivingWorker.Read(b)
  147. if nBytes > 0 {
  148. return nBytes, nil
  149. }
  150. var timer *time.Timer
  151. if !this.rd.IsZero() {
  152. duration := this.rd.Sub(time.Now())
  153. if duration <= 0 {
  154. return 0, errTimeout
  155. }
  156. timer = time.AfterFunc(duration, this.dataInputCond.Signal)
  157. }
  158. this.dataInputCond.L.Lock()
  159. this.dataInputCond.Wait()
  160. this.dataInputCond.L.Unlock()
  161. if timer != nil {
  162. timer.Stop()
  163. }
  164. if !this.rd.IsZero() && this.rd.Before(time.Now()) {
  165. return 0, errTimeout
  166. }
  167. }
  168. }
  169. // Write implements the Conn Write method.
  170. func (this *Connection) Write(b []byte) (int, error) {
  171. if this == nil || this.State() != StateActive {
  172. return 0, io.ErrClosedPipe
  173. }
  174. totalWritten := 0
  175. for {
  176. if this == nil || this.State() != StateActive {
  177. return totalWritten, io.ErrClosedPipe
  178. }
  179. nBytes := this.sendingWorker.Push(b[totalWritten:])
  180. if nBytes > 0 {
  181. totalWritten += nBytes
  182. if totalWritten == len(b) {
  183. return totalWritten, nil
  184. }
  185. }
  186. if !this.wd.IsZero() && this.wd.Before(time.Now()) {
  187. return totalWritten, errTimeout
  188. }
  189. // Sending windows is 1024 for the moment. This amount is not gonna sent in 1 sec.
  190. time.Sleep(time.Second)
  191. }
  192. }
  193. func (this *Connection) SetState(state State) {
  194. current := this.Elapsed()
  195. atomic.StoreInt32((*int32)(&this.state), int32(state))
  196. atomic.StoreUint32(&this.stateBeginTime, current)
  197. log.Info("KCP|Connection: #", this.conv, " entering state ", state, " at ", current)
  198. switch state {
  199. case StateReadyToClose:
  200. this.receivingWorker.CloseRead()
  201. case StatePeerClosed:
  202. this.sendingWorker.CloseWrite()
  203. case StateTerminating:
  204. this.receivingWorker.CloseRead()
  205. this.sendingWorker.CloseWrite()
  206. case StateTerminated:
  207. this.receivingWorker.CloseRead()
  208. this.sendingWorker.CloseWrite()
  209. }
  210. }
  211. // Close closes the connection.
  212. func (this *Connection) Close() error {
  213. if this == nil {
  214. return errClosedConnection
  215. }
  216. this.dataInputCond.Broadcast()
  217. state := this.State()
  218. if state == StateReadyToClose ||
  219. state == StateTerminating ||
  220. state == StateTerminated {
  221. return errClosedConnection
  222. }
  223. log.Info("KCP|Connection: Closing connection to ", this.remote)
  224. if state == StateActive {
  225. this.SetState(StateReadyToClose)
  226. }
  227. if state == StatePeerClosed {
  228. this.SetState(StateTerminating)
  229. }
  230. return nil
  231. }
  232. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  233. func (this *Connection) LocalAddr() net.Addr {
  234. if this == nil {
  235. return nil
  236. }
  237. return this.local
  238. }
  239. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  240. func (this *Connection) RemoteAddr() net.Addr {
  241. if this == nil {
  242. return nil
  243. }
  244. return this.remote
  245. }
  246. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  247. func (this *Connection) SetDeadline(t time.Time) error {
  248. if err := this.SetReadDeadline(t); err != nil {
  249. return err
  250. }
  251. if err := this.SetWriteDeadline(t); err != nil {
  252. return err
  253. }
  254. return nil
  255. }
  256. // SetReadDeadline implements the Conn SetReadDeadline method.
  257. func (this *Connection) SetReadDeadline(t time.Time) error {
  258. if this == nil || this.State() != StateActive {
  259. return errClosedConnection
  260. }
  261. this.rd = t
  262. return nil
  263. }
  264. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  265. func (this *Connection) SetWriteDeadline(t time.Time) error {
  266. if this == nil || this.State() != StateActive {
  267. return errClosedConnection
  268. }
  269. this.wd = t
  270. return nil
  271. }
  272. // kcp update, input loop
  273. func (this *Connection) updateTask() {
  274. for this.State() != StateTerminated {
  275. this.flush()
  276. interval := time.Duration(effectiveConfig.Tti) * time.Millisecond
  277. if this.State() == StateTerminating {
  278. interval = time.Second
  279. }
  280. time.Sleep(interval)
  281. }
  282. this.Terminate()
  283. }
  284. func (this *Connection) FetchInputFrom(conn io.Reader) {
  285. go func() {
  286. payload := alloc.NewBuffer()
  287. defer payload.Release()
  288. for {
  289. payload.Reset()
  290. nBytes, err := conn.Read(payload.Value)
  291. if err != nil {
  292. return
  293. }
  294. payload.Slice(0, nBytes)
  295. if this.block.Open(payload) {
  296. this.Input(payload.Value)
  297. }
  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. this.dataInputCond.Signal()
  341. case *AckSegment:
  342. this.HandleOption(seg.Opt)
  343. this.sendingWorker.ProcessSegment(current, seg)
  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-atomic.LoadUint32(&this.lastIncomingTime) >= 30000 {
  369. this.Close()
  370. }
  371. if this.State() == StateReadyToClose && this.sendingWorker.IsEmpty() {
  372. this.SetState(StateTerminating)
  373. }
  374. if this.State() == StateTerminating {
  375. log.Debug("KCP|Connection: #", this.conv, " sending terminating cmd.")
  376. seg := NewCmdOnlySegment()
  377. defer seg.Release()
  378. seg.Conv = this.conv
  379. seg.Cmd = SegmentCommandTerminated
  380. this.output.Write(seg)
  381. this.output.Flush()
  382. if current-atomic.LoadUint32(&this.stateBeginTime) > 8000 {
  383. this.SetState(StateTerminated)
  384. }
  385. return
  386. }
  387. if this.State() == StateReadyToClose && current-atomic.LoadUint32(&this.stateBeginTime) > 15000 {
  388. this.SetState(StateTerminating)
  389. }
  390. // flush acknowledges
  391. this.receivingWorker.Flush(current)
  392. this.sendingWorker.Flush(current)
  393. if this.sendingWorker.PingNecessary() || this.receivingWorker.PingNecessary() || current-atomic.LoadUint32(&this.lastPingTime) >= 5000 {
  394. seg := NewCmdOnlySegment()
  395. seg.Conv = this.conv
  396. seg.Cmd = SegmentCommandPing
  397. seg.ReceivinNext = this.receivingWorker.nextNumber
  398. seg.SendingNext = this.sendingWorker.firstUnacknowledged
  399. if this.State() == StateReadyToClose {
  400. seg.Opt = SegmentOptionClose
  401. }
  402. this.output.Write(seg)
  403. this.lastPingTime = current
  404. this.sendingWorker.MarkPingNecessary(false)
  405. this.receivingWorker.MarkPingNecessary(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. }