github.com/Psiphon-Labs/psiphon-tunnel-core@v2.0.28+incompatible/psiphon/common/networkConfig.go (about)

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