2020-02-05 22:16:58 +00:00
|
|
|
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package ipnserver
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
2021-05-10 17:38:19 +00:00
|
|
|
"bytes"
|
2020-02-05 22:16:58 +00:00
|
|
|
"context"
|
2021-05-10 17:38:19 +00:00
|
|
|
"encoding/json"
|
2020-10-09 19:15:57 +00:00
|
|
|
"errors"
|
2020-02-05 22:16:58 +00:00
|
|
|
"fmt"
|
2020-09-11 22:11:28 +00:00
|
|
|
"io"
|
2020-02-05 22:16:58 +00:00
|
|
|
"log"
|
|
|
|
"net"
|
2020-03-26 05:57:46 +00:00
|
|
|
"net/http"
|
2022-07-26 03:55:44 +00:00
|
|
|
"net/netip"
|
2020-02-05 22:16:58 +00:00
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"os/signal"
|
2020-09-11 22:11:28 +00:00
|
|
|
"os/user"
|
2022-01-10 18:00:15 +00:00
|
|
|
"path/filepath"
|
2020-09-11 22:11:28 +00:00
|
|
|
"runtime"
|
2021-03-02 19:59:48 +00:00
|
|
|
"strconv"
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
"strings"
|
2020-02-05 22:16:58 +00:00
|
|
|
"sync"
|
|
|
|
"syscall"
|
|
|
|
"time"
|
|
|
|
|
2021-02-15 18:41:52 +00:00
|
|
|
"go4.org/mem"
|
2021-02-16 04:50:20 +00:00
|
|
|
"inet.af/peercred"
|
2020-02-05 22:16:58 +00:00
|
|
|
"tailscale.com/control/controlclient"
|
2022-01-25 18:33:11 +00:00
|
|
|
"tailscale.com/envknob"
|
2020-02-05 22:16:58 +00:00
|
|
|
"tailscale.com/ipn"
|
2021-02-04 21:12:42 +00:00
|
|
|
"tailscale.com/ipn/ipnlocal"
|
2021-02-15 18:41:52 +00:00
|
|
|
"tailscale.com/ipn/localapi"
|
2020-02-05 22:16:58 +00:00
|
|
|
"tailscale.com/logtail/backoff"
|
2022-09-05 18:36:30 +00:00
|
|
|
"tailscale.com/net/dnsfallback"
|
2020-09-11 22:11:28 +00:00
|
|
|
"tailscale.com/net/netstat"
|
2022-02-13 22:45:50 +00:00
|
|
|
"tailscale.com/net/netutil"
|
2021-12-01 04:39:12 +00:00
|
|
|
"tailscale.com/net/tsdial"
|
2020-02-05 22:16:58 +00:00
|
|
|
"tailscale.com/safesocket"
|
2020-07-02 18:26:33 +00:00
|
|
|
"tailscale.com/smallzstd"
|
2020-02-15 03:23:16 +00:00
|
|
|
"tailscale.com/types/logger"
|
2021-06-10 08:08:02 +00:00
|
|
|
"tailscale.com/util/groupmember"
|
2020-09-11 22:11:28 +00:00
|
|
|
"tailscale.com/util/pidowner"
|
2020-11-24 23:35:04 +00:00
|
|
|
"tailscale.com/util/systemd"
|
2022-02-02 17:55:32 +00:00
|
|
|
"tailscale.com/util/winutil"
|
2020-02-16 02:14:50 +00:00
|
|
|
"tailscale.com/version"
|
2021-06-10 08:08:02 +00:00
|
|
|
"tailscale.com/version/distro"
|
2020-02-05 22:16:58 +00:00
|
|
|
"tailscale.com/wgengine"
|
2021-12-01 17:18:17 +00:00
|
|
|
"tailscale.com/wgengine/monitor"
|
2022-06-03 19:08:33 +00:00
|
|
|
"tailscale.com/wgengine/netstack"
|
2020-02-05 22:16:58 +00:00
|
|
|
)
|
|
|
|
|
2020-02-16 02:14:50 +00:00
|
|
|
// Options is the configuration of the Tailscale node agent.
|
2020-02-05 22:16:58 +00:00
|
|
|
type Options struct {
|
2022-09-25 18:29:55 +00:00
|
|
|
// VarRoot is the Tailscale daemon's private writable
|
2021-11-03 16:03:11 +00:00
|
|
|
// directory (usually "/var/lib/tailscale" on Linux) that
|
|
|
|
// contains the "tailscaled.state" file, the "certs" directory
|
|
|
|
// for TLS certs, and the "files" directory for incoming
|
|
|
|
// Taildrop files before they're moved to a user directory.
|
|
|
|
// If empty, Taildrop and TLS certs don't function.
|
|
|
|
VarRoot string
|
|
|
|
|
2020-02-16 02:14:50 +00:00
|
|
|
// AutostartStateKey, if non-empty, immediately starts the agent
|
|
|
|
// using the given StateKey. If empty, the agent stays idle and
|
|
|
|
// waits for a frontend to start it.
|
|
|
|
AutostartStateKey ipn.StateKey
|
2020-07-08 21:15:33 +00:00
|
|
|
|
2020-02-16 02:14:50 +00:00
|
|
|
// SurviveDisconnects specifies how the server reacts to its
|
|
|
|
// frontend disconnecting. If true, the server keeps running on
|
|
|
|
// its existing state, and accepts new frontend connections. If
|
|
|
|
// false, the server dumps its state and becomes idle.
|
2020-07-15 19:23:36 +00:00
|
|
|
//
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
// This is effectively whether the platform is in "server
|
|
|
|
// mode" by default. On Linux, it's true; on Windows, it's
|
|
|
|
// false. But on some platforms (currently only Windows), the
|
|
|
|
// "server mode" can be overridden at runtime with a change in
|
|
|
|
// Prefs.ForceDaemon/WantRunning.
|
|
|
|
//
|
2020-07-15 19:23:36 +00:00
|
|
|
// To support CLI connections (notably, "tailscale status"),
|
|
|
|
// the actual definition of "disconnect" is when the
|
|
|
|
// connection count transitions from 1 to 0.
|
2020-02-05 22:16:58 +00:00
|
|
|
SurviveDisconnects bool
|
2022-02-18 20:55:22 +00:00
|
|
|
|
|
|
|
// LoginFlags specifies the LoginFlags to pass to the client.
|
|
|
|
LoginFlags controlclient.LoginFlags
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2021-10-27 22:44:14 +00:00
|
|
|
// Server is an IPN backend and its set of 0 or more active localhost
|
|
|
|
// TCP or unix socket connections talking to that backend.
|
|
|
|
type Server struct {
|
2021-03-30 22:59:44 +00:00
|
|
|
b *ipnlocal.LocalBackend
|
|
|
|
logf logger.Logf
|
|
|
|
backendLogID string
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
// resetOnZero is whether to call bs.Reset on transition from
|
|
|
|
// 1->0 connections. That is, this is whether the backend is
|
|
|
|
// being run in "client mode" that requires an active GUI
|
|
|
|
// connection (such as on Windows by default). Even if this
|
|
|
|
// is true, the ForceDaemon pref can override this.
|
2022-11-09 05:58:10 +00:00
|
|
|
resetOnZero bool
|
2020-07-15 19:23:36 +00:00
|
|
|
|
|
|
|
bsMu sync.Mutex // lock order: bsMu, then mu
|
|
|
|
bs *ipn.BackendServer
|
2020-02-05 22:16:58 +00:00
|
|
|
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
mu sync.Mutex
|
2020-11-02 17:52:59 +00:00
|
|
|
serverModeUser *user.User // or nil if not in server mode
|
|
|
|
lastUserID string // tracks last userid; on change, Reset state for paranoia
|
|
|
|
allClients map[net.Conn]connIdentity // HTTP or IPN
|
|
|
|
clients map[net.Conn]bool // subset of allClients; only IPN protocol
|
|
|
|
disconnectSub map[chan<- struct{}]struct{} // keys are subscribers of disconnects
|
2020-07-15 19:23:36 +00:00
|
|
|
}
|
|
|
|
|
2021-11-07 19:22:08 +00:00
|
|
|
// LocalBackend returns the server's LocalBackend.
|
|
|
|
func (s *Server) LocalBackend() *ipnlocal.LocalBackend { return s.b }
|
|
|
|
|
2021-03-05 20:05:53 +00:00
|
|
|
// connIdentity represents the owner of a localhost TCP or unix socket connection.
|
2020-10-09 19:15:57 +00:00
|
|
|
type connIdentity struct {
|
2021-03-05 20:05:53 +00:00
|
|
|
Conn net.Conn
|
2021-03-06 05:40:41 +00:00
|
|
|
NotWindows bool // runtime.GOOS != "windows"
|
|
|
|
|
|
|
|
// Fields used when NotWindows:
|
|
|
|
IsUnixSock bool // Conn is a *net.UnixConn
|
|
|
|
Creds *peercred.Creds // or nil
|
|
|
|
|
|
|
|
// Used on Windows:
|
|
|
|
// TODO(bradfitz): merge these into the peercreds package and
|
|
|
|
// use that for all.
|
|
|
|
Pid int
|
|
|
|
UserID string
|
|
|
|
User *user.User
|
2020-10-09 19:15:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// getConnIdentity returns the localhost TCP connection's identity information
|
|
|
|
// (pid, userid, user). If it's not Windows (for now), it returns a nil error
|
2021-03-06 05:40:41 +00:00
|
|
|
// and a ConnIdentity with NotWindows set true. It's only an error if we expected
|
2020-10-09 19:15:57 +00:00
|
|
|
// to be able to map it and couldn't.
|
2021-10-27 22:44:14 +00:00
|
|
|
func (s *Server) getConnIdentity(c net.Conn) (ci connIdentity, err error) {
|
2021-03-06 05:40:41 +00:00
|
|
|
ci = connIdentity{Conn: c}
|
2020-10-09 19:15:57 +00:00
|
|
|
if runtime.GOOS != "windows" { // for now; TODO: expand to other OSes
|
2021-03-06 05:40:41 +00:00
|
|
|
ci.NotWindows = true
|
2021-01-29 21:18:23 +00:00
|
|
|
_, ci.IsUnixSock = c.(*net.UnixConn)
|
2021-03-06 05:40:41 +00:00
|
|
|
ci.Creds, _ = peercred.Get(c)
|
2021-01-29 21:18:23 +00:00
|
|
|
return ci, nil
|
2020-10-09 19:15:57 +00:00
|
|
|
}
|
2022-07-26 03:55:44 +00:00
|
|
|
la, err := netip.ParseAddrPort(c.LocalAddr().String())
|
2020-10-09 19:15:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return ci, fmt.Errorf("parsing local address: %w", err)
|
|
|
|
}
|
2022-07-26 03:55:44 +00:00
|
|
|
ra, err := netip.ParseAddrPort(c.RemoteAddr().String())
|
2020-10-09 19:15:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return ci, fmt.Errorf("parsing local remote: %w", err)
|
|
|
|
}
|
2022-07-25 03:08:42 +00:00
|
|
|
if !la.Addr().IsLoopback() || !ra.Addr().IsLoopback() {
|
2020-10-09 19:15:57 +00:00
|
|
|
return ci, errors.New("non-loopback connection")
|
|
|
|
}
|
|
|
|
tab, err := netstat.Get()
|
|
|
|
if err != nil {
|
|
|
|
return ci, fmt.Errorf("failed to get local connection table: %w", err)
|
|
|
|
}
|
|
|
|
pid := peerPid(tab.Entries, la, ra)
|
|
|
|
if pid == 0 {
|
|
|
|
return ci, errors.New("no local process found matching localhost connection")
|
|
|
|
}
|
|
|
|
ci.Pid = pid
|
|
|
|
uid, err := pidowner.OwnerOfPID(pid)
|
|
|
|
if err != nil {
|
|
|
|
var hint string
|
|
|
|
if runtime.GOOS == "windows" {
|
|
|
|
hint = " (WSL?)"
|
|
|
|
}
|
|
|
|
return ci, fmt.Errorf("failed to map connection's pid to a user%s: %w", hint, err)
|
|
|
|
}
|
|
|
|
ci.UserID = uid
|
2021-10-27 23:10:24 +00:00
|
|
|
u, err := lookupUserFromID(s.logf, uid)
|
2020-10-09 19:15:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return ci, fmt.Errorf("failed to look up user from userid: %w", err)
|
|
|
|
}
|
|
|
|
ci.User = u
|
|
|
|
return ci, nil
|
|
|
|
}
|
2020-09-11 22:11:28 +00:00
|
|
|
|
2021-10-27 23:10:24 +00:00
|
|
|
func lookupUserFromID(logf logger.Logf, uid string) (*user.User, error) {
|
2020-10-29 16:57:21 +00:00
|
|
|
u, err := user.LookupId(uid)
|
|
|
|
if err != nil && runtime.GOOS == "windows" && errors.Is(err, syscall.Errno(0x534)) {
|
2022-02-02 17:55:32 +00:00
|
|
|
// The below workaround is only applicable when uid represents a
|
|
|
|
// valid security principal. Omitting this check causes us to succeed
|
|
|
|
// even when uid represents a deleted user.
|
|
|
|
if !winutil.IsSIDValidPrincipal(uid) {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2021-10-27 23:10:24 +00:00
|
|
|
logf("[warning] issue 869: os/user.LookupId failed; ignoring")
|
2020-10-29 16:57:21 +00:00
|
|
|
// Work around https://github.com/tailscale/tailscale/issues/869 for
|
|
|
|
// now. We don't strictly need the username. It's just a nice-to-have.
|
|
|
|
// So make up a *user.User if their machine is broken in this way.
|
|
|
|
return &user.User{
|
|
|
|
Uid: uid,
|
|
|
|
Username: "unknown-user-" + uid,
|
|
|
|
Name: "unknown user " + uid,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
return u, err
|
|
|
|
}
|
|
|
|
|
2020-11-02 17:52:59 +00:00
|
|
|
// blockWhileInUse blocks while until either a Read from conn fails
|
|
|
|
// (i.e. it's closed) or until the server is able to accept ci as a
|
|
|
|
// user.
|
2021-10-27 22:44:14 +00:00
|
|
|
func (s *Server) blockWhileInUse(conn io.Reader, ci connIdentity) {
|
2020-11-02 17:52:59 +00:00
|
|
|
s.logf("blocking client while server in use; connIdentity=%v", ci)
|
|
|
|
connDone := make(chan struct{})
|
|
|
|
go func() {
|
2022-09-15 12:06:59 +00:00
|
|
|
io.Copy(io.Discard, conn)
|
2020-11-02 17:52:59 +00:00
|
|
|
close(connDone)
|
|
|
|
}()
|
|
|
|
ch := make(chan struct{}, 1)
|
|
|
|
s.registerDisconnectSub(ch, true)
|
|
|
|
defer s.registerDisconnectSub(ch, false)
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-connDone:
|
|
|
|
s.logf("blocked client Read completed; connIdentity=%v", ci)
|
|
|
|
return
|
|
|
|
case <-ch:
|
|
|
|
s.mu.Lock()
|
|
|
|
err := s.checkConnIdentityLocked(ci)
|
|
|
|
s.mu.Unlock()
|
|
|
|
if err == nil {
|
|
|
|
s.logf("unblocking client, server is free; connIdentity=%v", ci)
|
|
|
|
// Server is now available again for a new user.
|
|
|
|
// TODO(bradfitz): keep this connection alive. But for
|
|
|
|
// now just return and have our caller close the connection
|
|
|
|
// (which unblocks the io.Copy goroutine we started above)
|
|
|
|
// and then the client (e.g. Windows) will reconnect and
|
|
|
|
// discover that it works.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-15 18:41:52 +00:00
|
|
|
// bufferHasHTTPRequest reports whether br looks like it has an HTTP
|
|
|
|
// request in it, without reading any bytes from it.
|
|
|
|
func bufferHasHTTPRequest(br *bufio.Reader) bool {
|
|
|
|
peek, _ := br.Peek(br.Buffered())
|
|
|
|
return mem.HasPrefix(mem.B(peek), mem.S("GET ")) ||
|
|
|
|
mem.HasPrefix(mem.B(peek), mem.S("POST ")) ||
|
|
|
|
mem.Contains(mem.B(peek), mem.S(" HTTP/"))
|
|
|
|
}
|
|
|
|
|
2021-12-17 20:40:24 +00:00
|
|
|
// bufferIsConnect reports whether br looks like it's likely an HTTP
|
|
|
|
// CONNECT request.
|
|
|
|
//
|
|
|
|
// Invariant: br has already had at least 4 bytes Peek'ed.
|
|
|
|
func bufferIsConnect(br *bufio.Reader) bool {
|
|
|
|
peek, _ := br.Peek(br.Buffered())
|
|
|
|
return mem.HasPrefix(mem.B(peek), mem.S("CONN"))
|
|
|
|
}
|
|
|
|
|
2021-10-27 22:44:14 +00:00
|
|
|
func (s *Server) serveConn(ctx context.Context, c net.Conn, logf logger.Logf) {
|
2020-09-11 22:11:28 +00:00
|
|
|
// First see if it's an HTTP request.
|
2020-10-09 19:15:57 +00:00
|
|
|
br := bufio.NewReader(c)
|
2020-09-11 22:11:28 +00:00
|
|
|
c.SetReadDeadline(time.Now().Add(time.Second))
|
2021-02-15 18:41:52 +00:00
|
|
|
br.Peek(4)
|
2020-09-11 22:11:28 +00:00
|
|
|
c.SetReadDeadline(time.Time{})
|
2021-12-17 20:40:24 +00:00
|
|
|
|
|
|
|
// Handle logtail CONNECT requests early. (See docs on handleProxyConnectConn)
|
|
|
|
if bufferIsConnect(br) {
|
|
|
|
s.handleProxyConnectConn(ctx, br, c, logf)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-02-15 18:41:52 +00:00
|
|
|
isHTTPReq := bufferHasHTTPRequest(br)
|
2020-10-09 19:15:57 +00:00
|
|
|
|
|
|
|
ci, err := s.addConn(c, isHTTPReq)
|
|
|
|
if err != nil {
|
|
|
|
if isHTTPReq {
|
|
|
|
fmt.Fprintf(c, "HTTP/1.0 500 Nope\r\nContent-Type: text/plain\r\nX-Content-Type-Options: nosniff\r\n\r\n%s\n", err.Error())
|
|
|
|
c.Close()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer c.Close()
|
2021-05-10 17:38:19 +00:00
|
|
|
bs := ipn.NewBackendServer(logf, nil, jsonNotifier(c, s.logf))
|
2020-11-02 17:52:59 +00:00
|
|
|
_, occupied := err.(inUseOtherUserError)
|
|
|
|
if occupied {
|
|
|
|
bs.SendInUseOtherUserErrorMessage(err.Error())
|
|
|
|
s.blockWhileInUse(c, ci)
|
|
|
|
} else {
|
|
|
|
bs.SendErrorMessage(err.Error())
|
|
|
|
time.Sleep(time.Second)
|
|
|
|
}
|
2020-10-09 19:15:57 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
// Tell the LocalBackend about the identity we're now running as.
|
|
|
|
s.b.SetCurrentUserID(ci.UserID)
|
|
|
|
|
2020-10-09 19:15:57 +00:00
|
|
|
if isHTTPReq {
|
2021-02-15 18:41:52 +00:00
|
|
|
httpServer := &http.Server{
|
2020-10-09 19:15:57 +00:00
|
|
|
// Localhost connections are cheap; so only do
|
|
|
|
// keep-alives for a short period of time, as these
|
|
|
|
// active connections lock the server into only serving
|
|
|
|
// that user. If the user has this page open, we don't
|
|
|
|
// want another switching user to be locked out for
|
|
|
|
// minutes. 5 seconds is enough to let browser hit
|
|
|
|
// favicon.ico and such.
|
|
|
|
IdleTimeout: 5 * time.Second,
|
|
|
|
ErrorLog: logger.StdLogger(logf),
|
|
|
|
Handler: s.localhostHandler(ci),
|
|
|
|
}
|
2022-02-22 21:29:17 +00:00
|
|
|
httpServer.Serve(netutil.NewOneConnListener(&protoSwitchConn{s: s, br: br, Conn: c}, nil))
|
2020-09-11 22:11:28 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-07-15 19:23:36 +00:00
|
|
|
defer s.removeAndCloseConn(c)
|
2020-12-21 18:58:06 +00:00
|
|
|
logf("[v1] incoming control connection")
|
2020-10-09 19:15:57 +00:00
|
|
|
|
2021-04-17 04:01:29 +00:00
|
|
|
if isReadonlyConn(ci, s.b.OperatorUserID(), logf) {
|
2021-01-15 16:43:23 +00:00
|
|
|
ctx = ipn.ReadonlyContextOf(ctx)
|
|
|
|
}
|
|
|
|
|
2020-07-15 19:23:36 +00:00
|
|
|
for ctx.Err() == nil {
|
2020-09-11 22:11:28 +00:00
|
|
|
msg, err := ipn.ReadMsg(br)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2020-12-21 18:58:06 +00:00
|
|
|
if errors.Is(err, io.EOF) {
|
|
|
|
logf("[v1] ReadMsg: %v", err)
|
|
|
|
} else if ctx.Err() == nil {
|
2020-07-15 19:23:36 +00:00
|
|
|
logf("ReadMsg: %v", err)
|
|
|
|
}
|
|
|
|
return
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-07-15 19:23:36 +00:00
|
|
|
s.bsMu.Lock()
|
2021-01-15 16:43:23 +00:00
|
|
|
if err := s.bs.GotCommandMsg(ctx, msg); err != nil {
|
2020-04-11 15:35:34 +00:00
|
|
|
logf("GotCommandMsg: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-07-15 19:23:36 +00:00
|
|
|
gotQuit := s.bs.GotQuit
|
|
|
|
s.bsMu.Unlock()
|
|
|
|
if gotQuit {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-17 04:01:29 +00:00
|
|
|
func isReadonlyConn(ci connIdentity, operatorUID string, logf logger.Logf) bool {
|
2021-02-23 21:25:10 +00:00
|
|
|
if runtime.GOOS == "windows" {
|
|
|
|
// Windows doesn't need/use this mechanism, at least yet. It
|
|
|
|
// has a different last-user-wins auth model.
|
|
|
|
return false
|
|
|
|
}
|
2021-02-17 05:06:10 +00:00
|
|
|
const ro = true
|
|
|
|
const rw = false
|
2021-03-02 19:12:14 +00:00
|
|
|
if !safesocket.PlatformUsesPeerCreds() {
|
|
|
|
return rw
|
|
|
|
}
|
2021-03-06 05:40:41 +00:00
|
|
|
creds := ci.Creds
|
|
|
|
if creds == nil {
|
2021-02-17 05:06:10 +00:00
|
|
|
logf("connection from unknown peer; read-only")
|
|
|
|
return ro
|
2021-02-16 04:50:20 +00:00
|
|
|
}
|
|
|
|
uid, ok := creds.UserID()
|
|
|
|
if !ok {
|
2021-02-17 05:06:10 +00:00
|
|
|
logf("connection from peer with unknown userid; read-only")
|
|
|
|
return ro
|
2021-02-16 04:50:20 +00:00
|
|
|
}
|
2021-02-17 05:06:10 +00:00
|
|
|
if uid == "0" {
|
|
|
|
logf("connection from userid %v; root has access", uid)
|
|
|
|
return rw
|
|
|
|
}
|
2021-03-02 19:59:48 +00:00
|
|
|
if selfUID := os.Getuid(); selfUID != 0 && uid == strconv.Itoa(selfUID) {
|
|
|
|
logf("connection from userid %v; connection from non-root user matching daemon has access", uid)
|
|
|
|
return rw
|
|
|
|
}
|
2021-04-17 04:01:29 +00:00
|
|
|
if operatorUID != "" && uid == operatorUID {
|
|
|
|
logf("connection from userid %v; is configured operator", uid)
|
|
|
|
return rw
|
|
|
|
}
|
2021-06-10 08:08:02 +00:00
|
|
|
if yes, err := isLocalAdmin(uid); err != nil {
|
|
|
|
logf("connection from userid %v; read-only; %v", uid, err)
|
2021-02-17 05:06:10 +00:00
|
|
|
return ro
|
2021-06-10 08:08:02 +00:00
|
|
|
} else if yes {
|
|
|
|
logf("connection from userid %v; is local admin, has access", uid)
|
|
|
|
return rw
|
2021-02-17 05:06:10 +00:00
|
|
|
}
|
|
|
|
logf("connection from userid %v; read-only", uid)
|
|
|
|
return ro
|
|
|
|
}
|
|
|
|
|
2021-06-10 08:08:02 +00:00
|
|
|
func isLocalAdmin(uid string) (bool, error) {
|
|
|
|
u, err := user.LookupId(uid)
|
2021-02-17 05:06:10 +00:00
|
|
|
if err != nil {
|
2021-06-10 08:08:02 +00:00
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
var adminGroup string
|
|
|
|
switch {
|
|
|
|
case runtime.GOOS == "darwin":
|
|
|
|
adminGroup = "admin"
|
|
|
|
case distro.Get() == distro.QNAP:
|
|
|
|
adminGroup = "administrators"
|
|
|
|
default:
|
|
|
|
return false, fmt.Errorf("no system admin group found")
|
2021-02-17 05:06:10 +00:00
|
|
|
}
|
2021-06-10 08:08:02 +00:00
|
|
|
return groupmember.IsMemberOfGroup(adminGroup, u.Username)
|
2021-02-16 04:50:20 +00:00
|
|
|
}
|
|
|
|
|
2020-11-02 17:52:59 +00:00
|
|
|
// inUseOtherUserError is the error type for when the server is in use
|
|
|
|
// by a different local user.
|
|
|
|
type inUseOtherUserError struct{ error }
|
|
|
|
|
|
|
|
func (e inUseOtherUserError) Unwrap() error { return e.error }
|
|
|
|
|
|
|
|
// checkConnIdentityLocked checks whether the provided identity is
|
|
|
|
// allowed to connect to the server.
|
|
|
|
//
|
|
|
|
// The returned error, when non-nil, will be of type inUseOtherUserError.
|
|
|
|
//
|
|
|
|
// s.mu must be held.
|
2021-10-27 22:44:14 +00:00
|
|
|
func (s *Server) checkConnIdentityLocked(ci connIdentity) error {
|
2020-11-02 17:52:59 +00:00
|
|
|
// If clients are already connected, verify they're the same user.
|
|
|
|
// This mostly matters on Windows at the moment.
|
|
|
|
if len(s.allClients) > 0 {
|
|
|
|
var active connIdentity
|
|
|
|
for _, active = range s.allClients {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if ci.UserID != active.UserID {
|
|
|
|
return inUseOtherUserError{fmt.Errorf("Tailscale already in use by %s, pid %d", active.User.Username, active.Pid)}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if su := s.serverModeUser; su != nil && ci.UserID != su.Uid {
|
2020-11-03 05:11:20 +00:00
|
|
|
return inUseOtherUserError{fmt.Errorf("Tailscale already in use by %s", su.Username)}
|
2020-11-02 17:52:59 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-03-06 05:40:41 +00:00
|
|
|
// localAPIPermissions returns the permissions for the given identity accessing
|
|
|
|
// the Tailscale local daemon API.
|
|
|
|
//
|
|
|
|
// s.mu must not be held.
|
2021-10-27 22:44:14 +00:00
|
|
|
func (s *Server) localAPIPermissions(ci connIdentity) (read, write bool) {
|
2021-11-07 20:10:47 +00:00
|
|
|
switch runtime.GOOS {
|
|
|
|
case "windows":
|
2021-03-06 05:40:41 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
if s.checkConnIdentityLocked(ci) == nil {
|
|
|
|
return true, true
|
|
|
|
}
|
|
|
|
return false, false
|
2021-11-07 20:10:47 +00:00
|
|
|
case "js":
|
|
|
|
return true, true
|
2021-03-06 05:40:41 +00:00
|
|
|
}
|
|
|
|
if ci.IsUnixSock {
|
2021-04-17 04:01:29 +00:00
|
|
|
return true, !isReadonlyConn(ci, s.b.OperatorUserID(), logger.Discard)
|
2021-03-06 05:40:41 +00:00
|
|
|
}
|
|
|
|
return false, false
|
|
|
|
}
|
|
|
|
|
2022-02-19 23:45:59 +00:00
|
|
|
// userIDFromString maps from either a numeric user id in string form
|
|
|
|
// ("998") or username ("caddy") to its string userid ("998").
|
|
|
|
// It returns the empty string on error.
|
|
|
|
func userIDFromString(v string) string {
|
|
|
|
if v == "" || isAllDigit(v) {
|
|
|
|
return v
|
|
|
|
}
|
|
|
|
u, err := user.Lookup(v)
|
|
|
|
if err != nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
return u.Uid
|
|
|
|
}
|
|
|
|
|
|
|
|
func isAllDigit(s string) bool {
|
|
|
|
for i := 0; i < len(s); i++ {
|
|
|
|
if b := s[i]; b < '0' || b > '9' {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2022-01-25 18:33:11 +00:00
|
|
|
// connCanFetchCerts reports whether ci is allowed to fetch HTTPS
|
|
|
|
// certs from this server when it wouldn't otherwise be able to.
|
|
|
|
//
|
|
|
|
// That is, this reports whether ci should grant additional
|
|
|
|
// capabilities over what the conn would otherwise be able to do.
|
|
|
|
//
|
|
|
|
// For now this only returns true on Unix machines when
|
|
|
|
// TS_PERMIT_CERT_UID is set the to the userid of the peer
|
|
|
|
// connection. It's intended to give your non-root webserver access
|
|
|
|
// (www-data, caddy, nginx, etc) to certs.
|
|
|
|
func (s *Server) connCanFetchCerts(ci connIdentity) bool {
|
|
|
|
if ci.IsUnixSock && ci.Creds != nil {
|
|
|
|
connUID, ok := ci.Creds.UserID()
|
2022-02-19 23:45:59 +00:00
|
|
|
if ok && connUID == userIDFromString(envknob.String("TS_PERMIT_CERT_UID")) {
|
2022-01-25 18:33:11 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-11-02 17:52:59 +00:00
|
|
|
// registerDisconnectSub adds ch as a subscribe to connection disconnect
|
|
|
|
// events. If add is false, the subscriber is removed.
|
2021-10-27 22:44:14 +00:00
|
|
|
func (s *Server) registerDisconnectSub(ch chan<- struct{}, add bool) {
|
2020-11-02 17:52:59 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
if add {
|
|
|
|
if s.disconnectSub == nil {
|
|
|
|
s.disconnectSub = make(map[chan<- struct{}]struct{})
|
|
|
|
}
|
|
|
|
s.disconnectSub[ch] = struct{}{}
|
|
|
|
} else {
|
|
|
|
delete(s.disconnectSub, ch)
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// addConn adds c to the server's list of clients.
|
|
|
|
//
|
|
|
|
// If the returned error is of type inUseOtherUserError then the
|
|
|
|
// returned connIdentity is also valid.
|
2021-10-27 22:44:14 +00:00
|
|
|
func (s *Server) addConn(c net.Conn, isHTTP bool) (ci connIdentity, err error) {
|
2020-10-29 16:57:21 +00:00
|
|
|
ci, err = s.getConnIdentity(c)
|
2020-10-09 19:15:57 +00:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
// If the connected user changes, reset the backend server state to make
|
|
|
|
// sure node keys don't leak between users.
|
|
|
|
var doReset bool
|
|
|
|
defer func() {
|
|
|
|
if doReset {
|
|
|
|
s.logf("identity changed; resetting server")
|
2021-04-20 18:56:36 +00:00
|
|
|
s.b.ResetForClientDisconnect()
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2020-07-15 19:23:36 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
2020-10-09 19:15:57 +00:00
|
|
|
|
2020-07-15 19:23:36 +00:00
|
|
|
if s.clients == nil {
|
|
|
|
s.clients = map[net.Conn]bool{}
|
|
|
|
}
|
2020-10-09 19:15:57 +00:00
|
|
|
if s.allClients == nil {
|
|
|
|
s.allClients = map[net.Conn]connIdentity{}
|
|
|
|
}
|
|
|
|
|
2020-11-02 17:52:59 +00:00
|
|
|
if err := s.checkConnIdentityLocked(ci); err != nil {
|
|
|
|
return ci, err
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
}
|
2020-10-09 19:15:57 +00:00
|
|
|
|
|
|
|
if !isHTTP {
|
|
|
|
s.clients[c] = true
|
|
|
|
}
|
|
|
|
s.allClients[c] = ci
|
|
|
|
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
if s.lastUserID != ci.UserID {
|
|
|
|
if s.lastUserID != "" {
|
|
|
|
doReset = true
|
|
|
|
}
|
|
|
|
s.lastUserID = ci.UserID
|
|
|
|
}
|
2020-10-09 19:15:57 +00:00
|
|
|
return ci, nil
|
2020-07-15 19:23:36 +00:00
|
|
|
}
|
|
|
|
|
2021-10-27 22:44:14 +00:00
|
|
|
func (s *Server) removeAndCloseConn(c net.Conn) {
|
2020-07-15 19:23:36 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
delete(s.clients, c)
|
2020-10-09 19:15:57 +00:00
|
|
|
delete(s.allClients, c)
|
|
|
|
remain := len(s.allClients)
|
2020-11-02 17:52:59 +00:00
|
|
|
for sub := range s.disconnectSub {
|
|
|
|
select {
|
|
|
|
case sub <- struct{}{}:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
2020-07-15 19:23:36 +00:00
|
|
|
s.mu.Unlock()
|
|
|
|
|
|
|
|
if remain == 0 && s.resetOnZero {
|
2020-11-02 17:52:59 +00:00
|
|
|
if s.b.InServerMode() {
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
s.logf("client disconnected; staying alive in server mode")
|
|
|
|
} else {
|
|
|
|
s.logf("client disconnected; stopping server")
|
2021-04-20 18:56:36 +00:00
|
|
|
s.b.ResetForClientDisconnect()
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
}
|
2020-07-15 19:23:36 +00:00
|
|
|
}
|
|
|
|
c.Close()
|
|
|
|
}
|
|
|
|
|
2021-10-27 22:44:14 +00:00
|
|
|
func (s *Server) stopAll() {
|
2020-07-15 19:23:36 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
for c := range s.clients {
|
|
|
|
safesocket.ConnCloseRead(c)
|
|
|
|
safesocket.ConnCloseWrite(c)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-07-15 19:23:36 +00:00
|
|
|
s.clients = nil
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
// setServerModeUserLocked is called when we're in server mode but our s.serverModeUser is nil.
|
|
|
|
//
|
|
|
|
// s.mu must be held
|
2021-10-27 22:44:14 +00:00
|
|
|
func (s *Server) setServerModeUserLocked() {
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
var ci connIdentity
|
|
|
|
var ok bool
|
|
|
|
for _, ci = range s.allClients {
|
|
|
|
ok = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if !ok {
|
|
|
|
s.logf("ipnserver: [unexpected] now in server mode, but no connected client")
|
|
|
|
return
|
|
|
|
}
|
2021-03-06 05:40:41 +00:00
|
|
|
if ci.NotWindows {
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if ci.User != nil {
|
|
|
|
s.logf("ipnserver: now in server mode; user=%v", ci.User.Username)
|
|
|
|
s.serverModeUser = ci.User
|
|
|
|
} else {
|
|
|
|
s.logf("ipnserver: [unexpected] now in server mode, but nil User")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-10 17:38:19 +00:00
|
|
|
var jsonEscapedZero = []byte(`\u0000`)
|
|
|
|
|
2021-10-27 22:44:14 +00:00
|
|
|
func (s *Server) writeToClients(n ipn.Notify) {
|
2020-11-02 17:52:59 +00:00
|
|
|
inServerMode := s.b.InServerMode()
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
|
2020-07-15 19:23:36 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
|
|
|
|
if inServerMode {
|
|
|
|
if s.serverModeUser == nil {
|
|
|
|
s.setServerModeUserLocked()
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if s.serverModeUser != nil {
|
|
|
|
s.logf("ipnserver: no longer in server mode")
|
|
|
|
s.serverModeUser = nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-10 17:38:19 +00:00
|
|
|
if len(s.clients) == 0 {
|
|
|
|
// Common case (at least on busy servers): nobody
|
|
|
|
// connected (no GUI, etc), so return before
|
|
|
|
// serializing JSON.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if b, ok := marshalNotify(n, s.logf); ok {
|
|
|
|
for c := range s.clients {
|
|
|
|
ipn.WriteMsg(c, b)
|
|
|
|
}
|
2020-07-15 19:23:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-29 20:38:09 +00:00
|
|
|
// Run runs a Tailscale backend service.
|
|
|
|
// The getEngine func is called repeatedly, once per connection, until it returns an engine successfully.
|
2021-11-05 19:40:07 +00:00
|
|
|
//
|
|
|
|
// Deprecated: use New and Server.Run instead.
|
2022-06-03 19:08:33 +00:00
|
|
|
func Run(ctx context.Context, logf logger.Logf, ln net.Listener, store ipn.StateStore, linkMon *monitor.Mon, dialer *tsdial.Dialer, logid string, getEngine func() (wgengine.Engine, *netstack.Impl, error), opts Options) error {
|
cmd/tailscaled: don't block ipnserver startup behind engine init on Windows
With this change, the ipnserver's safesocket.Listen (the localhost
tcp.Listen) happens right away, before any synchronous
TUN/DNS/Engine/etc setup work, which might be slow, especially on
early boot on Windows.
Because the safesocket.Listen starts up early, that means localhost
TCP dials (the safesocket.Connect from the GUI) complete successfully
and thus the GUI avoids the MessageBox error. (I verified that
pacifies it, even without a Listener.Accept; I'd feared that Windows
localhost was maybe special and avoided the normal listener backlog).
Once the GUI can then connect immediately without errors, the various
timeouts then matter less, because the backend is no longer trying to
race against the GUI's timeout. So keep retrying on errors for a
minute, or 10 minutes if the system just booted in the past 10
minutes.
This should fix the problem with Windows 10 desktops auto-logging in
and starting the Tailscale frontend which was then showing a
MessageBox error about failing to connect to tailscaled, which was
slow coming up because the Windows networking stack wasn't up
yet. Fingers crossed.
Fixes #1313 (previously #1187, etc)
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2021-04-19 20:45:55 +00:00
|
|
|
getEngine = getEngineUntilItWorksWrapper(getEngine)
|
2020-07-08 21:15:33 +00:00
|
|
|
runDone := make(chan struct{})
|
|
|
|
defer close(runDone)
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2021-10-27 23:10:24 +00:00
|
|
|
var serverMu sync.Mutex
|
|
|
|
var serverOrNil *Server
|
2020-07-15 19:23:36 +00:00
|
|
|
|
2021-10-13 00:28:44 +00:00
|
|
|
// When the context is closed or when we return, whichever is first, close our listener
|
2020-07-15 19:23:36 +00:00
|
|
|
// and all open connections.
|
2020-02-16 02:14:50 +00:00
|
|
|
go func() {
|
2020-02-25 15:36:32 +00:00
|
|
|
select {
|
2020-07-15 19:23:36 +00:00
|
|
|
case <-ctx.Done():
|
2020-02-25 15:36:32 +00:00
|
|
|
case <-runDone:
|
|
|
|
}
|
2021-10-27 23:10:24 +00:00
|
|
|
serverMu.Lock()
|
|
|
|
if s := serverOrNil; s != nil {
|
|
|
|
s.stopAll()
|
|
|
|
}
|
|
|
|
serverMu.Unlock()
|
2021-11-05 19:40:07 +00:00
|
|
|
ln.Close()
|
2020-02-16 02:14:50 +00:00
|
|
|
}()
|
2021-11-05 19:40:07 +00:00
|
|
|
logf("Listening on %v", ln.Addr())
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-08-09 04:03:20 +00:00
|
|
|
bo := backoff.NewBackoff("ipnserver", logf, 30*time.Second)
|
2020-07-30 00:46:06 +00:00
|
|
|
var unservedConn net.Conn // if non-nil, accepted, but hasn't served yet
|
|
|
|
|
2022-06-03 19:08:33 +00:00
|
|
|
eng, ns, err := getEngine()
|
2020-07-29 20:38:09 +00:00
|
|
|
if err != nil {
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
logf("ipnserver: initial getEngine call: %v", err)
|
2020-07-15 19:23:36 +00:00
|
|
|
for i := 1; ctx.Err() == nil; i++ {
|
2021-11-05 19:40:07 +00:00
|
|
|
c, err := ln.Accept()
|
2020-07-08 21:15:33 +00:00
|
|
|
if err != nil {
|
|
|
|
logf("%d: Accept: %v", i, err)
|
2020-07-15 19:23:36 +00:00
|
|
|
bo.BackOff(ctx, err)
|
2020-07-08 21:15:33 +00:00
|
|
|
continue
|
|
|
|
}
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
logf("ipnserver: try%d: trying getEngine again...", i)
|
2022-06-03 19:08:33 +00:00
|
|
|
eng, ns, err = getEngine()
|
2020-07-29 20:38:09 +00:00
|
|
|
if err == nil {
|
|
|
|
logf("%d: GetEngine worked; exiting failure loop", i)
|
2020-07-30 00:46:06 +00:00
|
|
|
unservedConn = c
|
2020-07-29 20:38:09 +00:00
|
|
|
break
|
2020-07-08 21:15:33 +00:00
|
|
|
}
|
ipn, ipnserver, cmd/tailscale: add "server mode" support on Windows
This partially (but not yet fully) migrates Windows to tailscaled's
StateStore storage system.
This adds a new bool Pref, ForceDaemon, defined as:
// ForceDaemon specifies whether a platform that normally
// operates in "client mode" (that is, requires an active user
// logged in with the GUI app running) should keep running after the
// GUI ends and/or the user logs out.
//
// The only current applicable platform is Windows. This
// forced Windows to go into "server mode" where Tailscale is
// running even with no users logged in. This might also be
// used for macOS in the future. This setting has no effect
// for Linux/etc, which always operate in daemon mode.
Then, when ForceDaemon becomes true, we now write use the StateStore
to track which user started it in server mode, and store their prefs
under that key.
The ipnserver validates the connections/identities and informs that
LocalBackend which userid is currently in charge.
The GUI can then enable/disable server mode at runtime, without using
the CLI.
But the "tailscale up" CLI was also fixed, so Windows users can use
authkeys or ACL tags, etc.
Updates #275
2020-10-12 21:28:21 +00:00
|
|
|
logf("ipnserver%d: getEngine failed again: %v", i, err)
|
2020-07-29 20:38:09 +00:00
|
|
|
errMsg := err.Error()
|
2020-07-08 21:15:33 +00:00
|
|
|
go func() {
|
2020-07-30 00:46:06 +00:00
|
|
|
defer c.Close()
|
2021-05-10 17:38:19 +00:00
|
|
|
bs := ipn.NewBackendServer(logf, nil, jsonNotifier(c, logf))
|
2020-07-29 20:38:09 +00:00
|
|
|
bs.SendErrorMessage(errMsg)
|
2020-07-30 00:46:06 +00:00
|
|
|
time.Sleep(time.Second)
|
2020-07-08 21:15:33 +00:00
|
|
|
}()
|
|
|
|
}
|
2020-07-29 22:15:05 +00:00
|
|
|
if err := ctx.Err(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-07-08 21:15:33 +00:00
|
|
|
}
|
2021-10-27 23:33:15 +00:00
|
|
|
if unservedConn != nil {
|
2021-11-05 19:40:07 +00:00
|
|
|
ln = &listenerWithReadyConn{
|
|
|
|
Listener: ln,
|
2021-10-27 23:33:15 +00:00
|
|
|
c: unservedConn,
|
|
|
|
}
|
|
|
|
}
|
2020-07-08 21:15:33 +00:00
|
|
|
|
2022-11-09 05:58:10 +00:00
|
|
|
server, err := New(logf, logid, store, eng, dialer, opts)
|
2021-10-27 23:45:55 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-06-03 19:08:33 +00:00
|
|
|
if ns != nil {
|
|
|
|
ns.SetLocalBackend(server.LocalBackend())
|
|
|
|
}
|
2021-10-27 23:45:55 +00:00
|
|
|
serverMu.Lock()
|
|
|
|
serverOrNil = server
|
|
|
|
serverMu.Unlock()
|
2021-11-05 19:40:07 +00:00
|
|
|
return server.Run(ctx, ln)
|
2021-10-27 23:45:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// New returns a new Server.
|
|
|
|
//
|
2021-11-05 19:40:07 +00:00
|
|
|
// To start it, use the Server.Run method.
|
2022-11-09 05:58:10 +00:00
|
|
|
func New(logf logger.Logf, logid string, store ipn.StateStore, eng wgengine.Engine, dialer *tsdial.Dialer, opts Options) (*Server, error) {
|
|
|
|
b, err := ipnlocal.NewLocalBackend(logf, logid, store, opts.AutostartStateKey, dialer, eng, opts.LoginFlags)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2021-10-27 23:45:55 +00:00
|
|
|
return nil, fmt.Errorf("NewLocalBackend: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2021-11-03 16:03:11 +00:00
|
|
|
b.SetVarRoot(opts.VarRoot)
|
2020-02-05 22:16:58 +00:00
|
|
|
b.SetDecompressor(func() (controlclient.Decompressor, error) {
|
2020-07-02 18:26:33 +00:00
|
|
|
return smallzstd.NewDecoder(nil)
|
2020-02-05 22:16:58 +00:00
|
|
|
})
|
2021-12-07 04:33:45 +00:00
|
|
|
|
2022-08-01 22:46:41 +00:00
|
|
|
if root := b.TailscaleVarRoot(); root != "" {
|
2022-09-05 18:36:30 +00:00
|
|
|
dnsfallback.SetCachePath(filepath.Join(root, "derpmap.cached.json"))
|
2022-08-01 22:46:41 +00:00
|
|
|
}
|
|
|
|
|
2021-12-07 04:33:45 +00:00
|
|
|
dg := distro.Get()
|
|
|
|
switch dg {
|
2022-07-17 17:05:36 +00:00
|
|
|
case distro.Synology, distro.TrueNAS, distro.QNAP:
|
2021-12-06 20:24:25 +00:00
|
|
|
// See if they have a "Taildrop" share.
|
|
|
|
// See https://github.com/tailscale/tailscale/issues/2179#issuecomment-982821319
|
2021-12-07 04:33:45 +00:00
|
|
|
path, err := findTaildropDir(dg)
|
2021-12-06 20:24:25 +00:00
|
|
|
if err != nil {
|
2021-12-07 04:33:45 +00:00
|
|
|
logf("%s Taildrop support: %v", dg, err)
|
2021-12-06 20:24:25 +00:00
|
|
|
} else {
|
2021-12-07 04:33:45 +00:00
|
|
|
logf("%s Taildrop: using %v", dg, path)
|
2021-12-06 20:24:25 +00:00
|
|
|
b.SetDirectFileRoot(path)
|
|
|
|
b.SetDirectFileDoFinalRename(true)
|
|
|
|
}
|
2021-12-07 04:33:45 +00:00
|
|
|
|
2021-12-06 20:24:25 +00:00
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2022-11-09 05:58:10 +00:00
|
|
|
var serverModeUser *user.User
|
|
|
|
if uid := b.CurrentUser(); uid != "" {
|
|
|
|
u, err := lookupUserFromID(logf, uid)
|
|
|
|
if err != nil {
|
|
|
|
logf("ipnserver: found server mode auto-start key; failed to load user: %v", err)
|
|
|
|
} else {
|
|
|
|
logf("ipnserver: found server mode auto-start key (user %s)", u.Username)
|
|
|
|
serverModeUser = u
|
2021-11-05 19:40:07 +00:00
|
|
|
}
|
2020-03-26 05:57:46 +00:00
|
|
|
}
|
|
|
|
|
2021-10-27 23:10:24 +00:00
|
|
|
server := &Server{
|
2022-11-09 05:58:10 +00:00
|
|
|
b: b,
|
|
|
|
backendLogID: logid,
|
|
|
|
logf: logf,
|
|
|
|
resetOnZero: !opts.SurviveDisconnects,
|
|
|
|
serverModeUser: serverModeUser,
|
2021-10-27 23:10:24 +00:00
|
|
|
}
|
2020-07-15 19:23:36 +00:00
|
|
|
server.bs = ipn.NewBackendServer(logf, b, server.writeToClients)
|
2021-10-27 23:45:55 +00:00
|
|
|
return server, nil
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2021-11-05 19:40:07 +00:00
|
|
|
// Run runs the server, accepting connections from ln forever.
|
2021-10-27 23:45:55 +00:00
|
|
|
//
|
2021-11-05 19:40:07 +00:00
|
|
|
// If the context is done, the listener is closed.
|
|
|
|
func (s *Server) Run(ctx context.Context, ln net.Listener) error {
|
2021-10-27 23:45:55 +00:00
|
|
|
defer s.b.Shutdown()
|
2021-11-05 19:40:07 +00:00
|
|
|
|
|
|
|
runDone := make(chan struct{})
|
|
|
|
defer close(runDone)
|
|
|
|
|
|
|
|
// When the context is closed or when we return, whichever is first, close our listener
|
|
|
|
// and all open connections.
|
|
|
|
go func() {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
case <-runDone:
|
|
|
|
}
|
|
|
|
s.stopAll()
|
|
|
|
ln.Close()
|
|
|
|
}()
|
|
|
|
|
2022-11-09 05:58:10 +00:00
|
|
|
if s.b.Prefs().Valid() {
|
2021-10-27 23:45:55 +00:00
|
|
|
s.bs.GotCommand(ctx, &ipn.Command{
|
2020-10-27 04:23:58 +00:00
|
|
|
Version: version.Long,
|
2020-02-16 02:14:50 +00:00
|
|
|
Start: &ipn.StartArgs{
|
2022-11-09 05:58:10 +00:00
|
|
|
Opts: ipn.Options{},
|
2020-02-16 02:14:50 +00:00
|
|
|
},
|
|
|
|
})
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-11-24 23:35:04 +00:00
|
|
|
systemd.Ready()
|
2021-10-27 23:45:55 +00:00
|
|
|
bo := backoff.NewBackoff("ipnserver", s.logf, 30*time.Second)
|
|
|
|
var connNum int
|
|
|
|
for {
|
|
|
|
if ctx.Err() != nil {
|
|
|
|
return ctx.Err()
|
|
|
|
}
|
|
|
|
c, err := ln.Accept()
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2021-10-27 23:45:55 +00:00
|
|
|
if ctx.Err() != nil {
|
|
|
|
return ctx.Err()
|
2020-07-15 19:23:36 +00:00
|
|
|
}
|
2021-10-27 23:45:55 +00:00
|
|
|
s.logf("ipnserver: Accept: %v", err)
|
|
|
|
bo.BackOff(ctx, err)
|
2020-02-05 22:16:58 +00:00
|
|
|
continue
|
|
|
|
}
|
2021-10-27 23:45:55 +00:00
|
|
|
connNum++
|
|
|
|
go s.serveConn(ctx, c, logger.WithPrefix(s.logf, fmt.Sprintf("ipnserver: conn%d: ", connNum)))
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-29 22:02:04 +00:00
|
|
|
// BabysitProc runs the current executable as a child process with the
|
|
|
|
// provided args, capturing its output, writing it to files, and
|
|
|
|
// restarting the process on any crashes.
|
|
|
|
//
|
|
|
|
// It's only currently (2020-10-29) used on Windows.
|
2020-02-05 22:16:58 +00:00
|
|
|
func BabysitProc(ctx context.Context, args []string, logf logger.Logf) {
|
|
|
|
|
|
|
|
executable, err := os.Executable()
|
|
|
|
if err != nil {
|
|
|
|
panic("cannot determine executable: " + err.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
var proc struct {
|
|
|
|
mu sync.Mutex
|
|
|
|
p *os.Process
|
|
|
|
}
|
|
|
|
|
|
|
|
done := make(chan struct{})
|
|
|
|
go func() {
|
|
|
|
interrupt := make(chan os.Signal, 1)
|
|
|
|
signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)
|
|
|
|
var sig os.Signal
|
|
|
|
select {
|
|
|
|
case sig = <-interrupt:
|
2020-04-11 15:35:34 +00:00
|
|
|
logf("BabysitProc: got signal: %v", sig)
|
2020-02-05 22:16:58 +00:00
|
|
|
close(done)
|
|
|
|
case <-ctx.Done():
|
2020-04-11 15:35:34 +00:00
|
|
|
logf("BabysitProc: context done")
|
2020-02-05 22:16:58 +00:00
|
|
|
sig = os.Kill
|
|
|
|
close(done)
|
|
|
|
}
|
|
|
|
|
|
|
|
proc.mu.Lock()
|
|
|
|
proc.p.Signal(sig)
|
|
|
|
proc.mu.Unlock()
|
|
|
|
}()
|
|
|
|
|
2020-08-09 04:03:20 +00:00
|
|
|
bo := backoff.NewBackoff("BabysitProc", logf, 30*time.Second)
|
2020-02-05 22:16:58 +00:00
|
|
|
|
|
|
|
for {
|
|
|
|
startTime := time.Now()
|
2020-04-11 15:35:34 +00:00
|
|
|
log.Printf("exec: %#v %v", executable, args)
|
2020-02-05 22:16:58 +00:00
|
|
|
cmd := exec.Command(executable, args...)
|
|
|
|
|
|
|
|
// Create a pipe object to use as the subproc's stdin.
|
|
|
|
// When the writer goes away, the reader gets EOF.
|
|
|
|
// A subproc can watch its stdin and exit when it gets EOF;
|
|
|
|
// this is a very reliable way to have a subproc die when
|
|
|
|
// its parent (us) disappears.
|
|
|
|
// We never need to actually write to wStdin.
|
|
|
|
rStdin, wStdin, err := os.Pipe()
|
|
|
|
if err != nil {
|
2020-04-11 15:35:34 +00:00
|
|
|
log.Printf("os.Pipe 1: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create a pipe object to use as the subproc's stdout/stderr.
|
|
|
|
// We'll read from this pipe and send it to logf, line by line.
|
|
|
|
// We can't use os.exec's io.Writer for this because it
|
|
|
|
// doesn't care about lines, and thus ends up merging multiple
|
|
|
|
// log lines into one or splitting one line into multiple
|
|
|
|
// logf() calls. bufio is more appropriate.
|
|
|
|
rStdout, wStdout, err := os.Pipe()
|
|
|
|
if err != nil {
|
2020-04-11 15:35:34 +00:00
|
|
|
log.Printf("os.Pipe 2: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
go func(r *os.File) {
|
|
|
|
defer r.Close()
|
|
|
|
rb := bufio.NewReader(r)
|
|
|
|
for {
|
|
|
|
s, err := rb.ReadString('\n')
|
|
|
|
if s != "" {
|
2020-04-11 15:35:34 +00:00
|
|
|
logf("%s", s)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}(rStdout)
|
|
|
|
|
|
|
|
cmd.Stdin = rStdin
|
|
|
|
cmd.Stdout = wStdout
|
|
|
|
cmd.Stderr = wStdout
|
|
|
|
err = cmd.Start()
|
|
|
|
|
|
|
|
// Now that the subproc is started, get rid of our copy of the
|
|
|
|
// pipe reader. Bad things happen on Windows if more than one
|
|
|
|
// process owns the read side of a pipe.
|
|
|
|
rStdin.Close()
|
|
|
|
wStdout.Close()
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("starting subprocess failed: %v", err)
|
|
|
|
} else {
|
|
|
|
proc.mu.Lock()
|
|
|
|
proc.p = cmd.Process
|
|
|
|
proc.mu.Unlock()
|
|
|
|
|
|
|
|
err = cmd.Wait()
|
|
|
|
log.Printf("subprocess exited: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the process finishes, clean up the write side of the
|
|
|
|
// pipe. We'll make a new one when we restart the subproc.
|
|
|
|
wStdin.Close()
|
|
|
|
|
2020-11-17 23:26:39 +00:00
|
|
|
if os.Getenv("TS_DEBUG_RESTART_CRASHED") == "0" {
|
|
|
|
log.Fatalf("Process ended.")
|
|
|
|
}
|
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
if time.Since(startTime) < 60*time.Second {
|
|
|
|
bo.BackOff(ctx, fmt.Errorf("subproc early exit: %v", err))
|
|
|
|
} else {
|
|
|
|
// Reset the timeout, since the process ran for a while.
|
|
|
|
bo.BackOff(ctx, nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-done:
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-07-29 20:38:09 +00:00
|
|
|
|
2021-01-25 22:53:31 +00:00
|
|
|
// getEngineUntilItWorksWrapper returns a getEngine wrapper that does
|
|
|
|
// not call getEngine concurrently and stops calling getEngine once
|
|
|
|
// it's returned a working engine.
|
2022-06-03 19:08:33 +00:00
|
|
|
func getEngineUntilItWorksWrapper(getEngine func() (wgengine.Engine, *netstack.Impl, error)) func() (wgengine.Engine, *netstack.Impl, error) {
|
2021-01-25 22:53:31 +00:00
|
|
|
var mu sync.Mutex
|
|
|
|
var engGood wgengine.Engine
|
2022-06-03 19:08:33 +00:00
|
|
|
var nsGood *netstack.Impl
|
|
|
|
return func() (wgengine.Engine, *netstack.Impl, error) {
|
2021-01-25 22:53:31 +00:00
|
|
|
mu.Lock()
|
|
|
|
defer mu.Unlock()
|
|
|
|
if engGood != nil {
|
2022-06-03 19:08:33 +00:00
|
|
|
return engGood, nsGood, nil
|
2021-01-25 22:53:31 +00:00
|
|
|
}
|
2022-06-03 19:08:33 +00:00
|
|
|
e, ns, err := getEngine()
|
2021-01-25 22:53:31 +00:00
|
|
|
if err != nil {
|
2022-06-03 19:08:33 +00:00
|
|
|
return nil, nil, err
|
2021-01-25 22:53:31 +00:00
|
|
|
}
|
|
|
|
engGood = e
|
2022-06-03 19:08:33 +00:00
|
|
|
nsGood = ns
|
|
|
|
return e, ns, nil
|
2021-01-25 22:53:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-09 19:15:57 +00:00
|
|
|
// protoSwitchConn is a net.Conn that's we want to speak HTTP to but
|
|
|
|
// it's already had a few bytes read from it to determine that it's
|
|
|
|
// HTTP. So we Read from its bufio.Reader. On Close, we we tell the
|
|
|
|
// server it's closed, so the server can account the who's connected.
|
|
|
|
type protoSwitchConn struct {
|
2021-10-27 22:44:14 +00:00
|
|
|
s *Server
|
2020-09-11 22:11:28 +00:00
|
|
|
net.Conn
|
2020-10-09 19:15:57 +00:00
|
|
|
br *bufio.Reader
|
|
|
|
closeOnce sync.Once
|
2020-09-11 22:11:28 +00:00
|
|
|
}
|
|
|
|
|
2020-10-09 19:15:57 +00:00
|
|
|
func (psc *protoSwitchConn) Read(p []byte) (int, error) { return psc.br.Read(p) }
|
|
|
|
func (psc *protoSwitchConn) Close() error {
|
|
|
|
psc.closeOnce.Do(func() { psc.s.removeAndCloseConn(psc.Conn) })
|
|
|
|
return nil
|
|
|
|
}
|
2020-09-11 22:11:28 +00:00
|
|
|
|
2021-10-27 22:44:14 +00:00
|
|
|
func (s *Server) localhostHandler(ci connIdentity) http.Handler {
|
2021-03-30 22:59:44 +00:00
|
|
|
lah := localapi.NewHandler(s.b, s.logf, s.backendLogID)
|
2021-03-06 05:40:41 +00:00
|
|
|
lah.PermitRead, lah.PermitWrite = s.localAPIPermissions(ci)
|
2022-01-25 18:33:11 +00:00
|
|
|
lah.PermitCert = s.connCanFetchCerts(ci)
|
2021-03-06 05:40:41 +00:00
|
|
|
|
2020-09-11 22:11:28 +00:00
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2021-03-06 05:40:41 +00:00
|
|
|
if strings.HasPrefix(r.URL.Path, "/localapi/") {
|
|
|
|
lah.ServeHTTP(w, r)
|
2021-01-29 21:18:23 +00:00
|
|
|
return
|
|
|
|
}
|
2021-03-06 05:40:41 +00:00
|
|
|
if ci.NotWindows {
|
2020-10-09 19:15:57 +00:00
|
|
|
io.WriteString(w, "<html><title>Tailscale</title><body><h1>Tailscale</h1>This is the local Tailscale daemon.")
|
2020-09-11 22:11:28 +00:00
|
|
|
return
|
|
|
|
}
|
2021-11-05 19:40:07 +00:00
|
|
|
s.ServeHTMLStatus(w, r)
|
2020-09-11 22:11:28 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-11-05 19:40:07 +00:00
|
|
|
func (s *Server) ServeHTMLStatus(w http.ResponseWriter, r *http.Request) {
|
2020-10-09 19:15:57 +00:00
|
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
2021-11-05 19:40:07 +00:00
|
|
|
st := s.b.Status()
|
2020-10-09 19:15:57 +00:00
|
|
|
// TODO(bradfitz): add LogID and opts to st?
|
|
|
|
st.WriteHTML(w)
|
|
|
|
}
|
|
|
|
|
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
|
|
|
func peerPid(entries []netstat.Entry, la, ra netip.AddrPort) int {
|
2020-09-11 22:11:28 +00:00
|
|
|
for _, e := range entries {
|
|
|
|
if e.Local == ra && e.Remote == la {
|
|
|
|
return e.Pid
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return 0
|
|
|
|
}
|
2021-05-10 17:38:19 +00:00
|
|
|
|
|
|
|
// jsonNotifier returns a notify-writer func that writes ipn.Notify
|
|
|
|
// messages to w.
|
|
|
|
func jsonNotifier(w io.Writer, logf logger.Logf) func(ipn.Notify) {
|
|
|
|
return func(n ipn.Notify) {
|
|
|
|
if b, ok := marshalNotify(n, logf); ok {
|
|
|
|
ipn.WriteMsg(w, b)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func marshalNotify(n ipn.Notify, logf logger.Logf) (b []byte, ok bool) {
|
|
|
|
b, err := json.Marshal(n)
|
|
|
|
if err != nil {
|
|
|
|
logf("ipnserver: [unexpected] error serializing JSON: %v", err)
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
if bytes.Contains(b, jsonEscapedZero) {
|
|
|
|
logf("[unexpected] zero byte in BackendServer.send notify message: %q", b)
|
|
|
|
}
|
|
|
|
return b, true
|
|
|
|
}
|
2021-10-27 23:33:15 +00:00
|
|
|
|
|
|
|
// listenerWithReadyConn is a net.Listener wrapper that has
|
|
|
|
// one net.Conn ready to be accepted already.
|
|
|
|
type listenerWithReadyConn struct {
|
|
|
|
net.Listener
|
|
|
|
|
|
|
|
mu sync.Mutex
|
|
|
|
c net.Conn // if non-nil, ready to be Accepted
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ln *listenerWithReadyConn) Accept() (net.Conn, error) {
|
|
|
|
ln.mu.Lock()
|
|
|
|
c := ln.c
|
|
|
|
ln.c = nil
|
|
|
|
ln.mu.Unlock()
|
|
|
|
if c != nil {
|
|
|
|
return c, nil
|
|
|
|
}
|
|
|
|
return ln.Listener.Accept()
|
|
|
|
}
|
2021-12-06 20:24:25 +00:00
|
|
|
|
2021-12-07 04:33:45 +00:00
|
|
|
func findTaildropDir(dg distro.Distro) (string, error) {
|
|
|
|
const name = "Taildrop"
|
|
|
|
switch dg {
|
|
|
|
case distro.Synology:
|
|
|
|
return findSynologyTaildropDir(name)
|
|
|
|
case distro.TrueNAS:
|
|
|
|
return findTrueNASTaildropDir(name)
|
2022-07-17 17:05:36 +00:00
|
|
|
case distro.QNAP:
|
|
|
|
return findQnapTaildropDir(name)
|
2021-12-07 04:33:45 +00:00
|
|
|
}
|
|
|
|
return "", fmt.Errorf("%s is an unsupported distro for Taildrop dir", dg)
|
|
|
|
}
|
|
|
|
|
2021-12-06 20:24:25 +00:00
|
|
|
// findSynologyTaildropDir looks for the first volume containing a
|
|
|
|
// "Taildrop" directory. We'd run "synoshare --get Taildrop" command
|
|
|
|
// but on DSM7 at least, we lack permissions to run that.
|
2021-12-07 04:33:45 +00:00
|
|
|
func findSynologyTaildropDir(name string) (dir string, err error) {
|
2021-12-06 20:24:25 +00:00
|
|
|
for i := 1; i <= 16; i++ {
|
|
|
|
dir = fmt.Sprintf("/volume%v/%s", i, name)
|
|
|
|
if fi, err := os.Stat(dir); err == nil && fi.IsDir() {
|
|
|
|
return dir, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return "", fmt.Errorf("shared folder %q not found", name)
|
|
|
|
}
|
2021-12-07 04:33:45 +00:00
|
|
|
|
|
|
|
// findTrueNASTaildropDir returns the first matching directory of
|
|
|
|
// /mnt/{name} or /mnt/*/{name}
|
|
|
|
func findTrueNASTaildropDir(name string) (dir string, err error) {
|
|
|
|
// If we're running in a jail, a mount point could just be added at /mnt/Taildrop
|
|
|
|
dir = fmt.Sprintf("/mnt/%s", name)
|
|
|
|
if fi, err := os.Stat(dir); err == nil && fi.IsDir() {
|
|
|
|
return dir, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// but if running on the host, it may be something like /mnt/Primary/Taildrop
|
2022-09-15 12:06:59 +00:00
|
|
|
fis, err := os.ReadDir("/mnt")
|
2021-12-07 04:33:45 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("error reading /mnt: %w", err)
|
|
|
|
}
|
|
|
|
for _, fi := range fis {
|
|
|
|
dir = fmt.Sprintf("/mnt/%s/%s", fi.Name(), name)
|
|
|
|
if fi, err := os.Stat(dir); err == nil && fi.IsDir() {
|
|
|
|
return dir, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return "", fmt.Errorf("shared folder %q not found", name)
|
|
|
|
}
|
2022-01-10 18:00:15 +00:00
|
|
|
|
2022-07-17 17:05:36 +00:00
|
|
|
// findQnapTaildropDir checks if a Shared Folder named "Taildrop" exists.
|
|
|
|
func findQnapTaildropDir(name string) (string, error) {
|
|
|
|
dir := fmt.Sprintf("/share/%s", name)
|
2022-07-25 03:08:42 +00:00
|
|
|
fi, err := os.Stat(dir)
|
2022-07-17 17:05:36 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("shared folder %q not found", name)
|
|
|
|
}
|
|
|
|
if fi.IsDir() {
|
|
|
|
return dir, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// share/Taildrop is usually a symlink to CACHEDEV1_DATA/Taildrop/ or some such.
|
|
|
|
fullpath, err := filepath.EvalSymlinks(dir)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("symlink to shared folder %q not found", name)
|
|
|
|
}
|
2022-07-25 03:08:42 +00:00
|
|
|
if fi, err = os.Stat(fullpath); err == nil && fi.IsDir() {
|
2022-07-17 17:05:36 +00:00
|
|
|
return dir, nil // return the symlink, how QNAP set it up
|
|
|
|
}
|
|
|
|
return "", fmt.Errorf("shared folder %q not found", name)
|
|
|
|
}
|