1
0

sess.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  1. package kcp
  2. import (
  3. "crypto/rand"
  4. "encoding/binary"
  5. "hash/crc32"
  6. "io"
  7. "net"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. "github.com/pkg/errors"
  12. "golang.org/x/net/ipv4"
  13. )
  14. type errTimeout struct {
  15. error
  16. }
  17. func (errTimeout) Timeout() bool { return true }
  18. func (errTimeout) Temporary() bool { return true }
  19. func (errTimeout) Error() string { return "i/o timeout" }
  20. const (
  21. // 16-bytes magic number for each packet
  22. nonceSize = 16
  23. // 4-bytes packet checksum
  24. crcSize = 4
  25. // overall crypto header size
  26. cryptHeaderSize = nonceSize + crcSize
  27. // maximum packet size
  28. mtuLimit = 1500
  29. // FEC keeps rxFECMulti* (dataShard+parityShard) ordered packets in memory
  30. rxFECMulti = 3
  31. // accept backlog
  32. acceptBacklog = 128
  33. // prerouting(to session) queue
  34. qlen = 128
  35. )
  36. const (
  37. errBrokenPipe = "broken pipe"
  38. errInvalidOperation = "invalid operation"
  39. )
  40. var (
  41. // global packet buffer
  42. // shared among sending/receiving/FEC
  43. xmitBuf sync.Pool
  44. )
  45. func init() {
  46. xmitBuf.New = func() interface{} {
  47. return make([]byte, mtuLimit)
  48. }
  49. }
  50. type (
  51. // UDPSession defines a KCP session implemented by UDP
  52. UDPSession struct {
  53. updaterIdx int // record slice index in updater
  54. conn net.PacketConn // the underlying packet connection
  55. kcp *KCP // KCP ARQ protocol
  56. l *Listener // point to the Listener if it's accepted by Listener
  57. block BlockCrypt // block encryption
  58. // kcp receiving is based on packets
  59. // recvbuf turns packets into stream
  60. recvbuf []byte
  61. bufptr []byte
  62. // extended output buffer(with header)
  63. ext []byte
  64. // FEC
  65. fecDecoder *fecDecoder
  66. fecEncoder *fecEncoder
  67. // settings
  68. remote net.Addr // remote peer address
  69. rd time.Time // read deadline
  70. wd time.Time // write deadline
  71. headerSize int // the overall header size added before KCP frame
  72. ackNoDelay bool // send ack immediately for each incoming packet
  73. writeDelay bool // delay kcp.flush() for Write() for bulk transfer
  74. dup int // duplicate udp packets
  75. // notifications
  76. die chan struct{} // notify session has Closed
  77. chReadEvent chan struct{} // notify Read() can be called without blocking
  78. chWriteEvent chan struct{} // notify Write() can be called without blocking
  79. chErrorEvent chan error // notify Read() have an error
  80. isClosed bool // flag the session has Closed
  81. mu sync.Mutex
  82. }
  83. setReadBuffer interface {
  84. SetReadBuffer(bytes int) error
  85. }
  86. setWriteBuffer interface {
  87. SetWriteBuffer(bytes int) error
  88. }
  89. )
  90. // newUDPSession create a new udp session for client or server
  91. func newUDPSession(conv uint32, dataShards, parityShards int, l *Listener, conn net.PacketConn, remote net.Addr, block BlockCrypt) *UDPSession {
  92. sess := new(UDPSession)
  93. sess.die = make(chan struct{})
  94. sess.chReadEvent = make(chan struct{}, 1)
  95. sess.chWriteEvent = make(chan struct{}, 1)
  96. sess.chErrorEvent = make(chan error, 1)
  97. sess.remote = remote
  98. sess.conn = conn
  99. sess.l = l
  100. sess.block = block
  101. sess.recvbuf = make([]byte, mtuLimit)
  102. // FEC initialization
  103. sess.fecDecoder = newFECDecoder(rxFECMulti*(dataShards+parityShards), dataShards, parityShards)
  104. if sess.block != nil {
  105. sess.fecEncoder = newFECEncoder(dataShards, parityShards, cryptHeaderSize)
  106. } else {
  107. sess.fecEncoder = newFECEncoder(dataShards, parityShards, 0)
  108. }
  109. // calculate header size
  110. if sess.block != nil {
  111. sess.headerSize += cryptHeaderSize
  112. }
  113. if sess.fecEncoder != nil {
  114. sess.headerSize += fecHeaderSizePlus2
  115. }
  116. // only allocate extended packet buffer
  117. // when the extra header is required
  118. if sess.headerSize > 0 {
  119. sess.ext = make([]byte, mtuLimit)
  120. }
  121. sess.kcp = NewKCP(conv, func(buf []byte, size int) {
  122. if size >= IKCP_OVERHEAD {
  123. sess.output(buf[:size])
  124. }
  125. })
  126. sess.kcp.SetMtu(IKCP_MTU_DEF - sess.headerSize)
  127. // add current session to the global updater,
  128. // which periodically calls sess.update()
  129. updater.addSession(sess)
  130. if sess.l == nil { // it's a client connection
  131. go sess.readLoop()
  132. atomic.AddUint64(&DefaultSnmp.ActiveOpens, 1)
  133. } else {
  134. atomic.AddUint64(&DefaultSnmp.PassiveOpens, 1)
  135. }
  136. currestab := atomic.AddUint64(&DefaultSnmp.CurrEstab, 1)
  137. maxconn := atomic.LoadUint64(&DefaultSnmp.MaxConn)
  138. if currestab > maxconn {
  139. atomic.CompareAndSwapUint64(&DefaultSnmp.MaxConn, maxconn, currestab)
  140. }
  141. return sess
  142. }
  143. // Read implements net.Conn
  144. func (s *UDPSession) Read(b []byte) (n int, err error) {
  145. for {
  146. s.mu.Lock()
  147. if len(s.bufptr) > 0 { // copy from buffer into b
  148. n = copy(b, s.bufptr)
  149. s.bufptr = s.bufptr[n:]
  150. s.mu.Unlock()
  151. return n, nil
  152. }
  153. if s.isClosed {
  154. s.mu.Unlock()
  155. return 0, errors.New(errBrokenPipe)
  156. }
  157. if size := s.kcp.PeekSize(); size > 0 { // peek data size from kcp
  158. atomic.AddUint64(&DefaultSnmp.BytesReceived, uint64(size))
  159. if len(b) >= size { // direct write to b
  160. s.kcp.Recv(b)
  161. s.mu.Unlock()
  162. return size, nil
  163. }
  164. // resize kcp receive buffer
  165. // to make sure recvbuf has enough capacity
  166. if cap(s.recvbuf) < size {
  167. s.recvbuf = make([]byte, size)
  168. }
  169. // resize recvbuf slice length
  170. s.recvbuf = s.recvbuf[:size]
  171. s.kcp.Recv(s.recvbuf)
  172. n = copy(b, s.recvbuf) // copy to b
  173. s.bufptr = s.recvbuf[n:] // update pointer
  174. s.mu.Unlock()
  175. return n, nil
  176. }
  177. // read deadline
  178. var timeout *time.Timer
  179. var c <-chan time.Time
  180. if !s.rd.IsZero() {
  181. if time.Now().After(s.rd) {
  182. s.mu.Unlock()
  183. return 0, errTimeout{}
  184. }
  185. delay := s.rd.Sub(time.Now())
  186. timeout = time.NewTimer(delay)
  187. c = timeout.C
  188. }
  189. s.mu.Unlock()
  190. // wait for read event or timeout
  191. select {
  192. case <-s.chReadEvent:
  193. case <-c:
  194. case <-s.die:
  195. case err = <-s.chErrorEvent:
  196. if timeout != nil {
  197. timeout.Stop()
  198. }
  199. return n, err
  200. }
  201. if timeout != nil {
  202. timeout.Stop()
  203. }
  204. }
  205. }
  206. // Write implements net.Conn
  207. func (s *UDPSession) Write(b []byte) (n int, err error) {
  208. for {
  209. s.mu.Lock()
  210. if s.isClosed {
  211. s.mu.Unlock()
  212. return 0, errors.New(errBrokenPipe)
  213. }
  214. // api flow control
  215. if s.kcp.WaitSnd() < int(s.kcp.snd_wnd) {
  216. n = len(b)
  217. for {
  218. if len(b) <= int(s.kcp.mss) {
  219. s.kcp.Send(b)
  220. break
  221. } else {
  222. s.kcp.Send(b[:s.kcp.mss])
  223. b = b[s.kcp.mss:]
  224. }
  225. }
  226. if !s.writeDelay {
  227. s.kcp.flush(false)
  228. }
  229. s.mu.Unlock()
  230. atomic.AddUint64(&DefaultSnmp.BytesSent, uint64(n))
  231. return n, nil
  232. }
  233. // write deadline
  234. var timeout *time.Timer
  235. var c <-chan time.Time
  236. if !s.wd.IsZero() {
  237. if time.Now().After(s.wd) {
  238. s.mu.Unlock()
  239. return 0, errTimeout{}
  240. }
  241. delay := s.wd.Sub(time.Now())
  242. timeout = time.NewTimer(delay)
  243. c = timeout.C
  244. }
  245. s.mu.Unlock()
  246. // wait for write event or timeout
  247. select {
  248. case <-s.chWriteEvent:
  249. case <-c:
  250. case <-s.die:
  251. }
  252. if timeout != nil {
  253. timeout.Stop()
  254. }
  255. }
  256. }
  257. // Close closes the connection.
  258. func (s *UDPSession) Close() error {
  259. // remove this session from updater & listener(if necessary)
  260. updater.removeSession(s)
  261. if s.l != nil { // notify listener
  262. s.l.closeSession(s.remote)
  263. }
  264. s.mu.Lock()
  265. defer s.mu.Unlock()
  266. if s.isClosed {
  267. return errors.New(errBrokenPipe)
  268. }
  269. close(s.die)
  270. s.isClosed = true
  271. atomic.AddUint64(&DefaultSnmp.CurrEstab, ^uint64(0))
  272. if s.l == nil { // client socket close
  273. return s.conn.Close()
  274. }
  275. return nil
  276. }
  277. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  278. func (s *UDPSession) LocalAddr() net.Addr { return s.conn.LocalAddr() }
  279. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  280. func (s *UDPSession) RemoteAddr() net.Addr { return s.remote }
  281. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  282. func (s *UDPSession) SetDeadline(t time.Time) error {
  283. s.mu.Lock()
  284. defer s.mu.Unlock()
  285. s.rd = t
  286. s.wd = t
  287. return nil
  288. }
  289. // SetReadDeadline implements the Conn SetReadDeadline method.
  290. func (s *UDPSession) SetReadDeadline(t time.Time) error {
  291. s.mu.Lock()
  292. defer s.mu.Unlock()
  293. s.rd = t
  294. return nil
  295. }
  296. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  297. func (s *UDPSession) SetWriteDeadline(t time.Time) error {
  298. s.mu.Lock()
  299. defer s.mu.Unlock()
  300. s.wd = t
  301. return nil
  302. }
  303. // SetWriteDelay delays write for bulk transfer until the next update interval
  304. func (s *UDPSession) SetWriteDelay(delay bool) {
  305. s.mu.Lock()
  306. defer s.mu.Unlock()
  307. s.writeDelay = delay
  308. }
  309. // SetWindowSize set maximum window size
  310. func (s *UDPSession) SetWindowSize(sndwnd, rcvwnd int) {
  311. s.mu.Lock()
  312. defer s.mu.Unlock()
  313. s.kcp.WndSize(sndwnd, rcvwnd)
  314. }
  315. // SetMtu sets the maximum transmission unit(not including UDP header)
  316. func (s *UDPSession) SetMtu(mtu int) bool {
  317. if mtu > mtuLimit {
  318. return false
  319. }
  320. s.mu.Lock()
  321. defer s.mu.Unlock()
  322. s.kcp.SetMtu(mtu - s.headerSize)
  323. return true
  324. }
  325. // SetStreamMode toggles the stream mode on/off
  326. func (s *UDPSession) SetStreamMode(enable bool) {
  327. s.mu.Lock()
  328. defer s.mu.Unlock()
  329. if enable {
  330. s.kcp.stream = 1
  331. } else {
  332. s.kcp.stream = 0
  333. }
  334. }
  335. // SetACKNoDelay changes ack flush option, set true to flush ack immediately,
  336. func (s *UDPSession) SetACKNoDelay(nodelay bool) {
  337. s.mu.Lock()
  338. defer s.mu.Unlock()
  339. s.ackNoDelay = nodelay
  340. }
  341. // SetDUP duplicates udp packets for kcp output, for testing purpose only
  342. func (s *UDPSession) SetDUP(dup int) {
  343. s.mu.Lock()
  344. defer s.mu.Unlock()
  345. s.dup = dup
  346. }
  347. // SetNoDelay calls nodelay() of kcp
  348. // https://github.com/skywind3000/kcp/blob/master/README.en.md#protocol-configuration
  349. func (s *UDPSession) SetNoDelay(nodelay, interval, resend, nc int) {
  350. s.mu.Lock()
  351. defer s.mu.Unlock()
  352. s.kcp.NoDelay(nodelay, interval, resend, nc)
  353. }
  354. // SetDSCP sets the 6bit DSCP field of IP header, no effect if it's accepted from Listener
  355. func (s *UDPSession) SetDSCP(dscp int) error {
  356. s.mu.Lock()
  357. defer s.mu.Unlock()
  358. if s.l == nil {
  359. if nc, ok := s.conn.(*connectedUDPConn); ok {
  360. return ipv4.NewConn(nc.UDPConn).SetTOS(dscp << 2)
  361. } else if nc, ok := s.conn.(net.Conn); ok {
  362. return ipv4.NewConn(nc).SetTOS(dscp << 2)
  363. }
  364. }
  365. return errors.New(errInvalidOperation)
  366. }
  367. // SetReadBuffer sets the socket read buffer, no effect if it's accepted from Listener
  368. func (s *UDPSession) SetReadBuffer(bytes int) error {
  369. s.mu.Lock()
  370. defer s.mu.Unlock()
  371. if s.l == nil {
  372. if nc, ok := s.conn.(setReadBuffer); ok {
  373. return nc.SetReadBuffer(bytes)
  374. }
  375. }
  376. return errors.New(errInvalidOperation)
  377. }
  378. // SetWriteBuffer sets the socket write buffer, no effect if it's accepted from Listener
  379. func (s *UDPSession) SetWriteBuffer(bytes int) error {
  380. s.mu.Lock()
  381. defer s.mu.Unlock()
  382. if s.l == nil {
  383. if nc, ok := s.conn.(setWriteBuffer); ok {
  384. return nc.SetWriteBuffer(bytes)
  385. }
  386. }
  387. return errors.New(errInvalidOperation)
  388. }
  389. // output pipeline entry
  390. // steps for output data processing:
  391. // 0. Header extends
  392. // 1. FEC
  393. // 2. CRC32
  394. // 3. Encryption
  395. // 4. WriteTo kernel
  396. func (s *UDPSession) output(buf []byte) {
  397. var ecc [][]byte
  398. // 0. extend buf's header space(if necessary)
  399. ext := buf
  400. if s.headerSize > 0 {
  401. ext = s.ext[:s.headerSize+len(buf)]
  402. copy(ext[s.headerSize:], buf)
  403. }
  404. // 1. FEC encoding
  405. if s.fecEncoder != nil {
  406. ecc = s.fecEncoder.encode(ext)
  407. }
  408. // 2&3. crc32 & encryption
  409. if s.block != nil {
  410. io.ReadFull(rand.Reader, ext[:nonceSize])
  411. checksum := crc32.ChecksumIEEE(ext[cryptHeaderSize:])
  412. binary.LittleEndian.PutUint32(ext[nonceSize:], checksum)
  413. s.block.Encrypt(ext, ext)
  414. for k := range ecc {
  415. io.ReadFull(rand.Reader, ecc[k][:nonceSize])
  416. checksum := crc32.ChecksumIEEE(ecc[k][cryptHeaderSize:])
  417. binary.LittleEndian.PutUint32(ecc[k][nonceSize:], checksum)
  418. s.block.Encrypt(ecc[k], ecc[k])
  419. }
  420. }
  421. // 4. WriteTo kernel
  422. nbytes := 0
  423. npkts := 0
  424. for i := 0; i < s.dup+1; i++ {
  425. if n, err := s.conn.WriteTo(ext, s.remote); err == nil {
  426. nbytes += n
  427. npkts++
  428. }
  429. }
  430. for k := range ecc {
  431. if n, err := s.conn.WriteTo(ecc[k], s.remote); err == nil {
  432. nbytes += n
  433. npkts++
  434. }
  435. }
  436. atomic.AddUint64(&DefaultSnmp.OutPkts, uint64(npkts))
  437. atomic.AddUint64(&DefaultSnmp.OutBytes, uint64(nbytes))
  438. }
  439. // kcp update, returns interval for next calling
  440. func (s *UDPSession) update() (interval time.Duration) {
  441. s.mu.Lock()
  442. s.kcp.flush(false)
  443. if s.kcp.WaitSnd() < int(s.kcp.snd_wnd) {
  444. s.notifyWriteEvent()
  445. }
  446. interval = time.Duration(s.kcp.interval) * time.Millisecond
  447. s.mu.Unlock()
  448. return
  449. }
  450. // GetConv gets conversation id of a session
  451. func (s *UDPSession) GetConv() uint32 { return s.kcp.conv }
  452. func (s *UDPSession) notifyReadEvent() {
  453. select {
  454. case s.chReadEvent <- struct{}{}:
  455. default:
  456. }
  457. }
  458. func (s *UDPSession) notifyWriteEvent() {
  459. select {
  460. case s.chWriteEvent <- struct{}{}:
  461. default:
  462. }
  463. }
  464. func (s *UDPSession) kcpInput(data []byte) {
  465. var kcpInErrors, fecErrs, fecRecovered, fecParityShards uint64
  466. if s.fecDecoder != nil {
  467. f := s.fecDecoder.decodeBytes(data)
  468. s.mu.Lock()
  469. if f.flag == typeData {
  470. if ret := s.kcp.Input(data[fecHeaderSizePlus2:], true, s.ackNoDelay); ret != 0 {
  471. kcpInErrors++
  472. }
  473. }
  474. if f.flag == typeData || f.flag == typeFEC {
  475. if f.flag == typeFEC {
  476. fecParityShards++
  477. }
  478. recovers := s.fecDecoder.decode(f)
  479. for _, r := range recovers {
  480. if len(r) >= 2 { // must be larger than 2bytes
  481. sz := binary.LittleEndian.Uint16(r)
  482. if int(sz) <= len(r) && sz >= 2 {
  483. if ret := s.kcp.Input(r[2:sz], false, s.ackNoDelay); ret == 0 {
  484. fecRecovered++
  485. } else {
  486. kcpInErrors++
  487. }
  488. } else {
  489. fecErrs++
  490. }
  491. } else {
  492. fecErrs++
  493. }
  494. }
  495. }
  496. // notify reader
  497. if n := s.kcp.PeekSize(); n > 0 {
  498. s.notifyReadEvent()
  499. }
  500. s.mu.Unlock()
  501. } else {
  502. s.mu.Lock()
  503. if ret := s.kcp.Input(data, true, s.ackNoDelay); ret != 0 {
  504. kcpInErrors++
  505. }
  506. // notify reader
  507. if n := s.kcp.PeekSize(); n > 0 {
  508. s.notifyReadEvent()
  509. }
  510. s.mu.Unlock()
  511. }
  512. atomic.AddUint64(&DefaultSnmp.InPkts, 1)
  513. atomic.AddUint64(&DefaultSnmp.InBytes, uint64(len(data)))
  514. if fecParityShards > 0 {
  515. atomic.AddUint64(&DefaultSnmp.FECParityShards, fecParityShards)
  516. }
  517. if kcpInErrors > 0 {
  518. atomic.AddUint64(&DefaultSnmp.KCPInErrors, kcpInErrors)
  519. }
  520. if fecErrs > 0 {
  521. atomic.AddUint64(&DefaultSnmp.FECErrs, fecErrs)
  522. }
  523. if fecRecovered > 0 {
  524. atomic.AddUint64(&DefaultSnmp.FECRecovered, fecRecovered)
  525. }
  526. }
  527. func (s *UDPSession) receiver(ch chan<- []byte) {
  528. for {
  529. data := xmitBuf.Get().([]byte)[:mtuLimit]
  530. if n, _, err := s.conn.ReadFrom(data); err == nil && n >= s.headerSize+IKCP_OVERHEAD {
  531. select {
  532. case ch <- data[:n]:
  533. case <-s.die:
  534. return
  535. }
  536. } else if err != nil {
  537. s.chErrorEvent <- err
  538. return
  539. } else {
  540. atomic.AddUint64(&DefaultSnmp.InErrs, 1)
  541. }
  542. }
  543. }
  544. // read loop for client session
  545. func (s *UDPSession) readLoop() {
  546. chPacket := make(chan []byte, qlen)
  547. go s.receiver(chPacket)
  548. for {
  549. select {
  550. case data := <-chPacket:
  551. raw := data
  552. dataValid := false
  553. if s.block != nil {
  554. s.block.Decrypt(data, data)
  555. data = data[nonceSize:]
  556. checksum := crc32.ChecksumIEEE(data[crcSize:])
  557. if checksum == binary.LittleEndian.Uint32(data) {
  558. data = data[crcSize:]
  559. dataValid = true
  560. } else {
  561. atomic.AddUint64(&DefaultSnmp.InCsumErrors, 1)
  562. }
  563. } else if s.block == nil {
  564. dataValid = true
  565. }
  566. if dataValid {
  567. s.kcpInput(data)
  568. }
  569. xmitBuf.Put(raw)
  570. case <-s.die:
  571. return
  572. }
  573. }
  574. }
  575. type (
  576. // Listener defines a server listening for connections
  577. Listener struct {
  578. block BlockCrypt // block encryption
  579. dataShards int // FEC data shard
  580. parityShards int // FEC parity shard
  581. fecDecoder *fecDecoder // FEC mock initialization
  582. conn net.PacketConn // the underlying packet connection
  583. sessions map[string]*UDPSession // all sessions accepted by this Listener
  584. chAccepts chan *UDPSession // Listen() backlog
  585. chSessionClosed chan net.Addr // session close queue
  586. headerSize int // the overall header size added before KCP frame
  587. die chan struct{} // notify the listener has closed
  588. rd atomic.Value // read deadline for Accept()
  589. wd atomic.Value
  590. }
  591. // incoming packet
  592. inPacket struct {
  593. from net.Addr
  594. data []byte
  595. }
  596. )
  597. // monitor incoming data for all connections of server
  598. func (l *Listener) monitor() {
  599. chPacket := make(chan inPacket, qlen)
  600. go l.receiver(chPacket)
  601. for {
  602. select {
  603. case p := <-chPacket:
  604. raw := p.data
  605. data := p.data
  606. from := p.from
  607. dataValid := false
  608. if l.block != nil {
  609. l.block.Decrypt(data, data)
  610. data = data[nonceSize:]
  611. checksum := crc32.ChecksumIEEE(data[crcSize:])
  612. if checksum == binary.LittleEndian.Uint32(data) {
  613. data = data[crcSize:]
  614. dataValid = true
  615. } else {
  616. atomic.AddUint64(&DefaultSnmp.InCsumErrors, 1)
  617. }
  618. } else if l.block == nil {
  619. dataValid = true
  620. }
  621. if dataValid {
  622. addr := from.String()
  623. s, ok := l.sessions[addr]
  624. if !ok { // new session
  625. if len(l.chAccepts) < cap(l.chAccepts) { // do not let new session overwhelm accept queue
  626. var conv uint32
  627. convValid := false
  628. if l.fecDecoder != nil {
  629. isfec := binary.LittleEndian.Uint16(data[4:])
  630. if isfec == typeData {
  631. conv = binary.LittleEndian.Uint32(data[fecHeaderSizePlus2:])
  632. convValid = true
  633. }
  634. } else {
  635. conv = binary.LittleEndian.Uint32(data)
  636. convValid = true
  637. }
  638. if convValid {
  639. s := newUDPSession(conv, l.dataShards, l.parityShards, l, l.conn, from, l.block)
  640. s.kcpInput(data)
  641. l.sessions[addr] = s
  642. l.chAccepts <- s
  643. }
  644. }
  645. } else {
  646. s.kcpInput(data)
  647. }
  648. }
  649. xmitBuf.Put(raw)
  650. case deadlink := <-l.chSessionClosed:
  651. delete(l.sessions, deadlink.String())
  652. case <-l.die:
  653. return
  654. }
  655. }
  656. }
  657. func (l *Listener) receiver(ch chan<- inPacket) {
  658. for {
  659. data := xmitBuf.Get().([]byte)[:mtuLimit]
  660. if n, from, err := l.conn.ReadFrom(data); err == nil && n >= l.headerSize+IKCP_OVERHEAD {
  661. select {
  662. case ch <- inPacket{from, data[:n]}:
  663. case <-l.die:
  664. return
  665. }
  666. } else if err != nil {
  667. return
  668. } else {
  669. atomic.AddUint64(&DefaultSnmp.InErrs, 1)
  670. }
  671. }
  672. }
  673. // SetReadBuffer sets the socket read buffer for the Listener
  674. func (l *Listener) SetReadBuffer(bytes int) error {
  675. if nc, ok := l.conn.(setReadBuffer); ok {
  676. return nc.SetReadBuffer(bytes)
  677. }
  678. return errors.New(errInvalidOperation)
  679. }
  680. // SetWriteBuffer sets the socket write buffer for the Listener
  681. func (l *Listener) SetWriteBuffer(bytes int) error {
  682. if nc, ok := l.conn.(setWriteBuffer); ok {
  683. return nc.SetWriteBuffer(bytes)
  684. }
  685. return errors.New(errInvalidOperation)
  686. }
  687. // SetDSCP sets the 6bit DSCP field of IP header
  688. func (l *Listener) SetDSCP(dscp int) error {
  689. if nc, ok := l.conn.(net.Conn); ok {
  690. return ipv4.NewConn(nc).SetTOS(dscp << 2)
  691. }
  692. return errors.New(errInvalidOperation)
  693. }
  694. // Accept implements the Accept method in the Listener interface; it waits for the next call and returns a generic Conn.
  695. func (l *Listener) Accept() (net.Conn, error) {
  696. return l.AcceptKCP()
  697. }
  698. // AcceptKCP accepts a KCP connection
  699. func (l *Listener) AcceptKCP() (*UDPSession, error) {
  700. var timeout <-chan time.Time
  701. if tdeadline, ok := l.rd.Load().(time.Time); ok && !tdeadline.IsZero() {
  702. timeout = time.After(tdeadline.Sub(time.Now()))
  703. }
  704. select {
  705. case <-timeout:
  706. return nil, &errTimeout{}
  707. case c := <-l.chAccepts:
  708. return c, nil
  709. case <-l.die:
  710. return nil, errors.New(errBrokenPipe)
  711. }
  712. }
  713. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  714. func (l *Listener) SetDeadline(t time.Time) error {
  715. l.SetReadDeadline(t)
  716. l.SetWriteDeadline(t)
  717. return nil
  718. }
  719. // SetReadDeadline implements the Conn SetReadDeadline method.
  720. func (l *Listener) SetReadDeadline(t time.Time) error {
  721. l.rd.Store(t)
  722. return nil
  723. }
  724. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  725. func (l *Listener) SetWriteDeadline(t time.Time) error {
  726. l.wd.Store(t)
  727. return nil
  728. }
  729. // Close stops listening on the UDP address. Already Accepted connections are not closed.
  730. func (l *Listener) Close() error {
  731. close(l.die)
  732. return l.conn.Close()
  733. }
  734. // closeSession notify the listener that a session has closed
  735. func (l *Listener) closeSession(remote net.Addr) bool {
  736. select {
  737. case l.chSessionClosed <- remote:
  738. return true
  739. case <-l.die:
  740. return false
  741. }
  742. }
  743. // Addr returns the listener's network address, The Addr returned is shared by all invocations of Addr, so do not modify it.
  744. func (l *Listener) Addr() net.Addr { return l.conn.LocalAddr() }
  745. // Listen listens for incoming KCP packets addressed to the local address laddr on the network "udp",
  746. func Listen(laddr string) (net.Listener, error) { return ListenWithOptions(laddr, nil, 0, 0) }
  747. // ListenWithOptions listens for incoming KCP packets addressed to the local address laddr on the network "udp" with packet encryption,
  748. // dataShards, parityShards defines Reed-Solomon Erasure Coding parameters
  749. func ListenWithOptions(laddr string, block BlockCrypt, dataShards, parityShards int) (*Listener, error) {
  750. udpaddr, err := net.ResolveUDPAddr("udp", laddr)
  751. if err != nil {
  752. return nil, errors.Wrap(err, "net.ResolveUDPAddr")
  753. }
  754. conn, err := net.ListenUDP("udp", udpaddr)
  755. if err != nil {
  756. return nil, errors.Wrap(err, "net.ListenUDP")
  757. }
  758. return ServeConn(block, dataShards, parityShards, conn)
  759. }
  760. // ServeConn serves KCP protocol for a single packet connection.
  761. func ServeConn(block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*Listener, error) {
  762. l := new(Listener)
  763. l.conn = conn
  764. l.sessions = make(map[string]*UDPSession)
  765. l.chAccepts = make(chan *UDPSession, acceptBacklog)
  766. l.chSessionClosed = make(chan net.Addr)
  767. l.die = make(chan struct{})
  768. l.dataShards = dataShards
  769. l.parityShards = parityShards
  770. l.block = block
  771. l.fecDecoder = newFECDecoder(rxFECMulti*(dataShards+parityShards), dataShards, parityShards)
  772. // calculate header size
  773. if l.block != nil {
  774. l.headerSize += cryptHeaderSize
  775. }
  776. if l.fecDecoder != nil {
  777. l.headerSize += fecHeaderSizePlus2
  778. }
  779. go l.monitor()
  780. return l, nil
  781. }
  782. // Dial connects to the remote address "raddr" on the network "udp"
  783. func Dial(raddr string) (net.Conn, error) { return DialWithOptions(raddr, nil, 0, 0) }
  784. // DialWithOptions connects to the remote address "raddr" on the network "udp" with packet encryption
  785. func DialWithOptions(raddr string, block BlockCrypt, dataShards, parityShards int) (*UDPSession, error) {
  786. udpaddr, err := net.ResolveUDPAddr("udp", raddr)
  787. if err != nil {
  788. return nil, errors.Wrap(err, "net.ResolveUDPAddr")
  789. }
  790. udpconn, err := net.DialUDP("udp", nil, udpaddr)
  791. if err != nil {
  792. return nil, errors.Wrap(err, "net.DialUDP")
  793. }
  794. return NewConn(raddr, block, dataShards, parityShards, &connectedUDPConn{udpconn})
  795. }
  796. // NewConn establishes a session and talks KCP protocol over a packet connection.
  797. func NewConn(raddr string, block BlockCrypt, dataShards, parityShards int, conn net.PacketConn) (*UDPSession, error) {
  798. udpaddr, err := net.ResolveUDPAddr("udp", raddr)
  799. if err != nil {
  800. return nil, errors.Wrap(err, "net.ResolveUDPAddr")
  801. }
  802. var convid uint32
  803. binary.Read(rand.Reader, binary.LittleEndian, &convid)
  804. return newUDPSession(convid, dataShards, parityShards, nil, conn, udpaddr, block), nil
  805. }
  806. // returns current time in milliseconds
  807. func currentMs() uint32 { return uint32(time.Now().UnixNano() / int64(time.Millisecond)) }
  808. // connectedUDPConn is a wrapper for net.UDPConn which converts WriteTo syscalls
  809. // to Write syscalls that are 4 times faster on some OS'es. This should only be
  810. // used for connections that were produced by a net.Dial* call.
  811. type connectedUDPConn struct{ *net.UDPConn }
  812. // WriteTo redirects all writes to the Write syscall, which is 4 times faster.
  813. func (c *connectedUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) { return c.Write(b) }