connection.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. dataOutputCond *sync.Cond
  93. conv uint16
  94. state State
  95. stateBeginTime uint32
  96. lastIncomingTime uint32
  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. conn.dataOutputCond = sync.NewCond(new(sync.Mutex))
  118. authWriter := &AuthenticationWriter{
  119. Authenticator: block,
  120. Writer: writerCloser,
  121. }
  122. conn.conv = conv
  123. conn.output = NewSegmentWriter(authWriter)
  124. conn.mss = authWriter.Mtu() - DataSegmentOverhead
  125. conn.roundTrip = &RountTripInfo{
  126. rto: 100,
  127. minRtt: effectiveConfig.Tti,
  128. }
  129. conn.interval = effectiveConfig.Tti
  130. conn.receivingWorker = NewReceivingWorker(conn)
  131. conn.fastresend = 2
  132. conn.congestionControl = effectiveConfig.Congestion
  133. conn.sendingWorker = NewSendingWorker(conn)
  134. go conn.updateTask()
  135. return conn
  136. }
  137. func (this *Connection) Elapsed() uint32 {
  138. return uint32(nowMillisec() - this.since)
  139. }
  140. // Read implements the Conn Read method.
  141. func (this *Connection) Read(b []byte) (int, error) {
  142. if this == nil {
  143. return 0, io.EOF
  144. }
  145. for {
  146. if this.State() == StateReadyToClose || this.State() == StateTerminating || this.State() == StateTerminated {
  147. return 0, io.EOF
  148. }
  149. nBytes := this.receivingWorker.Read(b)
  150. if nBytes > 0 {
  151. return nBytes, nil
  152. }
  153. if this.State() == StatePeerTerminating {
  154. return 0, io.EOF
  155. }
  156. var timer *time.Timer
  157. if !this.rd.IsZero() {
  158. duration := this.rd.Sub(time.Now())
  159. if duration <= 0 {
  160. return 0, errTimeout
  161. }
  162. timer = time.AfterFunc(duration, this.dataInputCond.Signal)
  163. }
  164. this.dataInputCond.L.Lock()
  165. this.dataInputCond.Wait()
  166. this.dataInputCond.L.Unlock()
  167. if timer != nil {
  168. timer.Stop()
  169. }
  170. if !this.rd.IsZero() && this.rd.Before(time.Now()) {
  171. return 0, errTimeout
  172. }
  173. }
  174. }
  175. // Write implements the Conn Write method.
  176. func (this *Connection) Write(b []byte) (int, error) {
  177. if this == nil || this.State() != StateActive {
  178. return 0, io.ErrClosedPipe
  179. }
  180. totalWritten := 0
  181. for {
  182. if this == nil || this.State() != StateActive {
  183. return totalWritten, io.ErrClosedPipe
  184. }
  185. nBytes := this.sendingWorker.Push(b[totalWritten:])
  186. if nBytes > 0 {
  187. totalWritten += nBytes
  188. if totalWritten == len(b) {
  189. return totalWritten, nil
  190. }
  191. }
  192. var timer *time.Timer
  193. if !this.wd.IsZero() {
  194. duration := this.wd.Sub(time.Now())
  195. if duration <= 0 {
  196. return totalWritten, errTimeout
  197. }
  198. timer = time.AfterFunc(duration, this.dataOutputCond.Signal)
  199. }
  200. this.dataOutputCond.L.Lock()
  201. this.dataOutputCond.Wait()
  202. this.dataOutputCond.L.Unlock()
  203. if timer != nil {
  204. timer.Stop()
  205. }
  206. if !this.wd.IsZero() && this.wd.Before(time.Now()) {
  207. return totalWritten, errTimeout
  208. }
  209. }
  210. }
  211. func (this *Connection) SetState(state State) {
  212. current := this.Elapsed()
  213. atomic.StoreInt32((*int32)(&this.state), int32(state))
  214. atomic.StoreUint32(&this.stateBeginTime, current)
  215. log.Info("KCP|Connection: #", this.conv, " entering state ", state, " at ", current)
  216. switch state {
  217. case StateReadyToClose:
  218. this.receivingWorker.CloseRead()
  219. case StatePeerClosed:
  220. this.sendingWorker.CloseWrite()
  221. case StateTerminating:
  222. this.receivingWorker.CloseRead()
  223. this.sendingWorker.CloseWrite()
  224. case StatePeerTerminating:
  225. this.sendingWorker.CloseWrite()
  226. case StateTerminated:
  227. this.receivingWorker.CloseRead()
  228. this.sendingWorker.CloseWrite()
  229. }
  230. }
  231. // Close closes the connection.
  232. func (this *Connection) Close() error {
  233. if this == nil {
  234. return errClosedConnection
  235. }
  236. this.dataInputCond.Broadcast()
  237. this.dataOutputCond.Broadcast()
  238. state := this.State()
  239. if state == StateReadyToClose ||
  240. state == StateTerminating ||
  241. state == StateTerminated {
  242. return errClosedConnection
  243. }
  244. log.Info("KCP|Connection: Closing connection to ", this.remote)
  245. if state == StateActive {
  246. this.SetState(StateReadyToClose)
  247. }
  248. if state == StatePeerClosed {
  249. this.SetState(StateTerminating)
  250. }
  251. if state == StatePeerTerminating {
  252. this.SetState(StateTerminated)
  253. }
  254. return nil
  255. }
  256. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  257. func (this *Connection) LocalAddr() net.Addr {
  258. if this == nil {
  259. return nil
  260. }
  261. return this.local
  262. }
  263. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  264. func (this *Connection) RemoteAddr() net.Addr {
  265. if this == nil {
  266. return nil
  267. }
  268. return this.remote
  269. }
  270. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  271. func (this *Connection) SetDeadline(t time.Time) error {
  272. if err := this.SetReadDeadline(t); err != nil {
  273. return err
  274. }
  275. if err := this.SetWriteDeadline(t); err != nil {
  276. return err
  277. }
  278. return nil
  279. }
  280. // SetReadDeadline implements the Conn SetReadDeadline method.
  281. func (this *Connection) SetReadDeadline(t time.Time) error {
  282. if this == nil || this.State() != StateActive {
  283. return errClosedConnection
  284. }
  285. this.rd = t
  286. return nil
  287. }
  288. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  289. func (this *Connection) SetWriteDeadline(t time.Time) error {
  290. if this == nil || this.State() != StateActive {
  291. return errClosedConnection
  292. }
  293. this.wd = t
  294. return nil
  295. }
  296. // kcp update, input loop
  297. func (this *Connection) updateTask() {
  298. for this.State() != StateTerminated {
  299. this.flush()
  300. interval := time.Duration(effectiveConfig.Tti) * time.Millisecond
  301. if this.State() == StateTerminating {
  302. interval = time.Second
  303. }
  304. time.Sleep(interval)
  305. }
  306. this.Terminate()
  307. }
  308. func (this *Connection) FetchInputFrom(conn io.Reader) {
  309. go func() {
  310. payload := alloc.NewBuffer()
  311. defer payload.Release()
  312. for {
  313. payload.Reset()
  314. nBytes, err := conn.Read(payload.Value)
  315. if err != nil {
  316. return
  317. }
  318. payload.Slice(0, nBytes)
  319. if this.block.Open(payload) {
  320. this.Input(payload.Value)
  321. }
  322. }
  323. }()
  324. }
  325. func (this *Connection) Reusable() bool {
  326. return false
  327. }
  328. func (this *Connection) SetReusable(b bool) {}
  329. func (this *Connection) Terminate() {
  330. if this == nil || this.writer == nil {
  331. return
  332. }
  333. log.Info("KCP|Connection: Terminating connection to ", this.RemoteAddr())
  334. this.writer.Close()
  335. }
  336. func (this *Connection) HandleOption(opt SegmentOption) {
  337. if (opt & SegmentOptionClose) == SegmentOptionClose {
  338. this.OnPeerClosed()
  339. }
  340. }
  341. func (this *Connection) OnPeerClosed() {
  342. state := this.State()
  343. if state == StateReadyToClose {
  344. this.SetState(StateTerminating)
  345. }
  346. if state == StateActive {
  347. this.SetState(StatePeerClosed)
  348. }
  349. }
  350. // Input when you received a low level packet (eg. UDP packet), call it
  351. func (this *Connection) Input(data []byte) int {
  352. current := this.Elapsed()
  353. atomic.StoreUint32(&this.lastIncomingTime, current)
  354. var seg Segment
  355. for {
  356. seg, data = ReadSegment(data)
  357. if seg == nil {
  358. break
  359. }
  360. switch seg := seg.(type) {
  361. case *DataSegment:
  362. this.HandleOption(seg.Opt)
  363. this.receivingWorker.ProcessSegment(seg)
  364. this.dataInputCond.Signal()
  365. case *AckSegment:
  366. this.HandleOption(seg.Opt)
  367. this.sendingWorker.ProcessSegment(current, seg)
  368. this.dataOutputCond.Signal()
  369. case *CmdOnlySegment:
  370. this.HandleOption(seg.Opt)
  371. if seg.Cmd == CommandTerminate {
  372. state := this.State()
  373. if state == StateActive ||
  374. state == StatePeerClosed {
  375. this.SetState(StatePeerTerminating)
  376. } else if state == StateReadyToClose {
  377. this.SetState(StateTerminating)
  378. } else if state == StateTerminating {
  379. this.SetState(StateTerminated)
  380. }
  381. }
  382. this.sendingWorker.ProcessReceivingNext(seg.ReceivinNext)
  383. this.receivingWorker.ProcessSendingNext(seg.SendingNext)
  384. seg.Release()
  385. default:
  386. }
  387. }
  388. return 0
  389. }
  390. func (this *Connection) flush() {
  391. current := this.Elapsed()
  392. if this.State() == StateTerminated {
  393. return
  394. }
  395. if this.State() == StateActive && current-atomic.LoadUint32(&this.lastIncomingTime) >= 30000 {
  396. this.Close()
  397. }
  398. if this.State() == StateReadyToClose && this.sendingWorker.IsEmpty() {
  399. this.SetState(StateTerminating)
  400. }
  401. if this.State() == StateTerminating {
  402. log.Debug("KCP|Connection: #", this.conv, " sending terminating cmd.")
  403. seg := NewCmdOnlySegment()
  404. defer seg.Release()
  405. seg.Conv = this.conv
  406. seg.Cmd = CommandTerminate
  407. this.output.Write(seg)
  408. this.output.Flush()
  409. if current-atomic.LoadUint32(&this.stateBeginTime) > 8000 {
  410. this.SetState(StateTerminated)
  411. }
  412. return
  413. }
  414. if this.State() == StatePeerTerminating && current-atomic.LoadUint32(&this.stateBeginTime) > 4000 {
  415. this.SetState(StateTerminating)
  416. }
  417. if this.State() == StateReadyToClose && current-atomic.LoadUint32(&this.stateBeginTime) > 15000 {
  418. this.SetState(StateTerminating)
  419. }
  420. // flush acknowledges
  421. this.receivingWorker.Flush(current)
  422. this.sendingWorker.Flush(current)
  423. if this.sendingWorker.PingNecessary() || this.receivingWorker.PingNecessary() || current-atomic.LoadUint32(&this.lastPingTime) >= 5000 {
  424. seg := NewCmdOnlySegment()
  425. seg.Conv = this.conv
  426. seg.Cmd = CommandPing
  427. seg.ReceivinNext = this.receivingWorker.nextNumber
  428. seg.SendingNext = this.sendingWorker.firstUnacknowledged
  429. if this.State() == StateReadyToClose {
  430. seg.Opt = SegmentOptionClose
  431. }
  432. this.output.Write(seg)
  433. this.lastPingTime = current
  434. this.sendingWorker.MarkPingNecessary(false)
  435. this.receivingWorker.MarkPingNecessary(false)
  436. seg.Release()
  437. }
  438. // flash remain segments
  439. this.output.Flush()
  440. }
  441. func (this *Connection) State() State {
  442. return State(atomic.LoadInt32((*int32)(&this.state)))
  443. }