UDPConn_bind.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // +build !windows
  2. /*
  3. * Copyright (c) 2018, Psiphon Inc.
  4. * All rights reserved.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. package psiphon
  21. import (
  22. "fmt"
  23. "net"
  24. "os"
  25. "syscall"
  26. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  27. )
  28. func newUDPConn(domain int, config *DialConfig) (net.PacketConn, error) {
  29. // TODO: use https://golang.org/pkg/net/#Dialer.Control, introduced in Go 1.11?
  30. socketFD, err := syscall.Socket(domain, syscall.SOCK_DGRAM, 0)
  31. if err != nil {
  32. return nil, common.ContextError(err)
  33. }
  34. syscall.CloseOnExec(socketFD)
  35. setAdditionalSocketOptions(socketFD)
  36. if config.DeviceBinder != nil {
  37. err := bindToDeviceCallWrapper(config.DeviceBinder, socketFD)
  38. if err != nil {
  39. syscall.Close(socketFD)
  40. return nil, common.ContextError(fmt.Errorf("BindToDevice failed: %s", err))
  41. }
  42. }
  43. // Convert the socket fd to a net.PacketConn
  44. // This code block is from:
  45. // https://github.com/golang/go/issues/6966
  46. file := os.NewFile(uintptr(socketFD), "")
  47. conn, err := net.FilePacketConn(file) // net.FilePackateConn() dups socketFD
  48. file.Close() // file.Close() closes socketFD
  49. if err != nil {
  50. return nil, common.ContextError(err)
  51. }
  52. return conn, nil
  53. }