kcp.go 19 KB

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