networkConfig.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (c) 2020, 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 common
  20. import (
  21. "fmt"
  22. "os/exec"
  23. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  24. )
  25. // RunNetworkConfigCommand execs a network config command, such as "ifconfig"
  26. // or "iptables". On platforms that support capabilities, the network config
  27. // capabilities of the current process is made available to the command
  28. // subprocess. Alternatively, "sudo" will be used when useSudo is true.
  29. func RunNetworkConfigCommand(
  30. logger Logger,
  31. useSudo bool,
  32. commandName string, commandArgs ...string) error {
  33. // configureSubprocessCapabilities will set inheritable
  34. // capabilities on platforms which support that (Linux).
  35. // Specifically, CAP_NET_ADMIN will be transferred from
  36. // this process to the child command.
  37. err := configureNetworkConfigSubprocessCapabilities()
  38. if err != nil {
  39. return errors.Trace(err)
  40. }
  41. // TODO: use CommandContext to interrupt on process shutdown?
  42. // (the commands currently being issued shouldn't block...)
  43. if useSudo {
  44. commandArgs = append([]string{commandName}, commandArgs...)
  45. commandName = "sudo"
  46. }
  47. cmd := exec.Command(commandName, commandArgs...)
  48. output, err := cmd.CombinedOutput()
  49. logger.WithTraceFields(LogFields{
  50. "command": commandName,
  51. "args": commandArgs,
  52. "output": string(output),
  53. "error": err,
  54. }).Debug("exec")
  55. if err != nil {
  56. err := fmt.Errorf(
  57. "command %s %+v failed with %s", commandName, commandArgs, string(output))
  58. return errors.Trace(err)
  59. }
  60. return nil
  61. }