lkcp9.go 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  1. // Package lkcp9 - A Fast and Reliable ARQ Protocol
  2. //
  3. // Copyright © 2015 Daniel Fu <daniel820313@gmail.com>.
  4. // Copyright © 2019 Loki 'l0k18' Verloren <stalker.loki@protonmail.ch>.
  5. // Copyright © 2020 Gridfinity, LLC. <admin@gridfinity.com>.
  6. // Copyright © 2020 Jeffrey H. Johnson <jeff@gridfinity.com>.
  7. //
  8. // All rights reserved.
  9. //
  10. // All use of this code is governed by the MIT license.
  11. // The complete license is available in the LICENSE file.
  12. package lkcp9 // import "go.gridfinity.dev/lkcp9"
  13. import (
  14. "encoding/binary"
  15. "sync/atomic"
  16. lkcp9Legal "go4.org/legal"
  17. )
  18. const (
  19. IKCP_RTO_NDL = 30 // no delay min rto
  20. IKCP_RTO_MIN = 100 // normal min rto
  21. IKCP_RTO_DEF = 200
  22. IKCP_RTO_MAX = 60000
  23. IKCP_CMD_PUSH = 81 // cmd: push data
  24. IKCP_CMD_ACK = 82 // cmd: ack
  25. IKCP_CMD_WASK = 83 // cmd: window probe (ask)
  26. IKCP_CMD_WINS = 84 // cmd: window size (tell)
  27. IKCP_ASK_SEND = 1 // need to send IKCP_CMD_WASK
  28. IKCP_ASK_TELL = 2 // need to send IKCP_CMD_WINS
  29. IKCP_WND_SND = 32
  30. IKCP_WND_RCV = 32
  31. IKCP_MTU_DEF = 1400
  32. IKCP_ACK_FAST = 3
  33. IKCP_INTERVAL = 100
  34. IKCP_OVERHEAD = 24
  35. IKCP_DEADLINK = 20
  36. IKCP_THRESH_INIT = 2
  37. IKCP_THRESH_MIN = 2
  38. IKCP_PROBE_INIT = 7000 // 7 secs to probe window size
  39. IKCP_PROBE_LIMIT = 120000 // up to 120 secs to probe window
  40. )
  41. type output_callback func(
  42. buf []byte,
  43. size int,
  44. )
  45. func iKcp_encode8u(
  46. p []byte,
  47. c byte,
  48. ) []byte {
  49. p[0] = c
  50. return p[1:]
  51. }
  52. func iKcp_decode8u(
  53. p []byte,
  54. c *byte,
  55. ) []byte {
  56. *c = p[0]
  57. return p[1:]
  58. }
  59. func iKcp_encode16u(
  60. p []byte,
  61. w uint16,
  62. ) []byte {
  63. binary.LittleEndian.PutUint16(
  64. p,
  65. w,
  66. )
  67. return p[2:]
  68. }
  69. func iKcp_decode16u(
  70. p []byte,
  71. w *uint16,
  72. ) []byte {
  73. *w = binary.LittleEndian.Uint16(
  74. p,
  75. )
  76. return p[2:]
  77. }
  78. func iKcp_encode32u(
  79. p []byte,
  80. l uint32,
  81. ) []byte {
  82. binary.LittleEndian.PutUint32(
  83. p,
  84. l,
  85. )
  86. return p[4:]
  87. }
  88. func iKcp_decode32u(
  89. p []byte,
  90. l *uint32,
  91. ) []byte {
  92. *l = binary.LittleEndian.Uint32(
  93. p,
  94. )
  95. return p[4:]
  96. }
  97. func _imin_(
  98. a,
  99. b uint32,
  100. ) uint32 {
  101. if a <= b {
  102. return a
  103. }
  104. return b
  105. }
  106. func _imax_(
  107. a,
  108. b uint32,
  109. ) uint32 {
  110. if a >= b {
  111. return a
  112. }
  113. return b
  114. }
  115. func _ibound_(
  116. lower,
  117. middle,
  118. upper uint32,
  119. ) uint32 {
  120. return _imin_(
  121. _imax_(
  122. lower,
  123. middle,
  124. ),
  125. upper,
  126. )
  127. }
  128. func _itimediff(
  129. later,
  130. earlier uint32,
  131. ) int32 {
  132. return (int32)(later - earlier)
  133. }
  134. type KcpSegment struct {
  135. conv uint32
  136. cmd uint8
  137. frg uint8
  138. wnd uint16
  139. ts uint32
  140. sn uint32
  141. una uint32
  142. rto uint32
  143. Kxmit uint32
  144. KcpResendTs uint32
  145. fastack uint32
  146. acked uint32
  147. data []byte
  148. }
  149. func (
  150. KcpSeg *KcpSegment,
  151. ) encode(
  152. ptr []byte,
  153. ) []byte {
  154. ptr = iKcp_encode32u(
  155. ptr,
  156. KcpSeg.conv,
  157. )
  158. ptr = iKcp_encode8u(
  159. ptr,
  160. KcpSeg.cmd,
  161. )
  162. ptr = iKcp_encode8u(
  163. ptr,
  164. KcpSeg.frg,
  165. )
  166. ptr = iKcp_encode16u(
  167. ptr,
  168. KcpSeg.wnd,
  169. )
  170. ptr = iKcp_encode32u(
  171. ptr,
  172. KcpSeg.ts,
  173. )
  174. ptr = iKcp_encode32u(
  175. ptr,
  176. KcpSeg.sn,
  177. )
  178. ptr = iKcp_encode32u(
  179. ptr,
  180. KcpSeg.una,
  181. )
  182. ptr = iKcp_encode32u(
  183. ptr, uint32(len(
  184. KcpSeg.data,
  185. )))
  186. atomic.AddUint64(
  187. &DefaultSnsi.KcpOutputSegments,
  188. 1,
  189. )
  190. return ptr
  191. }
  192. type KCP struct {
  193. conv, mtu, mss, state uint32
  194. snd_una, snd_nxt, rcv_nxt uint32
  195. ssthresh uint32
  196. rx_rttvar, rx_srtt int32
  197. rx_rto, rx_minrto uint32
  198. snd_wnd, rcv_wnd, rmt_wnd, cwnd, probe uint32
  199. interval, ts_Flush uint32
  200. nodelay, updated uint32
  201. ts_probe, probe_wait uint32
  202. dead_link, incr uint32
  203. fastresend int32
  204. nocwnd, stream int32
  205. snd_queue []KcpSegment
  206. rcv_queue []KcpSegment
  207. SndBuf []KcpSegment
  208. rcv_buf []KcpSegment
  209. acklist []ackItem
  210. buffer []byte
  211. reserved int
  212. output output_callback
  213. }
  214. type ackItem struct {
  215. sn uint32
  216. ts uint32
  217. }
  218. // NewKCP creates a new Kcp control object.
  219. func NewKCP(
  220. conv uint32,
  221. output output_callback,
  222. ) *KCP {
  223. Kcp := new(
  224. KCP,
  225. )
  226. Kcp.conv = conv
  227. Kcp.snd_wnd = IKCP_WND_SND
  228. Kcp.rcv_wnd = IKCP_WND_RCV
  229. Kcp.rmt_wnd = IKCP_WND_RCV
  230. Kcp.mtu = IKCP_MTU_DEF
  231. Kcp.mss = Kcp.mtu - IKCP_OVERHEAD
  232. Kcp.buffer = make(
  233. []byte,
  234. Kcp.mtu,
  235. )
  236. Kcp.rx_rto = IKCP_RTO_DEF
  237. Kcp.rx_minrto = IKCP_RTO_MIN
  238. Kcp.interval = IKCP_INTERVAL
  239. Kcp.ts_Flush = IKCP_INTERVAL
  240. Kcp.ssthresh = IKCP_THRESH_INIT
  241. Kcp.dead_link = IKCP_DEADLINK
  242. Kcp.output = output
  243. return Kcp
  244. }
  245. func (
  246. Kcp *KCP,
  247. ) newSegment(
  248. size int,
  249. ) (
  250. KcpSeg KcpSegment,
  251. ) {
  252. KcpSeg.data = KxmitBuf.Get().([]byte)[:size]
  253. return
  254. }
  255. func (Kcp *KCP) delSegment(
  256. KcpSeg *KcpSegment,
  257. ) {
  258. if KcpSeg.data != nil {
  259. KxmitBuf.Put(
  260. KcpSeg.data,
  261. )
  262. KcpSeg.data = nil
  263. }
  264. }
  265. // ReserveBytes keeps 'n' bytes from the beginning of buffering.
  266. // Output callbacks use this to return 'false' if 'n' >= 'mss'.
  267. func (
  268. Kcp *KCP,
  269. ) ReserveBytes(
  270. n int,
  271. ) bool {
  272. if n >= int(
  273. Kcp.mtu-IKCP_OVERHEAD,
  274. ) || n < 0 {
  275. return false
  276. }
  277. Kcp.reserved = n
  278. Kcp.mss = Kcp.mtu - IKCP_OVERHEAD - uint32(
  279. n,
  280. )
  281. return true
  282. }
  283. // PeekSize checks the size of next message in the receive queue.
  284. func (
  285. Kcp *KCP,
  286. ) PeekSize() (
  287. length int,
  288. ) {
  289. if len(
  290. Kcp.rcv_queue,
  291. ) == 0 {
  292. return -1
  293. }
  294. KcpSeg := &Kcp.rcv_queue[0]
  295. if KcpSeg.frg == 0 {
  296. return len(
  297. KcpSeg.data,
  298. )
  299. }
  300. if len(
  301. Kcp.rcv_queue,
  302. ) < int(KcpSeg.frg+1) {
  303. return -1
  304. }
  305. for k := range Kcp.rcv_queue {
  306. KcpSeg := &Kcp.rcv_queue[k]
  307. length += len(
  308. KcpSeg.data,
  309. )
  310. if KcpSeg.frg == 0 {
  311. break
  312. }
  313. }
  314. return
  315. }
  316. // Recv is upper level recviver; returns size or EAGAIN on error.
  317. func (
  318. Kcp *KCP,
  319. ) Recv(
  320. buffer []byte,
  321. ) (
  322. n int,
  323. ) {
  324. if len(
  325. Kcp.rcv_queue,
  326. ) == 0 {
  327. return -1
  328. }
  329. peeksize := Kcp.PeekSize()
  330. if peeksize < 0 {
  331. return -2
  332. }
  333. if peeksize > len(
  334. buffer,
  335. ) {
  336. return -3
  337. }
  338. var fast_recover bool
  339. if len(
  340. Kcp.rcv_queue,
  341. ) >= int(
  342. Kcp.rcv_wnd,
  343. ) {
  344. fast_recover = true
  345. }
  346. count := 0
  347. for k := range Kcp.rcv_queue {
  348. KcpSeg := &Kcp.rcv_queue[k]
  349. copy(
  350. buffer,
  351. KcpSeg.data,
  352. )
  353. buffer = buffer[len(KcpSeg.data):]
  354. n += len(
  355. KcpSeg.data,
  356. )
  357. count++
  358. Kcp.delSegment(
  359. KcpSeg,
  360. )
  361. if KcpSeg.frg == 0 {
  362. break
  363. }
  364. }
  365. if count > 0 {
  366. Kcp.rcv_queue = Kcp.remove_front(
  367. Kcp.rcv_queue,
  368. count,
  369. )
  370. }
  371. count = 0
  372. for k := range Kcp.rcv_buf {
  373. KcpSeg := &Kcp.rcv_buf[k]
  374. if KcpSeg.sn == Kcp.rcv_nxt && len(
  375. Kcp.rcv_queue,
  376. ) < int(Kcp.rcv_wnd) {
  377. Kcp.rcv_nxt++
  378. count++
  379. } else {
  380. break
  381. }
  382. }
  383. if count > 0 {
  384. Kcp.rcv_queue = append(
  385. Kcp.rcv_queue,
  386. Kcp.rcv_buf[:count]...,
  387. )
  388. Kcp.rcv_buf = Kcp.remove_front(
  389. Kcp.rcv_buf,
  390. count,
  391. )
  392. }
  393. if len(
  394. Kcp.rcv_queue,
  395. ) < int(Kcp.rcv_wnd) && fast_recover {
  396. Kcp.probe |= IKCP_ASK_TELL
  397. }
  398. return
  399. }
  400. // Send is upper level sender, returns <0 on error.
  401. func (
  402. Kcp *KCP,
  403. ) Send(
  404. buffer []byte,
  405. ) int {
  406. var count int
  407. if len(
  408. buffer,
  409. ) == 0 {
  410. return -1
  411. }
  412. if Kcp.stream != 0 {
  413. n := len(
  414. Kcp.snd_queue,
  415. )
  416. if n > 0 {
  417. KcpSeg := &Kcp.snd_queue[n-1]
  418. if len(KcpSeg.data) < int(Kcp.mss) {
  419. capacity := int(Kcp.mss) - len(
  420. KcpSeg.data,
  421. )
  422. extend := capacity
  423. if len(
  424. buffer,
  425. ) < capacity {
  426. extend = len(
  427. buffer,
  428. )
  429. }
  430. oldlen := len(
  431. KcpSeg.data,
  432. )
  433. KcpSeg.data = KcpSeg.data[:oldlen+extend]
  434. copy(KcpSeg.data[oldlen:], buffer)
  435. buffer = buffer[extend:]
  436. }
  437. }
  438. if len(buffer) == 0 {
  439. return 0
  440. }
  441. }
  442. if len(buffer) <= int(Kcp.mss) {
  443. count = 1
  444. } else {
  445. count = (len(
  446. buffer,
  447. ) + int(Kcp.mss) - 1) / int(Kcp.mss)
  448. }
  449. if count > 255 {
  450. return -2
  451. }
  452. if count == 0 {
  453. count = 1
  454. }
  455. for i := 0; i < count; i++ {
  456. var size int
  457. if len(
  458. buffer,
  459. ) > int(
  460. Kcp.mss,
  461. ) {
  462. size = int(
  463. Kcp.mss,
  464. )
  465. } else {
  466. size = len(
  467. buffer,
  468. )
  469. }
  470. KcpSeg := Kcp.newSegment(
  471. size,
  472. )
  473. copy(
  474. KcpSeg.data,
  475. buffer[:size],
  476. )
  477. if Kcp.stream == 0 {
  478. KcpSeg.frg = uint8(
  479. count - i - 1,
  480. )
  481. } else {
  482. KcpSeg.frg = 0
  483. }
  484. Kcp.snd_queue = append(
  485. Kcp.snd_queue,
  486. KcpSeg,
  487. )
  488. buffer = buffer[size:]
  489. }
  490. return 0
  491. }
  492. func (
  493. Kcp *KCP,
  494. ) update_ack(
  495. rtt int32,
  496. ) {
  497. var rto uint32
  498. if Kcp.rx_srtt == 0 {
  499. Kcp.rx_srtt = rtt
  500. Kcp.rx_rttvar = rtt >> 1
  501. } else {
  502. delta := rtt - Kcp.rx_srtt
  503. Kcp.rx_srtt += delta >> 3
  504. if delta < 0 {
  505. delta = -delta
  506. }
  507. if rtt < Kcp.rx_srtt-Kcp.rx_rttvar {
  508. Kcp.rx_rttvar += (delta - Kcp.rx_rttvar) >> 5
  509. } else {
  510. Kcp.rx_rttvar += (delta - Kcp.rx_rttvar) >> 2
  511. }
  512. }
  513. rto = uint32(
  514. Kcp.rx_srtt,
  515. ) + _imax_(
  516. Kcp.interval,
  517. uint32(Kcp.rx_rttvar)<<2)
  518. Kcp.rx_rto = _ibound_(
  519. Kcp.rx_minrto,
  520. rto,
  521. IKCP_RTO_MAX,
  522. )
  523. }
  524. func (
  525. Kcp *KCP,
  526. ) shrink_buf() {
  527. if len(
  528. Kcp.SndBuf,
  529. ) > 0 {
  530. KcpSeg := &Kcp.SndBuf[0]
  531. Kcp.snd_una = KcpSeg.sn
  532. } else {
  533. Kcp.snd_una = Kcp.snd_nxt
  534. }
  535. }
  536. func (
  537. Kcp *KCP,
  538. ) parse_ack(
  539. sn uint32,
  540. ) {
  541. if _itimediff(
  542. sn,
  543. Kcp.snd_una,
  544. ) < 0 || _itimediff(
  545. sn,
  546. Kcp.snd_nxt,
  547. ) >= 0 {
  548. return
  549. }
  550. for k := range Kcp.SndBuf {
  551. KcpSeg := &Kcp.SndBuf[k]
  552. if sn == KcpSeg.sn {
  553. KcpSeg.acked = 1
  554. Kcp.delSegment(
  555. KcpSeg,
  556. )
  557. break
  558. }
  559. if _itimediff(
  560. sn,
  561. KcpSeg.sn,
  562. ) < 0 {
  563. break
  564. }
  565. }
  566. }
  567. func (
  568. Kcp *KCP,
  569. ) parse_fastack(
  570. sn, ts uint32,
  571. ) {
  572. if _itimediff(
  573. sn,
  574. Kcp.snd_una,
  575. ) < 0 || _itimediff(
  576. sn,
  577. Kcp.snd_nxt,
  578. ) >= 0 {
  579. return
  580. }
  581. for k := range Kcp.SndBuf {
  582. KcpSeg := &Kcp.SndBuf[k]
  583. if _itimediff(
  584. sn,
  585. KcpSeg.sn,
  586. ) < 0 {
  587. break
  588. } else if sn != KcpSeg.sn && _itimediff(
  589. KcpSeg.ts,
  590. ts,
  591. ) <= 0 {
  592. KcpSeg.fastack++
  593. }
  594. }
  595. }
  596. func (
  597. Kcp *KCP,
  598. ) parse_una(
  599. una uint32,
  600. ) {
  601. count := 0
  602. for k := range Kcp.SndBuf {
  603. KcpSeg := &Kcp.SndBuf[k]
  604. if _itimediff(
  605. una,
  606. KcpSeg.sn,
  607. ) > 0 {
  608. Kcp.delSegment(
  609. KcpSeg,
  610. )
  611. count++
  612. } else {
  613. break
  614. }
  615. }
  616. if count > 0 {
  617. Kcp.SndBuf = Kcp.remove_front(
  618. Kcp.SndBuf,
  619. count,
  620. )
  621. }
  622. }
  623. func (
  624. Kcp *KCP,
  625. ) ack_push(
  626. sn,
  627. ts uint32,
  628. ) {
  629. Kcp.acklist = append(
  630. Kcp.acklist,
  631. ackItem{
  632. sn,
  633. ts,
  634. })
  635. }
  636. func (
  637. Kcp *KCP,
  638. ) parse_data(
  639. newKcpSeg KcpSegment,
  640. ) bool {
  641. sn := newKcpSeg.sn
  642. if _itimediff(
  643. sn,
  644. Kcp.rcv_nxt+Kcp.rcv_wnd,
  645. ) >= 0 ||
  646. _itimediff(
  647. sn,
  648. Kcp.rcv_nxt,
  649. ) < 0 {
  650. return true
  651. }
  652. n := len(
  653. Kcp.rcv_buf,
  654. ) - 1
  655. insert_idx := 0
  656. repeat := false
  657. for i := n; i >= 0; i-- {
  658. KcpSeg := &Kcp.rcv_buf[i]
  659. if KcpSeg.sn == sn {
  660. repeat = true
  661. break
  662. }
  663. if _itimediff(
  664. sn,
  665. KcpSeg.sn,
  666. ) > 0 {
  667. insert_idx = i + 1
  668. break
  669. }
  670. }
  671. if !repeat {
  672. dataCopy := KxmitBuf.Get().([]byte)[:len(
  673. newKcpSeg.data,
  674. )]
  675. copy(
  676. dataCopy,
  677. newKcpSeg.data,
  678. )
  679. newKcpSeg.data = dataCopy
  680. if insert_idx == n+1 {
  681. Kcp.rcv_buf = append(
  682. Kcp.rcv_buf,
  683. newKcpSeg,
  684. )
  685. } else {
  686. Kcp.rcv_buf = append(
  687. Kcp.rcv_buf,
  688. KcpSegment{},
  689. )
  690. copy(
  691. Kcp.rcv_buf[insert_idx+1:],
  692. Kcp.rcv_buf[insert_idx:],
  693. )
  694. Kcp.rcv_buf[insert_idx] = newKcpSeg
  695. }
  696. }
  697. count := 0
  698. for k := range Kcp.rcv_buf {
  699. KcpSeg := &Kcp.rcv_buf[k]
  700. if KcpSeg.sn == Kcp.rcv_nxt && len(
  701. Kcp.rcv_queue,
  702. ) < int(Kcp.rcv_wnd) {
  703. Kcp.rcv_nxt++
  704. count++
  705. } else {
  706. break
  707. }
  708. }
  709. if count > 0 {
  710. Kcp.rcv_queue = append(
  711. Kcp.rcv_queue,
  712. Kcp.rcv_buf[:count]...,
  713. )
  714. Kcp.rcv_buf = Kcp.remove_front(
  715. Kcp.rcv_buf,
  716. count,
  717. )
  718. }
  719. return repeat
  720. }
  721. // Input receives a (low-level) UDP packet, and determinines if
  722. // a complete packet has processsedd (not by the FEC algorithm.)
  723. func (
  724. Kcp *KCP,
  725. ) Input(
  726. data []byte,
  727. regular,
  728. ackNoDelay bool,
  729. ) int {
  730. snd_una := Kcp.snd_una
  731. if len(
  732. data,
  733. ) < IKCP_OVERHEAD {
  734. return -1
  735. }
  736. var latest uint32
  737. var flag int
  738. var inSegs uint64
  739. for {
  740. var ts,
  741. sn,
  742. length,
  743. una,
  744. conv uint32
  745. var wnd uint16
  746. var cmd,
  747. frg uint8
  748. if len(
  749. data,
  750. ) < int(IKCP_OVERHEAD) {
  751. break
  752. }
  753. data = iKcp_decode32u(
  754. data,
  755. &conv,
  756. )
  757. if conv != Kcp.conv {
  758. return -1
  759. }
  760. data = iKcp_decode8u(
  761. data,
  762. &cmd,
  763. )
  764. data = iKcp_decode8u(
  765. data,
  766. &frg,
  767. )
  768. data = iKcp_decode16u(
  769. data,
  770. &wnd,
  771. )
  772. data = iKcp_decode32u(
  773. data,
  774. &ts,
  775. )
  776. data = iKcp_decode32u(
  777. data,
  778. &sn,
  779. )
  780. data = iKcp_decode32u(
  781. data,
  782. &una,
  783. )
  784. data = iKcp_decode32u(
  785. data,
  786. &length,
  787. )
  788. if len(
  789. data,
  790. ) < int(
  791. length,
  792. ) {
  793. return -2
  794. }
  795. if cmd != IKCP_CMD_PUSH && cmd != IKCP_CMD_ACK &&
  796. cmd != IKCP_CMD_WASK && cmd != IKCP_CMD_WINS {
  797. return -3
  798. }
  799. if regular {
  800. Kcp.rmt_wnd = uint32(wnd)
  801. }
  802. Kcp.parse_una(
  803. una,
  804. )
  805. Kcp.shrink_buf()
  806. if cmd == IKCP_CMD_ACK {
  807. Kcp.parse_ack(
  808. sn,
  809. )
  810. Kcp.parse_fastack(
  811. sn,
  812. ts,
  813. )
  814. flag |= 1
  815. latest = ts
  816. } else if cmd == IKCP_CMD_PUSH {
  817. repeat := true
  818. if _itimediff(
  819. sn,
  820. Kcp.rcv_nxt+Kcp.rcv_wnd,
  821. ) < 0 {
  822. Kcp.ack_push(
  823. sn,
  824. ts,
  825. )
  826. if _itimediff(
  827. sn,
  828. Kcp.rcv_nxt,
  829. ) >= 0 {
  830. var KcpSeg KcpSegment
  831. KcpSeg.conv = conv
  832. KcpSeg.cmd = cmd
  833. KcpSeg.frg = frg
  834. KcpSeg.wnd = wnd
  835. KcpSeg.ts = ts
  836. KcpSeg.sn = sn
  837. KcpSeg.una = una
  838. KcpSeg.data = data[:length]
  839. repeat = Kcp.parse_data(
  840. KcpSeg,
  841. )
  842. }
  843. }
  844. if regular && repeat {
  845. atomic.AddUint64(
  846. &DefaultSnsi.DuplicateSegments,
  847. 1,
  848. )
  849. }
  850. } else if cmd == IKCP_CMD_WASK {
  851. Kcp.probe |= IKCP_ASK_TELL
  852. } else if cmd == IKCP_CMD_WINS {
  853. } else {
  854. return -3
  855. }
  856. inSegs++
  857. data = data[length:]
  858. }
  859. atomic.AddUint64(&DefaultSnsi.KcpInputSegments, inSegs)
  860. if flag != 0 && regular {
  861. current := KcpCurrentMs()
  862. if _itimediff(
  863. current,
  864. latest,
  865. ) >= 0 {
  866. Kcp.update_ack(
  867. _itimediff(
  868. current,
  869. latest,
  870. ),
  871. )
  872. }
  873. }
  874. if Kcp.nocwnd == 0 {
  875. if _itimediff(
  876. Kcp.snd_una,
  877. snd_una,
  878. ) > 0 {
  879. if Kcp.cwnd < Kcp.rmt_wnd {
  880. mss := Kcp.mss
  881. if Kcp.cwnd < Kcp.ssthresh {
  882. Kcp.cwnd++
  883. Kcp.incr += mss
  884. } else {
  885. if Kcp.incr < mss {
  886. Kcp.incr = mss
  887. }
  888. Kcp.incr += (mss*mss)/Kcp.incr + (mss / 16)
  889. if (Kcp.cwnd+1)*mss <= Kcp.incr {
  890. Kcp.cwnd++
  891. }
  892. }
  893. if Kcp.cwnd > Kcp.rmt_wnd {
  894. Kcp.cwnd = Kcp.rmt_wnd
  895. Kcp.incr = Kcp.rmt_wnd * mss
  896. }
  897. }
  898. }
  899. }
  900. if ackNoDelay && len(
  901. Kcp.acklist,
  902. ) > 0 {
  903. Kcp.Flush(
  904. true,
  905. )
  906. }
  907. return 0
  908. }
  909. func (
  910. Kcp *KCP,
  911. ) wnd_unused() uint16 {
  912. if len(
  913. Kcp.rcv_queue,
  914. ) < int(Kcp.rcv_wnd) {
  915. return uint16(int(Kcp.rcv_wnd) - len(
  916. Kcp.rcv_queue,
  917. ),
  918. )
  919. }
  920. return 0
  921. }
  922. func (
  923. Kcp *KCP,
  924. ) Flush(
  925. ackOnly bool,
  926. ) uint32 {
  927. var KcpSeg KcpSegment
  928. KcpSeg.conv = Kcp.conv
  929. KcpSeg.cmd = IKCP_CMD_ACK
  930. KcpSeg.wnd = Kcp.wnd_unused()
  931. KcpSeg.una = Kcp.rcv_nxt
  932. buffer := Kcp.buffer
  933. ptr := buffer[Kcp.reserved:]
  934. makeSpace := func(
  935. space int,
  936. ) {
  937. size := len(
  938. buffer,
  939. ) - len(
  940. ptr,
  941. )
  942. if size+space > int(Kcp.mtu) {
  943. Kcp.output(
  944. buffer,
  945. size,
  946. )
  947. ptr = buffer[Kcp.reserved:]
  948. }
  949. }
  950. FlushBuffer := func() {
  951. size := len(
  952. buffer,
  953. ) - len(
  954. ptr,
  955. )
  956. if size > Kcp.reserved {
  957. Kcp.output(
  958. buffer,
  959. size,
  960. )
  961. }
  962. }
  963. for i, ack := range Kcp.acklist {
  964. makeSpace(
  965. IKCP_OVERHEAD,
  966. )
  967. if ack.sn >= Kcp.rcv_nxt || len(
  968. Kcp.acklist,
  969. )-1 == i {
  970. KcpSeg.sn,
  971. KcpSeg.ts = ack.sn,
  972. ack.ts
  973. ptr = KcpSeg.encode(
  974. ptr,
  975. )
  976. }
  977. }
  978. Kcp.acklist = Kcp.acklist[0:0]
  979. if ackOnly {
  980. FlushBuffer()
  981. return Kcp.interval
  982. }
  983. if Kcp.rmt_wnd == 0 {
  984. current := KcpCurrentMs()
  985. if Kcp.probe_wait == 0 {
  986. Kcp.probe_wait = IKCP_PROBE_INIT
  987. Kcp.ts_probe = current + Kcp.probe_wait
  988. } else if _itimediff(current, Kcp.ts_probe) >= 0 {
  989. if Kcp.probe_wait < IKCP_PROBE_INIT {
  990. Kcp.probe_wait = IKCP_PROBE_INIT
  991. }
  992. Kcp.probe_wait += Kcp.probe_wait / 2
  993. if Kcp.probe_wait > IKCP_PROBE_LIMIT {
  994. Kcp.probe_wait = IKCP_PROBE_LIMIT
  995. }
  996. Kcp.ts_probe = current + Kcp.probe_wait
  997. Kcp.probe |= IKCP_ASK_SEND
  998. }
  999. }
  1000. Kcp.ts_probe = 0
  1001. Kcp.probe_wait = 0
  1002. if (Kcp.probe & IKCP_ASK_SEND) != 0 {
  1003. KcpSeg.cmd = IKCP_CMD_WASK
  1004. makeSpace(
  1005. IKCP_OVERHEAD,
  1006. )
  1007. ptr = KcpSeg.encode(
  1008. ptr,
  1009. )
  1010. }
  1011. if (Kcp.probe & IKCP_ASK_TELL) != 0 {
  1012. KcpSeg.cmd = IKCP_CMD_WINS
  1013. makeSpace(
  1014. IKCP_OVERHEAD,
  1015. )
  1016. ptr = KcpSeg.encode(
  1017. ptr,
  1018. )
  1019. }
  1020. Kcp.probe = 0
  1021. cwnd := _imin_(
  1022. Kcp.snd_wnd,
  1023. Kcp.rmt_wnd,
  1024. )
  1025. if Kcp.nocwnd == 0 {
  1026. cwnd = _imin_(
  1027. Kcp.cwnd,
  1028. cwnd,
  1029. )
  1030. }
  1031. newSegsCount := 0
  1032. for k := range Kcp.snd_queue {
  1033. if _itimediff(
  1034. Kcp.snd_nxt,
  1035. Kcp.snd_una+cwnd,
  1036. ) >= 0 {
  1037. break
  1038. }
  1039. newKcpSeg := Kcp.snd_queue[k]
  1040. newKcpSeg.conv = Kcp.conv
  1041. newKcpSeg.cmd = IKCP_CMD_PUSH
  1042. newKcpSeg.sn = Kcp.snd_nxt
  1043. Kcp.SndBuf = append(
  1044. Kcp.SndBuf,
  1045. newKcpSeg,
  1046. )
  1047. Kcp.snd_nxt++
  1048. newSegsCount++
  1049. }
  1050. if newSegsCount > 0 {
  1051. Kcp.snd_queue = Kcp.remove_front(
  1052. Kcp.snd_queue,
  1053. newSegsCount,
  1054. )
  1055. }
  1056. resent := uint32(Kcp.fastresend)
  1057. if Kcp.fastresend <= 0 {
  1058. resent = 0xFFFFFFFF
  1059. }
  1060. current := KcpCurrentMs()
  1061. var change,
  1062. lost,
  1063. lostSegs,
  1064. fastKcpRestransmittedSegments,
  1065. earlyKcpRestransmittedSegments uint64
  1066. minrto := int32(Kcp.interval)
  1067. ref := Kcp.SndBuf[:len(
  1068. Kcp.SndBuf,
  1069. )]
  1070. for k := range ref {
  1071. KcpSegment := &ref[k]
  1072. needsend := false
  1073. if KcpSegment.acked == 1 {
  1074. continue
  1075. }
  1076. if KcpSegment.Kxmit == 0 {
  1077. needsend = true
  1078. KcpSegment.rto = Kcp.rx_rto
  1079. KcpSegment.KcpResendTs = current + KcpSegment.rto
  1080. } else if _itimediff(
  1081. current,
  1082. KcpSegment.KcpResendTs,
  1083. ) >= 0 {
  1084. needsend = true
  1085. if Kcp.nodelay == 0 {
  1086. KcpSegment.rto += Kcp.rx_rto
  1087. } else {
  1088. KcpSegment.rto += Kcp.rx_rto / 2
  1089. }
  1090. KcpSegment.KcpResendTs = current + KcpSegment.rto
  1091. lost++
  1092. lostSegs++
  1093. } else if KcpSegment.fastack >= resent {
  1094. needsend = true
  1095. KcpSegment.fastack = 0
  1096. KcpSegment.rto = Kcp.rx_rto
  1097. KcpSegment.KcpResendTs = current + KcpSegment.rto
  1098. change++
  1099. fastKcpRestransmittedSegments++
  1100. } else if KcpSegment.fastack > 0 && newSegsCount == 0 {
  1101. needsend = true
  1102. KcpSegment.fastack = 0
  1103. KcpSegment.rto = Kcp.rx_rto
  1104. KcpSegment.KcpResendTs = current + KcpSegment.rto
  1105. change++
  1106. earlyKcpRestransmittedSegments++
  1107. }
  1108. if needsend {
  1109. current = KcpCurrentMs()
  1110. KcpSegment.Kxmit++
  1111. KcpSegment.ts = current
  1112. KcpSegment.wnd = KcpSeg.wnd
  1113. KcpSegment.una = KcpSeg.una
  1114. need := IKCP_OVERHEAD + len(
  1115. KcpSegment.data,
  1116. )
  1117. makeSpace(
  1118. need,
  1119. )
  1120. ptr = KcpSegment.encode(
  1121. ptr,
  1122. )
  1123. copy(
  1124. ptr,
  1125. KcpSegment.data,
  1126. )
  1127. ptr = ptr[len(
  1128. KcpSegment.data,
  1129. ):]
  1130. if KcpSegment.Kxmit >= Kcp.dead_link {
  1131. Kcp.state = 0xFFFFFFFF
  1132. }
  1133. }
  1134. if rto := _itimediff(
  1135. KcpSegment.KcpResendTs,
  1136. current,
  1137. ); rto > 0 && rto < minrto {
  1138. minrto = rto
  1139. }
  1140. }
  1141. FlushBuffer()
  1142. sum := lostSegs
  1143. if lostSegs > 0 {
  1144. atomic.AddUint64(
  1145. &DefaultSnsi.LostSegments,
  1146. lostSegs,
  1147. )
  1148. }
  1149. if fastKcpRestransmittedSegments > 0 {
  1150. atomic.AddUint64(
  1151. &DefaultSnsi.FastKcpRestransmittedSegments,
  1152. fastKcpRestransmittedSegments,
  1153. )
  1154. sum += fastKcpRestransmittedSegments
  1155. }
  1156. if earlyKcpRestransmittedSegments > 0 {
  1157. atomic.AddUint64(
  1158. &DefaultSnsi.EarlyKcpRestransmittedSegments,
  1159. earlyKcpRestransmittedSegments,
  1160. )
  1161. sum += earlyKcpRestransmittedSegments
  1162. }
  1163. if sum > 0 {
  1164. atomic.AddUint64(
  1165. &DefaultSnsi.KcpRestransmittedSegments,
  1166. sum,
  1167. )
  1168. }
  1169. if Kcp.nocwnd == 0 {
  1170. if change > 0 {
  1171. inflight := Kcp.snd_nxt - Kcp.snd_una
  1172. Kcp.ssthresh = inflight / 2
  1173. if Kcp.ssthresh < IKCP_THRESH_MIN {
  1174. Kcp.ssthresh = IKCP_THRESH_MIN
  1175. }
  1176. Kcp.cwnd = Kcp.ssthresh + resent
  1177. Kcp.incr = Kcp.cwnd * Kcp.mss
  1178. }
  1179. if lost > 0 {
  1180. Kcp.ssthresh = cwnd / 2
  1181. if Kcp.ssthresh < IKCP_THRESH_MIN {
  1182. Kcp.ssthresh = IKCP_THRESH_MIN
  1183. }
  1184. Kcp.cwnd = 1
  1185. Kcp.incr = Kcp.mss
  1186. }
  1187. if Kcp.cwnd < 1 {
  1188. Kcp.cwnd = 1
  1189. Kcp.incr = Kcp.mss
  1190. }
  1191. }
  1192. return uint32(
  1193. minrto,
  1194. )
  1195. }
  1196. // Update is called repeatedly, 10ms to 100ms, queried via iKcp_check
  1197. // without iKcp_input or _send executing, returning timestamp in ms.
  1198. func (
  1199. Kcp *KCP,
  1200. ) Update() {
  1201. var slap int32
  1202. current := KcpCurrentMs()
  1203. if Kcp.updated == 0 {
  1204. Kcp.updated = 1
  1205. Kcp.ts_Flush = current
  1206. }
  1207. slap = _itimediff(
  1208. current,
  1209. Kcp.ts_Flush,
  1210. )
  1211. if slap >= 10000 || slap < -10000 {
  1212. Kcp.ts_Flush = current
  1213. slap = 0
  1214. }
  1215. if slap >= 0 {
  1216. Kcp.ts_Flush += Kcp.interval
  1217. if _itimediff(
  1218. current,
  1219. Kcp.ts_Flush,
  1220. ) >= 0 {
  1221. Kcp.ts_Flush = current + Kcp.interval
  1222. }
  1223. Kcp.Flush(
  1224. false,
  1225. )
  1226. }
  1227. }
  1228. // Check function helps determine when to invoke an iKcp_update.
  1229. // It returns when you should invoke iKcp_update, in milliseconds,
  1230. // if there is no iKcp_input or _send calling. You may repeatdly
  1231. // call iKcp_update instead of update, to reduce most unnacessary
  1232. // iKcp_update invocations. This function may be used to schedule
  1233. // iKcp_updates, when implementing an epoll-like mechanism, or for
  1234. // optimizing an iKcp_update loop handling massive Kcp connections.
  1235. func (
  1236. Kcp *KCP,
  1237. ) Check() uint32 {
  1238. current := KcpCurrentMs()
  1239. ts_Flush := Kcp.ts_Flush
  1240. tm_Flush := int32(0x7FFFFFFF)
  1241. tm_packet := int32(0x7FFFFFFF)
  1242. minimal := uint32(0)
  1243. if Kcp.updated == 0 {
  1244. return current
  1245. }
  1246. if _itimediff(
  1247. current,
  1248. ts_Flush,
  1249. ) >= 10000 ||
  1250. _itimediff(
  1251. current,
  1252. ts_Flush,
  1253. ) < -10000 {
  1254. ts_Flush = current
  1255. }
  1256. if _itimediff(
  1257. current,
  1258. ts_Flush,
  1259. ) >= 0 {
  1260. return current
  1261. }
  1262. tm_Flush = _itimediff(
  1263. ts_Flush,
  1264. current,
  1265. )
  1266. for k := range Kcp.SndBuf {
  1267. KcpSeg := &Kcp.SndBuf[k]
  1268. diff := _itimediff(
  1269. KcpSeg.KcpResendTs,
  1270. current,
  1271. )
  1272. if diff <= 0 {
  1273. return current
  1274. }
  1275. if diff < tm_packet {
  1276. tm_packet = diff
  1277. }
  1278. }
  1279. minimal = uint32(tm_packet)
  1280. if tm_packet >= tm_Flush {
  1281. minimal = uint32(tm_Flush)
  1282. }
  1283. if minimal >= Kcp.interval {
  1284. minimal = Kcp.interval
  1285. }
  1286. return current + minimal
  1287. }
  1288. // SetMtu changes MTU size.
  1289. // Defult MTU is 1400 byes.
  1290. func (
  1291. Kcp *KCP,
  1292. ) SetMtu(
  1293. mtu int,
  1294. ) int {
  1295. if mtu < 50 || mtu < IKCP_OVERHEAD {
  1296. return -1
  1297. }
  1298. if Kcp.reserved >= int(Kcp.mtu-IKCP_OVERHEAD) || Kcp.reserved < 0 {
  1299. return -1
  1300. }
  1301. buffer := make(
  1302. []byte,
  1303. mtu,
  1304. )
  1305. if buffer == nil {
  1306. return -2
  1307. }
  1308. Kcp.mtu = uint32(mtu)
  1309. Kcp.mss = Kcp.mtu - IKCP_OVERHEAD - uint32(Kcp.reserved)
  1310. Kcp.buffer = buffer
  1311. return 0
  1312. }
  1313. // NoDelay options:
  1314. // * fastest: iKcp_nodelay(Kcp, 1, 20, 2, 1)
  1315. // * nodelay: 0: disable (default), 1: enable
  1316. // * interval: internal update timer interval in milliseconds, defaults to 100ms
  1317. // * resend: 0: disable fast resends (default), 1: enable fast resends
  1318. // * nc: 0: normal congestion control (default), 1: disable congestion control
  1319. func (
  1320. Kcp *KCP,
  1321. ) NoDelay(
  1322. nodelay,
  1323. interval,
  1324. resend,
  1325. nc int,
  1326. ) int {
  1327. if nodelay >= 0 {
  1328. Kcp.nodelay = uint32(nodelay)
  1329. if nodelay != 0 {
  1330. Kcp.rx_minrto = IKCP_RTO_NDL
  1331. } else {
  1332. Kcp.rx_minrto = IKCP_RTO_MIN
  1333. }
  1334. }
  1335. if interval >= 0 {
  1336. if interval > 5000 {
  1337. interval = 5000
  1338. } else if interval < 10 {
  1339. interval = 10
  1340. }
  1341. Kcp.interval = uint32(interval)
  1342. }
  1343. if resend >= 0 {
  1344. Kcp.fastresend = int32(resend)
  1345. }
  1346. if nc >= 0 {
  1347. Kcp.nocwnd = int32(nc)
  1348. }
  1349. return 0
  1350. }
  1351. // WndSize sets maximum window size (efaults: sndwnd=32 and rcvwnd=32)
  1352. func (
  1353. Kcp *KCP,
  1354. ) WndSize(
  1355. sndwnd,
  1356. rcvwnd int,
  1357. ) int {
  1358. if sndwnd > 0 {
  1359. Kcp.snd_wnd = uint32(sndwnd)
  1360. }
  1361. if rcvwnd > 0 {
  1362. Kcp.rcv_wnd = uint32(rcvwnd)
  1363. }
  1364. return 0
  1365. }
  1366. // WaitSnd shows how many packets are queued to be sent
  1367. func (
  1368. Kcp *KCP,
  1369. ) WaitSnd() int {
  1370. return len(
  1371. Kcp.SndBuf,
  1372. ) + len(
  1373. Kcp.snd_queue,
  1374. )
  1375. }
  1376. func (
  1377. Kcp *KCP,
  1378. ) remove_front(
  1379. q []KcpSegment,
  1380. n int,
  1381. ) []KcpSegment {
  1382. if n > cap(
  1383. q,
  1384. )/2 {
  1385. newn := copy(
  1386. q,
  1387. q[n:],
  1388. )
  1389. return q[:newn]
  1390. }
  1391. return q[n:]
  1392. }
  1393. func init() {
  1394. // Register the MIT License
  1395. lkcp9Legal.RegisterLicense(
  1396. "\nThe MIT License (MIT)\n\nCopyright © 2015 Daniel Fu <daniel820313@gmail.com>.\nCopyright © 2019 Loki 'l0k18' Verloren <stalker.loki@protonmail.ch>.\nCopyright © 2020 Gridfinity, LLC. <admin@gridfinity.com>.\nCopyright © 2020 Jeffrey H. Johnson <jeff@gridfinity.com>.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including, without limitation, the rights\nto use, copy, modify, merge, publish, distribute, sub-license, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice, and this permission notice, shall be\nincluded in all copies, or substantial portions, of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING, BUT NOT LIMITED TO, THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF, OR IN CONNECTION WITH THE SOFTWARE, OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n",
  1397. )
  1398. }