udp.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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.getPortForwardActivityUpdaters(
  231. portForwardTypeUDP, dialIP)
  232. }
  233. conn, err := common.NewActivityMonitoredConn(
  234. udpConn,
  235. mux.sshClient.idleUDPPortForwardTimeout(),
  236. true,
  237. lruEntry,
  238. activityUpdaters...)
  239. if err != nil {
  240. lruEntry.Remove()
  241. mux.sshClient.closedPortForward(portForwardTypeUDP, 0, 0)
  242. log.WithTraceFields(LogFields{"error": err}).Error("NewActivityMonitoredConn failed")
  243. continue
  244. }
  245. portForward = &udpgwPortForward{
  246. connID: message.connID,
  247. preambleSize: message.preambleSize,
  248. remoteIP: message.remoteIP,
  249. remotePort: message.remotePort,
  250. dialIP: dialIP,
  251. conn: conn,
  252. lruEntry: lruEntry,
  253. relayWaitGroup: new(sync.WaitGroup),
  254. mux: mux,
  255. }
  256. if message.forwardDNS {
  257. portForward.dnsFirstWriteTime.Store(int64(monotime.Now()))
  258. }
  259. mux.portForwardsMutex.Lock()
  260. mux.portForwards[portForward.connID] = portForward
  261. mux.portForwardsMutex.Unlock()
  262. portForward.relayWaitGroup.Add(1)
  263. mux.relayWaitGroup.Add(1)
  264. go portForward.relayDownstream()
  265. }
  266. // Note: assumes UDP writes won't block (https://golang.org/pkg/net/#UDPConn.WriteToUDP)
  267. _, err = portForward.conn.Write(message.packet)
  268. if err != nil {
  269. // Debug since errors such as "write: operation not permitted" occur during normal operation
  270. log.WithTraceFields(LogFields{"error": err}).Debug("upstream UDP relay failed")
  271. // The port forward's goroutine will complete cleanup
  272. portForward.conn.Close()
  273. }
  274. portForward.lruEntry.Touch()
  275. portForward.bytesUp.Add(int64(len(message.packet)))
  276. }
  277. // Cleanup all udpgw port forward workers when exiting
  278. mux.portForwardsMutex.Lock()
  279. for _, portForward := range mux.portForwards {
  280. // The port forward's goroutine will complete cleanup
  281. portForward.conn.Close()
  282. }
  283. mux.portForwardsMutex.Unlock()
  284. mux.relayWaitGroup.Wait()
  285. }
  286. func (mux *udpgwPortForwardMultiplexer) removePortForward(connID uint16) {
  287. mux.portForwardsMutex.Lock()
  288. delete(mux.portForwards, connID)
  289. mux.portForwardsMutex.Unlock()
  290. }
  291. type udpgwPortForward struct {
  292. dnsFirstWriteTime atomic.Int64
  293. dnsFirstReadTime atomic.Int64
  294. bytesUp atomic.Int64
  295. bytesDown atomic.Int64
  296. connID uint16
  297. preambleSize int
  298. remoteIP []byte
  299. remotePort uint16
  300. dialIP net.IP
  301. conn net.Conn
  302. lruEntry *common.LRUConnsEntry
  303. relayWaitGroup *sync.WaitGroup
  304. mux *udpgwPortForwardMultiplexer
  305. }
  306. var udpgwBufferPool = &sync.Pool{
  307. New: func() any {
  308. b := make([]byte, udpgwProtocolMaxMessageSize)
  309. return &b
  310. },
  311. }
  312. func (portForward *udpgwPortForward) relayDownstream() {
  313. defer portForward.relayWaitGroup.Done()
  314. defer portForward.mux.relayWaitGroup.Done()
  315. // Downstream UDP packets are read into the reusable memory
  316. // in "buffer" starting at the offset past the udpgw message
  317. // header and address, leaving enough space to write the udpgw
  318. // values into the same buffer and use for writing to the ssh
  319. // channel.
  320. //
  321. // Note: there is one downstream buffer per UDP port forward,
  322. // while for upstream there is one buffer per client.
  323. // TODO: is the buffer size larger than necessary?
  324. // Use a buffer pool to minimize GC churn resulting from frequent,
  325. // short-lived UDP flows, including DNS requests. A pointer to a slice is
  326. // used with sync.Pool to avoid an allocation on Put, as would happen if
  327. // passing in a slice instead of a pointer; see
  328. // https://github.com/dominikh/go-tools/issues/1042#issuecomment-869064445
  329. // and
  330. // https://github.com/dominikh/go-tools/issues/1336#issuecomment-1331206290
  331. // (which should not apply here).
  332. b := udpgwBufferPool.Get().(*[]byte)
  333. buffer := *b
  334. clear(buffer)
  335. defer udpgwBufferPool.Put(b)
  336. packetBuffer := buffer[portForward.preambleSize:udpgwProtocolMaxMessageSize]
  337. for {
  338. // TODO: if read buffer is too small, excess bytes are discarded?
  339. packetSize, err := portForward.conn.Read(packetBuffer)
  340. if packetSize > udpgwProtocolMaxPayloadSize {
  341. err = fmt.Errorf("unexpected packet size: %d", packetSize)
  342. }
  343. if err != nil {
  344. if err != io.EOF {
  345. // Debug since errors such as "use of closed network connection" occur during normal operation
  346. if IsLogLevelDebug() {
  347. log.WithTraceFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  348. }
  349. }
  350. break
  351. }
  352. if portForward.dnsFirstWriteTime.Load() > 0 &&
  353. portForward.dnsFirstReadTime.Load() == 0 { // Check if already set before invoking Now.
  354. portForward.dnsFirstReadTime.CompareAndSwap(0, int64(monotime.Now()))
  355. }
  356. err = writeUdpgwPreamble(
  357. portForward.preambleSize,
  358. 0,
  359. portForward.connID,
  360. portForward.remoteIP,
  361. portForward.remotePort,
  362. uint16(packetSize),
  363. buffer)
  364. if err == nil {
  365. // ssh.Channel.Write cannot be called concurrently.
  366. // See: https://github.com/Psiphon-Inc/crypto/blob/82d98b4c7c05e81f92545f6fddb45d4541e6da00/ssh/channel.go#L272,
  367. // https://codereview.appspot.com/136420043/diff/80002/ssh/channel.go
  368. portForward.mux.sshChannelWriteMutex.Lock()
  369. _, err = portForward.mux.sshChannel.Write(buffer[0 : portForward.preambleSize+packetSize])
  370. portForward.mux.sshChannelWriteMutex.Unlock()
  371. }
  372. if err != nil {
  373. // Close the channel, which will interrupt the main loop.
  374. portForward.mux.sshChannel.Close()
  375. log.WithTraceFields(LogFields{"error": err}).Debug("downstream UDP relay failed")
  376. break
  377. }
  378. portForward.lruEntry.Touch()
  379. portForward.bytesDown.Add(int64(packetSize))
  380. }
  381. portForward.mux.removePortForward(portForward.connID)
  382. portForward.lruEntry.Remove()
  383. portForward.conn.Close()
  384. bytesUp := portForward.bytesUp.Load()
  385. bytesDown := portForward.bytesDown.Load()
  386. portForward.mux.sshClient.closedPortForward(portForwardTypeUDP, bytesUp, bytesDown)
  387. dnsStartTime := monotime.Time(portForward.dnsFirstWriteTime.Load())
  388. if dnsStartTime > 0 {
  389. // Record DNS metrics using a heuristic: if a UDP packet was written and
  390. // then a packet was read, assume the DNS request successfully received a
  391. // valid response; failure occurs when the resolver fails to provide a
  392. // response; a "no such host" response is still a success. Limitations: we
  393. // assume a resolver will not respond when, e.g., rate limiting; we ignore
  394. // subsequent requests made via the same UDP port forward.
  395. dnsEndTime := monotime.Time(portForward.dnsFirstReadTime.Load())
  396. dnsSuccess := true
  397. if dnsEndTime == 0 {
  398. dnsSuccess = false
  399. dnsEndTime = monotime.Now()
  400. }
  401. resolveElapsedTime := dnsEndTime.Sub(dnsStartTime)
  402. portForward.mux.sshClient.updateQualityMetricsWithDNSResult(
  403. dnsSuccess,
  404. resolveElapsedTime,
  405. net.IP(portForward.dialIP))
  406. }
  407. log.WithTraceFields(
  408. LogFields{
  409. "remoteAddr": net.JoinHostPort(
  410. net.IP(portForward.remoteIP).String(), strconv.Itoa(int(portForward.remotePort))),
  411. "bytesUp": bytesUp,
  412. "bytesDown": bytesDown,
  413. "connID": portForward.connID}).Debug("exiting")
  414. }
  415. // TODO: express and/or calculate udpgwProtocolMaxPayloadSize as function of MTU?
  416. const (
  417. udpgwProtocolFlagKeepalive = 1 << 0
  418. udpgwProtocolFlagRebind = 1 << 1
  419. udpgwProtocolFlagDNS = 1 << 2
  420. udpgwProtocolFlagIPv6 = 1 << 3
  421. udpgwProtocolMaxPreambleSize = 23
  422. udpgwProtocolMaxPayloadSize = 32768
  423. udpgwProtocolMaxMessageSize = udpgwProtocolMaxPreambleSize + udpgwProtocolMaxPayloadSize
  424. )
  425. type udpgwProtocolMessage struct {
  426. connID uint16
  427. preambleSize int
  428. remoteIP []byte
  429. remotePort uint16
  430. discardExistingConn bool
  431. forwardDNS bool
  432. packet []byte
  433. }
  434. func readUdpgwMessage(
  435. reader io.Reader, buffer []byte) (*udpgwProtocolMessage, error) {
  436. // udpgw message layout:
  437. //
  438. // | 2 byte size | 3 byte header | 6 or 18 byte address | variable length packet |
  439. for {
  440. // Read message
  441. _, err := io.ReadFull(reader, buffer[0:2])
  442. if err != nil {
  443. if err != io.EOF {
  444. err = errors.Trace(err)
  445. }
  446. return nil, err
  447. }
  448. size := binary.LittleEndian.Uint16(buffer[0:2])
  449. if size < 3 || int(size) > len(buffer)-2 {
  450. return nil, errors.TraceNew("invalid udpgw message size")
  451. }
  452. _, err = io.ReadFull(reader, buffer[2:2+size])
  453. if err != nil {
  454. if err != io.EOF {
  455. err = errors.Trace(err)
  456. }
  457. return nil, err
  458. }
  459. flags := buffer[2]
  460. connID := binary.LittleEndian.Uint16(buffer[3:5])
  461. // Ignore udpgw keep-alive messages -- read another message
  462. if flags&udpgwProtocolFlagKeepalive == udpgwProtocolFlagKeepalive {
  463. continue
  464. }
  465. // Read address
  466. var remoteIP []byte
  467. var remotePort uint16
  468. var packetStart, packetEnd int
  469. if flags&udpgwProtocolFlagIPv6 == udpgwProtocolFlagIPv6 {
  470. if size < 21 {
  471. return nil, errors.TraceNew("invalid udpgw message size")
  472. }
  473. remoteIP = make([]byte, 16)
  474. copy(remoteIP, buffer[5:21])
  475. remotePort = binary.BigEndian.Uint16(buffer[21:23])
  476. packetStart = 23
  477. packetEnd = 23 + int(size) - 21
  478. } else {
  479. if size < 9 {
  480. return nil, errors.TraceNew("invalid udpgw message size")
  481. }
  482. remoteIP = make([]byte, 4)
  483. copy(remoteIP, buffer[5:9])
  484. remotePort = binary.BigEndian.Uint16(buffer[9:11])
  485. packetStart = 11
  486. packetEnd = 11 + int(size) - 9
  487. }
  488. // Assemble message
  489. // Note: udpgwProtocolMessage.packet references memory in the input buffer
  490. message := &udpgwProtocolMessage{
  491. connID: connID,
  492. preambleSize: packetStart,
  493. remoteIP: remoteIP,
  494. remotePort: remotePort,
  495. discardExistingConn: flags&udpgwProtocolFlagRebind == udpgwProtocolFlagRebind,
  496. forwardDNS: flags&udpgwProtocolFlagDNS == udpgwProtocolFlagDNS,
  497. packet: buffer[packetStart:packetEnd],
  498. }
  499. return message, nil
  500. }
  501. }
  502. func writeUdpgwPreamble(
  503. preambleSize int,
  504. flags uint8,
  505. connID uint16,
  506. remoteIP []byte,
  507. remotePort uint16,
  508. packetSize uint16,
  509. buffer []byte) error {
  510. if preambleSize != 7+len(remoteIP) {
  511. return errors.TraceNew("invalid udpgw preamble size")
  512. }
  513. size := uint16(preambleSize-2) + packetSize
  514. // size
  515. binary.LittleEndian.PutUint16(buffer[0:2], size)
  516. // flags
  517. buffer[2] = flags
  518. // connID
  519. binary.LittleEndian.PutUint16(buffer[3:5], connID)
  520. // addr
  521. copy(buffer[5:5+len(remoteIP)], remoteIP)
  522. binary.BigEndian.PutUint16(buffer[5+len(remoteIP):7+len(remoteIP)], remotePort)
  523. return nil
  524. }