kcp.go 19 KB

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