kcp.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. // Package kcp - A Fast and Reliable ARQ Protocol
  2. //
  3. // Acknowledgement:
  4. // skywind3000@github for inventing the KCP protocol
  5. // xtaci@github for translating to Golang
  6. package kcp
  7. import (
  8. "encoding/binary"
  9. "github.com/v2ray/v2ray-core/common/alloc"
  10. )
  11. const (
  12. IKCP_RTO_NDL = 30 // no delay min rto
  13. IKCP_RTO_MIN = 100 // normal min rto
  14. IKCP_RTO_DEF = 200
  15. IKCP_RTO_MAX = 60000
  16. IKCP_CMD_PUSH = 81 // cmd: push data
  17. IKCP_CMD_ACK = 82 // cmd: ack
  18. IKCP_CMD_WASK = 83 // cmd: window probe (ask)
  19. IKCP_CMD_WINS = 84 // cmd: window size (tell)
  20. IKCP_ASK_SEND = 1 // need to send IKCP_CMD_WASK
  21. IKCP_ASK_TELL = 2 // need to send IKCP_CMD_WINS
  22. IKCP_WND_SND = 32
  23. IKCP_WND_RCV = 32
  24. IKCP_MTU_DEF = 1350
  25. IKCP_ACK_FAST = 3
  26. IKCP_INTERVAL = 100
  27. IKCP_OVERHEAD = 24
  28. IKCP_DEADLINK = 20
  29. IKCP_THRESH_INIT = 2
  30. IKCP_THRESH_MIN = 2
  31. IKCP_PROBE_INIT = 7000 // 7 secs to probe window size
  32. IKCP_PROBE_LIMIT = 120000 // up to 120 secs to probe window
  33. )
  34. // Output is a closure which captures conn and calls conn.Write
  35. type Output func(buf []byte)
  36. /* encode 8 bits unsigned int */
  37. func ikcp_encode8u(p []byte, c byte) []byte {
  38. p[0] = c
  39. return p[1:]
  40. }
  41. /* decode 8 bits unsigned int */
  42. func ikcp_decode8u(p []byte, c *byte) []byte {
  43. *c = p[0]
  44. return p[1:]
  45. }
  46. /* encode 16 bits unsigned int (lsb) */
  47. func ikcp_encode16u(p []byte, w uint16) []byte {
  48. binary.LittleEndian.PutUint16(p, w)
  49. return p[2:]
  50. }
  51. /* decode 16 bits unsigned int (lsb) */
  52. func ikcp_decode16u(p []byte, w *uint16) []byte {
  53. *w = binary.LittleEndian.Uint16(p)
  54. return p[2:]
  55. }
  56. /* encode 32 bits unsigned int (lsb) */
  57. func ikcp_encode32u(p []byte, l uint32) []byte {
  58. binary.LittleEndian.PutUint32(p, l)
  59. return p[4:]
  60. }
  61. /* decode 32 bits unsigned int (lsb) */
  62. func ikcp_decode32u(p []byte, l *uint32) []byte {
  63. *l = binary.LittleEndian.Uint32(p)
  64. return p[4:]
  65. }
  66. func _imin_(a, b uint32) uint32 {
  67. if a <= b {
  68. return a
  69. } else {
  70. return b
  71. }
  72. }
  73. func _imax_(a, b uint32) uint32 {
  74. if a >= b {
  75. return a
  76. } else {
  77. return b
  78. }
  79. }
  80. func _itimediff(later, earlier uint32) int32 {
  81. return (int32)(later - earlier)
  82. }
  83. // Segment defines a KCP segment
  84. type Segment struct {
  85. conv uint32
  86. cmd uint32
  87. frg uint32
  88. wnd uint32
  89. ts uint32
  90. sn uint32
  91. una uint32
  92. resendts uint32
  93. rto uint32
  94. fastack uint32
  95. xmit uint32
  96. data *alloc.Buffer
  97. }
  98. // encode a segment into buffer
  99. func (seg *Segment) encode(ptr []byte) []byte {
  100. ptr = ikcp_encode32u(ptr, seg.conv)
  101. ptr = ikcp_encode8u(ptr, uint8(seg.cmd))
  102. ptr = ikcp_encode8u(ptr, uint8(seg.frg))
  103. ptr = ikcp_encode16u(ptr, uint16(seg.wnd))
  104. ptr = ikcp_encode32u(ptr, seg.ts)
  105. ptr = ikcp_encode32u(ptr, seg.sn)
  106. ptr = ikcp_encode32u(ptr, seg.una)
  107. ptr = ikcp_encode32u(ptr, uint32(seg.data.Len()))
  108. return ptr
  109. }
  110. // NewSegment creates a KCP segment
  111. func NewSegment() *Segment {
  112. return &Segment{
  113. data: alloc.NewSmallBuffer().Clear(),
  114. }
  115. }
  116. // KCP defines a single KCP connection
  117. type KCP struct {
  118. conv, mtu, mss, state uint32
  119. snd_una, snd_nxt, rcv_nxt uint32
  120. ts_recent, ts_lastack, ssthresh uint32
  121. rx_rttval, rx_srtt, rx_rto, rx_minrto uint32
  122. snd_wnd, rcv_wnd, rmt_wnd, cwnd, probe uint32
  123. current, interval, ts_flush, xmit uint32
  124. nodelay, updated uint32
  125. ts_probe, probe_wait uint32
  126. dead_link, incr uint32
  127. snd_queue []Segment
  128. rcv_queue []Segment
  129. snd_buf []Segment
  130. rcv_buf []Segment
  131. acklist []uint32
  132. buffer []byte
  133. fastresend int32
  134. nocwnd int32
  135. logmask int32
  136. output Output
  137. }
  138. // NewKCP create a new kcp control object, 'conv' must equal in two endpoint
  139. // from the same connection.
  140. func NewKCP(conv uint32, mtu uint32, output Output) *KCP {
  141. kcp := new(KCP)
  142. kcp.conv = conv
  143. kcp.snd_wnd = IKCP_WND_SND
  144. kcp.rcv_wnd = IKCP_WND_RCV
  145. kcp.rmt_wnd = IKCP_WND_RCV
  146. kcp.mtu = mtu
  147. kcp.mss = kcp.mtu - IKCP_OVERHEAD
  148. kcp.buffer = make([]byte, (kcp.mtu+IKCP_OVERHEAD)*3)
  149. kcp.rx_rto = IKCP_RTO_DEF
  150. kcp.rx_minrto = IKCP_RTO_MIN
  151. kcp.interval = IKCP_INTERVAL
  152. kcp.ts_flush = IKCP_INTERVAL
  153. kcp.ssthresh = IKCP_THRESH_INIT
  154. kcp.dead_link = IKCP_DEADLINK
  155. kcp.output = output
  156. return kcp
  157. }
  158. // Recv is user/upper level recv: returns size, returns below zero for EAGAIN
  159. func (kcp *KCP) Recv(buffer []byte) (n int) {
  160. if len(kcp.rcv_queue) == 0 {
  161. return -1
  162. }
  163. var fast_recover bool
  164. if len(kcp.rcv_queue) >= int(kcp.rcv_wnd) {
  165. fast_recover = true
  166. }
  167. // merge fragment
  168. count := 0
  169. for k := range kcp.rcv_queue {
  170. seg := &kcp.rcv_queue[k]
  171. dataLen := seg.data.Len()
  172. if dataLen > len(buffer) {
  173. break
  174. }
  175. copy(buffer, seg.data.Value)
  176. buffer = buffer[dataLen:]
  177. n += dataLen
  178. count++
  179. }
  180. kcp.rcv_queue = kcp.rcv_queue[count:]
  181. // move available data from rcv_buf -> rcv_queue
  182. count = 0
  183. for k := range kcp.rcv_buf {
  184. seg := &kcp.rcv_buf[k]
  185. if seg.sn == kcp.rcv_nxt && len(kcp.rcv_queue) < int(kcp.rcv_wnd) {
  186. kcp.rcv_queue = append(kcp.rcv_queue, *seg)
  187. kcp.rcv_nxt++
  188. count++
  189. } else {
  190. break
  191. }
  192. }
  193. kcp.rcv_buf = kcp.rcv_buf[count:]
  194. // fast recover
  195. if len(kcp.rcv_queue) < int(kcp.rcv_wnd) && fast_recover {
  196. // ready to send back IKCP_CMD_WINS in ikcp_flush
  197. // tell remote my window size
  198. kcp.probe |= IKCP_ASK_TELL
  199. }
  200. return
  201. }
  202. // Send is user/upper level send, returns below zero for error
  203. func (kcp *KCP) Send(buffer []byte) int {
  204. var count int
  205. if len(buffer) == 0 {
  206. return -1
  207. }
  208. if len(buffer) < int(kcp.mss) {
  209. count = 1
  210. } else {
  211. count = (len(buffer) + int(kcp.mss) - 1) / int(kcp.mss)
  212. }
  213. if count > 255 {
  214. return -2
  215. }
  216. if count == 0 {
  217. count = 1
  218. }
  219. for i := 0; i < count; i++ {
  220. var size int
  221. if len(buffer) > int(kcp.mss) {
  222. size = int(kcp.mss)
  223. } else {
  224. size = len(buffer)
  225. }
  226. seg := NewSegment()
  227. seg.data.Append(buffer[:size])
  228. seg.frg = uint32(count - i - 1)
  229. kcp.snd_queue = append(kcp.snd_queue, *seg)
  230. buffer = buffer[size:]
  231. }
  232. return 0
  233. }
  234. // https://tools.ietf.org/html/rfc6298
  235. func (kcp *KCP) update_ack(rtt int32) {
  236. var rto uint32 = 0
  237. if kcp.rx_srtt == 0 {
  238. kcp.rx_srtt = uint32(rtt)
  239. kcp.rx_rttval = uint32(rtt) / 2
  240. } else {
  241. delta := rtt - int32(kcp.rx_srtt)
  242. if delta < 0 {
  243. delta = -delta
  244. }
  245. kcp.rx_rttval = (3*kcp.rx_rttval + uint32(delta)) / 4
  246. kcp.rx_srtt = (7*kcp.rx_srtt + uint32(rtt)) / 8
  247. if kcp.rx_srtt < 1 {
  248. kcp.rx_srtt = 1
  249. }
  250. }
  251. rto = kcp.rx_srtt + _imax_(1, 4*kcp.rx_rttval)
  252. if rto > IKCP_RTO_MAX {
  253. rto = IKCP_RTO_MAX
  254. }
  255. if rto < kcp.rx_minrto {
  256. rto = kcp.rx_minrto
  257. }
  258. kcp.rx_rto = rto
  259. }
  260. func (kcp *KCP) shrink_buf() {
  261. if len(kcp.snd_buf) > 0 {
  262. seg := &kcp.snd_buf[0]
  263. kcp.snd_una = seg.sn
  264. } else {
  265. kcp.snd_una = kcp.snd_nxt
  266. }
  267. }
  268. func (kcp *KCP) parse_ack(sn uint32) {
  269. if _itimediff(sn, kcp.snd_una) < 0 || _itimediff(sn, kcp.snd_nxt) >= 0 {
  270. return
  271. }
  272. for k := range kcp.snd_buf {
  273. seg := &kcp.snd_buf[k]
  274. if sn == seg.sn {
  275. kcp.snd_buf = append(kcp.snd_buf[:k], kcp.snd_buf[k+1:]...)
  276. break
  277. }
  278. if _itimediff(sn, seg.sn) < 0 {
  279. break
  280. }
  281. }
  282. }
  283. func (kcp *KCP) parse_fastack(sn uint32) {
  284. if _itimediff(sn, kcp.snd_una) < 0 || _itimediff(sn, kcp.snd_nxt) >= 0 {
  285. return
  286. }
  287. for k := range kcp.snd_buf {
  288. seg := &kcp.snd_buf[k]
  289. if _itimediff(sn, seg.sn) < 0 {
  290. break
  291. } else if sn != seg.sn {
  292. seg.fastack++
  293. }
  294. }
  295. }
  296. func (kcp *KCP) parse_una(una uint32) {
  297. count := 0
  298. for k := range kcp.snd_buf {
  299. seg := &kcp.snd_buf[k]
  300. if _itimediff(una, seg.sn) > 0 {
  301. count++
  302. } else {
  303. break
  304. }
  305. }
  306. kcp.snd_buf = kcp.snd_buf[count:]
  307. }
  308. // ack append
  309. func (kcp *KCP) ack_push(sn, ts uint32) {
  310. kcp.acklist = append(kcp.acklist, sn, ts)
  311. }
  312. func (kcp *KCP) ack_get(p int) (sn, ts uint32) {
  313. return kcp.acklist[p*2+0], kcp.acklist[p*2+1]
  314. }
  315. func (kcp *KCP) parse_data(newseg *Segment) {
  316. sn := newseg.sn
  317. if _itimediff(sn, kcp.rcv_nxt+kcp.rcv_wnd) >= 0 ||
  318. _itimediff(sn, kcp.rcv_nxt) < 0 {
  319. return
  320. }
  321. n := len(kcp.rcv_buf) - 1
  322. insert_idx := 0
  323. repeat := false
  324. for i := n; i >= 0; i-- {
  325. seg := &kcp.rcv_buf[i]
  326. if seg.sn == sn {
  327. repeat = true
  328. break
  329. }
  330. if _itimediff(sn, seg.sn) > 0 {
  331. insert_idx = i + 1
  332. break
  333. }
  334. }
  335. if !repeat {
  336. if insert_idx == n+1 {
  337. kcp.rcv_buf = append(kcp.rcv_buf, *newseg)
  338. } else {
  339. kcp.rcv_buf = append(kcp.rcv_buf, Segment{})
  340. copy(kcp.rcv_buf[insert_idx+1:], kcp.rcv_buf[insert_idx:])
  341. kcp.rcv_buf[insert_idx] = *newseg
  342. }
  343. }
  344. // move available data from rcv_buf -> rcv_queue
  345. count := 0
  346. for k := range kcp.rcv_buf {
  347. seg := &kcp.rcv_buf[k]
  348. if seg.sn == kcp.rcv_nxt && len(kcp.rcv_queue) < int(kcp.rcv_wnd) {
  349. kcp.rcv_queue = append(kcp.rcv_queue, kcp.rcv_buf[k])
  350. kcp.rcv_nxt++
  351. count++
  352. } else {
  353. break
  354. }
  355. }
  356. kcp.rcv_buf = kcp.rcv_buf[count:]
  357. }
  358. // Input when you received a low level packet (eg. UDP packet), call it
  359. func (kcp *KCP) Input(data []byte) int {
  360. una := kcp.snd_una
  361. if len(data) < IKCP_OVERHEAD {
  362. return -1
  363. }
  364. var maxack uint32
  365. var flag int
  366. for {
  367. var ts, sn, length, una, conv uint32
  368. var wnd uint16
  369. var cmd, frg uint8
  370. if len(data) < int(IKCP_OVERHEAD) {
  371. break
  372. }
  373. data = ikcp_decode32u(data, &conv)
  374. if conv != kcp.conv {
  375. return -1
  376. }
  377. data = ikcp_decode8u(data, &cmd)
  378. data = ikcp_decode8u(data, &frg)
  379. data = ikcp_decode16u(data, &wnd)
  380. data = ikcp_decode32u(data, &ts)
  381. data = ikcp_decode32u(data, &sn)
  382. data = ikcp_decode32u(data, &una)
  383. data = ikcp_decode32u(data, &length)
  384. if len(data) < int(length) {
  385. return -2
  386. }
  387. if cmd != IKCP_CMD_PUSH && cmd != IKCP_CMD_ACK &&
  388. cmd != IKCP_CMD_WASK && cmd != IKCP_CMD_WINS {
  389. return -3
  390. }
  391. kcp.rmt_wnd = uint32(wnd)
  392. kcp.parse_una(una)
  393. kcp.shrink_buf()
  394. if cmd == IKCP_CMD_ACK {
  395. if _itimediff(kcp.current, ts) >= 0 {
  396. kcp.update_ack(_itimediff(kcp.current, ts))
  397. }
  398. kcp.parse_ack(sn)
  399. kcp.shrink_buf()
  400. if flag == 0 {
  401. flag = 1
  402. maxack = sn
  403. } else if _itimediff(sn, maxack) > 0 {
  404. maxack = sn
  405. }
  406. } else if cmd == IKCP_CMD_PUSH {
  407. if _itimediff(sn, kcp.rcv_nxt+kcp.rcv_wnd) < 0 {
  408. kcp.ack_push(sn, ts)
  409. if _itimediff(sn, kcp.rcv_nxt) >= 0 {
  410. seg := NewSegment()
  411. seg.conv = conv
  412. seg.cmd = uint32(cmd)
  413. seg.frg = uint32(frg)
  414. seg.wnd = uint32(wnd)
  415. seg.ts = ts
  416. seg.sn = sn
  417. seg.una = una
  418. seg.data.Append(data[:length])
  419. kcp.parse_data(seg)
  420. }
  421. }
  422. } else if cmd == IKCP_CMD_WASK {
  423. // ready to send back IKCP_CMD_WINS in Ikcp_flush
  424. // tell remote my window size
  425. kcp.probe |= IKCP_ASK_TELL
  426. } else if cmd == IKCP_CMD_WINS {
  427. // do nothing
  428. } else {
  429. return -3
  430. }
  431. data = data[length:]
  432. }
  433. if flag != 0 {
  434. kcp.parse_fastack(maxack)
  435. }
  436. if _itimediff(kcp.snd_una, una) > 0 {
  437. if kcp.cwnd < kcp.rmt_wnd {
  438. mss := kcp.mss
  439. if kcp.cwnd < kcp.ssthresh {
  440. kcp.cwnd++
  441. kcp.incr += mss
  442. } else {
  443. if kcp.incr < mss {
  444. kcp.incr = mss
  445. }
  446. kcp.incr += (mss*mss)/kcp.incr + (mss / 16)
  447. if (kcp.cwnd+1)*mss <= kcp.incr {
  448. kcp.cwnd++
  449. }
  450. }
  451. if kcp.cwnd > kcp.rmt_wnd {
  452. kcp.cwnd = kcp.rmt_wnd
  453. kcp.incr = kcp.rmt_wnd * mss
  454. }
  455. }
  456. }
  457. return 0
  458. }
  459. func (kcp *KCP) wnd_unused() int32 {
  460. if len(kcp.rcv_queue) < int(kcp.rcv_wnd) {
  461. return int32(int(kcp.rcv_wnd) - len(kcp.rcv_queue))
  462. }
  463. return 0
  464. }
  465. // flush pending data
  466. func (kcp *KCP) flush() {
  467. current := kcp.current
  468. buffer := kcp.buffer
  469. change := 0
  470. lost := false
  471. if kcp.updated == 0 {
  472. return
  473. }
  474. var seg Segment
  475. seg.conv = kcp.conv
  476. seg.cmd = IKCP_CMD_ACK
  477. seg.wnd = uint32(kcp.wnd_unused())
  478. seg.una = kcp.rcv_nxt
  479. // flush acknowledges
  480. count := len(kcp.acklist) / 2
  481. ptr := buffer
  482. for i := 0; i < count; i++ {
  483. size := len(buffer) - len(ptr)
  484. if size+IKCP_OVERHEAD > int(kcp.mtu) {
  485. kcp.output(buffer[:size])
  486. ptr = buffer
  487. }
  488. seg.sn, seg.ts = kcp.ack_get(i)
  489. ptr = seg.encode(ptr)
  490. }
  491. kcp.acklist = nil
  492. // probe window size (if remote window size equals zero)
  493. if kcp.rmt_wnd == 0 {
  494. if kcp.probe_wait == 0 {
  495. kcp.probe_wait = IKCP_PROBE_INIT
  496. kcp.ts_probe = kcp.current + kcp.probe_wait
  497. } else {
  498. if _itimediff(kcp.current, kcp.ts_probe) >= 0 {
  499. if kcp.probe_wait < IKCP_PROBE_INIT {
  500. kcp.probe_wait = IKCP_PROBE_INIT
  501. }
  502. kcp.probe_wait += kcp.probe_wait / 2
  503. if kcp.probe_wait > IKCP_PROBE_LIMIT {
  504. kcp.probe_wait = IKCP_PROBE_LIMIT
  505. }
  506. kcp.ts_probe = kcp.current + kcp.probe_wait
  507. kcp.probe |= IKCP_ASK_SEND
  508. }
  509. }
  510. } else {
  511. kcp.ts_probe = 0
  512. kcp.probe_wait = 0
  513. }
  514. // flush window probing commands
  515. if (kcp.probe & IKCP_ASK_SEND) != 0 {
  516. seg.cmd = IKCP_CMD_WASK
  517. size := len(buffer) - len(ptr)
  518. if size+IKCP_OVERHEAD > int(kcp.mtu) {
  519. kcp.output(buffer[:size])
  520. ptr = buffer
  521. }
  522. ptr = seg.encode(ptr)
  523. }
  524. // flush window probing commands
  525. if (kcp.probe & IKCP_ASK_TELL) != 0 {
  526. seg.cmd = IKCP_CMD_WINS
  527. size := len(buffer) - len(ptr)
  528. if size+IKCP_OVERHEAD > int(kcp.mtu) {
  529. kcp.output(buffer[:size])
  530. ptr = buffer
  531. }
  532. ptr = seg.encode(ptr)
  533. }
  534. kcp.probe = 0
  535. // calculate window size
  536. cwnd := _imin_(kcp.snd_wnd, kcp.rmt_wnd)
  537. if kcp.nocwnd == 0 {
  538. cwnd = _imin_(kcp.cwnd, cwnd)
  539. }
  540. count = 0
  541. for k := range kcp.snd_queue {
  542. if _itimediff(kcp.snd_nxt, kcp.snd_una+cwnd) >= 0 {
  543. break
  544. }
  545. newseg := kcp.snd_queue[k]
  546. newseg.conv = kcp.conv
  547. newseg.cmd = IKCP_CMD_PUSH
  548. newseg.wnd = seg.wnd
  549. newseg.ts = current
  550. newseg.sn = kcp.snd_nxt
  551. newseg.una = kcp.rcv_nxt
  552. newseg.resendts = current
  553. newseg.rto = kcp.rx_rto
  554. newseg.fastack = 0
  555. newseg.xmit = 0
  556. kcp.snd_buf = append(kcp.snd_buf, newseg)
  557. kcp.snd_nxt++
  558. count++
  559. }
  560. kcp.snd_queue = kcp.snd_queue[count:]
  561. // calculate resent
  562. resent := uint32(kcp.fastresend)
  563. if kcp.fastresend <= 0 {
  564. resent = 0xffffffff
  565. }
  566. rtomin := (kcp.rx_rto >> 3)
  567. if kcp.nodelay != 0 {
  568. rtomin = 0
  569. }
  570. // flush data segments
  571. for k := range kcp.snd_buf {
  572. segment := &kcp.snd_buf[k]
  573. needsend := false
  574. if segment.xmit == 0 {
  575. needsend = true
  576. segment.xmit++
  577. segment.rto = kcp.rx_rto
  578. segment.resendts = current + segment.rto + rtomin
  579. } else if _itimediff(current, segment.resendts) >= 0 {
  580. needsend = true
  581. segment.xmit++
  582. kcp.xmit++
  583. if kcp.nodelay == 0 {
  584. segment.rto += kcp.rx_rto
  585. } else {
  586. segment.rto += kcp.rx_rto / 2
  587. }
  588. segment.resendts = current + segment.rto
  589. lost = true
  590. } else if segment.fastack >= resent {
  591. needsend = true
  592. segment.xmit++
  593. segment.fastack = 0
  594. segment.resendts = current + segment.rto
  595. change++
  596. }
  597. if needsend {
  598. segment.ts = current
  599. segment.wnd = seg.wnd
  600. segment.una = kcp.rcv_nxt
  601. size := len(buffer) - len(ptr)
  602. need := IKCP_OVERHEAD + segment.data.Len()
  603. if size+need >= int(kcp.mtu) {
  604. kcp.output(buffer[:size])
  605. ptr = buffer
  606. }
  607. ptr = segment.encode(ptr)
  608. copy(ptr, segment.data.Value)
  609. ptr = ptr[segment.data.Len():]
  610. segment.data.Release()
  611. if segment.xmit >= kcp.dead_link {
  612. kcp.state = 0xFFFFFFFF
  613. }
  614. }
  615. }
  616. // flash remain segments
  617. size := len(buffer) - len(ptr)
  618. if size > 0 {
  619. kcp.output(buffer[:size])
  620. }
  621. // update ssthresh
  622. // rate halving, https://tools.ietf.org/html/rfc6937
  623. if change != 0 {
  624. inflight := kcp.snd_nxt - kcp.snd_una
  625. kcp.ssthresh = inflight / 2
  626. if kcp.ssthresh < IKCP_THRESH_MIN {
  627. kcp.ssthresh = IKCP_THRESH_MIN
  628. }
  629. kcp.cwnd = kcp.ssthresh + resent
  630. kcp.incr = kcp.cwnd * kcp.mss
  631. }
  632. // congestion control, https://tools.ietf.org/html/rfc5681
  633. if lost {
  634. kcp.ssthresh = cwnd / 2
  635. if kcp.ssthresh < IKCP_THRESH_MIN {
  636. kcp.ssthresh = IKCP_THRESH_MIN
  637. }
  638. kcp.cwnd = 1
  639. kcp.incr = kcp.mss
  640. }
  641. if kcp.cwnd < 1 {
  642. kcp.cwnd = 1
  643. kcp.incr = kcp.mss
  644. }
  645. }
  646. // Update updates state (call it repeatedly, every 10ms-100ms), or you can ask
  647. // ikcp_check when to call it again (without ikcp_input/_send calling).
  648. // 'current' - current timestamp in millisec.
  649. func (kcp *KCP) Update(current uint32) {
  650. var slap int32
  651. kcp.current = current
  652. if kcp.updated == 0 {
  653. kcp.updated = 1
  654. kcp.ts_flush = kcp.current
  655. }
  656. slap = _itimediff(kcp.current, kcp.ts_flush)
  657. if slap >= 10000 || slap < -10000 {
  658. kcp.ts_flush = kcp.current
  659. slap = 0
  660. }
  661. if slap >= 0 {
  662. kcp.ts_flush += kcp.interval
  663. if _itimediff(kcp.current, kcp.ts_flush) >= 0 {
  664. kcp.ts_flush = kcp.current + kcp.interval
  665. }
  666. kcp.flush()
  667. }
  668. }
  669. // Check determines when should you invoke ikcp_update:
  670. // returns when you should invoke ikcp_update in millisec, if there
  671. // is no ikcp_input/_send calling. you can call ikcp_update in that
  672. // time, instead of call update repeatly.
  673. // Important to reduce unnacessary ikcp_update invoking. use it to
  674. // schedule ikcp_update (eg. implementing an epoll-like mechanism,
  675. // or optimize ikcp_update when handling massive kcp connections)
  676. func (kcp *KCP) Check(current uint32) uint32 {
  677. ts_flush := kcp.ts_flush
  678. tm_flush := int32(0x7fffffff)
  679. tm_packet := int32(0x7fffffff)
  680. minimal := uint32(0)
  681. if kcp.updated == 0 {
  682. return current
  683. }
  684. if _itimediff(current, ts_flush) >= 10000 ||
  685. _itimediff(current, ts_flush) < -10000 {
  686. ts_flush = current
  687. }
  688. if _itimediff(current, ts_flush) >= 0 {
  689. return current
  690. }
  691. tm_flush = _itimediff(ts_flush, current)
  692. for k := range kcp.snd_buf {
  693. seg := &kcp.snd_buf[k]
  694. diff := _itimediff(seg.resendts, current)
  695. if diff <= 0 {
  696. return current
  697. }
  698. if diff < tm_packet {
  699. tm_packet = diff
  700. }
  701. }
  702. minimal = uint32(tm_packet)
  703. if tm_packet >= tm_flush {
  704. minimal = uint32(tm_flush)
  705. }
  706. if minimal >= kcp.interval {
  707. minimal = kcp.interval
  708. }
  709. return current + minimal
  710. }
  711. // SetMtu changes MTU size, default is 1400
  712. func (kcp *KCP) SetMtu(mtu int) int {
  713. if mtu < 50 || mtu < IKCP_OVERHEAD {
  714. return -1
  715. }
  716. buffer := make([]byte, (mtu+IKCP_OVERHEAD)*3)
  717. if buffer == nil {
  718. return -2
  719. }
  720. kcp.mtu = uint32(mtu)
  721. kcp.mss = kcp.mtu - IKCP_OVERHEAD
  722. kcp.buffer = buffer
  723. return 0
  724. }
  725. // NoDelay options
  726. // fastest: ikcp_nodelay(kcp, 1, 20, 2, 1)
  727. // nodelay: 0:disable(default), 1:enable
  728. // interval: internal update timer interval in millisec, default is 100ms
  729. // resend: 0:disable fast resend(default), 1:enable fast resend
  730. // nc: 0:normal congestion control(default), 1:disable congestion control
  731. func (kcp *KCP) NoDelay(nodelay, interval, resend, nc int) int {
  732. if nodelay >= 0 {
  733. kcp.nodelay = uint32(nodelay)
  734. if nodelay != 0 {
  735. kcp.rx_minrto = IKCP_RTO_NDL
  736. } else {
  737. kcp.rx_minrto = IKCP_RTO_MIN
  738. }
  739. }
  740. if interval >= 0 {
  741. if interval > 5000 {
  742. interval = 5000
  743. } else if interval < 10 {
  744. interval = 10
  745. }
  746. kcp.interval = uint32(interval)
  747. }
  748. if resend >= 0 {
  749. kcp.fastresend = int32(resend)
  750. }
  751. if nc >= 0 {
  752. kcp.nocwnd = int32(nc)
  753. }
  754. return 0
  755. }
  756. // WndSize sets maximum window size: sndwnd=32, rcvwnd=32 by default
  757. func (kcp *KCP) WndSize(sndwnd, rcvwnd int) int {
  758. if sndwnd > 0 {
  759. kcp.snd_wnd = uint32(sndwnd)
  760. }
  761. if rcvwnd > 0 {
  762. kcp.rcv_wnd = uint32(rcvwnd)
  763. }
  764. return 0
  765. }
  766. // WaitSnd gets how many packet is waiting to be sent
  767. func (kcp *KCP) WaitSnd() int {
  768. return len(kcp.snd_buf) + len(kcp.snd_queue)
  769. }
  770. func (kcp *KCP) WaitRcv() int {
  771. return len(kcp.rcv_buf) + len(kcp.rcv_queue)
  772. }