tun_unix.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //go:build darwin || linux
  2. // +build darwin linux
  3. /*
  4. * Copyright (c) 2021, Psiphon Inc.
  5. * All rights reserved.
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. package tun
  22. import (
  23. "os"
  24. "syscall"
  25. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  26. "golang.org/x/sys/unix"
  27. )
  28. // fileFromFD duplicates the file descriptor; sets O_CLOEXEC to avoid leaking
  29. // to child processes; sets the mode to nonblocking; and creates a os.File
  30. // using os.NewFile.
  31. func fileFromFD(fd int, name string) (*os.File, error) {
  32. // Prevent fork between duplicating fd and setting CLOEXEC
  33. syscall.ForkLock.RLock()
  34. defer syscall.ForkLock.RUnlock()
  35. dupfd, err := unix.Dup(fd)
  36. if err != nil {
  37. return nil, errors.Trace(err)
  38. }
  39. // Set CLOEXEC so file descriptor not leaked to network config command
  40. // subprocesses.
  41. unix.CloseOnExec(dupfd)
  42. err = unix.SetNonblock(dupfd, true)
  43. if err != nil {
  44. unix.Close(dupfd)
  45. return nil, errors.Trace(err)
  46. }
  47. return os.NewFile(uintptr(dupfd), name), nil
  48. }