kcp.go 18 KB

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