Compare commits

...

23 Commits

Author SHA1 Message Date
Brad Fitzpatrick
5b781a70e8 wgengine/magicsock: fix typo in comment
Change-Id: I53fdc085ecb2c9123b21429b3d2ae80a06f22df2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2025-03-24 13:42:11 -07:00
Brad Fitzpatrick
261776e2e4 tempfork/netshell: delete, use github.com/go4org/plan9netshell instead
Change-Id: I2aee6b55f2084a7c3df0db830b28edd1fba0f528
2025-03-24 13:39:43 -07:00
Brad Fitzpatrick
391edc4712 ssh/tailssh: fix non-interactive ssh commands on plan9
Change-Id: Ic026db0548aa1ed8d25619cd98a85f031e987a33
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2025-03-24 13:39:43 -07:00
Brad Fitzpatrick
a193323479 net/dns: clean up plan9 manager
all: clean up logging noise

Change-Id: Id7a777b5697fb63cf8690fe971e1ece97427f678
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2025-03-24 13:39:43 -07:00
Brad Fitzpatrick
478028fce8 net/dns: more plan9 debugging
Change-Id: I9864835ffca4c4b14ec7c75b31e61ed30105c067
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2025-03-24 13:39:43 -07:00
Brad Fitzpatrick
835c7e1e90 net/dns: add more of DNS manager for plan9, tests, plumb netmon/tun name around more
Change-Id: Ia542d7c69f3fbcd2571e2da8b04ad34ec0e2645d
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2025-03-24 13:39:43 -07:00
Brad Fitzpatrick
abb77602a4 more plan9 fixes, to be cleaned up and merged separately later
Change-Id: I4c89609d7eb83bbe208aa87025365427d961b048
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2025-03-24 13:39:42 -07:00
Brad Fitzpatrick
0d67d7835a some more plan9 tweaks; notably DNS one
Change-Id: Ib14f2663d0f36623a42ce95574be61f0b9df1b14
2025-03-24 13:38:39 -07:00
Brad Fitzpatrick
9a0302a454 portlist: add plan9 impl
Change-Id: Ib69b02ad25dc3b94bc6e407aa7ace842a3e51fda
2025-03-24 13:38:39 -07:00
Brad Fitzpatrick
e62920165b fix pty dep back to what it was
Change-Id: I418d4ef0fd33e927e953c35ab028e02f84692243
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2025-03-24 13:38:39 -07:00
Brad Fitzpatrick
0a847f04f3 more plan9 work
Change-Id: I1f6bd742130f348917df3a00b95b0997f84ba1b4
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2025-03-24 13:38:39 -07:00
Brad Fitzpatrick
6a3f589f53 more plan9 ssh work
Change-Id: I7049b5b4f6c0f9902693e00ab6d12ac00bc554bc
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2025-03-24 13:38:39 -07:00
Brad Fitzpatrick
dd3d4e3fe9 ssh/tailssh: add plan9 incubator
wgengine/router: add missing router file

Change-Id: I1b6573ea5e2d3ab23f1d297209f822adee7b10e0
2025-03-24 13:38:39 -07:00
Brad Fitzpatrick
f3011fce04 more misc plan9 work; it works now
Change-Id: Iafc4ee41dd4d7ba9b9907c8e13bb1e161c8f78e3
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2025-03-24 13:38:39 -07:00
Brad Fitzpatrick
8a9bc098ab ssh/tailssh: work on Tailscale SSH for plan9
Updates #5794

Change-Id: I888a7a47752e09005f6d9e8a8412b42df19c5c89
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2025-03-24 13:38:39 -07:00
Brad Fitzpatrick
af61219a15 Makefile: add temporary plan9 rule
Updates #5794

Change-Id: I89113223560ae5734fca9f460e6a6f77d5c82135
2025-03-24 13:38:39 -07:00
Brad Fitzpatrick
9ef648c8df cmd/tailscaled: add default state dir on plan9
Updates #5794

Change-Id: I4729881a36276a5c39233b4aef9550230ccc9316
2025-03-24 13:38:39 -07:00
Brad Fitzpatrick
dc7c15fb84 safesocket: don't use srv(3) on plan9
The implementation wasn't right and spun up
infinite goroutines. Thanks to Russ Cox for debugging.

Updates #5794

Change-Id: I21048712401492829009ad6864cc71c6edf61a64
2025-03-24 13:38:39 -07:00
Brad Fitzpatrick
7a5633a859 logpolicy: disable logs on plan9 for now
They're just distracting at the moment.

Updates #5794

Change-Id: I3e3580ec4b31401c5fea24381387958bd730fba6
2025-03-24 13:38:39 -07:00
Brad Fitzpatrick
14db99241f net/netmon: use Monitor's tsIfName if set by SetTailscaleInterfaceName
Currently nobody calls SetTailscaleInterfaceName yet, so this is a
no-op. I checked oss, android, and the macOS/iOS client. Nobody calls
this, or ever did.

But I want to in the future.

Updates #15408
Updates #9040

Change-Id: I05dfabe505174f9067b929e91c6e0d8bc42628d7
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2025-03-24 13:34:02 -07:00
Brad Fitzpatrick
156cd53e77 net/netmon: unexport GetState
Baby step towards #15408.

Updates #15408

Change-Id: I11fca6e677af2ad2f065d83aa0d83550143bff29
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2025-03-24 10:43:15 -07:00
Brad Fitzpatrick
5c0e08fbbd tstest/mts: add multiple-tailscaled development tool
To let you easily run multiple tailscaled instances for development
and let you route CLI commands to the right one.

Updates #15145

Change-Id: I06b6a7bf024f341c204f30705b4c3068ac89b1a2
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2025-03-24 10:10:35 -07:00
Brad Fitzpatrick
d0c50c6072 clientupdate: cache CanAutoUpdate, avoid log spam when false
I noticed logs on one of my machines where it can't auto-update with
scary log spam about "failed to apply tailnet-wide default for
auto-updates".

This avoids trying to do the EditPrefs if we know it's just going to
fail anyway.

Updates #282

Change-Id: Ib7db3b122185faa70efe08b60ebd05a6094eed8c
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2025-03-24 09:46:48 -07:00
40 changed files with 1781 additions and 164 deletions

View File

@@ -110,6 +110,15 @@ publishdevnameserver: ## Build and publish k8s-nameserver image to location spec
@test "${REPO}" != "ghcr.io/tailscale/k8s-nameserver" || (echo "REPO=... must not be ghcr.io/tailscale/k8s-nameserver" && exit 1)
TAGS="${TAGS}" REPOS=${REPO} PLATFORM=${PLATFORM} PUSH=true TARGET=k8s-nameserver ./build_docker.sh
plan93:
GOOS=plan9 GOARCH=386 ${HOME}/hack/go/bin/go build -o ${HOME}/hack/rsc-plan9/386/bin/tailscaled ./cmd/tailscaled
GOOS=plan9 GOARCH=386 ${HOME}/hack/go/bin/go build -o ${HOME}/hack/rsc-plan9/386/bin/tailscale ./cmd/tailscale
plan9a:
GOOS=plan9 GOARCH=amd64 ${HOME}/hack/go/bin/go build -o ${HOME}/hack/rsc-plan9/amd64/bin/tailscaled ./cmd/tailscaled
GOOS=plan9 GOARCH=amd64 ${HOME}/hack/go/bin/go build -o ${HOME}/hack/rsc-plan9/amd64/bin/tailscale ./cmd/tailscale
.PHONY: sshintegrationtest
sshintegrationtest: ## Run the SSH integration tests in various Docker containers
@GOOS=linux GOARCH=amd64 ./tool/go test -tags integrationtest -c ./ssh/tailssh -o ssh/tailssh/testcontainers/tailssh.test && \

View File

