Files
tailscale/net/dns/wsl_windows.go
Will Norris 3ec5be3f51 all: remove AUTHORS file and references to it
This file was never truly necessary and has never actually been used in
the history of Tailscale's open source releases.

A Brief History of AUTHORS files
---

The AUTHORS file was a pattern developed at Google, originally for
Chromium, then adopted by Go and a bunch of other projects. The problem
was that Chromium originally had a copyright line only recognizing
Google as the copyright holder. Because Google (and most open source
projects) do not require copyright assignemnt for contributions, each
contributor maintains their copyright. Some large corporate contributors
then tried to add their own name to the copyright line in the LICENSE
file or in file headers. This quickly becomes unwieldy, and puts a
tremendous burden on anyone building on top of Chromium, since the
license requires that they keep all copyright lines intact.

The compromise was to create an AUTHORS file that would list all of the
copyright holders. The LICENSE file and source file headers would then
include that list by reference, listing the copyright holder as "The
Chromium Authors".

This also become cumbersome to simply keep the file up to date with a
high rate of new contributors. Plus it's not always obvious who the
copyright holder is. Sometimes it is the individual making the
contribution, but many times it may be their employer. There is no way
for the proejct maintainer to know.

Eventually, Google changed their policy to no longer recommend trying to
keep the AUTHORS file up to date proactively, and instead to only add to
it when requested: https://opensource.google/docs/releasing/authors.
They are also clear that:

> Adding contributors to the AUTHORS file is entirely within the
> project's discretion and has no implications for copyright ownership.

It was primarily added to appease a small number of large contributors
that insisted that they be recognized as copyright holders (which was
entirely their right to do). But it's not truly necessary, and not even
the most accurate way of identifying contributors and/or copyright
holders.

In practice, we've never added anyone to our AUTHORS file. It only lists
Tailscale, so it's not really serving any purpose. It also causes
confusion because Tailscalars put the "Tailscale Inc & AUTHORS" header
in other open source repos which don't actually have an AUTHORS file, so
it's ambiguous what that means.

Instead, we just acknowledge that the contributors to Tailscale (whoever
they are) are copyright holders for their individual contributions. We
also have the benefit of using the DCO (developercertificate.org) which
provides some additional certification of their right to make the
contribution.

The source file changes were purely mechanical with:

    git ls-files | xargs sed -i -e 's/\(Tailscale Inc &\) AUTHORS/\1 contributors/g'

Updates #cleanup

Change-Id: Ia101a4a3005adb9118051b3416f5a64a4a45987d
Signed-off-by: Will Norris <will@tailscale.com>
2026-01-23 15:49:45 -08:00

240 lines
6.1 KiB
Go

// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package dns
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"os/user"
"strings"
"syscall"
"time"
"golang.org/x/sys/windows"
"tailscale.com/health"
"tailscale.com/types/logger"
"tailscale.com/util/winutil"
)
// wslDistros reports the names of the installed WSL2 linux distributions.
func wslDistros() ([]string, error) {
// There is a bug in some builds of wsl.exe that causes it to block
// indefinitely while executing this operation. Set a timeout so that we don't
// get wedged! (Issue #7476)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
b, err := wslCombinedOutput(exec.CommandContext(ctx, "wsl.exe", "-l"))
if err != nil {
return nil, fmt.Errorf("%v: %q", err, string(b))
}
lines := strings.Split(string(b), "\n")
if len(lines) < 1 {
return nil, nil
}
lines = lines[1:] // drop "Windows Subsystem For Linux" header
var distros []string
for _, name := range lines {
name = strings.TrimSpace(name)
name = strings.TrimSuffix(name, " (Default)")
if name == "" {
continue
}
distros = append(distros, name)
}
return distros, nil
}
// wslManager is a DNS manager for WSL2 linux distributions.
// It configures /etc/wsl.conf and /etc/resolv.conf.
type wslManager struct {
logf logger.Logf
health *health.Tracker
}
func newWSLManager(logf logger.Logf, health *health.Tracker) *wslManager {
m := &wslManager{
logf: logf,
health: health,
}
return m
}
func (wm *wslManager) SetDNS(cfg OSConfig) error {
distros, err := wslDistros()
if err != nil {
return err
} else if len(distros) == 0 {
return nil
}
managers := make(map[string]*directManager)
for _, distro := range distros {
managers[distro] = newDirectManagerOnFS(wm.logf, wm.health, nil, wslFS{
user: "root",
distro: distro,
})
}
if !cfg.IsZero() {
if wm.setWSLConf(managers) {
// What's this? So glad you asked.
//
// WSL2 writes the /etc/resolv.conf.
// It is aggressive about it. Every time you execute wsl.exe,
// it writes it. (Opening a terminal is done by running wsl.exe.)
// You can turn this off using /etc/wsl.conf! But: this wsl.conf
// file is only parsed when the VM boots up. To do that, we
// have to shut down WSL2.
//
// So we do it here, before we call wsl.exe to write resolv.conf.
if b, err := wslCombinedOutput(wslCommand("--shutdown")); err != nil {
wm.logf("WSL SetDNS shutdown: %v: %s", err, b)
}
}
}
for distro, m := range managers {
if err := m.SetDNS(cfg); err != nil {
wm.logf("WSL(%q) SetDNS: %v", distro, err)
}
}
return nil
}
const wslConf = "/etc/wsl.conf"
const wslConfSection = `# added by tailscale
[network]
generateResolvConf = false
`
// setWSLConf attempts to disable generateResolvConf in each WSL2 linux.
// If any are changed, it reports true.
func (wm *wslManager) setWSLConf(managers map[string]*directManager) (changed bool) {
for distro, m := range managers {
b, err := m.fs.ReadFile(wslConf)
if err != nil && !os.IsNotExist(err) {
wm.logf("WSL(%q) wsl.conf: read: %v", distro, err)
continue
}
ini := parseIni(string(b))
if v := ini["network"]["generateResolvConf"]; v == "" {
b = append(b, wslConfSection...)
if err := m.fs.WriteFile(wslConf, b, 0644); err != nil {
wm.logf("WSL(%q) wsl.conf: write: %v", distro, err)
continue
}
changed = true
}
}
return changed
}
func (m *wslManager) SupportsSplitDNS() bool { return false }
func (m *wslManager) Close() error { return m.SetDNS(OSConfig{}) }
// wslFS is a pinholeFS implemented on top of wsl.exe.
//
// We access WSL2 file systems via wsl.exe instead of \\wsl$\ because
// the netpath appears to operate as the standard user, not root.
type wslFS struct {
user string
distro string
}
func (fs wslFS) Stat(name string) (isRegular bool, err error) {
err = wslRun(fs.cmd("test", "-f", name))
if ee, _ := err.(*exec.ExitError); ee != nil {
if ee.ExitCode() == 1 {
return false, os.ErrNotExist
}
return false, err
}
return true, nil
}
func (fs wslFS) Chmod(name string, perm os.FileMode) error {
return wslRun(fs.cmd("chmod", "--", fmt.Sprintf("%04o", perm), name))
}
func (fs wslFS) Rename(oldName, newName string) error {
return wslRun(fs.cmd("mv", "--", oldName, newName))
}
func (fs wslFS) Remove(name string) error { return wslRun(fs.cmd("rm", "--", name)) }
func (fs wslFS) Truncate(name string) error { return fs.WriteFile(name, nil, 0644) }
func (fs wslFS) ReadFile(name string) ([]byte, error) {
b, err := wslCombinedOutput(fs.cmd("cat", "--", name))
var ee *exec.ExitError
if errors.As(err, &ee) && ee.ExitCode() == 1 {
return nil, os.ErrNotExist
}
return b, err
}
func (fs wslFS) WriteFile(name string, contents []byte, perm os.FileMode) error {
cmd := fs.cmd("tee", "--", name)
cmd.Stdin = bytes.NewReader(contents)
cmd.Stdout = nil
if err := wslRun(cmd); err != nil {
return err
}
return wslRun(fs.cmd("chmod", "--", fmt.Sprintf("%04o", perm), name))
}
func (fs wslFS) cmd(args ...string) *exec.Cmd {
cmd := wslCommand("-u", fs.user, "-d", fs.distro, "-e")
cmd.Args = append(cmd.Args, args...)
return cmd
}
func wslCommand(args ...string) *exec.Cmd {
cmd := exec.Command("wsl.exe", args...)
return cmd
}
func wslCombinedOutput(cmd *exec.Cmd) ([]byte, error) {
buf := new(bytes.Buffer)
cmd.Stdout = buf
cmd.Stderr = buf
err := wslRun(cmd)
if err != nil {
return nil, err
}
return maybeUnUTF16(buf.Bytes()), nil
}
func wslRun(cmd *exec.Cmd) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("wslRun(%v): %w", cmd.Args, err)
}
}()
var token windows.Token
if u, err := user.Current(); err == nil && u.Name == "SYSTEM" {
// We need to switch user to run wsl.exe.
// https://github.com/microsoft/WSL/issues/4803
sessionID := winutil.WTSGetActiveConsoleSessionId()
if sessionID != 0xFFFFFFFF {
if err := windows.WTSQueryUserToken(sessionID, &token); err != nil {
return err
}
defer token.Close()
}
}
cmd.SysProcAttr = &syscall.SysProcAttr{
CreationFlags: windows.CREATE_NO_WINDOW,
Token: syscall.Token(token),
}
return cmd.Run()
}