|
| 1 | +package child |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io/ioutil" |
| 6 | + "os" |
| 7 | + "path/filepath" |
| 8 | + |
| 9 | + "github.com/pkg/errors" |
| 10 | + |
| 11 | + "github.com/rootless-containers/rootlesskit/pkg/common" |
| 12 | +) |
| 13 | + |
| 14 | +// generateEtcHosts makes sure the current hostname is resolved into |
| 15 | +// 127.0.0.1 or ::1, not into the host eth0 IP address. |
| 16 | +// |
| 17 | +// Note that /etc/hosts is not used by nslookup/dig. (Use `getent ahostsv4` instead.) |
| 18 | +func generateEtcHosts() ([]byte, error) { |
| 19 | + etcHosts, err := ioutil.ReadFile("/etc/hosts") |
| 20 | + if err != nil { |
| 21 | + return nil, err |
| 22 | + } |
| 23 | + hostname, err := os.Hostname() |
| 24 | + if err != nil { |
| 25 | + return nil, err |
| 26 | + } |
| 27 | + // FIXME: no need to add the entry if already added |
| 28 | + s := fmt.Sprintf("%s\n127.0.0.1 %s\n::1 %s\n", |
| 29 | + string(etcHosts), hostname, hostname) |
| 30 | + return []byte(s), nil |
| 31 | +} |
| 32 | + |
| 33 | +// writeEtcHosts is akin to writeResolvConf |
| 34 | +// TODO: dedupe |
| 35 | +func writeEtcHosts() error { |
| 36 | + newEtcHosts, err := generateEtcHosts() |
| 37 | + if err != nil { |
| 38 | + return err |
| 39 | + } |
| 40 | + // remove copied-up link |
| 41 | + _ = os.Remove("/etc/hosts") |
| 42 | + if err := ioutil.WriteFile("/etc/hosts", newEtcHosts, 0644); err != nil { |
| 43 | + return errors.Wrapf(err, "writing /etc/hosts") |
| 44 | + } |
| 45 | + return nil |
| 46 | +} |
| 47 | + |
| 48 | +// mountEtcHosts is akin to mountResolvConf |
| 49 | +// TODO: dedupe |
| 50 | +func mountEtcHosts(tempDir string) error { |
| 51 | + newEtcHosts, err := generateEtcHosts() |
| 52 | + if err != nil { |
| 53 | + return err |
| 54 | + } |
| 55 | + myEtcHosts := filepath.Join(tempDir, "hosts") |
| 56 | + if err := ioutil.WriteFile(myEtcHosts, newEtcHosts, 0644); err != nil { |
| 57 | + return errors.Wrapf(err, "writing %s", myEtcHosts) |
| 58 | + } |
| 59 | + cmds := [][]string{ |
| 60 | + {"mount", "--bind", myEtcHosts, "/etc/hosts"}, |
| 61 | + } |
| 62 | + if err := common.Execs(os.Stderr, os.Environ(), cmds); err != nil { |
| 63 | + return errors.Wrapf(err, "executing %v", cmds) |
| 64 | + } |
| 65 | + return nil |
| 66 | +} |
0 commit comments