@@ -28,6 +28,7 @@ import (
"strings"
"tailscale.com/hostinfo"
"tailscale.com/types/lazy"
"tailscale.com/types/logger"
"tailscale.com/util/cmpver"
"tailscale.com/version"
@@ -249,9 +250,13 @@ func (up *Updater) getUpdateFunction() (fn updateFunction, canAutoUpdate bool) {
return nil, false
}
var canAutoUpdateCache lazy.SyncValue[bool]
// CanAutoUpdate reports whether auto-updating via the clientupdate package
// is supported for the current os/distro.
func CanAutoUpdate() bool {
func CanAutoUpdate() bool { return canAutoUpdateCache.Get(canAutoUpdateUncached) }
func canAutoUpdateUncached() bool {
if version.IsMacSysExt() {
// Macsys uses Sparkle for auto-updates, which doesn't have an update
// function in this package.

View File

@@ -1,7 +1,7 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build (linux || darwin || freebsd || openbsd) && !ts_omit_ssh
//go:build (linux || darwin || freebsd || openbsd || plan9) && !ts_omit_ssh
package main

View File

@@ -82,7 +82,9 @@ func defaultTunName() string {
// "utun" is recognized by wireguard-go/tun/tun_darwin.go
// as a magic value that uses/creates any free number.
return "utun"
case "plan9", "aix", "solaris", "illumos":
case "plan9":
return "auto"
case "aix", "solaris", "illumos":
return "userspace-networking"
case "linux":
switch distro.Get() {
@@ -180,6 +182,10 @@ func main() {
return
}
if runtime.GOOS == "plan9" && os.Getenv("_NETSHELL_CHILD_") != "" {
os.Args = []string{"tailscaled", "be-child", "plan9-netshell"}
}
if len(os.Args) > 1 {
sub := os.Args[1]
if fp, ok := subCommands[sub]; ok {
@@ -230,7 +236,18 @@ func main() {
// Only apply a default statepath when neither have been provided, so that a
// user may specify only --statedir if they wish.
if args.statepath == "" && args.statedir == "" {
args.statepath = paths.DefaultTailscaledStateFile()
if runtime.GOOS == "plan9" {
home, err := os.UserHomeDir()
if err != nil {
log.Fatalf("failed to get home directory: %v", err)
}
args.statedir = filepath.Join(home, "tailscale-state")
if err := os.MkdirAll(args.statedir, 0700); err != nil {
log.Fatalf("failed to create state directory: %v", err)
}
} else {
args.statepath = paths.DefaultTailscaledStateFile()
}
}
if args.disableLogs {
@@ -731,6 +748,12 @@ func tryEngine(logf logger.Logf, sys *tsd.System, name string) (onlyNetstack boo
return false, err
}
if runtime.GOOS == "plan9" {
// TODO(bradfitz): why don't we do this on all platforms?
// We should. Doing it just on plan9 for now conservatively.
sys.NetMon.Get().SetTailscaleInterfaceName(devName)
}
r, err := router.New(logf, dev, sys.NetMon.Get(), sys.HealthTracker())
if err != nil {
dev.Close()

View File

@@ -246,6 +246,11 @@ func (a *Dialer) dial(ctx context.Context) (*ClientConn, error) {
results[i].conn = nil // so we don't close it in the defer
return conn, nil
}
if ctx.Err() != nil {
a.logf("controlhttp: context aborted dialing")
return nil, ctx.Err()
}
merr := multierr.New(errs...)
// If we get here, then we didn't get anywhere with our dial plan; fall back to just using DNS.

View File

@@ -40,7 +40,7 @@ func CanRunTailscaleSSH() error {
if version.IsSandboxedMacOS() {
return errors.New("The Tailscale SSH server does not run in sandboxed Tailscale GUI builds.")
}
case "freebsd", "openbsd":
case "freebsd", "openbsd", "plan9":
default:
return errors.New("The Tailscale SSH server is not supported on " + runtime.GOOS)
}

6
go.mod
View File

@@ -3,6 +3,7 @@ module tailscale.com
go 1.24.0
require (
9fans.net/go v0.0.8-0.20250307142834-96bdba94b63f
filippo.io/mkcert v1.4.4
fyne.io/systray v1.11.0
github.com/akutz/memconn v0.1.0
@@ -36,6 +37,7 @@ require (
github.com/go-json-experiment/json v0.0.0-20250223041408-d3c622f1b874
github.com/go-logr/zapr v1.3.0
github.com/go-ole/go-ole v1.3.0
github.com/go4org/plan9netshell v0.0.0-20250324183649-788daa080737
github.com/godbus/dbus/v5 v5.1.1-0.20230522191255-76236955d466
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da
github.com/golang/snappy v0.0.4
@@ -84,12 +86,12 @@ require (
github.com/tailscale/setec v0.0.0-20250205144240-8898a29c3fbb
github.com/tailscale/web-client-prebuilt v0.0.0-20250124233751-d4cd19a26976
github.com/tailscale/wf v0.0.0-20240214030419-6fbb0a674ee6
github.com/tailscale/wireguard-go v0.0.0-20250107165329-0b8b35511f19
github.com/tailscale/wireguard-go v0.0.0-20250304000100-91a0587fb251
github.com/tailscale/xnet v0.0.0-20240729143630-8497ac4dab2e
github.com/tc-hib/winres v0.2.1
github.com/tcnksm/go-httpstat v0.2.0
github.com/toqueteos/webbrowser v1.2.0
github.com/u-root/u-root v0.12.0
github.com/u-root/u-root v0.14.0
github.com/vishvananda/netns v0.0.4
go.uber.org/zap v1.27.0
go4.org/mem v0.0.0-20240501181205-ae6ca9944745

20
go.sum
View File

@@ -2,6 +2,8 @@
4d63.com/gocheckcompilerdirectives v1.2.1/go.mod h1:yjDJSxmDTtIHHCqX0ufRYZDL6vQtMG7tJdKVeWwsqvs=
4d63.com/gochecknoglobals v0.2.1 h1:1eiorGsgHOFOuoOiJDy2psSrQbRdIHrlge0IJIkUgDc=
4d63.com/gochecknoglobals v0.2.1/go.mod h1:KRE8wtJB3CXCsb1xy421JfTHIIbmT3U5ruxw2Qu8fSU=
9fans.net/go v0.0.8-0.20250307142834-96bdba94b63f h1:1C7nZuxUMNz7eiQALRfiqNOm04+m3edWlRff/BYHf0Q=
9fans.net/go v0.0.8-0.20250307142834-96bdba94b63f/go.mod h1:hHyrZRryGqVdqrknjq5OWDLGCTJ2NeEvtrpR96mjraM=
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU=
@@ -389,6 +391,8 @@ github.com/go-viper/mapstructure/v2 v2.0.0-alpha.1 h1:TQcrn6Wq+sKGkpyPvppOz99zsM
github.com/go-viper/mapstructure/v2 v2.0.0-alpha.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/go-xmlfmt/xmlfmt v1.1.2 h1:Nea7b4icn8s57fTx1M5AI4qQT5HEM3rVUO8MuE6g80U=
github.com/go-xmlfmt/xmlfmt v1.1.2/go.mod h1:aUCEOzzezBEjDBbFBoSiya/gduyIiWYRP6CnSFIV8AM=
github.com/go4org/plan9netshell v0.0.0-20250324183649-788daa080737 h1:cf60tHxREO3g1nroKr2osU3JWZsJzkfi7rEg+oAB0Lo=
github.com/go4org/plan9netshell v0.0.0-20250324183649-788daa080737/go.mod h1:MIS0jDzbU/vuM9MC4YnBITCv+RYuTRq8dJzmCrFsK9g=
github.com/gobuffalo/flect v1.0.3 h1:xeWBM2nui+qnVvNM4S3foBhCAL2XgPU+a7FdpelbTq4=
github.com/gobuffalo/flect v1.0.3/go.mod h1:A5msMlrHtLqh9umBSnvabjsMrCcCpAyzglnDvkbYKHs=
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
@@ -545,8 +549,8 @@ github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSo
github.com/huandu/xstrings v1.3.3/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI=
github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/hugelgupf/vmtest v0.0.0-20240102225328-693afabdd27f h1:ov45/OzrJG8EKbGjn7jJZQJTN7Z1t73sFYNIRd64YlI=
github.com/hugelgupf/vmtest v0.0.0-20240102225328-693afabdd27f/go.mod h1:JoDrYMZpDPYo6uH9/f6Peqms3zNNWT2XiGgioMOIGuI=
github.com/hugelgupf/vmtest v0.0.0-20240216064925-0561770280a1 h1:jWoR2Yqg8tzM0v6LAiP7i1bikZJu3gxpgvu3g1Lw+a0=
github.com/hugelgupf/vmtest v0.0.0-20240216064925-0561770280a1/go.mod h1:B63hDJMhTupLWCHwopAyEo7wRFowx9kOc8m8j1sfOqE=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/illarion/gonotify/v3 v3.0.2 h1:O7S6vcopHexutmpObkeWsnzMJt/r1hONIEogeVNmJMk=
github.com/illarion/gonotify/v3 v3.0.2/go.mod h1:HWGPdPe817GfvY3w7cx6zkbzNZfi3QjcBm/wgVvEL1U=
@@ -922,8 +926,8 @@ github.com/tailscale/web-client-prebuilt v0.0.0-20250124233751-d4cd19a26976 h1:U
github.com/tailscale/web-client-prebuilt v0.0.0-20250124233751-d4cd19a26976/go.mod h1:agQPE6y6ldqCOui2gkIh7ZMztTkIQKH049tv8siLuNQ=
github.com/tailscale/wf v0.0.0-20240214030419-6fbb0a674ee6 h1:l10Gi6w9jxvinoiq15g8OToDdASBni4CyJOdHY1Hr8M=
github.com/tailscale/wf v0.0.0-20240214030419-6fbb0a674ee6/go.mod h1:ZXRML051h7o4OcI0d3AaILDIad/Xw0IkXaHM17dic1Y=
github.com/tailscale/wireguard-go v0.0.0-20250107165329-0b8b35511f19 h1:BcEJP2ewTIK2ZCsqgl6YGpuO6+oKqqag5HHb7ehljKw=
github.com/tailscale/wireguard-go v0.0.0-20250107165329-0b8b35511f19/go.mod h1:BOm5fXUBFM+m9woLNBoxI9TaBXXhGNP50LX/TGIvGb4=
github.com/tailscale/wireguard-go v0.0.0-20250304000100-91a0587fb251 h1:h/41LFTrwMxB9Xvvug0kRdQCU5TlV1+pAMQw0ZtDE3U=
github.com/tailscale/wireguard-go v0.0.0-20250304000100-91a0587fb251/go.mod h1:BOm5fXUBFM+m9woLNBoxI9TaBXXhGNP50LX/TGIvGb4=
github.com/tailscale/xnet v0.0.0-20240729143630-8497ac4dab2e h1:zOGKqN5D5hHhiYUp091JqK7DPCqSARyUfduhGUY8Bek=
github.com/tailscale/xnet v0.0.0-20240729143630-8497ac4dab2e/go.mod h1:orPd6JZXXRyuDusYilywte7k094d7dycXXU5YnWsrwg=
github.com/tc-hib/winres v0.2.1 h1:YDE0FiP0VmtRaDn7+aaChp1KiF4owBiJa5l964l5ujA=
@@ -950,10 +954,10 @@ github.com/tommy-muehle/go-mnd/v2 v2.5.1 h1:NowYhSdyE/1zwK9QCLeRb6USWdoif80Ie+v+
github.com/tommy-muehle/go-mnd/v2 v2.5.1/go.mod h1:WsUAkMJMYww6l/ufffCD3m+P7LEvr8TnZn9lwVDlgzw=
github.com/toqueteos/webbrowser v1.2.0 h1:tVP/gpK69Fx+qMJKsLE7TD8LuGWPnEV71wBN9rrstGQ=
github.com/toqueteos/webbrowser v1.2.0/go.mod h1:XWoZq4cyp9WeUeak7w7LXRUQf1F1ATJMir8RTqb4ayM=
github.com/u-root/gobusybox/src v0.0.0-20231228173702-b69f654846aa h1:unMPGGK/CRzfg923allsikmvk2l7beBeFPUNC4RVX/8=
github.com/u-root/gobusybox/src v0.0.0-20231228173702-b69f654846aa/go.mod h1:Zj4Tt22fJVn/nz/y6Ergm1SahR9dio1Zm/D2/S0TmXM=
github.com/u-root/u-root v0.12.0 h1:K0AuBFriwr0w/PGS3HawiAw89e3+MU7ks80GpghAsNs=
github.com/u-root/u-root v0.12.0/go.mod h1:FYjTOh4IkIZHhjsd17lb8nYW6udgXdJhG1c0r6u0arI=
github.com/u-root/gobusybox/src v0.0.0-20240225013946-a274a8d5d83a h1:eg5FkNoQp76ZsswyGZ+TjYqA/rhKefxK8BW7XOlQsxo=
github.com/u-root/gobusybox/src v0.0.0-20240225013946-a274a8d5d83a/go.mod h1:e/8TmrdreH0sZOw2DFKBaUV7bvDWRq6SeM9PzkuVM68=
github.com/u-root/u-root v0.14.0 h1:Ka4T10EEML7dQ5XDvO9c3MBN8z4nuSnGjcd1jmU2ivg=
github.com/u-root/u-root v0.14.0/go.mod h1:hAyZorapJe4qzbLWlAkmSVCJGbfoU9Pu4jpJ1WMluqE=
github.com/u-root/uio v0.0.0-20240224005618-d2acac8f3701 h1:pyC9PaHYZFgEKFdlp3G8RaCKgVpHZnecvArXvPXcFkM=
github.com/u-root/uio v0.0.0-20240224005618-d2acac8f3701/go.mod h1:P3a5rG4X7tI17Nn3aOIAYr5HbIMukwXG0urG0WuL8OA=
github.com/ulikunitz/xz v0.5.11 h1:kpFauv27b6ynzBNT/Xy+1k+fK4WswhN/6PN5WhFAGw8=

View File

@@ -3479,18 +3479,20 @@ func (b *LocalBackend) onTailnetDefaultAutoUpdate(au bool) {
// can still manually enable auto-updates on this node.
return
}
b.logf("using tailnet default auto-update setting: %v", au)
prefsClone := prefs.AsStruct()
prefsClone.AutoUpdate.Apply = opt.NewBool(au)
_, err := b.editPrefsLockedOnEntry(&ipn.MaskedPrefs{
Prefs: *prefsClone,
AutoUpdateSet: ipn.AutoUpdatePrefsMask{
ApplySet: true,
},
}, unlock)
if err != nil {
b.logf("failed to apply tailnet-wide default for auto-updates (%v): %v", au, err)
return
if clientupdate.CanAutoUpdate() {
b.logf("using tailnet default auto-update setting: %v", au)
prefsClone := prefs.AsStruct()
prefsClone.AutoUpdate.Apply = opt.NewBool(au)
_, err := b.editPrefsLockedOnEntry(&ipn.MaskedPrefs{
Prefs: *prefsClone,
AutoUpdateSet: ipn.AutoUpdatePrefsMask{
ApplySet: true,
},
}, unlock)
if err != nil {
b.logf("failed to apply tailnet-wide default for auto-updates (%v): %v", au, err)
return
}
}
}
@@ -4966,7 +4968,7 @@ func (b *LocalBackend) authReconfig() {
return
}
oneCGNATRoute := shouldUseOneCGNATRoute(b.logf, b.sys.ControlKnobs(), version.OS())
oneCGNATRoute := shouldUseOneCGNATRoute(b.logf, b.sys.NetMon.Get(), b.sys.ControlKnobs(), version.OS())
rcfg := b.routerConfig(cfg, prefs, oneCGNATRoute)
err = b.e.Reconfig(cfg, rcfg, dcfg)
@@ -4990,7 +4992,7 @@ func (b *LocalBackend) authReconfig() {
//
// The versionOS is a Tailscale-style version ("iOS", "macOS") and not
// a runtime.GOOS.
func shouldUseOneCGNATRoute(logf logger.Logf, controlKnobs *controlknobs.Knobs, versionOS string) bool {
func shouldUseOneCGNATRoute(logf logger.Logf, mon *netmon.Monitor, controlKnobs *controlknobs.Knobs, versionOS string) bool {
if controlKnobs != nil {
// Explicit enabling or disabling always take precedence.
if v, ok := controlKnobs.OneCGNAT.Load().Get(); ok {
@@ -4999,13 +5001,18 @@ func shouldUseOneCGNATRoute(logf logger.Logf, controlKnobs *controlknobs.Knobs,
}
}
if versionOS == "plan9" {
// Just temporarily during plan9 bringup to have fewer routes to debug.
return true
}
// Also prefer to do this on the Mac, so that we don't need to constantly
// update the network extension configuration (which is disruptive to
// Chrome, see https://github.com/tailscale/tailscale/issues/3102). Only
// use fine-grained routes if another interfaces is also using the CGNAT
// IP range.
if versionOS == "macOS" {
hasCGNATInterface, err := netmon.HasCGNATInterface()
hasCGNATInterface, err := mon.HasCGNATInterface()
if err != nil {
logf("shouldUseOneCGNATRoute: Could not determine if any interfaces use CGNAT: %v", err)
return false

View File

@@ -481,7 +481,7 @@ func (h *peerAPIHandler) handleServeInterfaces(w http.ResponseWriter, r *http.Re
fmt.Fprintf(w, "<h3>Could not get the default route: %s</h3>\n", html.EscapeString(err.Error()))
}
if hasCGNATInterface, err := netmon.HasCGNATInterface(); hasCGNATInterface {
if hasCGNATInterface, err := h.ps.b.sys.NetMon.Get().HasCGNATInterface(); hasCGNATInterface {
fmt.Fprintln(w, "<p>There is another interface using the CGNAT range.</p>")
} else if err != nil {
fmt.Fprintf(w, "<p>Could not check for CGNAT interfaces: %s</p>\n", html.EscapeString(err.Error()))

View File

@@ -1,7 +1,7 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build linux || (darwin && !ios) || freebsd || openbsd
//go:build linux || (darwin && !ios) || freebsd || openbsd || plan9
package ipnlocal

View File

@@ -1,7 +1,7 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build ios || (!linux && !darwin && !freebsd && !openbsd)
//go:build ios || (!linux && !darwin && !freebsd && !openbsd && !plan9)
package ipnlocal

View File

@@ -331,7 +331,7 @@ func (a *actor) Permissions(operatorUID string) (read, write bool) {
// checks here. Note that this permission model is being changed in
// tailscale/corp#18342.
return true, true
case "js":
case "js", "plan9":
return true, true
}
if a.ci.IsUnixSock() {

View File

@@ -627,7 +627,7 @@ func (opts Options) New() *Policy {
conf.IncludeProcSequence = true
}
if envknob.NoLogsNoSupport() || testenv.InTest() {
if envknob.NoLogsNoSupport() || testenv.InTest() || runtime.GOOS == "plan9" {
opts.Logf("You have disabled logging. Tailscale will not be able to provide support.")
conf.HTTPC = &http.Client{Transport: noopPretendSuccessTransport{}}
} else {

View File

@@ -284,7 +284,7 @@ func (m *Manager) compileConfig(cfg Config) (rcfg resolver.Config, ocfg OSConfig
// Deal with trivial configs first.
switch {
case !cfg.needsOSResolver():
case !cfg.needsOSResolver() || runtime.GOOS == "plan9":
// Set search domains, but nothing else. This also covers the
// case where cfg is entirely zero, in which case these
// configs clear all Tailscale DNS settings.

View File

@@ -1,7 +1,7 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build !linux && !freebsd && !openbsd && !windows && !darwin && !illumos && !solaris
//go:build !linux && !freebsd && !openbsd && !windows && !darwin && !illumos && !solaris && !plan9
package dns

181
net/dns/manager_plan9.go Normal file
View File

@@ -0,0 +1,181 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
// TODO: man 6 ndb | grep -e 'suffix.*same line'
// to detect Russ's https://9fans.topicbox.com/groups/9fans/T9c9d81b5801a0820/ndb-suffix-specific-dns-changes
package dns
import (
"bufio"
"bytes"
"fmt"
"io"
"net/netip"
"os"
"regexp"
"strings"
"unicode"
"tailscale.com/control/controlknobs"
"tailscale.com/health"
"tailscale.com/types/logger"
"tailscale.com/util/set"
)
func NewOSConfigurator(logf logger.Logf, ht *health.Tracker, knobs *controlknobs.Knobs, interfaceName string) (OSConfigurator, error) {
return &plan9DNSManager{
logf: logf,
ht: ht,
knobs: knobs,
}, nil
}
type plan9DNSManager struct {
logf logger.Logf
ht *health.Tracker
knobs *controlknobs.Knobs
}
// netNDBBytesWithoutTailscale returns raw (the contents of /net/ndb) with any
// Tailscale bits removed.
func netNDBBytesWithoutTailscale(raw []byte) ([]byte, error) {
var ret bytes.Buffer
bs := bufio.NewScanner(bytes.NewReader(raw))
removeLine := set.Set[string]{}
for bs.Scan() {
t := bs.Text()
if rest, ok := strings.CutPrefix(t, "#tailscaled-added-line:"); ok {
removeLine.Add(strings.TrimSpace(rest))
continue
}
trimmed := strings.TrimSpace(t)
if removeLine.Contains(trimmed) {
removeLine.Delete(trimmed)
continue
}
// Also remove any DNS line referencing *.ts.net. This is
// Tailscale-specific (and won't work with, say, Headscale), but
// the Headscale case will be covered by the #tailscaled-added-line
// logic above, assuming the user didn't delete those comments.
if (strings.HasPrefix(trimmed, "dns=") || strings.Contains(trimmed, "dnsdomain=")) &&
strings.HasSuffix(trimmed, ".ts.net") {
continue
}
ret.WriteString(t)
ret.WriteByte('\n')
}
return ret.Bytes(), bs.Err()
}
// setNDBSuffix adds lines to tsFree (the contents of /net/ndb already cleaned
// of Tailscale-added lines) to add the optional DNS search domain (e.g.
// "foo.ts.net") and DNS server to it.
func setNDBSuffix(tsFree []byte, suffix string) []byte {
suffix = strings.TrimSuffix(suffix, ".")
if suffix == "" {
return tsFree
}
var buf bytes.Buffer
bs := bufio.NewScanner(bytes.NewReader(tsFree))
var added []string
addLine := func(s string) {
added = append(added, strings.TrimSpace(s))
buf.WriteString(s)
}
for bs.Scan() {
buf.Write(bs.Bytes())
buf.WriteByte('\n')
t := bs.Text()
if suffix != "" && len(added) == 0 && strings.HasPrefix(t, "\tdns=") {
addLine(fmt.Sprintf("\tdns=100.100.100.100 suffix=%s\n", suffix))
addLine(fmt.Sprintf("\tdnsdomain=%s\n", suffix))
}
}
bufTrim := bytes.TrimLeftFunc(buf.Bytes(), unicode.IsSpace)
if len(added) == 0 {
return bufTrim
}
var ret bytes.Buffer
for _, s := range added {
ret.WriteString("#tailscaled-added-line: ")
ret.WriteString(s)
ret.WriteString("\n")
}
ret.WriteString("\n")
ret.Write(bufTrim)
return ret.Bytes()
}
func (m *plan9DNSManager) SetDNS(c OSConfig) error {
ndbOnDisk, err := os.ReadFile("/net/ndb")
if err != nil {
return err
}
tsFree, err := netNDBBytesWithoutTailscale(ndbOnDisk)
if err != nil {
return err
}
var suffix string
if len(c.SearchDomains) > 0 {
suffix = string(c.SearchDomains[0])
}
newBuf := setNDBSuffix(tsFree, suffix)
if !bytes.Equal(newBuf, ndbOnDisk) {
if err := os.WriteFile("/net/ndb", newBuf, 0644); err != nil {
return fmt.Errorf("writing /net/ndb: %w", err)
}
if f, err := os.OpenFile("/net/dns", os.O_RDWR, 0); err == nil {
if _, err := io.WriteString(f, "refresh\n"); err != nil {
f.Close()
return fmt.Errorf("/net/dns refresh write: %w", err)
}
if err := f.Close(); err != nil {
return fmt.Errorf("/net/dns refresh close: %w", err)
}
}
}
return nil
}
func (m *plan9DNSManager) SupportsSplitDNS() bool { return false }
func (m *plan9DNSManager) Close() error {
// TODO(bradfitz): remove the Tailscale bits from /net/ndb ideally
return nil
}
var dnsRegex = regexp.MustCompile(`\bdns=(\d+\.\d+\.\d+\.\d+)\b`)
func (m *plan9DNSManager) GetBaseConfig() (OSConfig, error) {
var oc OSConfig
f, err := os.Open("/net/ndb")
if err != nil {
return oc, err
}
defer f.Close()
bs := bufio.NewScanner(f)
for bs.Scan() {
m := dnsRegex.FindSubmatch(bs.Bytes())
if m == nil {
continue
}
addr, err := netip.ParseAddr(string(m[1]))
if err != nil {
continue
}
oc.Nameservers = append(oc.Nameservers, addr)
}
if err := bs.Err(); err != nil {
return oc, err
}
return oc, nil
}

View File

@@ -0,0 +1,86 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build plan9
package dns
import "testing"
func TestNetNDBBytesWithoutTailscale(t *testing.T) {
tests := []struct {
name string
raw string
want string
}{
{
name: "empty",
raw: "",
want: "",
},
{
name: "no-tailscale",
raw: "# This is a comment\nip=10.0.2.15 ipmask=255.255.255.0 ipgw=10.0.2.2\n\tsys=gnot\n",
want: "# This is a comment\nip=10.0.2.15 ipmask=255.255.255.0 ipgw=10.0.2.2\n\tsys=gnot\n",
},
{
name: "remove-by-comments",
raw: "# This is a comment\n#tailscaled-added-line: dns=100.100.100.100\nip=10.0.2.15 ipmask=255.255.255.0 ipgw=10.0.2.2\n\tdns=100.100.100.100\n\tsys=gnot\n",
want: "# This is a comment\nip=10.0.2.15 ipmask=255.255.255.0 ipgw=10.0.2.2\n\tsys=gnot\n",
},
{
name: "remove-by-ts.net",
raw: "Some line\n\tdns=100.100.100.100 suffix=foo.ts.net\n\tfoo=bar\n",
want: "Some line\n\tfoo=bar\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := netNDBBytesWithoutTailscale([]byte(tt.raw))
if err != nil {
t.Fatal(err)
}
if string(got) != tt.want {
t.Errorf("GOT:\n%s\n\nWANT:\n%s\n", string(got), tt.want)
}
})
}
}
func TestSetNDBSuffix(t *testing.T) {
tests := []struct {
name string
raw string
want string
}{
{
name: "empty",
raw: "",
want: "",
},
{
name: "set",
raw: "ip=10.0.2.15 ipmask=255.255.255.0 ipgw=10.0.2.2\n\tsys=gnot\n\tdns=100.100.100.100\n\n# foo\n",
want: `#tailscaled-added-line: dns=100.100.100.100 suffix=foo.ts.net
#tailscaled-added-line: dnsdomain=foo.ts.net
ip=10.0.2.15 ipmask=255.255.255.0 ipgw=10.0.2.2
sys=gnot
dns=100.100.100.100
dns=100.100.100.100 suffix=foo.ts.net
dnsdomain=foo.ts.net
# foo
`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := setNDBSuffix([]byte(tt.raw), "foo.ts.net")
if string(got) != tt.want {
t.Errorf("wrong value\n GOT %q:\n%s\n\nWANT %q:\n%s\n", got, got, tt.want, tt.want)
}
})
}
}

View File

@@ -1188,6 +1188,10 @@ func (c *Client) measureAllICMPLatency(ctx context.Context, rs *reportState, nee
if len(need) == 0 {
return nil
}
if runtime.GOOS == "plan9" {
// ICMP isn't implemented.
return nil
}
ctx, done := context.WithTimeout(ctx, icmpProbeTimeout)
defer done()

View File

@@ -13,7 +13,7 @@ import (
)
func TestGetState(t *testing.T) {
st, err := GetState()
st, err := getState("")
if err != nil {
t.Fatal(err)
}

View File

@@ -161,7 +161,7 @@ func (m *Monitor) InterfaceState() *State {
}
func (m *Monitor) interfaceStateUncached() (*State, error) {
return GetState()
return getState(m.tsIfName)
}
// SetTailscaleInterfaceName sets the name of the Tailscale interface. For
@@ -596,7 +596,7 @@ func (m *Monitor) pollWallTime() {
//
// We don't do this on mobile platforms for battery reasons, and because these
// platforms don't really sleep in the same way.
const shouldMonitorTimeJump = runtime.GOOS != "android" && runtime.GOOS != "ios"
const shouldMonitorTimeJump = runtime.GOOS != "android" && runtime.GOOS != "ios" && runtime.GOOS != "plan9"
// checkWallTimeAdvanceLocked reports whether wall time jumped more than 150% of
// pollWallTimeInterval, indicating we probably just came out of sleep. Once a

View File

@@ -461,21 +461,22 @@ func isTailscaleInterface(name string, ips []netip.Prefix) bool {
// getPAC, if non-nil, returns the current PAC file URL.
var getPAC func() string
// GetState returns the state of all the current machine's network interfaces.
// getState returns the state of all the current machine's network interfaces.
//
// It does not set the returned State.IsExpensive. The caller can populate that.
//
// Deprecated: use netmon.Monitor.InterfaceState instead.
func GetState() (*State, error) {
// optTSInterfaceName is the name of the Tailscale interface, if known.
func getState(optTSInterfaceName string) (*State, error) {
s := &State{
InterfaceIPs: make(map[string][]netip.Prefix),
Interface: make(map[string]Interface),
}
if err := ForeachInterface(func(ni Interface, pfxs []netip.Prefix) {
isTSInterfaceName := optTSInterfaceName != "" && ni.Name == optTSInterfaceName
ifUp := ni.IsUp()
s.Interface[ni.Name] = ni
s.InterfaceIPs[ni.Name] = append(s.InterfaceIPs[ni.Name], pfxs...)
if !ifUp || isTailscaleInterface(ni.Name, pfxs) {
if !ifUp || isTSInterfaceName || isTailscaleInterface(ni.Name, pfxs) {
return
}
for _, pfx := range pfxs {
@@ -755,11 +756,12 @@ func DefaultRoute() (DefaultRouteDetails, error) {
// HasCGNATInterface reports whether there are any non-Tailscale interfaces that
// use a CGNAT IP range.
func HasCGNATInterface() (bool, error) {
func (m *Monitor) HasCGNATInterface() (bool, error) {
hasCGNATInterface := false
cgnatRange := tsaddr.CGNATRange()
err := ForeachInterface(func(i Interface, pfxs []netip.Prefix) {
if hasCGNATInterface || !i.IsUp() || isTailscaleInterface(i.Name, pfxs) {
isTSInterfaceName := m.tsIfName != "" && i.Name == m.tsIfName
if hasCGNATInterface || !i.IsUp() || isTSInterfaceName || isTailscaleInterface(i.Name, pfxs) {
return
}
for _, pfx := range pfxs {

View File

@@ -242,7 +242,7 @@ func changeAffectsConn(delta *netmon.ChangeDelta, conn net.Conn) bool {
// In a few cases, we don't have a new DefaultRouteInterface (e.g. on
// Android; see tailscale/corp#19124); if so, pessimistically assume
// that all connections are affected.
if delta.New.DefaultRouteInterface == "" {
if delta.New.DefaultRouteInterface == "" && runtime.GOOS != "plan9" {
return true
}

View File

@@ -1,7 +1,7 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build plan9 || aix || solaris || illumos
//go:build aix || solaris || illumos
package tstun

View File

@@ -1,7 +1,7 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build !wasm && !plan9 && !tamago && !aix && !solaris && !illumos
//go:build !wasm && !tamago && !aix && !solaris && !illumos
// Package tun creates a tuntap device, working around OS-specific
// quirks if necessary.
@@ -9,6 +9,9 @@ package tstun
import (
"errors"
"fmt"
"log"
"os"
"runtime"
"strings"
"time"
@@ -45,6 +48,9 @@ func New(logf logger.Logf, tunName string) (tun.Device, string, error) {
}
dev, err = CreateTAP.Get()(logf, tapName, bridgeName)
} else {
if runtime.GOOS == "plan9" {
cleanUpPlan9Interfaces()
}
dev, err = tun.CreateTUN(tunName, int(DefaultTUNMTU()))
}
if err != nil {
@@ -65,6 +71,35 @@ func New(logf logger.Logf, tunName string) (tun.Device, string, error) {
return dev, name, nil
}
func cleanUpPlan9Interfaces() {
maybeUnbind := func(n int) {
b, err := os.ReadFile(fmt.Sprintf("/net/ipifc/%d/status", n))
if err != nil {
return
}
status := string(b)
if !(strings.HasPrefix(status, "device maxtu ") ||
strings.Contains(status, "fd7a:115c:a1e0:")) {
return
}
f, err := os.OpenFile(fmt.Sprintf("/net/ipifc/%d/ctl", n), os.O_RDWR, 0)
if err != nil {
return
}
defer f.Close()
if _, err := fmt.Fprintf(f, "unbind\n"); err != nil {
log.Printf("unbind interface %v: %v", n, err)
return
}
log.Printf("tun: unbound stale interface %v", n)
}
// A common case: after unclean shutdown, the /net/ipifc/clone file
for n := 2; n < 5; n++ {
maybeUnbind(n)
}
}
// tunDiagnoseFailure, if non-nil, does OS-specific diagnostics of why
// TUN failed to work.
var tunDiagnoseFailure func(tunName string, logf logger.Logf, err error)

View File

@@ -928,8 +928,10 @@ func (t *Wrapper) Read(buffs [][]byte, sizes []int, offset int) (int, error) {
// packet from OS read and sent to WG
res, ok := <-t.vectorOutbound
if !ok {
t.logf("XXX Wrapper.vectorInbound done")
return 0, io.EOF
}
// t.logf("XXX Wrapper.vec in: err=%v, len(data)=%d, offset=%d", res.err, len(res.data), offset)
if res.err != nil && len(res.data) == 0 {
return 0, res.err
}
@@ -947,6 +949,7 @@ func (t *Wrapper) Read(buffs [][]byte, sizes []int, offset int) (int, error) {
var buffsGRO *gro.GRO
for _, data := range res.data {
p.Decode(data[res.dataOffset:])
// t.logf("XXX Wrapper.Read decode (off=%d): %v", res.dataOffset, p.String())
if m := t.destIPActivity.Load(); m != nil {
if fn := m[p.Dst.Addr()]; fn != nil {

122
portlist/portlist_plan9.go Normal file
View File

@@ -0,0 +1,122 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package portlist
import (
"bufio"
"bytes"
"os"
"strconv"
"strings"
"time"
)
func init() {
newOSImpl = newPlan9Impl
pollInterval = 5 * time.Second
}
type plan9Impl struct {
known map[protoPort]*portMeta // inode string => metadata
br *bufio.Reader // reused
portsBuf []Port
includeLocalhost bool
}
type protoPort struct {
proto string
port uint16
}
type portMeta struct {
port Port
keep bool
}
func newPlan9Impl(includeLocalhost bool) osImpl {
return &plan9Impl{
known: map[protoPort]*portMeta{},
br: bufio.NewReader(bytes.NewReader(nil)),
includeLocalhost: includeLocalhost,
}
}
func (*plan9Impl) Close() error { return nil }
func (im *plan9Impl) AppendListeningPorts(base []Port) ([]Port, error) {
ret := base
des, err := os.ReadDir("/proc")
if err != nil {
return nil, err
}
for _, de := range des {
if !de.IsDir() {
continue
}
pidStr := de.Name()
pid, err := strconv.Atoi(pidStr)
if err != nil {
continue
}
st, _ := os.ReadFile("/proc/" + pidStr + "/fd")
if !bytes.Contains(st, []byte("/net/tcp/clone")) {
continue
}
args, _ := os.ReadFile("/proc/" + pidStr + "/args")
procName := string(bytes.TrimSpace(args))
// term% cat /proc/417/fd
// /usr/glenda
// 0 r M 35 (0000000000000001 0 00) 16384 260 /dev/cons
// 1 w c 0 (000000000000000a 0 00) 0 471 /dev/null
// 2 w M 35 (0000000000000001 0 00) 16384 108 /dev/cons
// 3 rw I 0 (000000000000002c 0 00) 0 14 /net/tcp/clone
for line := range bytes.Lines(st) {
if !bytes.Contains(line, []byte("/net/tcp/clone")) {
continue
}
f := strings.Fields(string(line))
if len(f) < 10 {
continue
}
if f[9] != "/net/tcp/clone" {
continue
}
qid, err := strconv.ParseUint(strings.TrimPrefix(f[4], "("), 16, 64)
if err != nil {
continue
}
tcpN := (qid >> 5) & (1<<12 - 1)
tcpNStr := strconv.FormatUint(tcpN, 10)
st, _ := os.ReadFile("/net/tcp/" + tcpNStr + "/status")
if !bytes.Contains(st, []byte("Listen ")) {
// Unexpected. Or a race.
continue
}
bl, _ := os.ReadFile("/net/tcp/" + tcpNStr + "/local")
i := bytes.LastIndexByte(bl, '!')
if i == -1 {
continue
}
if bytes.HasPrefix(bl, []byte("127.0.0.1!")) && !im.includeLocalhost {
continue
}
portStr := strings.TrimSpace(string(bl[i+1:]))
port, _ := strconv.Atoi(portStr)
if port == 0 {
continue
}
ret = append(ret, Port{
Proto: "tcp",
Port: uint16(port),
Process: procName,
Pid: pid,
})
}
}
return ret, nil
}

View File

@@ -7,119 +7,13 @@ package safesocket
import (
"context"
"fmt"
"net"
"os"
"syscall"
"time"
"golang.org/x/sys/plan9"
)
// Plan 9's devsrv srv(3) is a server registry and
// it is conventionally bound to "/srv" in the default
// namespace. It is "a one level directory for holding
// already open channels to services". Post one end of
// a pipe to "/srv/tailscale.sock" and use the other
// end for communication with a requestor. Plan 9 pipes
// are bidirectional.
type plan9SrvAddr string
func (sl plan9SrvAddr) Network() string {
return "/srv"
}
func (sl plan9SrvAddr) String() string {
return string(sl)
}
// There is no net.FileListener for Plan 9 at this time
type plan9SrvListener struct {
name string
srvf *os.File
file *os.File
}
func (sl *plan9SrvListener) Accept() (net.Conn, error) {
// sl.file is the server end of the pipe that's
// connected to /srv/tailscale.sock
return plan9FileConn{name: sl.name, file: sl.file}, nil
}
func (sl *plan9SrvListener) Close() error {
sl.file.Close()
return sl.srvf.Close()
}
func (sl *plan9SrvListener) Addr() net.Addr {
return plan9SrvAddr(sl.name)
}
type plan9FileConn struct {
name string
file *os.File
}
func (fc plan9FileConn) Read(b []byte) (n int, err error) {
return fc.file.Read(b)
}
func (fc plan9FileConn) Write(b []byte) (n int, err error) {
return fc.file.Write(b)
}
func (fc plan9FileConn) Close() error {
return fc.file.Close()
}
func (fc plan9FileConn) LocalAddr() net.Addr {
return plan9SrvAddr(fc.name)
}
func (fc plan9FileConn) RemoteAddr() net.Addr {
return plan9SrvAddr(fc.name)
}
func (fc plan9FileConn) SetDeadline(t time.Time) error {
return syscall.EPLAN9
}
func (fc plan9FileConn) SetReadDeadline(t time.Time) error {
return syscall.EPLAN9
}
func (fc plan9FileConn) SetWriteDeadline(t time.Time) error {
return syscall.EPLAN9
}
func connect(_ context.Context, path string) (net.Conn, error) {
f, err := os.OpenFile(path, os.O_RDWR, 0666)
if err != nil {
return nil, err
}
return plan9FileConn{name: path, file: f}, nil
return net.Dial("tcp", "localhost:5252")
}
// Create an entry in /srv, open a pipe, write the
// client end to the entry and return the server
// end of the pipe to the caller. When the server
// end of the pipe is closed, /srv name associated
// with it will be removed (controlled by ORCLOSE flag)
func listen(path string) (net.Listener, error) {
const O_RCLOSE = 64 // remove on close; should be in plan9 package
var pip [2]int
err := plan9.Pipe(pip[:])
if err != nil {
return nil, err
}
defer plan9.Close(pip[1])
srvfd, err := plan9.Create(path, plan9.O_WRONLY|plan9.O_CLOEXEC|O_RCLOSE, 0600)
if err != nil {
return nil, err
}
srv := os.NewFile(uintptr(srvfd), path)
_, err = fmt.Fprintf(srv, "%d", pip[1])
if err != nil {
return nil, err
}
return &plan9SrvListener{name: path, srvf: srv, file: os.NewFile(uintptr(pip[0]), path)}, nil
return net.Listen("tcp", "localhost:5252")
}

View File

@@ -0,0 +1,421 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
// This file contains the plan9-specific version of the incubator. Tailscaled
// launches the incubator as the same user as it was launched as. The
// incubator then registers a new session with the OS, sets its UID
// and groups to the specified `--uid`, `--gid` and `--groups`, and
// then launches the requested `--cmd`.
package tailssh
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"sync/atomic"
"github.com/go4org/plan9netshell"
"github.com/pkg/sftp"
"tailscale.com/cmd/tailscaled/childproc"
"tailscale.com/tailcfg"
"tailscale.com/types/logger"
)
func init() {
childproc.Add("ssh", beIncubator)
childproc.Add("sftp", beSFTP)
childproc.Add("plan9-netshell", beNetshell)
}
// newIncubatorCommand returns a new exec.Cmd configured with
// `tailscaled be-child ssh` as the entrypoint.
//
// If ss.srv.tailscaledPath is empty, this method is equivalent to
// exec.CommandContext.
//
// The returned Cmd.Env is guaranteed to be nil; the caller populates it.
func (ss *sshSession) newIncubatorCommand(logf logger.Logf) (cmd *exec.Cmd, err error) {
defer func() {
if cmd.Env != nil {
panic("internal error")
}
}()
var isSFTP, isShell bool
switch ss.Subsystem() {
case "sftp":
isSFTP = true
case "":
isShell = ss.RawCommand() == ""
default:
panic(fmt.Sprintf("unexpected subsystem: %v", ss.Subsystem()))
}
if ss.conn.srv.tailscaledPath == "" {
if isSFTP {
// SFTP relies on the embedded Go-based SFTP server in tailscaled,
// so without tailscaled, we can't serve SFTP.
return nil, errors.New("no tailscaled found on path, can't serve SFTP")
}
loginShell := ss.conn.localUser.LoginShell()
logf("directly running /bin/rc -c %q", ss.RawCommand())
return exec.CommandContext(ss.ctx, loginShell, "-c", ss.RawCommand()), nil
}
lu := ss.conn.localUser
ci := ss.conn.info
remoteUser := ci.uprof.LoginName
if ci.node.IsTagged() {
remoteUser = strings.Join(ci.node.Tags().AsSlice(), ",")
}
incubatorArgs := []string{
"be-child",
"ssh",
// TODO: "--uid=" + lu.Uid,
// TODO: "--gid=" + lu.Gid,
"--local-user=" + lu.Username,
"--home-dir=" + lu.HomeDir,
"--remote-user=" + remoteUser,
"--remote-ip=" + ci.src.Addr().String(),
"--has-tty=false", // updated in-place by startWithPTY
"--tty-name=", // updated in-place by startWithPTY
}
nm := ss.conn.srv.lb.NetMap()
forceV1Behavior := nm.HasCap(tailcfg.NodeAttrSSHBehaviorV1) && !nm.HasCap(tailcfg.NodeAttrSSHBehaviorV2)
if forceV1Behavior {
incubatorArgs = append(incubatorArgs, "--force-v1-behavior")
}
if debugTest.Load() {
incubatorArgs = append(incubatorArgs, "--debug-test")
}
switch {
case isSFTP:
// Note that we include both the `--sftp` flag and a command to launch
// tailscaled as `be-child sftp`. If login or su is available, and
// we're not running with tailcfg.NodeAttrSSHBehaviorV1, this will
// result in serving SFTP within a login shell, with full PAM
// integration. Otherwise, we'll serve SFTP in the incubator process
// with no PAM integration.
incubatorArgs = append(incubatorArgs, "--sftp", fmt.Sprintf("--cmd=%s be-child sftp", ss.conn.srv.tailscaledPath))
case isShell:
incubatorArgs = append(incubatorArgs, "--shell")
default:
incubatorArgs = append(incubatorArgs, "--cmd="+ss.RawCommand())
}
allowSendEnv := nm.HasCap(tailcfg.NodeAttrSSHEnvironmentVariables)
if allowSendEnv {
env, err := filterEnv(ss.conn.acceptEnv, ss.Session.Environ())
if err != nil {
return nil, err
}
if len(env) > 0 {
encoded, err := json.Marshal(env)
if err != nil {
return nil, fmt.Errorf("failed to encode environment: %w", err)
}
incubatorArgs = append(incubatorArgs, fmt.Sprintf("--encoded-env=%q", encoded))
}
}
return exec.CommandContext(ss.ctx, ss.conn.srv.tailscaledPath, incubatorArgs...), nil
}
var debugTest atomic.Bool
type stdRWC struct{}
func (stdRWC) Read(p []byte) (n int, err error) {
return os.Stdin.Read(p)
}
func (stdRWC) Write(b []byte) (n int, err error) {
return os.Stdout.Write(b)
}
func (stdRWC) Close() error {
os.Exit(0)
return nil
}
type incubatorArgs struct {
localUser string
homeDir string
remoteUser string
remoteIP string
ttyName string
hasTTY bool
cmd string
isSFTP bool
isShell bool
forceV1Behavior bool
debugTest bool
isSELinuxEnforcing bool
encodedEnv string
}
func parseIncubatorArgs(args []string) (incubatorArgs, error) {
var ia incubatorArgs
flags := flag.NewFlagSet("", flag.ExitOnError)
flags.StringVar(&ia.localUser, "local-user", "", "the user to run as")
flags.StringVar(&ia.homeDir, "home-dir", "/", "the user's home directory")
flags.StringVar(&ia.remoteUser, "remote-user", "", "the remote user/tags")
flags.StringVar(&ia.remoteIP, "remote-ip", "", "the remote Tailscale IP")
flags.StringVar(&ia.ttyName, "tty-name", "", "the tty name (pts/3)")
flags.BoolVar(&ia.hasTTY, "has-tty", false, "is the output attached to a tty")
flags.StringVar(&ia.cmd, "cmd", "", "the cmd to launch, including all arguments (ignored in sftp mode)")
flags.BoolVar(&ia.isShell, "shell", false, "is launching a shell (with no cmds)")
flags.BoolVar(&ia.isSFTP, "sftp", false, "run sftp server (cmd is ignored)")
flags.BoolVar(&ia.forceV1Behavior, "force-v1-behavior", false, "allow falling back to the su command if login is unavailable")
flags.BoolVar(&ia.debugTest, "debug-test", false, "should debug in test mode")
flags.BoolVar(&ia.isSELinuxEnforcing, "is-selinux-enforcing", false, "whether SELinux is in enforcing mode")
flags.StringVar(&ia.encodedEnv, "encoded-env", "", "JSON encoded array of environment variables in '['key=value']' format")
flags.Parse(args)
return ia, nil
}
func (ia incubatorArgs) forwardedEnviron() ([]string, string, error) {
environ := os.Environ()
// pass through SSH_AUTH_SOCK environment variable to support ssh agent forwarding
allowListKeys := "SSH_AUTH_SOCK"
if ia.encodedEnv != "" {
unquoted, err := strconv.Unquote(ia.encodedEnv)
if err != nil {
return nil, "", fmt.Errorf("unable to parse encodedEnv %q: %w", ia.encodedEnv, err)
}
var extraEnviron []string
err = json.Unmarshal([]byte(unquoted), &extraEnviron)
if err != nil {
return nil, "", fmt.Errorf("unable to parse encodedEnv %q: %w", ia.encodedEnv, err)
}
environ = append(environ, extraEnviron...)
for _, v := range extraEnviron {
allowListKeys = fmt.Sprintf("%s,%s", allowListKeys, strings.Split(v, "=")[0])
}
}
return environ, allowListKeys, nil
}
func beNetshell(args []string) error {
plan9netshell.Main()
return nil
}
// beIncubator is the entrypoint to the `tailscaled be-child ssh` subcommand.
// It is responsible for informing the system of a new login session for the
// user. This is sometimes necessary for mounting home directories and
// decrypting file systems.
//
// Tailscaled launches the incubator as the same user as it was launched as.
func beIncubator(args []string) error {
// To defend against issues like https://golang.org/issue/1435,
// defensively lock our current goroutine's thread to the current
// system thread before we start making any UID/GID/group changes.
//
// This shouldn't matter on Linux because syscall.AllThreadsSyscall is
// used to invoke syscalls on all OS threads, but (as of 2023-03-23)
// that function is not implemented on all platforms.
runtime.LockOSThread()
defer runtime.UnlockOSThread()
ia, err := parseIncubatorArgs(args)
if err != nil {
return err
}
if ia.isSFTP && ia.isShell {
return fmt.Errorf("--sftp and --shell are mutually exclusive")
}
if ia.isShell {
plan9netshell.Main()
return nil
}
dlogf := logger.Discard
if ia.debugTest {
// In testing, we don't always have syslog, so log to a temp file.
if logFile, err := os.OpenFile("/tmp/tailscalessh.log", os.O_APPEND|os.O_WRONLY, 0666); err == nil {
lf := log.New(logFile, "", 0)
dlogf = func(msg string, args ...any) {
lf.Printf(msg, args...)
logFile.Sync()
}
defer logFile.Close()
}
}
return handleInProcess(dlogf, ia)
}
func handleInProcess(dlogf logger.Logf, ia incubatorArgs) error {
if ia.isSFTP {
return handleSFTPInProcess(dlogf, ia)
}
return handleSSHInProcess(dlogf, ia)
}
func handleSFTPInProcess(dlogf logger.Logf, ia incubatorArgs) error {
dlogf("handling sftp")
return serveSFTP()
}
// beSFTP serves SFTP in-process.
func beSFTP(args []string) error {
return serveSFTP()
}
func serveSFTP() error {
server, err := sftp.NewServer(stdRWC{})
if err != nil {
return err
}
// TODO(https://github.com/pkg/sftp/pull/554): Revert the check for io.EOF,
// when sftp is patched to report clean termination.
if err := server.Serve(); err != nil && err != io.EOF {
return err
}
return nil
}
// handleSSHInProcess is a last resort if we couldn't use login or su. It
// registers a new session with the OS, sets its UID, GID and groups to the
// specified values, and then launches the requested `--cmd` in the user's
// login shell.
func handleSSHInProcess(dlogf logger.Logf, ia incubatorArgs) error {
environ, _, err := ia.forwardedEnviron()
if err != nil {
return err
}
dlogf("running /bin/rc -c %q", ia.cmd)
cmd := newCommand("/bin/rc", environ, []string{"-c", ia.cmd})
err = cmd.Run()
if ee, ok := err.(*exec.ExitError); ok {
ps := ee.ProcessState
code := ps.ExitCode()
if code < 0 {
// TODO(bradfitz): do we need to also check the syscall.WaitStatus
// and make our process look like it also died by signal/same signal
// as our child process? For now we just do the exit code.
fmt.Fprintf(os.Stderr, "[tailscale-ssh: process died: %v]\n", ps.String())
code = 1 // for now. so we don't exit with negative
}
os.Exit(code)
}
return err
}
func newCommand(cmdPath string, cmdEnviron []string, cmdArgs []string) *exec.Cmd {
cmd := exec.Command(cmdPath, cmdArgs...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = cmdEnviron
return cmd
}
// launchProcess launches an incubator process for the provided session.
// It is responsible for configuring the process execution environment.
// The caller can wait for the process to exit by calling cmd.Wait().
//
// It sets ss.cmd, stdin, stdout, and stderr.
func (ss *sshSession) launchProcess() error {
var err error
ss.cmd, err = ss.newIncubatorCommand(ss.logf)
if err != nil {
return err
}
cmd := ss.cmd
cmd.Dir = "/"
cmd.Env = append(os.Environ(), envForUser(ss.conn.localUser)...)
for _, kv := range ss.Environ() {
if acceptEnvPair(kv) {
cmd.Env = append(cmd.Env, kv)
}
}
ci := ss.conn.info
cmd.Env = append(cmd.Env,
fmt.Sprintf("SSH_CLIENT=%s %d %d", ci.src.Addr(), ci.src.Port(), ci.dst.Port()),
fmt.Sprintf("SSH_CONNECTION=%s %d %s %d", ci.src.Addr(), ci.src.Port(), ci.dst.Addr(), ci.dst.Port()),
)
if ss.agentListener != nil {
cmd.Env = append(cmd.Env, fmt.Sprintf("SSH_AUTH_SOCK=%s", ss.agentListener.Addr()))
}
return ss.startWithStdPipes()
}
// startWithStdPipes starts cmd with os.Pipe for Stdin, Stdout and Stderr.
func (ss *sshSession) startWithStdPipes() (err error) {
var rdStdin, wrStdout, wrStderr io.ReadWriteCloser
defer func() {
if err != nil {
closeAll(rdStdin, ss.wrStdin, ss.rdStdout, wrStdout, ss.rdStderr, wrStderr)
}
}()
if ss.cmd == nil {
return errors.New("nil cmd")
}
if rdStdin, ss.wrStdin, err = os.Pipe(); err != nil {
return err
}
if ss.rdStdout, wrStdout, err = os.Pipe(); err != nil {
return err
}
if ss.rdStderr, wrStderr, err = os.Pipe(); err != nil {
return err
}
ss.cmd.Stdin = rdStdin
ss.cmd.Stdout = wrStdout
ss.cmd.Stderr = wrStderr
ss.childPipes = []io.Closer{rdStdin, wrStdout, wrStderr}
return ss.cmd.Start()
}
func envForUser(u *userMeta) []string {
return []string{
fmt.Sprintf("user=%s", u.Username),
fmt.Sprintf("home=%s", u.HomeDir),
fmt.Sprintf("path=%s", defaultPathForUser(&u.User)),
}
}
// acceptEnvPair reports whether the environment variable key=value pair
// should be accepted from the client. It uses the same default as OpenSSH
// AcceptEnv.
func acceptEnvPair(kv string) bool {
k, _, ok := strings.Cut(kv, "=")
if !ok {
return false
}
_ = k
return true // permit anything on plan9 during bringup, for debugging at least
}

View File

@@ -1,7 +1,7 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build linux || (darwin && !ios) || freebsd || openbsd
//go:build linux || (darwin && !ios) || freebsd || openbsd || plan9
// Package tailssh is an SSH server integrated into Tailscale.
package tailssh
@@ -672,7 +672,6 @@ type sshSession struct {
wrStdin io.WriteCloser
rdStdout io.ReadCloser
rdStderr io.ReadCloser // rdStderr is nil for pty sessions
ptyReq *ssh.Pty // non-nil for pty sessions
// childPipes is a list of pipes that need to be closed when the process exits.
// For pty sessions, this is the tty fd.
@@ -903,7 +902,7 @@ func (ss *sshSession) run() {
defer t.Stop()
}
if euid := os.Geteuid(); euid != 0 {
if euid := os.Geteuid(); euid != 0 && runtime.GOOS != "plan9" {
if lu.Uid != fmt.Sprint(euid) {
ss.logf("can't switch to user %q from process euid %v", lu.Username, euid)
fmt.Fprintf(ss, "can't switch user\r\n")

View File

@@ -1,7 +1,7 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build linux || (darwin && !ios) || freebsd || openbsd
//go:build linux || (darwin && !ios) || freebsd || openbsd || plan9
package tailssh
@@ -48,6 +48,9 @@ func userLookup(username string) (*userMeta, error) {
}
func (u *userMeta) LoginShell() string {
if runtime.GOOS == "plan9" {
return "/bin/rc"
}
if u.loginShellCached != "" {
// This field should be populated on Linux, at least, because
// func userLookup on Linux uses "getent" to look up the user
@@ -85,6 +88,9 @@ func defaultPathForUser(u *user.User) string {
if s := defaultPathTmpl(); s != "" {
return expandDefaultPathTmpl(s, u)
}
if runtime.GOOS == "plan9" {
return "/bin"
}
isRoot := u.Uid == "0"
switch distro.Get() {
case distro.Debian:

599
tstest/mts/mts.go Normal file
View File

@@ -0,0 +1,599 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build linux || darwin
// The mts ("Multiple Tailscale") command runs multiple tailscaled instances for
// development, managing their directories and sockets, and lets you easily direct
// tailscale CLI commands to them.
package main
import (
"bufio"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"maps"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"slices"
"strings"
"sync"
"syscall"
"time"
"tailscale.com/client/local"
"tailscale.com/types/bools"
"tailscale.com/types/lazy"
"tailscale.com/util/mak"
)
func usage(args ...any) {
var format string
if len(args) > 0 {
format, args = args[0].(string), args[1:]
}
if format != "" {
format = strings.TrimSpace(format) + "\n\n"
fmt.Fprintf(os.Stderr, format, args...)
}
io.WriteString(os.Stderr, strings.TrimSpace(`
usage:
mts server <subcommand> # manage tailscaled instances
mts server run # run the mts server (parent process of all tailscaled)
mts server list # list all tailscaled and their state
mts server list <name> # show details of named instance
mts server add <name> # add+start new named tailscaled
mts server start <name> # start a previously added tailscaled
mts server stop <name> # stop & remove a named tailscaled
mts server rm <name> # stop & remove a named tailscaled
mts server logs [-f] <name> # get/follow tailscaled logs
mts <inst-name> [tailscale CLI args] # run Tailscale CLI against a named instance
e.g.
mts gmail1 up
mts github2 status --json
`)+"\n")
os.Exit(1)
}
func main() {
// Don't use flag.Parse here; we mostly just delegate through
// to the Tailscale CLI.
if len(os.Args) < 2 {
usage()
}
firstArg, args := os.Args[1], os.Args[2:]
if firstArg == "server" || firstArg == "s" {
if err := runMTSServer(args); err != nil {
log.Fatal(err)
}
} else {
var c Client
inst := firstArg
c.RunCommand(inst, args)
}
}
func runMTSServer(args []string) error {
if len(args) == 0 {
usage()
}
cmd, args := args[0], args[1:]
if cmd == "run" {
var s Server
return s.Run()
}
// Commands other than "run" all use the HTTP client to
// hit the mts server over its unix socket.
var c Client
switch cmd {
default:
usage("unknown mts server subcommand %q", cmd)
case "list", "ls":
list, err := c.List()
if err != nil {
return err
}
if len(args) == 0 {
names := slices.Sorted(maps.Keys(list.Instances))
for _, name := range names {
running := list.Instances[name].Running
fmt.Printf("%10s %s\n", bools.IfElse(running, "RUNNING", "stopped"), name)
}
} else {
for _, name := range args {
inst, ok := list.Instances[name]
if !ok {
return fmt.Errorf("no instance named %q", name)
}
je := json.NewEncoder(os.Stdout)
je.SetIndent("", " ")
if err := je.Encode(inst); err != nil {
return err
}
}
}
case "rm":
if len(args) == 0 {
return fmt.Errorf("missing instance name(s) to remove")
}
log.SetFlags(0)
for _, name := range args {
ok, err := c.Remove(name)
if err != nil {
return err
}
if ok {
log.Printf("%s deleted.", name)
} else {
log.Printf("%s didn't exist.", name)
}
}
case "stop":
if len(args) == 0 {
return fmt.Errorf("missing instance name(s) to stop")
}
log.SetFlags(0)
for _, name := range args {
ok, err := c.Stop(name)
if err != nil {
return err
}
if ok {
log.Printf("%s stopped.", name)
} else {
log.Printf("%s didn't exist.", name)
}
}
case "start", "restart":
list, err := c.List()
if err != nil {
return err
}
shouldStop := cmd == "restart"
for _, arg := range args {
is, ok := list.Instances[arg]
if !ok {
return fmt.Errorf("no instance named %q", arg)
}
if is.Running {
if shouldStop {
if _, err := c.Stop(arg); err != nil {
return fmt.Errorf("stopping %q: %w", arg, err)
}
} else {
log.SetFlags(0)
log.Printf("%s already running.", arg)
continue
}
}
// Creating an existing one starts it up.
if err := c.Create(arg); err != nil {
return fmt.Errorf("starting %q: %w", arg, err)
}
}
case "add":
if len(args) == 0 {
return fmt.Errorf("missing instance name(s) to add")
}
for _, name := range args {
if err := c.Create(name); err != nil {
return fmt.Errorf("creating %q: %w", name, err)
}
}
case "logs":
fs := flag.NewFlagSet("logs", flag.ExitOnError)
fs.Usage = func() { usage() }
follow := fs.Bool("f", false, "follow logs")
fs.Parse(args)
log.Printf("Parsed; following=%v, args=%q", *follow, fs.Args())
if fs.NArg() != 1 {
usage()
}
cmd := bools.IfElse(*follow, "tail", "cat")
args := []string{cmd}
if *follow {
args = append(args, "-f")
}
path, err := exec.LookPath(cmd)
if err != nil {
return fmt.Errorf("looking up %q: %w", cmd, err)
}
args = append(args, instLogsFile(fs.Arg(0)))
log.Fatal(syscall.Exec(path, args, os.Environ()))
}
return nil
}
type Client struct {
}
func (c *Client) client() *http.Client {
return &http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return net.Dial("unix", mtsSock())
},
},
}
}
func getJSON[T any](res *http.Response, err error) (T, error) {
var ret T
if err != nil {
return ret, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
body, _ := io.ReadAll(res.Body)
return ret, fmt.Errorf("unexpected status: %v: %s", res.Status, body)
}
if err := json.NewDecoder(res.Body).Decode(&ret); err != nil {
return ret, err
}
return ret, nil
}
func (c *Client) List() (listResponse, error) {
return getJSON[listResponse](c.client().Get("http://mts/list"))
}
func (c *Client) Remove(name string) (found bool, err error) {
return getJSON[bool](c.client().PostForm("http://mts/rm", url.Values{
"name": []string{name},
}))
}
func (c *Client) Stop(name string) (found bool, err error) {
return getJSON[bool](c.client().PostForm("http://mts/stop", url.Values{
"name": []string{name},
}))
}
func (c *Client) Create(name string) error {
req, err := http.NewRequest("POST", "http://mts/create/"+name, nil)
if err != nil {
return err
}
resp, err := c.client().Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("unexpected status: %v: %s", resp.Status, body)
}
return nil
}
func (c *Client) RunCommand(name string, args []string) {
sock := instSock(name)
lc := &local.Client{
Socket: sock,
UseSocketOnly: true,
}
probeCtx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
defer cancel()
if _, err := lc.StatusWithoutPeers(probeCtx); err != nil {
log.Fatalf("instance %q not running? start with 'mts server start %q'; got error: %v", name, name, err)
}
args = append([]string{"run", "tailscale.com/cmd/tailscale", "--socket=" + sock}, args...)
cmd := exec.Command("go", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
err := cmd.Run()
if err == nil {
os.Exit(0)
}
if exitErr, ok := err.(*exec.ExitError); ok {
os.Exit(exitErr.ExitCode())
}
panic(err)
}
type Server struct {
lazyTailscaled lazy.GValue[string]
mu sync.Mutex
cmds map[string]*exec.Cmd // running tailscaled instances
}
func (s *Server) tailscaled() string {
v, err := s.lazyTailscaled.GetErr(func() (string, error) {
out, err := exec.Command("go", "list", "-f", "{{.Target}}", "tailscale.com/cmd/tailscaled").CombinedOutput()
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
})
if err != nil {
panic(err)
}
return v
}
func (s *Server) Run() error {
if err := os.MkdirAll(mtsRoot(), 0700); err != nil {
return err
}
sock := mtsSock()
os.Remove(sock)
log.Printf("Multi-Tailscaled Server running; listening on %q ...", sock)
ln, err := net.Listen("unix", sock)
if err != nil {
return err
}
return http.Serve(ln, s)
}
var validNameRx = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
func validInstanceName(name string) bool {
return validNameRx.MatchString(name)
}
func (s *Server) InstanceRunning(name string) bool {
s.mu.Lock()
defer s.mu.Unlock()
_, ok := s.cmds[name]
return ok
}
func (s *Server) Stop(name string) {
s.mu.Lock()
defer s.mu.Unlock()
if cmd, ok := s.cmds[name]; ok {
if err := cmd.Process.Kill(); err != nil {
log.Printf("error killing %q: %v", name, err)
}
delete(s.cmds, name)
}
}
func (s *Server) RunInstance(name string) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.cmds[name]; ok {
return fmt.Errorf("instance %q already running", name)
}
if !validInstanceName(name) {
return fmt.Errorf("invalid instance name %q", name)
}
dir := filepath.Join(mtsRoot(), name)
if err := os.MkdirAll(dir, 0700); err != nil {
return err
}
env := os.Environ()
env = append(env, "TS_DEBUG_LOG_RATE=all")
if ef, err := os.Open(instEnvFile(name)); err == nil {
defer ef.Close()
sc := bufio.NewScanner(ef)
for sc.Scan() {
t := strings.TrimSpace(sc.Text())
if strings.HasPrefix(t, "#") || !strings.Contains(t, "=") {
continue
}
env = append(env, t)
}
} else if os.IsNotExist(err) {
// Write an example one.
os.WriteFile(instEnvFile(name), fmt.Appendf(nil, "# Example mts env.txt file; uncomment/add stuff you want for %q\n\n#TS_DEBUG_MAP=1\n#TS_DEBUG_REGISTER=1\n#TS_NO_LOGS_NO_SUPPORT=1\n", name), 0600)
}
extraArgs := []string{"--verbose=1"}
if af, err := os.Open(instArgsFile(name)); err == nil {
extraArgs = nil // clear default args
defer af.Close()
sc := bufio.NewScanner(af)
for sc.Scan() {
t := strings.TrimSpace(sc.Text())
if strings.HasPrefix(t, "#") || t == "" {
continue
}
extraArgs = append(extraArgs, t)
}
} else if os.IsNotExist(err) {
// Write an example one.
os.WriteFile(instArgsFile(name), fmt.Appendf(nil, "# Example mts args.txt file for instance %q.\n# One line per extra arg to tailscaled; no magic string quoting\n\n--verbose=1\n#--socks5-server=127.0.0.1:5000\n", name), 0600)
}
log.Printf("Running Tailscale daemon %q in %q", name, dir)
args := []string{
"--tun=userspace-networking",
"--statedir=" + filepath.Join(dir),
"--socket=" + filepath.Join(dir, "tailscaled.sock"),
}
args = append(args, extraArgs...)
cmd := exec.Command(s.tailscaled(), args...)
cmd.Dir = dir
cmd.Env = env
out, err := cmd.StdoutPipe()
if err != nil {
return err
}
cmd.Stderr = cmd.Stdout
logs := instLogsFile(name)
logFile, err := os.OpenFile(logs, os.O_CREATE|os.O_WRONLY|os.O_APPEND|os.O_TRUNC, 0644)
if err != nil {
return fmt.Errorf("opening logs file: %w", err)
}
go func() {
bs := bufio.NewScanner(out)
for bs.Scan() {
// TODO(bradfitz): record in memory too, serve via HTTP
line := strings.TrimSpace(bs.Text())
fmt.Fprintf(logFile, "%s\n", line)
fmt.Printf("tailscaled[%s]: %s\n", name, line)
}
}()
if err := cmd.Start(); err != nil {
return err
}
go func() {
err := cmd.Wait()
logFile.Close()
log.Printf("Tailscale daemon %q exited: %v", name, err)
s.mu.Lock()
defer s.mu.Unlock()
delete(s.cmds, name)
}()
mak.Set(&s.cmds, name, cmd)
return nil
}
type listResponse struct {
// Instances maps instance name to its details.
Instances map[string]listResponseInstance `json:"instances"`
}
type listResponseInstance struct {
Name string `json:"name"`
Dir string `json:"dir"`
Sock string `json:"sock"`
Running bool `json:"running"`
Env string `json:"env"`
Args string `json:"args"`
Logs string `json:"logs"`
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
e := json.NewEncoder(w)
e.SetIndent("", " ")
e.Encode(v)
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/list" {
var res listResponse
for _, name := range s.InstanceNames() {
mak.Set(&res.Instances, name, listResponseInstance{
Name: name,
Dir: instDir(name),
Sock: instSock(name),
Running: s.InstanceRunning(name),
Env: instEnvFile(name),
Args: instArgsFile(name),
Logs: instLogsFile(name),
})
}
writeJSON(w, res)
return
}
if r.URL.Path == "/rm" || r.URL.Path == "/stop" {
shouldRemove := r.URL.Path == "/rm"
if r.Method != "POST" {
http.Error(w, "POST required", http.StatusMethodNotAllowed)
return
}
target := r.FormValue("name")
var ok bool
for _, name := range s.InstanceNames() {
if name != target {
continue
}
ok = true
s.Stop(name)
if shouldRemove {
if err := os.RemoveAll(instDir(name)); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
break
}
writeJSON(w, ok)
return
}
if inst, ok := strings.CutPrefix(r.URL.Path, "/create/"); ok {
if !s.InstanceRunning(inst) {
if err := s.RunInstance(inst); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
fmt.Fprintf(w, "OK\n")
return
}
if r.URL.Path == "/" {
fmt.Fprintf(w, "This is mts, the multi-tailscaled server.\n")
return
}
http.NotFound(w, r)
}
func (s *Server) InstanceNames() []string {
var ret []string
des, err := os.ReadDir(mtsRoot())
if err != nil {
if os.IsNotExist(err) {
return nil
}
panic(err)
}
for _, de := range des {
if !de.IsDir() {
continue
}
ret = append(ret, de.Name())
}
return ret
}
func mtsRoot() string {
dir, err := os.UserConfigDir()
if err != nil {
panic(err)
}
return filepath.Join(dir, "multi-tailscale-dev")
}
func instDir(name string) string {
return filepath.Join(mtsRoot(), name)
}
func instSock(name string) string {
return filepath.Join(instDir(name), "tailscaled.sock")
}
func instEnvFile(name string) string {
return filepath.Join(mtsRoot(), name, "env.txt")
}
func instArgsFile(name string) string {
return filepath.Join(mtsRoot(), name, "args.txt")
}
func instLogsFile(name string) string {
return filepath.Join(mtsRoot(), name, "logs.txt")
}
func mtsSock() string {
return filepath.Join(mtsRoot(), "mts.sock")
}

View File

@@ -14,6 +14,7 @@ import (
"fmt"
"io"
"log"
"runtime"
"strings"
"sync"
"time"
@@ -162,6 +163,10 @@ func RateLimitedFnWithClock(logf Logf, f time.Duration, burst int, maxCache int,
if envknob.String("TS_DEBUG_LOG_RATE") == "all" {
return logf
}
if runtime.GOOS == "plan9" {
// To ease bring-up.
return logf
}
var (
mu sync.Mutex
msgLim = make(map[string]*limitData) // keyed by logf format

View File

@@ -19,6 +19,10 @@ import (
// an error. It will first try to use the 'id' command to get the group IDs,
// and if that fails, it will fall back to the user.GroupIds method.
func GetGroupIds(user *user.User) ([]string, error) {
if runtime.GOOS == "plan9" {
return nil, nil
}
if runtime.GOOS != "linux" {
return user.GroupIds()
}

View File

@@ -54,9 +54,18 @@ func lookup(usernameOrUID string, std lookupStd, wantShell bool) (*user.User, st
// Skip getent entirely on Non-Unix platforms that won't ever have it.
// (Using HasPrefix for "wasip1", anticipating that WASI support will
// move beyond "preview 1" some day.)
if runtime.GOOS == "windows" || runtime.GOOS == "js" || runtime.GOARCH == "wasm" {
if runtime.GOOS == "windows" || runtime.GOOS == "js" || runtime.GOARCH == "wasm" || runtime.GOOS == "plan9" {
var shell string
if wantShell && runtime.GOOS == "plan9" {
shell = "/bin/rc"
}
if runtime.GOOS == "plan9" {
if u, err := user.Current(); err == nil {
return u, shell, nil
}
}
u, err := std(usernameOrUID)
return u, "", err
return u, shell, err
}
// No getent on Gokrazy. So hard-code the login shell.
@@ -78,6 +87,16 @@ func lookup(usernameOrUID string, std lookupStd, wantShell bool) (*user.User, st
return u, shell, nil
}
if runtime.GOOS == "plan9" {
return &user.User{
Uid: "0",
Gid: "0",
Username: "glenda",
Name: "Glenda",
HomeDir: "/",
}, "/bin/rc", nil
}
// Start with getent if caller wants to get the user shell.
if wantShell {
return userLookupGetent(usernameOrUID, std)

View File

@@ -3018,6 +3018,10 @@ func (c *Conn) DebugForcePreferDERP(n int) {
// portableTrySetSocketBuffer sets SO_SNDBUF and SO_RECVBUF on pconn to socketBufferSize,
// logging an error if it occurs.
func portableTrySetSocketBuffer(pconn nettype.PacketConn, logf logger.Logf) {
if runtime.GOOS == "plan9" {
// Not supported. Don't try. Avoid logspam.
return
}
if c, ok := pconn.(*net.UDPConn); ok {
// Attempt to increase the buffer size, and allow failures.
if err := c.SetReadBuffer(socketBufferSize); err != nil {

View File

@@ -7,9 +7,11 @@ import (
"errors"
"net"
"net/netip"
"runtime"
"sync"
"sync/atomic"
"syscall"
"time"
"golang.org/x/net/ipv6"
"tailscale.com/net/netaddr"
@@ -150,6 +152,12 @@ func (c *RebindingUDPConn) closeLocked() error {
return errNilPConn
}
c.port = 0
if runtime.GOOS == "plan9" {
// Work around Go bug https://github.com/golang/go/issues/72770.
// This does https://go-review.googlesource.com/c/go/+/656395
// manually until the upstream Go bug is fixed + released.
c.pconn.SetReadDeadline(time.Now().Add(-time.Hour))
}
return c.pconn.Close()
}

View File

@@ -1,7 +1,7 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
//go:build !windows && !linux && !darwin && !openbsd && !freebsd
//go:build !windows && !linux && !darwin && !openbsd && !freebsd && !plan9
package router

View File

@@ -0,0 +1,158 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package router
import (
"bufio"
"bytes"
"fmt"
"net/netip"
"os"
"strings"
"github.com/tailscale/wireguard-go/tun"
"tailscale.com/health"
"tailscale.com/net/netmon"
"tailscale.com/types/logger"
)
func newUserspaceRouter(logf logger.Logf, tundev tun.Device, netMon *netmon.Monitor, health *health.Tracker) (Router, error) {
r := &plan9Router{
logf: logf,
tundev: tundev,
netMon: netMon,
}
cleanAllTailscaleRoutes(logf)
return r, nil
}
type plan9Router struct {
logf logger.Logf
tundev tun.Device
netMon *netmon.Monitor
health *health.Tracker
}
func (r *plan9Router) Up() error {
return nil
}
func (r *plan9Router) Set(cfg *Config) error {
if cfg == nil {
cleanAllTailscaleRoutes(r.logf)
return nil
}
var self4, self6 netip.Addr
for _, addr := range cfg.LocalAddrs {
ctl := r.tundev.File()
maskBits := addr.Bits()
if addr.Addr().Is4() {
// The mask sizes in Plan9 are in IPv6 bits, even for IPv4.
maskBits += (128 - 32)
self4 = addr.Addr()
}
if addr.Addr().Is6() {
self6 = addr.Addr()
}
_, err := fmt.Fprintf(ctl, "add %s /%d\n", addr.Addr().String(), maskBits)
r.logf("route/plan9: add %s /%d = %v", addr.Addr().String(), maskBits, err)
}
ipr, err := os.OpenFile("/net/iproute", os.O_RDWR, 0)
if err != nil {
return fmt.Errorf("open /net/iproute: %w", err)
}
defer ipr.Close()
// TODO(bradfitz): read existing routes, delete ones tagged "tail"
// that aren't in cfg.LocalRoutes.
if _, err := fmt.Fprintf(ipr, "tag tail\n"); err != nil {
return fmt.Errorf("tag tail: %w", err)
}
for _, route := range cfg.Routes {
maskBits := route.Bits()
if route.Addr().Is4() {
// The mask sizes in Plan9 are in IPv6 bits, even for IPv4.
maskBits += (128 - 32)
}
var nextHop netip.Addr
if route.Addr().Is4() {
nextHop = self4
} else if route.Addr().Is6() {
nextHop = self6
}
if !nextHop.IsValid() {
r.logf("route/plan9: skipping route %s: no next hop (no self addr)", route.String())
continue
}
r.logf("route/plan9: plan9.router: add %s /%d %s", route.Addr(), maskBits, nextHop)
if _, err := fmt.Fprintf(ipr, "add %s /%d %s\n", route.Addr(), maskBits, nextHop); err != nil {
return fmt.Errorf("add %s: %w", route.String(), err)
}
}
if len(cfg.LocalRoutes) > 0 {
r.logf("route/plan9: TODO: Set LocalRoutes %v", cfg.LocalRoutes)
}
if len(cfg.SubnetRoutes) > 0 {
r.logf("route/plan9: TODO: Set SubnetRoutes %v", cfg.SubnetRoutes)
}
return nil
}
// UpdateMagicsockPort implements the Router interface. This implementation
// does nothing and returns nil because this router does not currently need
// to know what the magicsock UDP port is.
func (r *plan9Router) UpdateMagicsockPort(_ uint16, _ string) error {
return nil
}
func (r *plan9Router) Close() error {
// TODO(bradfitz): unbind
return nil
}
func cleanUp(logf logger.Logf, _ string) {
cleanAllTailscaleRoutes(logf)
}
func cleanAllTailscaleRoutes(logf logger.Logf) {
routes, err := os.OpenFile("/net/iproute", os.O_RDWR, 0)
if err != nil {
logf("cleaning routes: %v", err)
return
}
defer routes.Close()
// Using io.ReadAll or os.ReadFile on /net/iproute fails; it results in a
// 511 byte result when the actual /net/iproute contents are over 1k.
// So do it in one big read instead. Who knows.
routeBuf := make([]byte, 1<<20)
n, err := routes.Read(routeBuf)
if err != nil {
logf("cleaning routes: %v", err)
return
}
routeBuf = routeBuf[:n]
//logf("cleaning routes: %d bytes: %q", len(routeBuf), routeBuf)
bs := bufio.NewScanner(bytes.NewReader(routeBuf))
for bs.Scan() {
f := strings.Fields(bs.Text())
if len(f) < 6 {
continue
}
tag := f[4]
if tag != "tail" {
continue
}
_, err := fmt.Fprintf(routes, "remove %s %s\n", f[0], f[1])
logf("router: cleaning route %s %s: %v", f[0], f[1], err)
}
}

View File

@@ -569,6 +569,18 @@ func (e *userspaceEngine) handleLocalPackets(p *packet.Parsed, t *tstun.Wrapper)
return filter.Drop
}
}
if runtime.GOOS == "plan9" {
isLocalAddr, ok := e.isLocalAddr.LoadOk()
if ok {
if isLocalAddr(p.Dst.Addr()) {
e.logf("XXX plan9 inject inbound")
// On Plan9's "tun" equivalent, everything goes back in and out
// the tun, even when the kernel's replying to itself.
t.InjectInboundCopy(p.Buffer())
return filter.Drop
}
}
}
return filter.Accept
}