udp.go 20 KB

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