udp.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package server
  20. import (
  21. "bytes"
  22. "encoding/binary"
  23. "fmt"
  24. "io"
  25. "net"
  26. "strconv"
  27. "sync"
  28. "sync/atomic"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/monotime"
  33. )
  34. // handleUdpgwChannel implements UDP port forwarding. A single UDP
  35. // SSH channel follows the udpgw protocol, which multiplexes many
  36. // UDP port forwards.
  37. //
  38. // The udpgw protocol and original server implementation:
  39. // Copyright (c) 2009, Ambroz Bizjak <ambrop7@gmail.com>
  40. // https://github.com/ambrop72/badvpn
  41. func (sshClient *sshClient) handleUdpgwChannel(newChannel ssh.NewChannel) {
  42. // Accept this channel immediately. This channel will replace any
  43. // previously existing udpgw channel for this client.
  44. sshChannel, requests, err := newChannel.Accept()
  45. if err != nil {
  46. if !isExpectedTunnelIOError(err) {
  47. log.WithTraceFields(LogFields{"error": err}).Warning("accept new channel failed")
  48. }
  49. return
  50. }
  51. go ssh.DiscardRequests(requests)
  52. defer sshChannel.Close()
  53. multiplexer := &udpgwPortForwardMultiplexer{
  54. sshClient: sshClient,
  55. sshChannel: sshChannel,
  56. portForwards: make(map[uint16]*udpgwPortForward),
  57. portForwardLRU: common.NewLRUConns(),
  58. relayWaitGroup: new(sync.WaitGroup),
  59. runWaitGroup: new(sync.WaitGroup),
  60. }
  61. multiplexer.runWaitGroup.Add(1)
  62. // setUdpgwChannelHandler will close any existing
  63. // udpgwPortForwardMultiplexer, waiting for all run/relayDownstream
  64. // goroutines to first terminate and all UDP socket resources to be
  65. // cleaned up.
  66. //
  67. // This synchronous shutdown also ensures that the
  68. // concurrentPortForwardCount is reduced to 0 before installing the new
  69. // udpgwPortForwardMultiplexer and its LRU object. If the older handler
  70. // were to dangle with open port forwards, and concurrentPortForwardCount
  71. // were to hit the max, the wrong LRU, the new one, would be used to
  72. // close the LRU port forward.
  73. //
  74. // Call setUdpgwHandler only after runWaitGroup is initialized, to ensure
  75. // runWaitGroup.Wait() cannot be invoked (by some subsequent new udpgw
  76. // channel) before initialized.
  77. if !sshClient.setUdpgwChannelHandler(multiplexer) {
  78. // setUdpgwChannelHandler returns false if some other SSH channel
  79. // calls setUdpgwChannelHandler in the middle of this call. In that
  80. // case, discard this channel: the client's latest udpgw channel is
  81. // retained.
  82. return
  83. }
  84. multiplexer.run()
  85. multiplexer.runWaitGroup.Done()
  86. }
  87. type udpgwPortForwardMultiplexer struct {
  88. sshClient *sshClient
  89. sshChannelWriteMutex sync.Mutex
  90. sshChannel ssh.Channel
  91. portForwardsMutex sync.Mutex
  92. portForwards map[uint16]*udpgwPortForward
  93. portForwardLRU *common.LRUConns
  94. relayWaitGroup *sync.WaitGroup
  95. runWaitGroup *sync.WaitGroup
  96. }
  97. func (mux *udpgwPortForwardMultiplexer) stop() {
  98. // udpgwPortForwardMultiplexer must be initialized by handleUdpgwChannel.
  99. //
  100. // stop closes the udpgw SSH channel, which will cause the run goroutine
  101. // to exit its message read loop and await closure of all relayDownstream
  102. // goroutines. Closing all port forward UDP conns will cause all
  103. // relayDownstream to exit.
  104. _ = mux.sshChannel.Close()
  105. mux.portForwardsMutex.Lock()
  106. for _, portForward := range mux.portForwards {
  107. _ = portForward.conn.Close()
  108. }
  109. mux.portForwardsMutex.Unlock()
  110. mux.runWaitGroup.Wait()
  111. }
  112. func (mux *udpgwPortForwardMultiplexer) run() {
  113. // In a loop, read udpgw messages from the client to this channel. Each
  114. // message contains a UDP packet to send upstream either via a new port
  115. // forward, or on an existing port forward.
  116. //
  117. // A goroutine is run to read downstream packets for each UDP port forward. All read
  118. // packets are encapsulated in udpgw protocol and sent down the channel to the client.
  119. //
  120. // When the client disconnects or the server shuts down, the channel will close and
  121. // readUdpgwMessage will exit with EOF.
  122. buffer := make([]byte, udpgwProtocolMaxMessageSize)
  123. for {
  124. // Note: message.packet points to the reusable memory in "buffer".
  125. // Each readUdpgwMessage call will overwrite the last message.packet.
  126. message, err := readUdpgwMessage(mux.sshChannel, buffer)
  127. if err != nil {
  128. if err != io.EOF {
  129. // Debug since I/O errors occur during normal operation
  130. log.WithTraceFields(LogFields{"error": err}).Debug("readUdpgwMessage failed")
  131. }
  132. break
  133. }
  134. mux.portForwardsMutex.Lock()
  135. portForward := mux.portForwards[message.connID]
  136. mux.portForwardsMutex.Unlock()
  137. // In the udpgw protocol, an existing port forward is closed when
  138. // either the discard flag is set or the remote address has changed.
  139. if portForward != nil &&
  140. (message.discardExistingConn ||
  141. !bytes.Equal(portForward.remoteIP, message.remoteIP) ||
  142. portForward.remotePort != message.remotePort) {
  143. // The port forward's goroutine will complete cleanup, including
  144. // tallying stats and calling sshClient.closedPortForward.
  145. // portForward.conn.Close() will signal this shutdown.
  146. portForward.conn.Close()
  147. // Synchronously await the termination of the relayDownstream
  148. // goroutine. This ensures that the previous goroutine won't
  149. // invoke removePortForward, with the connID that will be reused
  150. // for the new port forward, after this point.
  151. //
  152. // Limitation: this synchronous shutdown cannot prevent a "wrong
  153. // remote address" error on the badvpn udpgw client, which occurs
  154. // when the client recycles a port forward (setting discard) but
  155. // receives, from the server, a udpgw message containing the old
  156. // remote address for the previous port forward with the same
  157. // conn ID. That downstream message from the server may be in
  158. // flight in the SSH channel when the client discard message arrives.
  159. portForward.relayWaitGroup.Wait()
  160. portForward = nil
  161. }
  162. if portForward == nil {
  163. // Create a new port forward
  164. dialIP := net.IP(message.remoteIP)
  165. dialPort := int(message.remotePort)
  166. // Validate DNS packets and check the domain blocklist both when the client
  167. // indicates DNS or when DNS is _not_ indicated and the destination port is
  168. // 53.
  169. if message.forwardDNS || message.remotePort == 53 {
  170. domain, err := common.ParseDNSQuestion(message.packet)
  171. if err != nil {
  172. log.WithTraceFields(LogFields{"error": err}).Debug("ParseDNSQuestion failed")
  173. // Drop packet
  174. continue
  175. }
  176. if domain != "" {
  177. ok, _ := mux.sshClient.isDomainPermitted(domain)
  178. if !ok {
  179. // Drop packet
  180. continue
  181. }
  182. }
  183. }
  184. if message.forwardDNS {
  185. // Transparent DNS forwarding. In this case, isPortForwardPermitted
  186. // traffic rules checks are bypassed, since DNS is essential.
  187. dialIP = mux.sshClient.sshServer.support.DNSResolver.Get()
  188. dialPort = DNS_RESOLVER_PORT
  189. } else if !mux.sshClient.isPortForwardPermitted(
  190. portForwardTypeUDP, dialIP, int(message.remotePort)) {
  191. // The udpgw protocol has no error response, so
  192. // we just discard the message and read another.
  193. continue
  194. }
  195. // Note: UDP port forward counting has no dialing phase
  196. // establishedPortForward increments the concurrent UDP port
  197. // forward counter and closes the LRU existing UDP port forward
  198. // when already at the limit.
  199. mux.sshClient.establishedPortForward(portForwardTypeUDP, mux.portForwardLRU)
  200. // Can't defer sshClient.closedPortForward() here;
  201. // relayDownstream will call sshClient.closedPortForward()
  202. // Pre-check log level to avoid overhead of rendering log for
  203. // every DNS query and other UDP port forward.
  204. if IsLogLevelDebug() {
  205. log.WithTraceFields(
  206. LogFields{
  207. "remoteAddr": net.JoinHostPort(dialIP.String(), strconv.Itoa(dialPort)),
  208. "connID": message.connID}).Debug("dialing")
  209. }
  210. udpConn, err := net.DialUDP(
  211. "udp", nil, &net.UDPAddr{IP: dialIP, Port: dialPort})
  212. if err != nil {
  213. mux.sshClient.closedPortForward(portForwardTypeUDP, 0, 0)
  214. // Monitor for low resource error conditions
  215. mux.sshClient.sshServer.monitorPortForwardDialError(err)
  216. // Note: Debug level, as logMessage may contain user traffic destination address information
  217. log.WithTraceFields(LogFields{"error": err}).Debug("DialUDP failed")
  218. continue
  219. }
  220. lruEntry := mux.portForwardLRU.Add(udpConn)
  221. // Can't defer lruEntry.Remove() here;
  222. // relayDownstream will call lruEntry.Remove()
  223. // ActivityMonitoredConn monitors the UDP port forward I/O and updates
  224. // its LRU status. ActivityMonitoredConn also times out I/O on the port
  225. // forward if both reads and writes have been idle for the specified
  226. // duration.
  227. var activityUpdaters []common.ActivityUpdater
  228. // Don't incur activity monitor overhead for DNS requests
  229. if !message.forwardDNS {
  230. activityUpdaters = mux.sshClient.getActivityUpdaters(portForwardTypeUDP, dialIP)
  231. }
  232. conn, err := common.NewActivityMonitoredConn(
  233. udpConn,
  234. mux.sshClient.idleUDPPortForwardTimeout(),
  235. true,
  236. lruEntry,
  237. activityUpdaters...)
  238. if err != nil {
  239. lruEntry.Remove()
  240. mux.sshClient.closedPortForward(portForwardTypeUDP, 0, 0)
  241. log.WithTraceFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  242. continue
  243. }
  244. portForward = &udpgwPortForward{
  245. connID: message.connID,
  246. preambleSize: message.preambleSize,
  247. remoteIP: message.remoteIP,
  248. remotePort: message.remotePort,
  249. dialIP: dialIP,
  250. conn: conn,
  251. lruEntry: lruEntry,
  252. bytesUp: 0,
  253. bytesDown: 0,
  254. relayWaitGroup: new(sync.WaitGroup),
  255. mux: mux,
  256. }
  257. if message.forwardDNS {
  258. portForward.dnsFirstWriteTime = int64(monotime.Now())
  259. }
  260. mux.portForwardsMutex.Lock()
  261. mux.portForwards[portForward.connID] = portForward
  262. mux.portForwardsMutex.Unlock()
  263. portForward.relayWaitGroup.Add(1)
  264. mux.relayWaitGroup.Add(1)
  265. go portForward.relayDownstream()
  266. }
  267. // Note: assumes UDP writes won't block (https://golang.org/pkg/net/#UDPConn.WriteToUDP)
  268. _, err = portForward.conn.Write(message.packet)
  269. if err != nil {
  270. // Debug since errors such as "write: operation not permitted" occur during normal operation
  271. log.WithTraceFields(LogFields{"error": err}).Debug("upstream UDP relay failed")
  272. // The port forward's goroutine will complete cleanup
  273. portForward.conn.Close()
  274. }
  275. portForward.lruEntry.Touch()
  276. atomic.AddInt64(&portForward.bytesUp, int64(len(message.packet)))
  277. }
  278. // Cleanup all udpgw port forward workers when exiting
  279. mux.portForwardsMutex.Lock()
  280. for _, portForward := range mux.portForwards {
  281. // The port forward's goroutine will complete cleanup
  282. portForward.conn.Close()
  283. }
  284. mux.portForwardsMutex.Unlock()
  285. mux.relayWaitGroup.Wait()
  286. }
  287. func (mux *udpgwPortForwardMultiplexer) removePortForward(connID uint16) {
  288. mux.portForwardsMutex.Lock()
  289. delete(mux.portForwards, connID)
  290. mux.portForwardsMutex.Unlock()
  291. }
  292. type udpgwPortForward struct {
  293. // Note: 64-bit ints used with atomic operations are placed
  294. // at the start of struct to ensure 64-bit alignment.
  295. // (https://golang.org/pkg/sync/atomic/#pkg-note-BUG)
  296. dnsFirstWriteTime int64
  297. dnsFirstReadTime int64
  298. bytesUp int64
  299. bytesDown int64
  300. connID uint16
  301. preambleSize int
  302. remoteIP []byte
  303. remotePort uint16
  304. dialIP net.IP
  305. conn net.Conn
  306. lruEntry *common.LRUConnsEntry
  307. relayWaitGroup *sync.WaitGroup
  308. mux *udpgwPortForwardMultiplexer
  309. }
  310. var udpgwBufferPool = &sync.Pool{
  311. New: func() any {
  312. return make([]byte, udpgwProtocolMaxMessageSize)
  313. },
  314. }
  315. func (portForward *udpgwPortForward) relayDownstream() {
  316. defer portForward.relayWaitGroup.Done()
  317. defer portForward.mux.relayWaitGroup.Done()
  318. // Downstream UDP packets are read into the reusable memory
  319. // in "buffer" starting at the offset past the udpgw message
  320. // header and address, leaving enough space to write the udpgw
  321. // values into the same buffer and use for writing to the ssh
  322. // channel.
  323. //
  324. // Note: there is one downstream buffer per UDP port forward,
  325. // while for upstream there is one buffer per client.
  326. // TODO: is the buffer size larger than necessary?
  327. // Use a buffer pool to minimize GC churn resulting from frequent,
  328. // short-lived UDP flows, including DNS requests.
  329. buffer := udpgwBufferPool.Get().([]byte)
  330. clear(buffer)
  331. defer udpgwBufferPool.Put(buffer)
  332. packetBuffer := buffer[portForward.preambleSize:udpgwProtocolMaxMessageSize]
  333. for {
  334. // TODO: if read buffer is too small, excess bytes are discarded?
  335. packetSize, err := portForward.conn.Read(packetBuffer)
  336. if packetSize > udpgwProtocolMaxPayloadSize {
  337. err = fmt.Errorf("unexpected packet size: %d", packetSize)
  338. }
  339. if err != nil {
  340. if err != io.EOF {
  341. // Debug since errors such as "use of closed network connection" occur during normal operation
  342. if IsLogLevelDebug() {
  343. log.WithTraceFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  344. }
  345. }
  346. break
  347. }
  348. if atomic.LoadInt64(&portForward.dnsFirstWriteTime) > 0 &&
  349. atomic.LoadInt64(&portForward.dnsFirstReadTime) == 0 { // Check if already set before invoking Now.
  350. atomic.CompareAndSwapInt64(&portForward.dnsFirstReadTime, 0, int64(monotime.Now()))
  351. }
  352. err = writeUdpgwPreamble(
  353. portForward.preambleSize,
  354. 0,
  355. portForward.connID,
  356. portForward.remoteIP,
  357. portForward.remotePort,
  358. uint16(packetSize),
  359. buffer)
  360. if err == nil {
  361. // ssh.Channel.Write cannot be called concurrently.
  362. // See: https://github.com/Psiphon-Inc/crypto/blob/82d98b4c7c05e81f92545f6fddb45d4541e6da00/ssh/channel.go#L272,
  363. // https://codereview.appspot.com/136420043/diff/80002/ssh/channel.go
  364. portForward.mux.sshChannelWriteMutex.Lock()
  365. _, err = portForward.mux.sshChannel.Write(buffer[0 : portForward.preambleSize+packetSize])
  366. portForward.mux.sshChannelWriteMutex.Unlock()
  367. }
  368. if err != nil {
  369. // Close the channel, which will interrupt the main loop.
  370. portForward.mux.sshChannel.Close()
  371. log.WithTraceFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  372. break
  373. }
  374. portForward.lruEntry.Touch()
  375. atomic.AddInt64(&portForward.bytesDown, int64(packetSize))
  376. }
  377. portForward.mux.removePortForward(portForward.connID)
  378. portForward.lruEntry.Remove()
  379. portForward.conn.Close()
  380. bytesUp := atomic.LoadInt64(&portForward.bytesUp)
  381. bytesDown := atomic.LoadInt64(&portForward.bytesDown)
  382. portForward.mux.sshClient.closedPortForward(portForwardTypeUDP, bytesUp, bytesDown)
  383. dnsStartTime := monotime.Time(atomic.LoadInt64(&portForward.dnsFirstWriteTime))
  384. if dnsStartTime > 0 {
  385. // Record DNS metrics using a heuristic: if a UDP packet was written and
  386. // then a packet was read, assume the DNS request successfully received a
  387. // valid response; failure occurs when the resolver fails to provide a
  388. // response; a "no such host" response is still a success. Limitations: we
  389. // assume a resolver will not respond when, e.g., rate limiting; we ignore
  390. // subsequent requests made via the same UDP port forward.
  391. dnsEndTime := monotime.Time(atomic.LoadInt64(&portForward.dnsFirstReadTime))
  392. dnsSuccess := true
  393. if dnsEndTime == 0 {
  394. dnsSuccess = false
  395. dnsEndTime = monotime.Now()
  396. }
  397. resolveElapsedTime := dnsEndTime.Sub(dnsStartTime)
  398. portForward.mux.sshClient.updateQualityMetricsWithDNSResult(
  399. dnsSuccess,
  400. resolveElapsedTime,
  401. net.IP(portForward.dialIP))
  402. }
  403. log.WithTraceFields(
  404. LogFields{
  405. "remoteAddr": net.JoinHostPort(
  406. net.IP(portForward.remoteIP).String(), strconv.Itoa(int(portForward.remotePort))),
  407. "bytesUp": bytesUp,
  408. "bytesDown": bytesDown,
  409. "connID": portForward.connID}).Debug("exiting")
  410. }
  411. // TODO: express and/or calculate udpgwProtocolMaxPayloadSize as function of MTU?
  412. const (
  413. udpgwProtocolFlagKeepalive = 1 << 0
  414. udpgwProtocolFlagRebind = 1 << 1
  415. udpgwProtocolFlagDNS = 1 << 2
  416. udpgwProtocolFlagIPv6 = 1 << 3
  417. udpgwProtocolMaxPreambleSize = 23
  418. udpgwProtocolMaxPayloadSize = 32768
  419. udpgwProtocolMaxMessageSize = udpgwProtocolMaxPreambleSize + udpgwProtocolMaxPayloadSize
  420. )
  421. type udpgwProtocolMessage struct {
  422. connID uint16
  423. preambleSize int
  424. remoteIP []byte
  425. remotePort uint16
  426. discardExistingConn bool
  427. forwardDNS bool
  428. packet []byte
  429. }
  430. func readUdpgwMessage(
  431. reader io.Reader, buffer []byte) (*udpgwProtocolMessage, error) {
  432. // udpgw message layout:
  433. //
  434. // | 2 byte size | 3 byte header | 6 or 18 byte address | variable length packet |
  435. for {
  436. // Read message
  437. _, err := io.ReadFull(reader, buffer[0:2])
  438. if err != nil {
  439. if err != io.EOF {
  440. err = errors.Trace(err)
  441. }
  442. return nil, err
  443. }
  444. size := binary.LittleEndian.Uint16(buffer[0:2])
  445. if size < 3 || int(size) > len(buffer)-2 {
  446. return nil, errors.TraceNew("invalid udpgw message size")
  447. }
  448. _, err = io.ReadFull(reader, buffer[2:2+size])
  449. if err != nil {
  450. if err != io.EOF {
  451. err = errors.Trace(err)
  452. }
  453. return nil, err
  454. }
  455. flags := buffer[2]
  456. connID := binary.LittleEndian.Uint16(buffer[3:5])
  457. // Ignore udpgw keep-alive messages -- read another message
  458. if flags&udpgwProtocolFlagKeepalive == udpgwProtocolFlagKeepalive {
  459. continue
  460. }
  461. // Read address
  462. var remoteIP []byte
  463. var remotePort uint16
  464. var packetStart, packetEnd int
  465. if flags&udpgwProtocolFlagIPv6 == udpgwProtocolFlagIPv6 {
  466. if size < 21 {
  467. return nil, errors.TraceNew("invalid udpgw message size")
  468. }
  469. remoteIP = make([]byte, 16)
  470. copy(remoteIP, buffer[5:21])
  471. remotePort = binary.BigEndian.Uint16(buffer[21:23])
  472. packetStart = 23
  473. packetEnd = 23 + int(size) - 21
  474. } else {
  475. if size < 9 {
  476. return nil, errors.TraceNew("invalid udpgw message size")
  477. }
  478. remoteIP = make([]byte, 4)
  479. copy(remoteIP, buffer[5:9])
  480. remotePort = binary.BigEndian.Uint16(buffer[9:11])
  481. packetStart = 11
  482. packetEnd = 11 + int(size) - 9
  483. }
  484. // Assemble message
  485. // Note: udpgwProtocolMessage.packet references memory in the input buffer
  486. message := &udpgwProtocolMessage{
  487. connID: connID,
  488. preambleSize: packetStart,
  489. remoteIP: remoteIP,
  490. remotePort: remotePort,
  491. discardExistingConn: flags&udpgwProtocolFlagRebind == udpgwProtocolFlagRebind,
  492. forwardDNS: flags&udpgwProtocolFlagDNS == udpgwProtocolFlagDNS,
  493. packet: buffer[packetStart:packetEnd],
  494. }
  495. return message, nil
  496. }
  497. }
  498. func writeUdpgwPreamble(
  499. preambleSize int,
  500. flags uint8,
  501. connID uint16,
  502. remoteIP []byte,
  503. remotePort uint16,
  504. packetSize uint16,
  505. buffer []byte) error {
  506. if preambleSize != 7+len(remoteIP) {
  507. return errors.TraceNew("invalid udpgw preamble size")
  508. }
  509. size := uint16(preambleSize-2) + packetSize
  510. // size
  511. binary.LittleEndian.PutUint16(buffer[0:2], size)
  512. // flags
  513. buffer[2] = flags
  514. // connID
  515. binary.LittleEndian.PutUint16(buffer[3:5], connID)
  516. // addr
  517. copy(buffer[5:5+len(remoteIP)], remoteIP)
  518. binary.BigEndian.PutUint16(buffer[5+len(remoteIP):7+len(remoteIP)], remotePort)
  519. return nil
  520. }