2023-01-27 21:37:20 +00:00
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
2021-02-15 18:41:52 +00:00
// Package localapi contains the HTTP server handlers for tailscaled's API server.
package localapi
import (
2022-03-29 20:43:26 +01:00
"bytes"
2022-11-20 21:25:54 +00:00
"context"
2023-09-12 00:33:20 +01:00
"crypto/sha256"
"encoding/hex"
2021-02-15 18:41:52 +00:00
"encoding/json"
2021-04-16 18:57:46 +01:00
"errors"
2021-03-30 20:56:00 +01:00
"fmt"
2021-02-15 18:41:52 +00:00
"io"
2022-03-24 16:04:01 +00:00
"net"
2021-02-15 18:41:52 +00:00
"net/http"
2021-04-06 21:38:47 +01:00
"net/http/httputil"
2022-07-26 04:55:44 +01:00
"net/netip"
2021-03-30 20:56:00 +01:00
"net/url"
2024-02-02 18:45:32 +00:00
"os"
2023-11-09 20:55:46 +00:00
"os/exec"
2024-02-02 18:45:32 +00:00
"path"
2021-03-05 20:07:00 +00:00
"runtime"
2023-08-17 06:09:53 +01:00
"slices"
2021-03-19 04:07:58 +00:00
"strconv"
2021-03-30 20:56:00 +01:00
"strings"
2022-07-08 19:57:34 +01:00
"sync"
2021-03-30 23:59:44 +01:00
"time"
2021-02-15 18:41:52 +00:00
2021-04-13 16:13:46 +01:00
"tailscale.com/client/tailscale/apitype"
2023-11-09 21:00:47 +00:00
"tailscale.com/clientupdate"
2022-09-13 15:09:57 +01:00
"tailscale.com/envknob"
2022-10-03 15:54:46 +01:00
"tailscale.com/health"
"tailscale.com/hostinfo"
2021-04-12 00:10:31 +01:00
"tailscale.com/ipn"
2023-11-09 20:55:46 +00:00
"tailscale.com/ipn/ipnauth"
2021-02-15 18:41:52 +00:00
"tailscale.com/ipn/ipnlocal"
2021-03-19 04:07:58 +00:00
"tailscale.com/ipn/ipnstate"
2022-12-24 04:54:30 +00:00
"tailscale.com/logtail"
2023-04-18 22:26:58 +01:00
"tailscale.com/net/netmon"
2022-03-24 16:04:01 +00:00
"tailscale.com/net/netutil"
2023-03-02 23:05:30 +00:00
"tailscale.com/net/portmapper"
2021-02-15 18:41:52 +00:00
"tailscale.com/tailcfg"
2023-10-16 18:36:31 +01:00
"tailscale.com/taildrop"
2024-02-02 18:45:32 +00:00
"tailscale.com/tailfs"
2022-08-11 18:43:09 +01:00
"tailscale.com/tka"
2023-07-27 20:41:31 +01:00
"tailscale.com/tstime"
2022-10-31 23:47:51 +00:00
"tailscale.com/types/key"
2021-03-30 23:59:44 +01:00
"tailscale.com/types/logger"
2023-03-23 17:49:56 +00:00
"tailscale.com/types/logid"
2022-12-01 22:39:03 +00:00
"tailscale.com/types/ptr"
2023-07-18 23:13:36 +01:00
"tailscale.com/types/tkatype"
2020-12-14 02:51:24 +00:00
"tailscale.com/util/clientmetric"
2023-10-16 18:36:31 +01:00
"tailscale.com/util/httphdr"
2023-01-27 03:35:26 +00:00
"tailscale.com/util/httpm"
2022-09-10 20:11:59 +01:00
"tailscale.com/util/mak"
go.mod, cmd/tailscaled, ipn/localapi, util/osdiag, util/winutil, util/winutil/authenticode: add Windows module list to OS-specific logs that are written upon bugreport
* We update wingoes to pick up new version information functionality
(See pe/version.go in the https://github.com/dblohm7/wingoes repo);
* We move the existing LogSupportInfo code (including necessary syscall
stubs) out of util/winutil into a new package, util/osdiag, and implement
the public LogSupportInfo function may be implemented for other platforms
as needed;
* We add a new reason argument to LogSupportInfo and wire that into
localapi's bugreport implementation;
* We add module information to the Windows implementation of LogSupportInfo
when reason indicates a bugreport. We enumerate all loaded modules in our
process, and for each one we gather debug, authenticode signature, and
version information.
Fixes #7802
Signed-off-by: Aaron Klotz <aaron@tailscale.com>
2023-06-26 18:50:45 +01:00
"tailscale.com/util/osdiag"
2023-11-09 20:55:46 +00:00
"tailscale.com/util/osuser"
2023-09-05 17:02:40 +01:00
"tailscale.com/util/rands"
2021-08-19 16:36:13 +01:00
"tailscale.com/version"
2023-09-22 16:49:09 +01:00
"tailscale.com/wgengine/magicsock"
2021-02-15 18:41:52 +00:00
)
2022-10-09 16:57:02 +01:00
type localAPIHandler func ( * Handler , http . ResponseWriter , * http . Request )
// handler is the set of LocalAPI handlers, keyed by the part of the
// Request.URL.Path after "/localapi/v0/". If the key ends with a trailing slash
// then it's a prefix match.
var handler = map [ string ] localAPIHandler {
// The prefix match handlers end with a slash:
2023-11-02 16:34:28 +00:00
"cert/" : ( * Handler ) . serveCert ,
"file-put/" : ( * Handler ) . serveFilePut ,
"files/" : ( * Handler ) . serveFiles ,
"profiles/" : ( * Handler ) . serveProfiles ,
2022-10-09 16:57:02 +01:00
// The other /localapi/v0/NAME handlers are exact matches and contain only NAME
// without a trailing slash:
2023-01-03 23:39:32 +00:00
"bugreport" : ( * Handler ) . serveBugReport ,
"check-ip-forwarding" : ( * Handler ) . serveCheckIPForwarding ,
2023-11-09 19:34:41 +00:00
"check-udp-gro-forwarding" : ( * Handler ) . serveCheckUDPGROForwarding ,
2023-01-03 23:39:32 +00:00
"check-prefs" : ( * Handler ) . serveCheckPrefs ,
"component-debug-logging" : ( * Handler ) . serveComponentDebugLogging ,
"debug" : ( * Handler ) . serveDebug ,
"debug-derp-region" : ( * Handler ) . serveDebugDERPRegion ,
2024-01-05 16:28:09 +00:00
"debug-dial-types" : ( * Handler ) . serveDebugDialTypes ,
2023-01-03 23:39:32 +00:00
"debug-packet-filter-matches" : ( * Handler ) . serveDebugPacketFilterMatches ,
"debug-packet-filter-rules" : ( * Handler ) . serveDebugPacketFilterRules ,
2023-03-02 23:05:30 +00:00
"debug-portmap" : ( * Handler ) . serveDebugPortmap ,
2023-02-21 20:57:08 +00:00
"debug-peer-endpoint-changes" : ( * Handler ) . serveDebugPeerEndpointChanges ,
2023-01-19 22:28:49 +00:00
"debug-capture" : ( * Handler ) . serveDebugCapture ,
2023-03-21 23:16:25 +00:00
"debug-log" : ( * Handler ) . serveDebugLog ,
2023-01-03 23:39:32 +00:00
"derpmap" : ( * Handler ) . serveDERPMap ,
"dev-set-state-store" : ( * Handler ) . serveDevSetStateStore ,
2023-01-29 22:04:40 +00:00
"set-push-device-token" : ( * Handler ) . serveSetPushDeviceToken ,
2023-10-31 01:35:53 +00:00
"handle-push-message" : ( * Handler ) . serveHandlePushMessage ,
2023-01-03 23:39:32 +00:00
"dial" : ( * Handler ) . serveDial ,
"file-targets" : ( * Handler ) . serveFileTargets ,
"goroutines" : ( * Handler ) . serveGoroutines ,
"id-token" : ( * Handler ) . serveIDToken ,
"login-interactive" : ( * Handler ) . serveLoginInteractive ,
"logout" : ( * Handler ) . serveLogout ,
2022-12-24 04:54:30 +00:00
"logtap" : ( * Handler ) . serveLogTap ,
2023-01-03 23:39:32 +00:00
"metrics" : ( * Handler ) . serveMetrics ,
"ping" : ( * Handler ) . servePing ,
"prefs" : ( * Handler ) . servePrefs ,
"pprof" : ( * Handler ) . servePprof ,
2023-10-11 21:55:57 +01:00
"reload-config" : ( * Handler ) . reloadConfig ,
2023-01-27 23:41:03 +00:00
"reset-auth" : ( * Handler ) . serveResetAuth ,
2023-01-03 23:39:32 +00:00
"serve-config" : ( * Handler ) . serveServeConfig ,
"set-dns" : ( * Handler ) . serveSetDNS ,
"set-expiry-sooner" : ( * Handler ) . serveSetExpirySooner ,
2024-02-29 17:36:35 +00:00
"set-gui-visible" : ( * Handler ) . serveSetGUIVisible ,
2024-02-09 17:26:43 +00:00
"tailfs/fileserver-address" : ( * Handler ) . serveTailFSFileServerAddr ,
2024-02-02 18:45:32 +00:00
"tailfs/shares" : ( * Handler ) . serveShares ,
2023-01-03 23:39:32 +00:00
"start" : ( * Handler ) . serveStart ,
"status" : ( * Handler ) . serveStatus ,
"tka/init" : ( * Handler ) . serveTKAInit ,
"tka/log" : ( * Handler ) . serveTKALog ,
"tka/modify" : ( * Handler ) . serveTKAModify ,
"tka/sign" : ( * Handler ) . serveTKASign ,
"tka/status" : ( * Handler ) . serveTKAStatus ,
"tka/disable" : ( * Handler ) . serveTKADisable ,
"tka/force-local-disable" : ( * Handler ) . serveTKALocalDisable ,
2023-03-01 20:47:29 +00:00
"tka/affected-sigs" : ( * Handler ) . serveTKAAffectedSigs ,
2023-03-02 21:24:26 +00:00
"tka/wrap-preauth-key" : ( * Handler ) . serveTKAWrapPreauthKey ,
2023-06-13 19:39:23 +01:00
"tka/verify-deeplink" : ( * Handler ) . serveTKAVerifySigningDeeplink ,
2023-07-18 23:13:36 +01:00
"tka/generate-recovery-aum" : ( * Handler ) . serveTKAGenerateRecoveryAUM ,
"tka/cosign-recovery-aum" : ( * Handler ) . serveTKACosignRecoveryAUM ,
"tka/submit-recovery-aum" : ( * Handler ) . serveTKASubmitRecoveryAUM ,
2023-01-03 23:39:32 +00:00
"upload-client-metrics" : ( * Handler ) . serveUploadClientMetrics ,
"watch-ipn-bus" : ( * Handler ) . serveWatchIPNBus ,
"whois" : ( * Handler ) . serveWhoIs ,
2023-08-02 15:56:18 +01:00
"query-feature" : ( * Handler ) . serveQueryFeature ,
2023-11-09 21:00:47 +00:00
"update/check" : ( * Handler ) . serveUpdateCheck ,
"update/install" : ( * Handler ) . serveUpdateInstall ,
"update/progress" : ( * Handler ) . serveUpdateProgress ,
2022-10-09 16:57:02 +01:00
}
2022-07-08 19:57:34 +01:00
var (
// The clientmetrics package is stateful, but we want to expose a simple
// imperative API to local clients, so we need to keep track of
// clientmetric.Metric instances that we've created for them. These need to
// be globals because we end up creating many Handler instances for the
// lifetime of a client.
metricsMu sync . Mutex
metrics = map [ string ] * clientmetric . Metric { }
)
2023-04-18 00:01:41 +01:00
// NewHandler creates a new LocalAPI HTTP handler. All parameters except netMon
// are required (if non-nil it's used to do faster interface lookups).
func NewHandler ( b * ipnlocal . LocalBackend , logf logger . Logf , netMon * netmon . Monitor , logID logid . PublicID ) * Handler {
2023-07-27 20:41:31 +01:00
return & Handler { b : b , logf : logf , netMon : netMon , backendLogID : logID , clock : tstime . StdClock { } }
2021-02-15 18:41:52 +00:00
}
type Handler struct {
// RequiredPassword, if non-empty, forces all HTTP
// requests to have HTTP basic auth with this password.
// It's used by the sandboxed macOS sameuserproof GUI auth mechanism.
RequiredPassword string
// PermitRead is whether read-only HTTP handlers are allowed.
PermitRead bool
// PermitWrite is whether mutating HTTP handlers are allowed.
2022-01-25 18:33:11 +00:00
// If PermitWrite is true, everything is allowed.
// It effectively means that the user is root or the admin
// (operator user).
2021-02-15 18:41:52 +00:00
PermitWrite bool
2022-01-25 18:33:11 +00:00
// PermitCert is whether the client is additionally granted
// cert fetching access.
PermitCert bool
2023-11-09 20:55:46 +00:00
// ConnIdentity is the identity of the client connected to the Handler.
ConnIdentity * ipnauth . ConnIdentity
// Test-only override for connIsLocalAdmin method. If non-nil,
// connIsLocalAdmin returns this value.
testConnIsLocalAdmin * bool
ipn, safesocket: use Windows token in LocalAPI
On Windows, the idiomatic way to check access on a named pipe is for
the server to impersonate the client on its current OS thread, perform
access checks using the client's access token, and then revert the OS
thread's access token back to its true self.
The access token is a better representation of the client's rights than just
a username/userid check, as it represents the client's effective rights
at connection time, which might differ from their normal rights.
This patch updates safesocket to do the aforementioned impersonation,
extract the token handle, and then revert the impersonation. We retain
the token handle for the remaining duration of the connection (the token
continues to be valid even after we have reverted back to self).
Since the token is a property of the connection, I changed ipnauth to wrap
the concrete net.Conn to include the token. I then plumbed that change
through ipnlocal, ipnserver, and localapi as necessary.
I also added a PermitLocalAdmin flag to the localapi Handler which I intend
to use for controlling access to a few new localapi endpoints intended
for configuring auto-update.
Updates https://github.com/tailscale/tailscale/issues/755
Signed-off-by: Aaron Klotz <aaron@tailscale.com>
2023-10-25 21:48:05 +01:00
2021-03-30 23:59:44 +01:00
b * ipnlocal . LocalBackend
logf logger . Logf
2023-04-18 00:01:41 +01:00
netMon * netmon . Monitor // optional; nil means interfaces will be looked up on-demand
2023-03-23 17:49:56 +00:00
backendLogID logid . PublicID
2023-07-27 20:41:31 +01:00
clock tstime . Clock
2021-02-15 18:41:52 +00:00
}
func ( h * Handler ) ServeHTTP ( w http . ResponseWriter , r * http . Request ) {
if h . b == nil {
http . Error ( w , "server has no local backend" , http . StatusInternalServerError )
return
}
2023-02-27 16:16:11 +00:00
if r . Referer ( ) != "" || r . Header . Get ( "Origin" ) != "" || ! h . validHost ( r . Host ) {
2022-12-09 22:21:53 +00:00
metricInvalidRequests . Add ( 1 )
2022-11-16 15:19:07 +00:00
http . Error ( w , "invalid localapi request" , http . StatusForbidden )
return
}
2023-02-11 06:20:36 +00:00
w . Header ( ) . Set ( "Tailscale-Version" , version . Long ( ) )
2023-01-19 20:40:58 +00:00
w . Header ( ) . Set ( "Tailscale-Cap" , strconv . Itoa ( int ( tailcfg . CurrentCapabilityVersion ) ) )
2022-11-17 14:24:21 +00:00
w . Header ( ) . Set ( "Content-Security-Policy" , ` default-src 'none'; frame-ancestors 'none'; script-src 'none'; script-src-elem 'none'; script-src-attr 'none' ` )
w . Header ( ) . Set ( "X-Frame-Options" , "DENY" )
w . Header ( ) . Set ( "X-Content-Type-Options" , "nosniff" )
2021-02-15 18:41:52 +00:00
if h . RequiredPassword != "" {
_ , pass , ok := r . BasicAuth ( )
if ! ok {
2022-12-09 22:21:53 +00:00
metricInvalidRequests . Add ( 1 )
2021-02-15 18:41:52 +00:00
http . Error ( w , "auth required" , http . StatusUnauthorized )
return
}
if pass != h . RequiredPassword {
2022-12-09 22:21:53 +00:00
metricInvalidRequests . Add ( 1 )
2021-02-15 18:41:52 +00:00
http . Error ( w , "bad password" , http . StatusForbidden )
return
}
}
2022-10-09 16:57:02 +01:00
if fn , ok := handlerForPath ( r . URL . Path ) ; ok {
fn ( h , w , r )
} else {
http . NotFound ( w , r )
}
}
2023-02-27 16:16:11 +00:00
// validLocalHostForTesting allows loopback handlers without RequiredPassword for testing.
var validLocalHostForTesting = false
2023-01-30 17:13:45 +00:00
2022-11-16 15:19:07 +00:00
// validHost reports whether h is a valid Host header value for a LocalAPI request.
2023-02-27 16:16:11 +00:00
func ( h * Handler ) validHost ( hostname string ) bool {
2022-11-16 15:19:07 +00:00
// The client code sends a hostname of "local-tailscaled.sock".
2023-02-27 16:16:11 +00:00
switch hostname {
2022-11-16 15:19:07 +00:00
case "" , apitype . LocalAPIHost :
return true
}
2023-02-27 16:16:11 +00:00
if ! validLocalHostForTesting && h . RequiredPassword == "" {
return false // only allow localhost with basic auth or in tests
2023-01-30 17:13:45 +00:00
}
2023-02-27 16:16:11 +00:00
host , _ , err := net . SplitHostPort ( hostname )
2022-11-16 15:19:07 +00:00
if err != nil {
return false
}
2022-11-16 19:35:01 +00:00
if host == "localhost" {
return true
}
2023-01-30 17:13:45 +00:00
addr , err := netip . ParseAddr ( host )
2022-11-16 19:35:01 +00:00
if err != nil {
2022-11-16 15:19:07 +00:00
return false
}
2022-11-16 19:35:01 +00:00
return addr . IsLoopback ( )
2022-11-16 15:19:07 +00:00
}
2022-10-09 16:57:02 +01:00
// handlerForPath returns the LocalAPI handler for the provided Request.URI.Path.
// (the path doesn't include any query parameters)
func handlerForPath ( urlPath string ) ( h localAPIHandler , ok bool ) {
if urlPath == "/" {
return ( * Handler ) . serveLocalAPIRoot , true
}
2023-02-01 21:43:06 +00:00
suff , ok := strings . CutPrefix ( urlPath , "/localapi/v0/" )
2022-10-09 16:57:02 +01:00
if ! ok {
// Currently all LocalAPI methods start with "/localapi/v0/" to signal
// to people that they're not necessarily stable APIs. In practice we'll
// probably need to keep them pretty stable anyway, but for now treat
// them as an internal implementation detail.
return nil , false
}
if fn , ok := handler [ suff ] ; ok {
// Here we match exact handler suffixes like "status" or ones with a
// slash already in their name, like "tka/status".
return fn , true
}
// Otherwise, it might be a prefix match like "files/*" which we look up
// by the prefix including first trailing slash.
if i := strings . IndexByte ( suff , '/' ) ; i != - 1 {
suff = suff [ : i + 1 ]
if fn , ok := handler [ suff ] ; ok {
return fn , true
}
2021-02-15 18:41:52 +00:00
}
2022-10-09 16:57:02 +01:00
return nil , false
}
func ( * Handler ) serveLocalAPIRoot ( w http . ResponseWriter , r * http . Request ) {
io . WriteString ( w , "tailscaled\n" )
2021-02-15 18:41:52 +00:00
}
2022-03-29 20:43:26 +01:00
// serveIDToken handles requests to get an OIDC ID token.
func ( h * Handler ) serveIDToken ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "id-token access denied" , http . StatusForbidden )
return
}
nm := h . b . NetMap ( )
if nm == nil {
http . Error ( w , "no netmap" , http . StatusServiceUnavailable )
return
}
aud := strings . TrimSpace ( r . FormValue ( "aud" ) )
if len ( aud ) == 0 {
http . Error ( w , "no audience requested" , http . StatusBadRequest )
return
}
req := & tailcfg . TokenRequest {
CapVersion : tailcfg . CurrentCapabilityVersion ,
Audience : aud ,
NodeKey : nm . NodeKey ,
}
b , err := json . Marshal ( req )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
2022-03-29 20:43:26 +01:00
return
}
httpReq , err := http . NewRequest ( "POST" , "https://unused/machine/id-token" , bytes . NewReader ( b ) )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
2022-03-29 20:43:26 +01:00
return
}
resp , err := h . b . DoNoiseRequest ( httpReq )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
2022-03-29 20:43:26 +01:00
return
}
defer resp . Body . Close ( )
w . WriteHeader ( resp . StatusCode )
if _ , err := io . Copy ( w , resp . Body ) ; err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
2022-03-29 20:43:26 +01:00
return
}
}
2021-03-30 23:59:44 +01:00
func ( h * Handler ) serveBugReport ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitRead {
http . Error ( w , "bugreport access denied" , http . StatusForbidden )
return
}
2022-11-18 05:40:40 +00:00
if r . Method != "POST" {
http . Error ( w , "only POST allowed" , http . StatusMethodNotAllowed )
return
}
2023-01-05 19:00:42 +00:00
defer h . b . TryFlushLogs ( ) // kick off upload after bugreport's done logging
2021-03-30 23:59:44 +01:00
2022-10-15 18:31:35 +01:00
logMarker := func ( ) string {
2023-09-05 17:02:40 +01:00
return fmt . Sprintf ( "BUG-%v-%v-%v" , h . backendLogID , h . clock . Now ( ) . UTC ( ) . Format ( "20060102150405Z" ) , rands . HexString ( 16 ) )
2022-10-15 18:31:35 +01:00
}
2022-09-13 15:09:57 +01:00
if envknob . NoLogsNoSupport ( ) {
2022-10-15 18:31:35 +01:00
logMarker = func ( ) string { return "BUG-NO-LOGS-NO-SUPPORT-this-node-has-had-its-logging-disabled" }
2022-09-13 15:09:57 +01:00
}
2022-10-15 18:31:35 +01:00
startMarker := logMarker ( )
h . logf ( "user bugreport: %s" , startMarker )
if note := r . URL . Query ( ) . Get ( "note" ) ; len ( note ) > 0 {
2021-03-30 23:59:44 +01:00
h . logf ( "user bugreport note: %s" , note )
}
2022-10-03 15:54:46 +01:00
hi , _ := json . Marshal ( hostinfo . New ( ) )
h . logf ( "user bugreport hostinfo: %s" , hi )
if err := health . OverallError ( ) ; err != nil {
h . logf ( "user bugreport health: %s" , err . Error ( ) )
} else {
h . logf ( "user bugreport health: ok" )
}
2023-02-07 16:43:55 +00:00
// Information about the current node from the netmap
2023-02-03 15:53:08 +00:00
if nm := h . b . NetMap ( ) ; nm != nil {
2023-08-21 18:53:57 +01:00
if self := nm . SelfNode ; self . Valid ( ) {
h . logf ( "user bugreport node info: nodeid=%q stableid=%q expiry=%q" , self . ID ( ) , self . StableID ( ) , self . KeyExpiry ( ) . Format ( time . RFC3339 ) )
2023-02-03 15:53:08 +00:00
}
h . logf ( "user bugreport public keys: machine=%q node=%q" , nm . MachineKey , nm . NodeKey )
} else {
h . logf ( "user bugreport netmap: no active netmap" )
}
2023-02-07 16:43:55 +00:00
// Print all envknobs; we otherwise only print these on startup, and
// printing them here ensures we don't have to go spelunking through
// logs for them.
envknob . LogCurrent ( logger . WithPrefix ( h . logf , "user bugreport: " ) )
go.mod, cmd/tailscaled, ipn/localapi, util/osdiag, util/winutil, util/winutil/authenticode: add Windows module list to OS-specific logs that are written upon bugreport
* We update wingoes to pick up new version information functionality
(See pe/version.go in the https://github.com/dblohm7/wingoes repo);
* We move the existing LogSupportInfo code (including necessary syscall
stubs) out of util/winutil into a new package, util/osdiag, and implement
the public LogSupportInfo function may be implemented for other platforms
as needed;
* We add a new reason argument to LogSupportInfo and wire that into
localapi's bugreport implementation;
* We add module information to the Windows implementation of LogSupportInfo
when reason indicates a bugreport. We enumerate all loaded modules in our
process, and for each one we gather debug, authenticode signature, and
version information.
Fixes #7802
Signed-off-by: Aaron Klotz <aaron@tailscale.com>
2023-06-26 18:50:45 +01:00
// OS-specific details
osdiag . LogSupportInfo ( logger . WithPrefix ( h . logf , "user bugreport OS: " ) , osdiag . LogSupportInfoReasonBugReport )
2022-10-15 18:31:35 +01:00
if defBool ( r . URL . Query ( ) . Get ( "diagnose" ) , false ) {
2022-09-26 18:07:28 +01:00
h . b . Doctor ( r . Context ( ) , logger . WithPrefix ( h . logf , "diag: " ) )
}
2021-03-30 23:59:44 +01:00
w . Header ( ) . Set ( "Content-Type" , "text/plain" )
2022-10-15 18:31:35 +01:00
fmt . Fprintln ( w , startMarker )
// Nothing else to do if we're not in record mode; we wrote the marker
// above, so we can just finish our response now.
if ! defBool ( r . URL . Query ( ) . Get ( "record" ) , false ) {
return
}
2023-07-27 20:41:31 +01:00
until := h . clock . Now ( ) . Add ( 12 * time . Hour )
2022-10-15 18:31:35 +01:00
var changed map [ string ] bool
for _ , component := range [ ] string { "magicsock" } {
if h . b . GetComponentDebugLogging ( component ) . IsZero ( ) {
if err := h . b . SetComponentDebugLogging ( component , until ) ; err != nil {
h . logf ( "bugreport: error setting component %q logging: %v" , component , err )
continue
}
mak . Set ( & changed , component , true )
}
}
defer func ( ) {
for component := range changed {
h . b . SetComponentDebugLogging ( component , time . Time { } )
}
} ( )
// NOTE(andrew): if we have anything else we want to do while recording
// a bugreport, we can add it here.
// Read from the client; this will also return when the client closes
// the connection.
var buf [ 1 ] byte
_ , err := r . Body . Read ( buf [ : ] )
switch {
case err == nil :
// good
case errors . Is ( err , io . EOF ) :
// good
case errors . Is ( err , io . ErrUnexpectedEOF ) :
// this happens when Ctrl-C'ing the tailscale client; don't
// bother logging an error
default :
// Log but continue anyway.
h . logf ( "user bugreport: error reading body: %v" , err )
}
// Generate another log marker and return it to the client.
endMarker := logMarker ( )
h . logf ( "user bugreport end: %s" , endMarker )
fmt . Fprintln ( w , endMarker )
2021-03-30 23:59:44 +01:00
}
2021-02-15 18:41:52 +00:00
func ( h * Handler ) serveWhoIs ( w http . ResponseWriter , r * http . Request ) {
2023-10-10 18:39:08 +01:00
h . serveWhoIsWithBackend ( w , r , h . b )
}
// localBackendWhoIsMethods is the subset of ipn.LocalBackend as needed
// by the localapi WhoIs method.
type localBackendWhoIsMethods interface {
WhoIs ( netip . AddrPort ) ( n tailcfg . NodeView , u tailcfg . UserProfile , ok bool )
PeerCaps ( netip . Addr ) tailcfg . PeerCapMap
}
func ( h * Handler ) serveWhoIsWithBackend ( w http . ResponseWriter , r * http . Request , b localBackendWhoIsMethods ) {
2021-02-15 18:41:52 +00:00
if ! h . PermitRead {
http . Error ( w , "whois access denied" , http . StatusForbidden )
return
}
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 05:14:09 +01:00
var ipp netip . AddrPort
2021-03-15 21:59:35 +00:00
if v := r . FormValue ( "addr" ) ; v != "" {
2023-10-10 18:39:08 +01:00
if ip , err := netip . ParseAddr ( v ) ; err == nil {
ipp = netip . AddrPortFrom ( ip , 0 )
} else {
var err error
ipp , err = netip . ParseAddrPort ( v )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "invalid 'addr' parameter" , http . StatusBadRequest )
2023-10-10 18:39:08 +01:00
return
}
2021-02-15 18:41:52 +00:00
}
} else {
2023-10-13 23:40:10 +01:00
http . Error ( w , "missing 'addr' parameter" , http . StatusBadRequest )
2021-02-15 18:41:52 +00:00
return
}
2021-03-15 21:59:35 +00:00
n , u , ok := b . WhoIs ( ipp )
2021-02-15 18:41:52 +00:00
if ! ok {
2023-10-13 23:40:10 +01:00
http . Error ( w , "no match for IP:port" , http . StatusNotFound )
2021-02-15 18:41:52 +00:00
return
}
2021-04-13 16:13:46 +01:00
res := & apitype . WhoIsResponse {
2023-08-18 15:57:44 +01:00
Node : n . AsStruct ( ) , // always non-nil per WhoIsResponse contract
UserProfile : & u , // always non-nil per WhoIsResponse contract
2023-10-10 18:39:08 +01:00
}
if n . Addresses ( ) . Len ( ) > 0 {
res . CapMap = b . PeerCaps ( n . Addresses ( ) . At ( 0 ) . Addr ( ) )
2021-02-15 18:41:52 +00:00
}
j , err := json . MarshalIndent ( res , "" , "\t" )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "JSON encoding error" , http . StatusInternalServerError )
2021-02-15 18:41:52 +00:00
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
w . Write ( j )
}
2021-03-05 20:07:00 +00:00
func ( h * Handler ) serveGoroutines ( w http . ResponseWriter , r * http . Request ) {
// Require write access out of paranoia that the goroutine dump
// (at least its arguments) might contain something sensitive.
if ! h . PermitWrite {
http . Error ( w , "goroutine dump access denied" , http . StatusForbidden )
return
}
buf := make ( [ ] byte , 2 << 20 )
buf = buf [ : runtime . Stack ( buf , true ) ]
w . Header ( ) . Set ( "Content-Type" , "text/plain" )
w . Write ( buf )
}
2021-03-19 02:34:59 +00:00
2022-12-24 04:54:30 +00:00
// serveLogTap taps into the tailscaled/logtail server output and streams
// it to the client.
func ( h * Handler ) serveLogTap ( w http . ResponseWriter , r * http . Request ) {
ctx := r . Context ( )
// Require write access (~root) as the logs could contain something
// sensitive.
if ! h . PermitWrite {
http . Error ( w , "logtap access denied" , http . StatusForbidden )
return
}
if r . Method != "GET" {
http . Error ( w , "GET required" , http . StatusMethodNotAllowed )
return
}
f , ok := w . ( http . Flusher )
if ! ok {
http . Error ( w , "streaming unsupported" , http . StatusInternalServerError )
return
}
io . WriteString ( w , ` { "text":"[logtap connected]\n"} ` + "\n" )
f . Flush ( )
msgc := make ( chan string , 16 )
unreg := logtail . RegisterLogTap ( msgc )
defer unreg ( )
for {
select {
case <- ctx . Done ( ) :
return
case msg := <- msgc :
io . WriteString ( w , msg )
f . Flush ( )
}
}
}
2020-12-14 02:51:24 +00:00
func ( h * Handler ) serveMetrics ( w http . ResponseWriter , r * http . Request ) {
// Require write access out of paranoia that the metrics
// might contain something sensitive.
if ! h . PermitWrite {
http . Error ( w , "metric access denied" , http . StatusForbidden )
return
}
w . Header ( ) . Set ( "Content-Type" , "text/plain" )
clientmetric . WritePrometheusExpositionFormat ( w )
}
2021-12-28 21:39:04 +00:00
func ( h * Handler ) serveDebug ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "debug access denied" , http . StatusForbidden )
return
}
if r . Method != "POST" {
http . Error ( w , "POST required" , http . StatusMethodNotAllowed )
return
}
2022-12-03 04:13:36 +00:00
// The action is normally in a POST form parameter, but
// some actions (like "notify") want a full JSON body, so
// permit some to have their action in a header.
var action string
switch v := r . Header . Get ( "Debug-Action" ) ; v {
case "notify" :
action = v
default :
action = r . FormValue ( "action" )
}
2021-12-28 21:39:04 +00:00
var err error
switch action {
2023-11-15 23:10:45 +00:00
case "derp-set-homeless" :
h . b . MagicConn ( ) . SetHomeless ( true )
case "derp-unset-homeless" :
h . b . MagicConn ( ) . SetHomeless ( false )
2021-12-28 21:39:04 +00:00
case "rebind" :
err = h . b . DebugRebind ( )
case "restun" :
err = h . b . DebugReSTUN ( )
2022-11-25 15:22:20 +00:00
case "enginestatus" :
// serveRequestEngineStatus kicks off a call to RequestEngineStatus (via
// LocalBackend => UserspaceEngine => LocalBackend =>
// ipn.Notify{Engine}).
//
// This is a temporary (2022-11-25) measure for the Windows client's
// move to the LocalAPI HTTP interface. It was polling this over the IPN
// bus before every 2 seconds which is wasteful. We should add a bit to
// WatchIPNMask instead to let an IPN bus watcher say that it's
// interested in that info and then only send it on demand, not via
// polling. But for now we keep this interface because that's what the
// client already did. A future change will remove this, so don't depend
// on it.
h . b . RequestEngineStatus ( )
2022-12-03 04:13:36 +00:00
case "notify" :
var n ipn . Notify
err = json . NewDecoder ( r . Body ) . Decode ( & n )
if err != nil {
break
}
h . b . DebugNotify ( n )
2023-08-11 05:45:16 +01:00
case "break-tcp-conns" :
err = h . b . DebugBreakTCPConns ( )
case "break-derp-conns" :
err = h . b . DebugBreakDERPConns ( )
2023-09-24 16:08:28 +01:00
case "force-netmap-update" :
h . b . DebugForceNetmapUpdate ( )
2023-09-12 05:44:38 +01:00
case "control-knobs" :
k := h . b . ControlKnobs ( )
w . Header ( ) . Set ( "Content-Type" , "application/json" )
err = json . NewEncoder ( w ) . Encode ( k . AsDebugJSON ( ) )
if err == nil {
return
}
2023-10-07 04:39:23 +01:00
case "pick-new-derp" :
err = h . b . DebugPickNewDERP ( )
2021-12-28 21:39:04 +00:00
case "" :
err = fmt . Errorf ( "missing parameter 'action'" )
default :
err = fmt . Errorf ( "unknown action %q" , action )
}
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , err . Error ( ) , http . StatusBadRequest )
2021-12-28 21:39:04 +00:00
return
}
w . Header ( ) . Set ( "Content-Type" , "text/plain" )
io . WriteString ( w , "done\n" )
}
2022-11-07 21:04:10 +00:00
func ( h * Handler ) serveDevSetStateStore ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "debug access denied" , http . StatusForbidden )
return
}
if r . Method != "POST" {
http . Error ( w , "POST required" , http . StatusMethodNotAllowed )
return
}
if err := h . b . SetDevStateStore ( r . FormValue ( "key" ) , r . FormValue ( "value" ) ) ; err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
2022-11-07 21:04:10 +00:00
return
}
w . Header ( ) . Set ( "Content-Type" , "text/plain" )
io . WriteString ( w , "done\n" )
}
2023-01-03 23:39:32 +00:00
func ( h * Handler ) serveDebugPacketFilterRules ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "debug access denied" , http . StatusForbidden )
return
}
nm := h . b . NetMap ( )
if nm == nil {
http . Error ( w , "no netmap" , http . StatusNotFound )
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
enc := json . NewEncoder ( w )
enc . SetIndent ( "" , "\t" )
enc . Encode ( nm . PacketFilterRules )
}
func ( h * Handler ) serveDebugPacketFilterMatches ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "debug access denied" , http . StatusForbidden )
return
}
nm := h . b . NetMap ( )
if nm == nil {
http . Error ( w , "no netmap" , http . StatusNotFound )
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
enc := json . NewEncoder ( w )
enc . SetIndent ( "" , "\t" )
enc . Encode ( nm . PacketFilter )
}
2023-03-02 23:05:30 +00:00
func ( h * Handler ) serveDebugPortmap ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "debug access denied" , http . StatusForbidden )
return
}
w . Header ( ) . Set ( "Content-Type" , "text/plain" )
dur , err := time . ParseDuration ( r . FormValue ( "duration" ) )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusBadRequest )
return
}
gwSelf := r . FormValue ( "gateway_and_self" )
// Update portmapper debug flags
debugKnobs := & portmapper . DebugKnobs { VerboseLogs : true }
switch r . FormValue ( "type" ) {
case "" :
case "pmp" :
debugKnobs . DisablePCP = true
debugKnobs . DisableUPnP = true
case "pcp" :
debugKnobs . DisablePMP = true
debugKnobs . DisableUPnP = true
case "upnp" :
debugKnobs . DisablePCP = true
debugKnobs . DisablePMP = true
default :
http . Error ( w , "unknown portmap debug type" , http . StatusBadRequest )
return
}
2023-08-21 21:53:47 +01:00
if defBool ( r . FormValue ( "log_http" ) , false ) {
debugKnobs . LogHTTP = true
}
2023-03-04 18:03:03 +00:00
var (
logLock sync . Mutex
handlerDone bool
)
2023-03-02 23:05:30 +00:00
logf := func ( format string , args ... any ) {
if ! strings . HasSuffix ( format , "\n" ) {
format = format + "\n"
}
logLock . Lock ( )
defer logLock . Unlock ( )
2023-03-04 18:03:03 +00:00
// The portmapper can call this log function after the HTTP
// handler returns, which is not allowed and can cause a panic.
// If this happens, ignore the log lines since this typically
// occurs due to a client disconnect.
if handlerDone {
return
}
2023-03-02 23:05:30 +00:00
// Write and flush each line to the client so that output is streamed
fmt . Fprintf ( w , format , args ... )
if f , ok := w . ( http . Flusher ) ; ok {
f . Flush ( )
}
}
2023-03-04 18:03:03 +00:00
defer func ( ) {
logLock . Lock ( )
handlerDone = true
logLock . Unlock ( )
} ( )
2023-03-02 23:05:30 +00:00
ctx , cancel := context . WithTimeout ( r . Context ( ) , dur )
defer cancel ( )
done := make ( chan bool , 1 )
var c * portmapper . Client
2023-09-11 20:03:39 +01:00
c = portmapper . NewClient ( logger . WithPrefix ( logf , "portmapper: " ) , h . netMon , debugKnobs , h . b . ControlKnobs ( ) , func ( ) {
2023-03-02 23:05:30 +00:00
logf ( "portmapping changed." )
logf ( "have mapping: %v" , c . HaveMapping ( ) )
if ext , ok := c . GetCachedMappingOrStartCreatingOne ( ) ; ok {
logf ( "cb: mapping: %v" , ext )
select {
case done <- true :
default :
}
return
}
logf ( "cb: no mapping" )
} )
2023-03-05 05:45:53 +00:00
defer c . Close ( )
2023-04-18 22:26:58 +01:00
netMon , err := netmon . New ( logger . WithPrefix ( logf , "monitor: " ) )
2023-03-02 23:05:30 +00:00
if err != nil {
logf ( "error creating monitor: %v" , err )
return
}
gatewayAndSelfIP := func ( ) ( gw , self netip . Addr , ok bool ) {
if a , b , ok := strings . Cut ( gwSelf , "/" ) ; ok {
gw = netip . MustParseAddr ( a )
self = netip . MustParseAddr ( b )
return gw , self , true
}
2023-04-18 22:26:58 +01:00
return netMon . GatewayAndSelfIP ( )
2023-03-02 23:05:30 +00:00
}
c . SetGatewayLookupFunc ( gatewayAndSelfIP )
gw , selfIP , ok := gatewayAndSelfIP ( )
if ! ok {
2023-04-18 22:26:58 +01:00
logf ( "no gateway or self IP; %v" , netMon . InterfaceState ( ) )
2023-03-02 23:05:30 +00:00
return
}
logf ( "gw=%v; self=%v" , gw , selfIP )
uc , err := net . ListenPacket ( "udp" , "0.0.0.0:0" )
if err != nil {
return
}
defer uc . Close ( )
c . SetLocalPort ( uint16 ( uc . LocalAddr ( ) . ( * net . UDPAddr ) . Port ) )
res , err := c . Probe ( ctx )
if err != nil {
logf ( "error in Probe: %v" , err )
return
}
logf ( "Probe: %+v" , res )
if ! res . PCP && ! res . PMP && ! res . UPnP {
logf ( "no portmapping services available" )
return
}
if ext , ok := c . GetCachedMappingOrStartCreatingOne ( ) ; ok {
logf ( "mapping: %v" , ext )
} else {
logf ( "no mapping" )
}
select {
case <- done :
case <- ctx . Done ( ) :
if r . Context ( ) . Err ( ) == nil {
logf ( "serveDebugPortmap: context done: %v" , ctx . Err ( ) )
} else {
h . logf ( "serveDebugPortmap: context done: %v" , ctx . Err ( ) )
}
}
}
2022-10-04 04:39:45 +01:00
func ( h * Handler ) serveComponentDebugLogging ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "debug access denied" , http . StatusForbidden )
return
}
component := r . FormValue ( "component" )
secs , _ := strconv . Atoi ( r . FormValue ( "secs" ) )
2023-07-27 20:41:31 +01:00
err := h . b . SetComponentDebugLogging ( component , h . clock . Now ( ) . Add ( time . Duration ( secs ) * time . Second ) )
2022-10-04 04:39:45 +01:00
var res struct {
Error string
}
if err != nil {
res . Error = err . Error ( )
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
json . NewEncoder ( w ) . Encode ( res )
}
2024-01-05 16:28:09 +00:00
func ( h * Handler ) serveDebugDialTypes ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "debug-dial-types access denied" , http . StatusForbidden )
return
}
if r . Method != httpm . POST {
http . Error ( w , "only POST allowed" , http . StatusMethodNotAllowed )
return
}
ip := r . FormValue ( "ip" )
port := r . FormValue ( "port" )
network := r . FormValue ( "network" )
addr := ip + ":" + port
if _ , err := netip . ParseAddrPort ( addr ) ; err != nil {
w . WriteHeader ( http . StatusBadRequest )
fmt . Fprintf ( w , "invalid address %q: %v" , addr , err )
return
}
ctx , cancel := context . WithTimeout ( r . Context ( ) , 5 * time . Second )
defer cancel ( )
var bareDialer net . Dialer
dialer := h . b . Dialer ( )
var peerDialer net . Dialer
peerDialer . Control = dialer . PeerDialControlFunc ( )
// Kick off a dial with each available dialer in parallel.
dialers := [ ] struct {
name string
dial func ( context . Context , string , string ) ( net . Conn , error )
} {
{ "SystemDial" , dialer . SystemDial } ,
{ "UserDial" , dialer . UserDial } ,
{ "PeerDial" , peerDialer . DialContext } ,
{ "BareDial" , bareDialer . DialContext } ,
}
type result struct {
name string
conn net . Conn
err error
}
results := make ( chan result , len ( dialers ) )
var wg sync . WaitGroup
for _ , dialer := range dialers {
dialer := dialer // loop capture
wg . Add ( 1 )
go func ( ) {
defer wg . Done ( )
conn , err := dialer . dial ( ctx , network , addr )
results <- result { dialer . name , conn , err }
} ( )
}
wg . Wait ( )
for i := 0 ; i < len ( dialers ) ; i ++ {
res := <- results
fmt . Fprintf ( w , "[%s] connected=%v err=%v\n" , res . name , res . conn != nil , res . err )
if res . conn != nil {
res . conn . Close ( )
}
}
}
2022-11-10 19:41:04 +00:00
// servePprofFunc is the implementation of Handler.servePprof, after auth,
2021-09-23 17:20:14 +01:00
// for platforms where we want to link it in.
2022-11-10 19:41:04 +00:00
var servePprofFunc func ( http . ResponseWriter , * http . Request )
2021-09-23 17:20:14 +01:00
2022-11-10 19:41:04 +00:00
func ( h * Handler ) servePprof ( w http . ResponseWriter , r * http . Request ) {
2021-09-23 17:20:14 +01:00
// Require write access out of paranoia that the profile dump
// might contain something sensitive.
if ! h . PermitWrite {
http . Error ( w , "profile access denied" , http . StatusForbidden )
return
}
2022-11-10 19:41:04 +00:00
if servePprofFunc == nil {
2021-09-23 17:20:14 +01:00
http . Error ( w , "not implemented on this platform" , http . StatusServiceUnavailable )
return
}
2022-11-10 19:41:04 +00:00
servePprofFunc ( w , r )
2021-09-23 17:20:14 +01:00
}
2023-10-11 21:55:57 +01:00
func ( h * Handler ) reloadConfig ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "access denied" , http . StatusForbidden )
return
}
if r . Method != httpm . POST {
http . Error ( w , "use POST" , http . StatusMethodNotAllowed )
return
}
ok , err := h . b . ReloadConfig ( )
var res apitype . ReloadConfigResponse
res . Reloaded = ok
if err != nil {
res . Err = err . Error ( )
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
json . NewEncoder ( w ) . Encode ( & res )
}
2023-01-27 23:41:03 +00:00
func ( h * Handler ) serveResetAuth ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "reset-auth modify access denied" , http . StatusForbidden )
return
}
if r . Method != httpm . POST {
http . Error ( w , "use POST" , http . StatusMethodNotAllowed )
return
}
if err := h . b . ResetAuth ( ) ; err != nil {
http . Error ( w , "reset-auth failed: " + err . Error ( ) , http . StatusInternalServerError )
return
}
w . WriteHeader ( http . StatusNoContent )
}
2022-11-11 03:58:40 +00:00
func ( h * Handler ) serveServeConfig ( w http . ResponseWriter , r * http . Request ) {
switch r . Method {
case "GET" :
2022-12-08 03:17:40 +00:00
if ! h . PermitRead {
http . Error ( w , "serve config denied" , http . StatusForbidden )
return
}
2022-11-11 03:58:40 +00:00
config := h . b . ServeConfig ( )
2023-09-12 00:33:20 +01:00
bts , err := json . Marshal ( config )
if err != nil {
http . Error ( w , "error encoding config: " + err . Error ( ) , http . StatusInternalServerError )
return
}
sum := sha256 . Sum256 ( bts )
etag := hex . EncodeToString ( sum [ : ] )
w . Header ( ) . Set ( "Etag" , etag )
w . Header ( ) . Set ( "Content-Type" , "application/json" )
w . Write ( bts )
2022-11-11 03:58:40 +00:00
case "POST" :
2022-12-08 03:17:40 +00:00
if ! h . PermitWrite {
http . Error ( w , "serve config denied" , http . StatusForbidden )
return
}
2022-11-11 03:58:40 +00:00
configIn := new ( ipn . ServeConfig )
if err := json . NewDecoder ( r . Body ) . Decode ( configIn ) ; err != nil {
2022-12-08 03:17:40 +00:00
writeErrorJSON ( w , fmt . Errorf ( "decoding config: %w" , err ) )
2022-11-11 03:58:40 +00:00
return
}
2023-10-26 22:40:44 +01:00
// require a local admin when setting a path handler
// TODO: roll-up this Windows-specific check into either PermitWrite
// or a global admin escalation check.
2023-11-07 20:31:33 +00:00
if err := authorizeServeConfigForGOOSAndUserContext ( runtime . GOOS , configIn , h ) ; err != nil {
http . Error ( w , err . Error ( ) , http . StatusUnauthorized )
2023-10-26 22:40:44 +01:00
return
}
2023-09-12 00:33:20 +01:00
etag := r . Header . Get ( "If-Match" )
if err := h . b . SetServeConfig ( configIn , etag ) ; err != nil {
if errors . Is ( err , ipnlocal . ErrETagMismatch ) {
http . Error ( w , err . Error ( ) , http . StatusPreconditionFailed )
return
}
2022-12-08 03:17:40 +00:00
writeErrorJSON ( w , fmt . Errorf ( "updating config: %w" , err ) )
2022-11-11 03:58:40 +00:00
return
}
w . WriteHeader ( http . StatusOK )
2022-12-08 03:17:40 +00:00
default :
http . Error ( w , "method not allowed" , http . StatusMethodNotAllowed )
2022-11-11 03:58:40 +00:00
}
}
2023-11-07 20:31:33 +00:00
func authorizeServeConfigForGOOSAndUserContext ( goos string , configIn * ipn . ServeConfig , h * Handler ) error {
2023-11-09 20:55:46 +00:00
switch goos {
case "windows" , "linux" , "darwin" :
default :
2023-11-07 20:31:33 +00:00
return nil
}
2023-11-09 20:55:46 +00:00
// Only check for local admin on tailscaled-on-mac (based on "sudo"
// permissions). On sandboxed variants (MacSys and AppStore), tailscaled
// cannot serve files outside of the sandbox and this check is not
// relevant.
if goos == "darwin" && version . IsSandboxedMacOS ( ) {
2023-11-07 20:31:33 +00:00
return nil
2023-10-26 22:40:44 +01:00
}
if ! configIn . HasPathHandler ( ) {
2023-11-07 20:31:33 +00:00
return nil
}
2023-11-09 20:55:46 +00:00
if h . connIsLocalAdmin ( ) {
2023-11-07 20:31:33 +00:00
return nil
2023-10-26 22:40:44 +01:00
}
2023-11-07 20:31:33 +00:00
switch goos {
case "windows" :
return errors . New ( "must be a Windows local admin to serve a path" )
case "linux" , "darwin" :
return errors . New ( "must be root, or be an operator and able to run 'sudo tailscale' to serve a path" )
default :
// We filter goos at the start of the func, this default case
// should never happen.
panic ( "unreachable" )
}
2023-10-26 22:40:44 +01:00
}
2023-11-09 20:55:46 +00:00
// connIsLocalAdmin reports whether the connected client has administrative
// access to the local machine, for whatever that means with respect to the
// current OS.
//
// This is useful because tailscaled itself always runs with elevated rights:
// we want to avoid privilege escalation for certain mutative operations.
func ( h * Handler ) connIsLocalAdmin ( ) bool {
if h . testConnIsLocalAdmin != nil {
return * h . testConnIsLocalAdmin
}
if h . ConnIdentity == nil {
h . logf ( "[unexpected] missing ConnIdentity in LocalAPI Handler" )
return false
}
switch runtime . GOOS {
case "windows" :
tok , err := h . ConnIdentity . WindowsToken ( )
if err != nil {
if ! errors . Is ( err , ipnauth . ErrNotImplemented ) {
h . logf ( "ipnauth.ConnIdentity.WindowsToken() error: %v" , err )
}
return false
}
defer tok . Close ( )
return tok . IsElevated ( )
case "darwin" :
// Unknown, or at least unchecked on sandboxed macOS variants. Err on
// the side of less permissions.
//
// authorizeServeConfigForGOOSAndUserContext should not call
// connIsLocalAdmin on sandboxed variants anyway.
if version . IsSandboxedMacOS ( ) {
return false
}
// This is a standalone tailscaled setup, use the same logic as on
// Linux.
fallthrough
case "linux" :
uid , ok := h . ConnIdentity . Creds ( ) . UserID ( )
if ! ok {
return false
}
// root is always admin.
if uid == "0" {
return true
}
// if non-root, must be operator AND able to execute "sudo tailscale".
operatorUID := h . b . OperatorUserID ( )
if operatorUID != "" && uid != operatorUID {
return false
}
u , err := osuser . LookupByUID ( uid )
if err != nil {
return false
}
2024-02-02 18:45:32 +00:00
// Short timeout just in case sudo hangs for some reason.
2023-11-09 20:55:46 +00:00
ctx , cancel := context . WithTimeout ( context . Background ( ) , 3 * time . Second )
defer cancel ( )
if err := exec . CommandContext ( ctx , "sudo" , "--other-user=" + u . Name , "--list" , "tailscale" ) . Run ( ) ; err != nil {
return false
}
return true
default :
return false
}
}
2024-02-02 18:45:32 +00:00
func ( h * Handler ) getUsername ( ) ( string , error ) {
if h . ConnIdentity == nil {
h . logf ( "[unexpected] missing ConnIdentity in LocalAPI Handler" )
return "" , errors . New ( "missing ConnIdentity" )
}
switch runtime . GOOS {
case "windows" :
tok , err := h . ConnIdentity . WindowsToken ( )
if err != nil {
return "" , fmt . Errorf ( "get windows token: %w" , err )
}
defer tok . Close ( )
return tok . Username ( )
case "darwin" , "linux" :
uid , ok := h . ConnIdentity . Creds ( ) . UserID ( )
if ! ok {
return "" , errors . New ( "missing user ID" )
}
u , err := osuser . LookupByUID ( uid )
if err != nil {
return "" , fmt . Errorf ( "lookup user: %w" , err )
}
return u . Username , nil
default :
return "" , errors . New ( "unsupported OS" )
}
}
2021-03-31 19:55:21 +01:00
func ( h * Handler ) serveCheckIPForwarding ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitRead {
http . Error ( w , "IP forwarding check access denied" , http . StatusForbidden )
return
}
var warning string
if err := h . b . CheckIPForwarding ( ) ; err != nil {
warning = err . Error ( )
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
json . NewEncoder ( w ) . Encode ( struct {
Warning string
} {
Warning : warning ,
} )
}
2023-11-09 19:34:41 +00:00
func ( h * Handler ) serveCheckUDPGROForwarding ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitRead {
http . Error ( w , "UDP GRO forwarding check access denied" , http . StatusForbidden )
return
}
var warning string
if err := h . b . CheckUDPGROForwarding ( ) ; err != nil {
warning = err . Error ( )
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
json . NewEncoder ( w ) . Encode ( struct {
Warning string
} {
Warning : warning ,
} )
}
2021-03-19 02:34:59 +00:00
func ( h * Handler ) serveStatus ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitRead {
http . Error ( w , "status access denied" , http . StatusForbidden )
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
2021-03-19 04:07:58 +00:00
var st * ipnstate . Status
if defBool ( r . FormValue ( "peers" ) , true ) {
st = h . b . Status ( )
} else {
st = h . b . StatusWithoutPeers ( )
}
2021-03-19 02:34:59 +00:00
e := json . NewEncoder ( w )
e . SetIndent ( "" , "\t" )
2021-03-19 04:07:58 +00:00
e . Encode ( st )
}
2023-02-21 20:57:08 +00:00
func ( h * Handler ) serveDebugPeerEndpointChanges ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitRead {
http . Error ( w , "status access denied" , http . StatusForbidden )
return
}
ipStr := r . FormValue ( "ip" )
if ipStr == "" {
2023-10-13 23:40:10 +01:00
http . Error ( w , "missing 'ip' parameter" , http . StatusBadRequest )
2023-02-21 20:57:08 +00:00
return
}
ip , err := netip . ParseAddr ( ipStr )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "invalid IP" , http . StatusBadRequest )
2023-02-21 20:57:08 +00:00
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
chs , err := h . b . GetPeerEndpointChanges ( r . Context ( ) , ip )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
2023-02-21 20:57:08 +00:00
return
}
e := json . NewEncoder ( w )
e . SetIndent ( "" , "\t" )
e . Encode ( chs )
}
2022-12-01 22:39:03 +00:00
// InUseOtherUserIPNStream reports whether r is a request for the watch-ipn-bus
// handler. If so, it writes an ipn.Notify InUseOtherUser message to the user
// and returns true. Otherwise it returns false, in which case it doesn't write
// to w.
//
// Unlike the regular watch-ipn-bus handler, this one doesn't block. The caller
// (in ipnserver.Server) provides the blocking until the connection is no longer
// in use.
func InUseOtherUserIPNStream ( w http . ResponseWriter , r * http . Request , err error ) ( handled bool ) {
if r . Method != "GET" || r . URL . Path != "/localapi/v0/watch-ipn-bus" {
return false
}
js , err := json . Marshal ( & ipn . Notify {
2023-02-11 06:20:36 +00:00
Version : version . Long ( ) ,
2022-12-01 22:39:03 +00:00
State : ptr . To ( ipn . InUseOtherUser ) ,
ErrMessage : ptr . To ( err . Error ( ) ) ,
} )
if err != nil {
return false
}
js = append ( js , '\n' )
w . Header ( ) . Set ( "Content-Type" , "application/json" )
w . Write ( js )
return true
}
2022-11-22 19:41:03 +00:00
func ( h * Handler ) serveWatchIPNBus ( w http . ResponseWriter , r * http . Request ) {
2023-06-04 17:05:21 +01:00
if ! h . PermitRead {
http . Error ( w , "watch ipn bus access denied" , http . StatusForbidden )
2022-11-22 19:41:03 +00:00
return
}
f , ok := w . ( http . Flusher )
if ! ok {
http . Error ( w , "not a flusher" , http . StatusInternalServerError )
return
}
2022-11-26 20:19:16 +00:00
var mask ipn . NotifyWatchOpt
if s := r . FormValue ( "mask" ) ; s != "" {
v , err := strconv . ParseUint ( s , 10 , 64 )
if err != nil {
http . Error ( w , "bad mask" , http . StatusBadRequest )
return
}
mask = ipn . NotifyWatchOpt ( v )
}
2023-11-02 16:48:10 +00:00
// Users with only read access must request private key filtering. If they
// don't filter out private keys, require write access.
if ( mask & ipn . NotifyNoPrivateKeys ) == 0 {
if ! h . PermitWrite {
http . Error ( w , "watch IPN bus access denied, must set ipn.NotifyNoPrivateKeys when not running as admin/root or operator" , http . StatusForbidden )
return
}
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
2022-11-22 19:41:03 +00:00
ctx := r . Context ( )
2023-01-17 20:59:03 +00:00
h . b . WatchNotifications ( ctx , mask , f . Flush , func ( roNotify * ipn . Notify ) ( keepGoing bool ) {
2022-11-22 19:41:03 +00:00
js , err := json . Marshal ( roNotify )
if err != nil {
h . logf ( "json.Marshal: %v" , err )
return false
}
if _ , err := fmt . Fprintf ( w , "%s\n" , js ) ; err != nil {
return false
}
f . Flush ( )
return true
} )
}
2022-05-26 19:08:27 +01:00
func ( h * Handler ) serveLoginInteractive ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "login access denied" , http . StatusForbidden )
return
}
if r . Method != "POST" {
2023-10-13 23:40:10 +01:00
http . Error ( w , "want POST" , http . StatusBadRequest )
2022-05-26 19:08:27 +01:00
return
}
h . b . StartLoginInteractive ( )
w . WriteHeader ( http . StatusNoContent )
return
}
2022-11-22 19:41:03 +00:00
func ( h * Handler ) serveStart ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "access denied" , http . StatusForbidden )
return
}
if r . Method != "POST" {
2023-10-13 23:40:10 +01:00
http . Error ( w , "want POST" , http . StatusBadRequest )
2022-11-22 19:41:03 +00:00
return
}
var o ipn . Options
if err := json . NewDecoder ( r . Body ) . Decode ( & o ) ; err != nil {
http . Error ( w , err . Error ( ) , http . StatusBadRequest )
return
}
err := h . b . Start ( o )
if err != nil {
// TODO(bradfitz): map error to a good HTTP error
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
w . WriteHeader ( http . StatusNoContent )
}
2021-04-08 05:06:31 +01:00
func ( h * Handler ) serveLogout ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "logout access denied" , http . StatusForbidden )
return
}
if r . Method != "POST" {
2023-10-13 23:40:10 +01:00
http . Error ( w , "want POST" , http . StatusBadRequest )
2021-04-08 05:06:31 +01:00
return
}
2023-09-01 03:11:20 +01:00
err := h . b . Logout ( r . Context ( ) )
2021-04-08 05:06:31 +01:00
if err == nil {
w . WriteHeader ( http . StatusNoContent )
return
}
2023-10-13 23:40:10 +01:00
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
2021-04-08 05:06:31 +01:00
}
2021-04-07 16:27:35 +01:00
func ( h * Handler ) servePrefs ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitRead {
http . Error ( w , "prefs access denied" , http . StatusForbidden )
return
}
2022-10-23 18:07:10 +01:00
var prefs ipn . PrefsView
2021-04-12 04:49:07 +01:00
switch r . Method {
case "PATCH" :
2021-04-12 05:31:15 +01:00
if ! h . PermitWrite {
http . Error ( w , "prefs write access denied" , http . StatusForbidden )
return
}
2021-04-12 00:10:31 +01:00
mp := new ( ipn . MaskedPrefs )
if err := json . NewDecoder ( r . Body ) . Decode ( mp ) ; err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , err . Error ( ) , http . StatusBadRequest )
2021-04-12 00:10:31 +01:00
return
}
var err error
prefs , err = h . b . EditPrefs ( mp )
if err != nil {
2022-04-18 17:37:23 +01:00
w . Header ( ) . Set ( "Content-Type" , "application/json" )
w . WriteHeader ( http . StatusBadRequest )
json . NewEncoder ( w ) . Encode ( resJSON { Error : err . Error ( ) } )
2021-04-12 00:10:31 +01:00
return
}
2021-04-12 04:49:07 +01:00
case "GET" , "HEAD" :
2022-10-24 01:15:04 +01:00
prefs = h . b . Prefs ( )
2021-04-12 04:49:07 +01:00
default :
http . Error ( w , "unsupported method" , http . StatusMethodNotAllowed )
return
2021-04-12 00:10:31 +01:00
}
2021-04-07 16:27:35 +01:00
w . Header ( ) . Set ( "Content-Type" , "application/json" )
e := json . NewEncoder ( w )
e . SetIndent ( "" , "\t" )
2021-04-12 00:10:31 +01:00
e . Encode ( prefs )
2021-04-07 16:27:35 +01:00
}
2022-04-18 17:37:23 +01:00
type resJSON struct {
Error string ` json:",omitempty" `
}
func ( h * Handler ) serveCheckPrefs ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "checkprefs access denied" , http . StatusForbidden )
return
}
if r . Method != "POST" {
http . Error ( w , "unsupported method" , http . StatusMethodNotAllowed )
return
}
p := new ( ipn . Prefs )
if err := json . NewDecoder ( r . Body ) . Decode ( p ) ; err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "invalid JSON body" , http . StatusBadRequest )
2022-04-18 17:37:23 +01:00
return
}
err := h . b . CheckPrefs ( p )
var res resJSON
if err != nil {
res . Error = err . Error ( )
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
json . NewEncoder ( w ) . Encode ( res )
}
2021-03-30 20:56:00 +01:00
func ( h * Handler ) serveFiles ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "file access denied" , http . StatusForbidden )
return
}
2023-02-01 21:43:06 +00:00
suffix , ok := strings . CutPrefix ( r . URL . EscapedPath ( ) , "/localapi/v0/files/" )
2022-11-18 18:13:14 +00:00
if ! ok {
http . Error ( w , "misconfigured" , http . StatusInternalServerError )
return
}
2021-03-30 20:56:00 +01:00
if suffix == "" {
if r . Method != "GET" {
2023-10-13 23:40:10 +01:00
http . Error ( w , "want GET to list files" , http . StatusBadRequest )
2021-03-30 20:56:00 +01:00
return
}
2022-11-20 21:25:54 +00:00
ctx := r . Context ( )
if s := r . FormValue ( "waitsec" ) ; s != "" && s != "0" {
d , err := strconv . Atoi ( s )
if err != nil {
http . Error ( w , "invalid waitsec" , http . StatusBadRequest )
return
}
deadline := time . Now ( ) . Add ( time . Duration ( d ) * time . Second )
var cancel context . CancelFunc
ctx , cancel = context . WithDeadline ( ctx , deadline )
defer cancel ( )
}
wfs , err := h . b . AwaitWaitingFiles ( ctx )
if err != nil && ctx . Err ( ) == nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
2021-03-30 20:56:00 +01:00
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
json . NewEncoder ( w ) . Encode ( wfs )
return
}
name , err := url . PathUnescape ( suffix )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "bad filename" , http . StatusBadRequest )
2021-03-30 20:56:00 +01:00
return
}
if r . Method == "DELETE" {
if err := h . b . DeleteFile ( name ) ; err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
2021-03-30 20:56:00 +01:00
return
}
w . WriteHeader ( http . StatusNoContent )
return
}
rc , size , err := h . b . OpenFile ( name )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
2021-03-30 20:56:00 +01:00
return
}
defer rc . Close ( )
w . Header ( ) . Set ( "Content-Length" , fmt . Sprint ( size ) )
2022-11-16 14:45:35 +00:00
w . Header ( ) . Set ( "Content-Type" , "application/octet-stream" )
2021-03-30 20:56:00 +01:00
io . Copy ( w , rc )
}
2021-04-16 18:57:46 +01:00
func writeErrorJSON ( w http . ResponseWriter , err error ) {
if err == nil {
err = errors . New ( "unexpected nil error" )
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
2023-10-13 23:40:10 +01:00
w . WriteHeader ( http . StatusInternalServerError )
2021-04-16 18:57:46 +01:00
type E struct {
Error string ` json:"error" `
}
json . NewEncoder ( w ) . Encode ( E { err . Error ( ) } )
}
2021-04-05 05:35:52 +01:00
func ( h * Handler ) serveFileTargets ( w http . ResponseWriter , r * http . Request ) {
2021-04-13 16:35:16 +01:00
if ! h . PermitRead {
http . Error ( w , "access denied" , http . StatusForbidden )
2021-04-05 05:35:52 +01:00
return
}
if r . Method != "GET" {
2023-10-13 23:40:10 +01:00
http . Error ( w , "want GET to list targets" , http . StatusBadRequest )
2021-04-05 05:35:52 +01:00
return
}
2021-04-06 21:38:47 +01:00
fts , err := h . b . FileTargets ( )
2021-04-05 05:35:52 +01:00
if err != nil {
2021-04-16 18:57:46 +01:00
writeErrorJSON ( w , err )
2021-04-05 05:35:52 +01:00
return
}
2022-09-10 20:11:59 +01:00
mak . NonNilSliceForJSON ( & fts )
2021-04-05 05:35:52 +01:00
w . Header ( ) . Set ( "Content-Type" , "application/json" )
2021-04-06 21:38:47 +01:00
json . NewEncoder ( w ) . Encode ( fts )
}
2021-11-30 16:47:52 +00:00
// serveFilePut sends a file to another node.
//
// It's sometimes possible for clients to do this themselves, without
// tailscaled, except in the case of tailscaled running in
// userspace-networking ("netstack") mode, in which case tailscaled
// needs to a do a netstack dial out.
//
// Instead, the CLI also goes through tailscaled so it doesn't need to be
// aware of the network mode in use.
//
// macOS/iOS have always used this localapi method to simplify the GUI
// clients.
//
// The Windows client currently (2021-11-30) uses the peerapi (/v0/put/)
// directly, as the Windows GUI always runs in tun mode anyway.
//
// URL format:
//
2022-08-02 17:33:46 +01:00
// - PUT /localapi/v0/file-put/:stableID/:escaped-filename
2021-04-06 21:38:47 +01:00
func ( h * Handler ) serveFilePut ( w http . ResponseWriter , r * http . Request ) {
2022-12-09 22:21:53 +00:00
metricFilePutCalls . Add ( 1 )
2021-04-06 21:38:47 +01:00
if ! h . PermitWrite {
http . Error ( w , "file access denied" , http . StatusForbidden )
return
}
if r . Method != "PUT" {
2023-10-13 23:40:10 +01:00
http . Error ( w , "want PUT to put file" , http . StatusBadRequest )
2021-04-06 21:38:47 +01:00
return
}
fts , err := h . b . FileTargets ( )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
2021-04-06 21:38:47 +01:00
return
}
2023-02-01 21:43:06 +00:00
upath , ok := strings . CutPrefix ( r . URL . EscapedPath ( ) , "/localapi/v0/file-put/" )
2022-11-18 18:13:14 +00:00
if ! ok {
http . Error ( w , "misconfigured" , http . StatusInternalServerError )
return
}
2022-03-16 21:25:31 +00:00
stableIDStr , filenameEscaped , ok := strings . Cut ( upath , "/" )
if ! ok {
2023-10-13 23:40:10 +01:00
http . Error ( w , "bogus URL" , http . StatusBadRequest )
2021-04-06 21:38:47 +01:00
return
}
2022-03-16 21:25:31 +00:00
stableID := tailcfg . StableNodeID ( stableIDStr )
2021-04-06 21:38:47 +01:00
2021-04-13 16:13:46 +01:00
var ft * apitype . FileTarget
2021-04-06 21:38:47 +01:00
for _ , x := range fts {
if x . Node . StableID == stableID {
ft = x
break
}
}
if ft == nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "node not found" , http . StatusNotFound )
2021-04-06 21:38:47 +01:00
return
}
dstURL , err := url . Parse ( ft . PeerAPIURL )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "bogus peer URL" , http . StatusInternalServerError )
2021-04-06 21:38:47 +01:00
return
}
2023-10-16 18:36:31 +01:00
// Before we PUT a file we check to see if there are any existing partial file and if so,
// we resume the upload from where we left off by sending the remaining file instead of
// the full file.
taildrop: switch hashing to be streaming based (#9861)
While the previous logic was correct, it did not perform well.
Resuming is a dance between the client and server, where
1. the client requests hashes for a partial file,
2. the server then computes those hashes,
3. the client computes hashes locally and compares them.
4. goto 1 while the partial file still has data
While step 2 is running, the client is sitting idle.
While step 3 is running, the server is sitting idle.
By streaming over the block hash immediately after the server
computes it, the client can start checking the hash,
while the server works on the next hash (in a pipelined manner).
This performs dramatically better and also uses less memory
as we don't need to hold a list of hashes, but only need to
handle one hash at a time.
There are two detriments to this approach:
* The HTTP API relies on a JSON stream,
which is not a standard REST-like pattern.
However, since we implement both client and server,
this is fine.
* While the stream is on-going, we hold an open file handle
on the server side while the file is being hashed.
On really slow streams, this could hold a file open forever.
Updates tailscale/corp#14772
Signed-off-by: Joe Tsai <joetsai@digital-static.net>
Co-authored-by: Rhea Ghosh <rhea@tailscale.com>
2023-10-18 01:53:40 +01:00
var offset int64
var resumeDuration time . Duration
remainingBody := io . Reader ( r . Body )
client := & http . Client {
Transport : h . b . Dialer ( ) . PeerAPITransport ( ) ,
Timeout : 10 * time . Second ,
}
req , err := http . NewRequestWithContext ( r . Context ( ) , "GET" , dstURL . String ( ) + "/v0/put/" + filenameEscaped , nil )
if err != nil {
http . Error ( w , "bogus peer URL" , http . StatusInternalServerError )
return
}
switch resp , err := client . Do ( req ) ; {
case err != nil :
h . logf ( "could not fetch remote hashes: %v" , err )
case resp . StatusCode == http . StatusMethodNotAllowed || resp . StatusCode == http . StatusNotFound :
// noop; implies older peerapi without resume support
case resp . StatusCode != http . StatusOK :
h . logf ( "fetch remote hashes status code: %d" , resp . StatusCode )
default :
resumeStart := time . Now ( )
dec := json . NewDecoder ( resp . Body )
offset , remainingBody , err = taildrop . ResumeReader ( r . Body , func ( ) ( out taildrop . BlockChecksum , err error ) {
err = dec . Decode ( & out )
return out , err
} )
2023-10-16 18:36:31 +01:00
if err != nil {
taildrop: switch hashing to be streaming based (#9861)
While the previous logic was correct, it did not perform well.
Resuming is a dance between the client and server, where
1. the client requests hashes for a partial file,
2. the server then computes those hashes,
3. the client computes hashes locally and compares them.
4. goto 1 while the partial file still has data
While step 2 is running, the client is sitting idle.
While step 3 is running, the server is sitting idle.
By streaming over the block hash immediately after the server
computes it, the client can start checking the hash,
while the server works on the next hash (in a pipelined manner).
This performs dramatically better and also uses less memory
as we don't need to hold a list of hashes, but only need to
handle one hash at a time.
There are two detriments to this approach:
* The HTTP API relies on a JSON stream,
which is not a standard REST-like pattern.
However, since we implement both client and server,
this is fine.
* While the stream is on-going, we hold an open file handle
on the server side while the file is being hashed.
On really slow streams, this could hold a file open forever.
Updates tailscale/corp#14772
Signed-off-by: Joe Tsai <joetsai@digital-static.net>
Co-authored-by: Rhea Ghosh <rhea@tailscale.com>
2023-10-18 01:53:40 +01:00
h . logf ( "reader could not be fully resumed: %v" , err )
2023-10-16 18:36:31 +01:00
}
taildrop: switch hashing to be streaming based (#9861)
While the previous logic was correct, it did not perform well.
Resuming is a dance between the client and server, where
1. the client requests hashes for a partial file,
2. the server then computes those hashes,
3. the client computes hashes locally and compares them.
4. goto 1 while the partial file still has data
While step 2 is running, the client is sitting idle.
While step 3 is running, the server is sitting idle.
By streaming over the block hash immediately after the server
computes it, the client can start checking the hash,
while the server works on the next hash (in a pipelined manner).
This performs dramatically better and also uses less memory
as we don't need to hold a list of hashes, but only need to
handle one hash at a time.
There are two detriments to this approach:
* The HTTP API relies on a JSON stream,
which is not a standard REST-like pattern.
However, since we implement both client and server,
this is fine.
* While the stream is on-going, we hold an open file handle
on the server side while the file is being hashed.
On really slow streams, this could hold a file open forever.
Updates tailscale/corp#14772
Signed-off-by: Joe Tsai <joetsai@digital-static.net>
Co-authored-by: Rhea Ghosh <rhea@tailscale.com>
2023-10-18 01:53:40 +01:00
resumeDuration = time . Since ( resumeStart ) . Round ( time . Millisecond )
2023-10-16 18:36:31 +01:00
}
outReq , err := http . NewRequestWithContext ( r . Context ( ) , "PUT" , "http://peer/v0/put/" + filenameEscaped , remainingBody )
2021-04-06 21:38:47 +01:00
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "bogus outreq" , http . StatusInternalServerError )
2021-04-06 21:38:47 +01:00
return
}
outReq . ContentLength = r . ContentLength
2023-10-16 18:36:31 +01:00
if offset > 0 {
taildrop: switch hashing to be streaming based (#9861)
While the previous logic was correct, it did not perform well.
Resuming is a dance between the client and server, where
1. the client requests hashes for a partial file,
2. the server then computes those hashes,
3. the client computes hashes locally and compares them.
4. goto 1 while the partial file still has data
While step 2 is running, the client is sitting idle.
While step 3 is running, the server is sitting idle.
By streaming over the block hash immediately after the server
computes it, the client can start checking the hash,
while the server works on the next hash (in a pipelined manner).
This performs dramatically better and also uses less memory
as we don't need to hold a list of hashes, but only need to
handle one hash at a time.
There are two detriments to this approach:
* The HTTP API relies on a JSON stream,
which is not a standard REST-like pattern.
However, since we implement both client and server,
this is fine.
* While the stream is on-going, we hold an open file handle
on the server side while the file is being hashed.
On really slow streams, this could hold a file open forever.
Updates tailscale/corp#14772
Signed-off-by: Joe Tsai <joetsai@digital-static.net>
Co-authored-by: Rhea Ghosh <rhea@tailscale.com>
2023-10-18 01:53:40 +01:00
h . logf ( "resuming put at offset %d after %v" , offset , resumeDuration )
2023-10-23 19:15:25 +01:00
rangeHdr , _ := httphdr . FormatRange ( [ ] httphdr . Range { { Start : offset , Length : 0 } } )
2023-10-16 18:36:31 +01:00
outReq . Header . Set ( "Range" , rangeHdr )
if outReq . ContentLength >= 0 {
outReq . ContentLength -= offset
}
}
2021-04-06 21:38:47 +01:00
rp := httputil . NewSingleHostReverseProxy ( dstURL )
2021-12-01 04:39:12 +00:00
rp . Transport = h . b . Dialer ( ) . PeerAPITransport ( )
2021-04-06 21:38:47 +01:00
rp . ServeHTTP ( w , outReq )
}
2021-06-08 00:03:16 +01:00
func ( h * Handler ) serveSetDNS ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "access denied" , http . StatusForbidden )
return
}
if r . Method != "POST" {
2023-10-13 23:40:10 +01:00
http . Error ( w , "want POST" , http . StatusBadRequest )
2021-06-08 00:03:16 +01:00
return
}
ctx := r . Context ( )
err := h . b . SetDNS ( ctx , r . FormValue ( "name" ) , r . FormValue ( "value" ) )
if err != nil {
writeErrorJSON ( w , err )
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
json . NewEncoder ( w ) . Encode ( struct { } { } )
}
2021-06-25 19:44:40 +01:00
func ( h * Handler ) serveDERPMap ( w http . ResponseWriter , r * http . Request ) {
if r . Method != "GET" {
2023-10-13 23:40:10 +01:00
http . Error ( w , "want GET" , http . StatusBadRequest )
2021-06-25 19:44:40 +01:00
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
e := json . NewEncoder ( w )
e . SetIndent ( "" , "\t" )
e . Encode ( h . b . DERPMap ( ) )
}
2022-03-09 22:42:42 +00:00
// serveSetExpirySooner sets the expiry date on the current machine, specified
// by an `expiry` unix timestamp as POST or query param.
func ( h * Handler ) serveSetExpirySooner ( w http . ResponseWriter , r * http . Request ) {
2023-01-23 22:55:36 +00:00
if ! h . PermitWrite {
http . Error ( w , "access denied" , http . StatusForbidden )
return
}
2022-03-09 22:42:42 +00:00
if r . Method != "POST" {
http . Error ( w , "POST required" , http . StatusMethodNotAllowed )
return
}
var expiryTime time . Time
if v := r . FormValue ( "expiry" ) ; v != "" {
expiryInt , err := strconv . ParseInt ( v , 10 , 64 )
if err != nil {
http . Error ( w , "can't parse expiry time, expects a unix timestamp" , http . StatusBadRequest )
return
}
expiryTime = time . Unix ( expiryInt , 0 )
} else {
http . Error ( w , "missing 'expiry' parameter, a unix timestamp" , http . StatusBadRequest )
return
}
err := h . b . SetExpirySooner ( r . Context ( ) , expiryTime )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusBadRequest )
return
}
w . Header ( ) . Set ( "Content-Type" , "text/plain" )
io . WriteString ( w , "done\n" )
}
2022-05-03 22:16:34 +01:00
func ( h * Handler ) servePing ( w http . ResponseWriter , r * http . Request ) {
ctx := r . Context ( )
if r . Method != "POST" {
2023-10-13 23:40:10 +01:00
http . Error ( w , "want POST" , http . StatusBadRequest )
2022-05-03 22:16:34 +01:00
return
}
ipStr := r . FormValue ( "ip" )
if ipStr == "" {
2023-10-13 23:40:10 +01:00
http . Error ( w , "missing 'ip' parameter" , http . StatusBadRequest )
2022-05-03 22:16:34 +01:00
return
}
2022-07-26 04:55:44 +01:00
ip , err := netip . ParseAddr ( ipStr )
2022-05-03 22:16:34 +01:00
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "invalid IP" , http . StatusBadRequest )
2022-05-03 22:16:34 +01:00
return
}
pingTypeStr := r . FormValue ( "type" )
2023-06-27 17:33:29 +01:00
if pingTypeStr == "" {
2023-10-13 23:40:10 +01:00
http . Error ( w , "missing 'type' parameter" , http . StatusBadRequest )
2022-05-03 22:16:34 +01:00
return
}
2023-08-08 13:11:28 +01:00
size := 0
sizeStr := r . FormValue ( "size" )
if sizeStr != "" {
size , err = strconv . Atoi ( sizeStr )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "invalid 'size' parameter" , http . StatusBadRequest )
2023-08-08 13:11:28 +01:00
return
}
if size != 0 && tailcfg . PingType ( pingTypeStr ) != tailcfg . PingDisco {
2023-10-13 23:40:10 +01:00
http . Error ( w , "'size' parameter is only supported with disco pings" , http . StatusBadRequest )
2023-08-08 13:11:28 +01:00
return
}
2023-09-22 16:49:09 +01:00
if size > magicsock . MaxDiscoPingSize {
2023-10-13 23:40:10 +01:00
http . Error ( w , fmt . Sprintf ( "maximum value for 'size' is %v" , magicsock . MaxDiscoPingSize ) , http . StatusBadRequest )
2023-08-08 13:11:28 +01:00
return
}
}
res , err := h . b . Ping ( ctx , ip , tailcfg . PingType ( pingTypeStr ) , size )
2022-05-03 22:16:34 +01:00
if err != nil {
writeErrorJSON ( w , err )
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
json . NewEncoder ( w ) . Encode ( res )
}
2022-03-24 16:04:01 +00:00
func ( h * Handler ) serveDial ( w http . ResponseWriter , r * http . Request ) {
if r . Method != "POST" {
http . Error ( w , "POST required" , http . StatusMethodNotAllowed )
return
}
const upgradeProto = "ts-dial"
if ! strings . Contains ( r . Header . Get ( "Connection" ) , "upgrade" ) ||
r . Header . Get ( "Upgrade" ) != upgradeProto {
http . Error ( w , "bad ts-dial upgrade" , http . StatusBadRequest )
return
}
hostStr , portStr := r . Header . Get ( "Dial-Host" ) , r . Header . Get ( "Dial-Port" )
if hostStr == "" || portStr == "" {
http . Error ( w , "missing Dial-Host or Dial-Port header" , http . StatusBadRequest )
return
}
hijacker , ok := w . ( http . Hijacker )
if ! ok {
http . Error ( w , "make request over HTTP/1" , http . StatusBadRequest )
return
}
addr := net . JoinHostPort ( hostStr , portStr )
outConn , err := h . b . Dialer ( ) . UserDial ( r . Context ( ) , "tcp" , addr )
if err != nil {
http . Error ( w , "dial failure: " + err . Error ( ) , http . StatusBadGateway )
return
}
defer outConn . Close ( )
w . Header ( ) . Set ( "Upgrade" , upgradeProto )
w . Header ( ) . Set ( "Connection" , "upgrade" )
w . WriteHeader ( http . StatusSwitchingProtocols )
reqConn , brw , err := hijacker . Hijack ( )
if err != nil {
h . logf ( "localapi dial Hijack error: %v" , err )
return
}
defer reqConn . Close ( )
if err := brw . Flush ( ) ; err != nil {
return
}
reqConn = netutil . NewDrainBufConn ( reqConn , brw . Reader )
errc := make ( chan error , 1 )
go func ( ) {
_ , err := io . Copy ( reqConn , outConn )
errc <- err
} ( )
go func ( ) {
_ , err := io . Copy ( outConn , reqConn )
errc <- err
} ( )
<- errc
}
2023-01-29 22:04:40 +00:00
func ( h * Handler ) serveSetPushDeviceToken ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "set push device token access denied" , http . StatusForbidden )
return
}
if r . Method != "POST" {
http . Error ( w , "unsupported method" , http . StatusMethodNotAllowed )
return
}
var params apitype . SetPushDeviceTokenRequest
if err := json . NewDecoder ( r . Body ) . Decode ( & params ) ; err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "invalid JSON body" , http . StatusBadRequest )
2023-01-29 22:04:40 +00:00
return
}
2023-10-23 18:22:34 +01:00
h . b . SetPushDeviceToken ( params . PushDeviceToken )
2023-01-29 22:04:40 +00:00
w . WriteHeader ( http . StatusOK )
}
2023-10-31 01:35:53 +00:00
func ( h * Handler ) serveHandlePushMessage ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "handle push message not allowed" , http . StatusForbidden )
return
}
if r . Method != "POST" {
http . Error ( w , "unsupported method" , http . StatusMethodNotAllowed )
return
}
var pushMessageBody map [ string ] any
if err := json . NewDecoder ( r . Body ) . Decode ( & pushMessageBody ) ; err != nil {
http . Error ( w , "failed to decode JSON body: " + err . Error ( ) , http . StatusBadRequest )
return
}
// TODO(bradfitz): do something with pushMessageBody
h . logf ( "localapi: got push message: %v" , logger . AsJSON ( pushMessageBody ) )
w . WriteHeader ( http . StatusNoContent )
}
2022-07-08 19:57:34 +01:00
func ( h * Handler ) serveUploadClientMetrics ( w http . ResponseWriter , r * http . Request ) {
if r . Method != "POST" {
http . Error ( w , "unsupported method" , http . StatusMethodNotAllowed )
return
}
type clientMetricJSON struct {
2023-08-14 23:01:43 +01:00
Name string ` json:"name" `
Type string ` json:"type" ` // one of "counter" or "gauge"
Value int ` json:"value" ` // amount to increment metric by
2022-07-08 19:57:34 +01:00
}
var clientMetrics [ ] clientMetricJSON
if err := json . NewDecoder ( r . Body ) . Decode ( & clientMetrics ) ; err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "invalid JSON body" , http . StatusBadRequest )
2022-07-08 19:57:34 +01:00
return
}
metricsMu . Lock ( )
defer metricsMu . Unlock ( )
for _ , m := range clientMetrics {
if metric , ok := metrics [ m . Name ] ; ok {
metric . Add ( int64 ( m . Value ) )
} else {
if clientmetric . HasPublished ( m . Name ) {
2023-10-13 23:40:10 +01:00
http . Error ( w , "Already have a metric named " + m . Name , http . StatusBadRequest )
2022-07-08 19:57:34 +01:00
return
}
var metric * clientmetric . Metric
switch m . Type {
case "counter" :
metric = clientmetric . NewCounter ( m . Name )
case "gauge" :
metric = clientmetric . NewGauge ( m . Name )
default :
2023-10-13 23:40:10 +01:00
http . Error ( w , "Unknown metric type " + m . Type , http . StatusBadRequest )
2022-07-08 19:57:34 +01:00
return
}
metrics [ m . Name ] = metric
metric . Add ( int64 ( m . Value ) )
}
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
json . NewEncoder ( w ) . Encode ( struct { } { } )
}
2022-10-09 16:57:02 +01:00
func ( h * Handler ) serveTKAStatus ( w http . ResponseWriter , r * http . Request ) {
2022-08-11 18:43:09 +01:00
if ! h . PermitRead {
http . Error ( w , "lock status access denied" , http . StatusForbidden )
return
}
2023-01-27 03:35:26 +00:00
if r . Method != httpm . GET {
2022-10-09 16:57:02 +01:00
http . Error ( w , "use GET" , http . StatusMethodNotAllowed )
2022-08-11 18:43:09 +01:00
return
}
j , err := json . MarshalIndent ( h . b . NetworkLockStatus ( ) , "" , "\t" )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "JSON encoding error" , http . StatusInternalServerError )
2022-08-11 18:43:09 +01:00
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
w . Write ( j )
}
2024-02-29 17:36:35 +00:00
func ( h * Handler ) serveSetGUIVisible ( w http . ResponseWriter , r * http . Request ) {
if r . Method != httpm . POST {
http . Error ( w , "use POST" , http . StatusMethodNotAllowed )
return
}
type setGUIVisibleRequest struct {
IsVisible bool // whether the Tailscale client UI is now presented to the user
SessionID string // the last SessionID sent to the client in ipn.Notify.SessionID
}
var req setGUIVisibleRequest
if err := json . NewDecoder ( r . Body ) . Decode ( & req ) ; err != nil {
http . Error ( w , "invalid JSON body" , http . StatusBadRequest )
return
}
// TODO(bradfitz): use `req.IsVisible == true` to flush netmap
w . WriteHeader ( http . StatusOK )
}
2022-10-31 23:47:51 +00:00
func ( h * Handler ) serveTKASign ( w http . ResponseWriter , r * http . Request ) {
2023-11-02 23:01:26 +00:00
if ! h . PermitWrite {
http . Error ( w , "lock sign access denied" , http . StatusForbidden )
2022-10-31 23:47:51 +00:00
return
}
2023-01-27 03:35:26 +00:00
if r . Method != httpm . POST {
2022-10-31 23:47:51 +00:00
http . Error ( w , "use POST" , http . StatusMethodNotAllowed )
return
}
type signRequest struct {
NodeKey key . NodePublic
RotationPublic [ ] byte
}
var req signRequest
if err := json . NewDecoder ( r . Body ) . Decode ( & req ) ; err != nil {
http . Error ( w , "invalid JSON body" , http . StatusBadRequest )
return
}
if err := h . b . NetworkLockSign ( req . NodeKey , req . RotationPublic ) ; err != nil {
http . Error ( w , "signing failed: " + err . Error ( ) , http . StatusInternalServerError )
return
}
w . WriteHeader ( http . StatusOK )
}
2022-10-09 16:57:02 +01:00
func ( h * Handler ) serveTKAInit ( w http . ResponseWriter , r * http . Request ) {
2022-08-11 18:43:09 +01:00
if ! h . PermitWrite {
http . Error ( w , "lock init access denied" , http . StatusForbidden )
return
}
2023-01-27 03:35:26 +00:00
if r . Method != httpm . POST {
2022-08-11 18:43:09 +01:00
http . Error ( w , "use POST" , http . StatusMethodNotAllowed )
return
}
type initRequest struct {
2022-11-23 19:19:30 +00:00
Keys [ ] tka . Key
DisablementValues [ ] [ ] byte
SupportDisablement [ ] byte
2022-08-11 18:43:09 +01:00
}
var req initRequest
if err := json . NewDecoder ( r . Body ) . Decode ( & req ) ; err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "invalid JSON body" , http . StatusBadRequest )
2022-08-11 18:43:09 +01:00
return
}
2022-11-23 19:19:30 +00:00
if err := h . b . NetworkLockInit ( req . Keys , req . DisablementValues , req . SupportDisablement ) ; err != nil {
2022-08-11 18:43:09 +01:00
http . Error ( w , "initialization failed: " + err . Error ( ) , http . StatusInternalServerError )
return
}
j , err := json . MarshalIndent ( h . b . NetworkLockStatus ( ) , "" , "\t" )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "JSON encoding error" , http . StatusInternalServerError )
2022-08-11 18:43:09 +01:00
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
w . Write ( j )
}
2022-10-09 16:57:02 +01:00
func ( h * Handler ) serveTKAModify ( w http . ResponseWriter , r * http . Request ) {
2022-09-15 18:51:23 +01:00
if ! h . PermitWrite {
http . Error ( w , "network-lock modify access denied" , http . StatusForbidden )
return
}
2023-01-27 03:35:26 +00:00
if r . Method != httpm . POST {
2022-09-15 18:51:23 +01:00
http . Error ( w , "use POST" , http . StatusMethodNotAllowed )
return
}
type modifyRequest struct {
AddKeys [ ] tka . Key
RemoveKeys [ ] tka . Key
}
var req modifyRequest
if err := json . NewDecoder ( r . Body ) . Decode ( & req ) ; err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "invalid JSON body" , http . StatusBadRequest )
2022-09-15 18:51:23 +01:00
return
}
if err := h . b . NetworkLockModify ( req . AddKeys , req . RemoveKeys ) ; err != nil {
http . Error ( w , "network-lock modify failed: " + err . Error ( ) , http . StatusInternalServerError )
return
}
2022-12-05 06:55:57 +00:00
w . WriteHeader ( 204 )
2022-09-15 18:51:23 +01:00
}
2023-03-02 21:24:26 +00:00
func ( h * Handler ) serveTKAWrapPreauthKey ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "network-lock modify access denied" , http . StatusForbidden )
return
}
if r . Method != httpm . POST {
http . Error ( w , "use POST" , http . StatusMethodNotAllowed )
return
}
type wrapRequest struct {
TSKey string
TKAKey string // key.NLPrivate.MarshalText
}
var req wrapRequest
if err := json . NewDecoder ( http . MaxBytesReader ( w , r . Body , 12 * 1024 ) ) . Decode ( & req ) ; err != nil {
http . Error ( w , "invalid JSON body" , http . StatusBadRequest )
return
}
var priv key . NLPrivate
if err := priv . UnmarshalText ( [ ] byte ( req . TKAKey ) ) ; err != nil {
http . Error ( w , "invalid JSON body" , http . StatusBadRequest )
return
}
wrappedKey , err := h . b . NetworkLockWrapPreauthKey ( req . TSKey , priv )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
2024-02-05 17:34:41 +00:00
w . WriteHeader ( http . StatusOK )
2023-03-02 21:24:26 +00:00
w . Write ( [ ] byte ( wrappedKey ) )
}
2023-06-13 19:39:23 +01:00
func ( h * Handler ) serveTKAVerifySigningDeeplink ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitRead {
http . Error ( w , "signing deeplink verification access denied" , http . StatusForbidden )
return
}
if r . Method != httpm . POST {
http . Error ( w , "use POST" , http . StatusMethodNotAllowed )
return
}
type verifyRequest struct {
URL string
}
var req verifyRequest
if err := json . NewDecoder ( r . Body ) . Decode ( & req ) ; err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "invalid JSON for verifyRequest body" , http . StatusBadRequest )
2023-06-13 19:39:23 +01:00
return
}
res := h . b . NetworkLockVerifySigningDeeplink ( req . URL )
j , err := json . MarshalIndent ( res , "" , "\t" )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "JSON encoding error" , http . StatusInternalServerError )
2023-06-13 19:39:23 +01:00
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
w . Write ( j )
}
2022-11-04 19:12:51 +00:00
func ( h * Handler ) serveTKADisable ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "network-lock modify access denied" , http . StatusForbidden )
return
}
2023-01-27 03:35:26 +00:00
if r . Method != httpm . POST {
2022-11-04 19:12:51 +00:00
http . Error ( w , "use POST" , http . StatusMethodNotAllowed )
return
}
body := io . LimitReader ( r . Body , 1024 * 1024 )
2023-08-23 16:42:44 +01:00
secret , err := io . ReadAll ( body )
2022-11-04 19:12:51 +00:00
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "reading secret" , http . StatusBadRequest )
2022-11-04 19:12:51 +00:00
return
}
if err := h . b . NetworkLockDisable ( secret ) ; err != nil {
http . Error ( w , "network-lock disable failed: " + err . Error ( ) , http . StatusBadRequest )
return
}
2024-02-05 17:34:41 +00:00
w . WriteHeader ( http . StatusOK )
2022-11-04 19:12:51 +00:00
}
2022-11-29 00:39:03 +00:00
func ( h * Handler ) serveTKALocalDisable ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "network-lock modify access denied" , http . StatusForbidden )
return
}
2023-01-27 03:35:26 +00:00
if r . Method != httpm . POST {
2022-11-29 00:39:03 +00:00
http . Error ( w , "use POST" , http . StatusMethodNotAllowed )
return
}
// Require a JSON stanza for the body as an additional CSRF protection.
var req struct { }
if err := json . NewDecoder ( r . Body ) . Decode ( & req ) ; err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "invalid JSON body" , http . StatusBadRequest )
2022-11-29 00:39:03 +00:00
return
}
if err := h . b . NetworkLockForceLocalDisable ( ) ; err != nil {
http . Error ( w , "network-lock local disable failed: " + err . Error ( ) , http . StatusBadRequest )
return
}
2024-02-05 17:34:41 +00:00
w . WriteHeader ( http . StatusOK )
2022-11-29 00:39:03 +00:00
}
2022-11-14 23:04:10 +00:00
func ( h * Handler ) serveTKALog ( w http . ResponseWriter , r * http . Request ) {
2023-01-27 03:35:26 +00:00
if r . Method != httpm . GET {
2022-11-14 23:04:10 +00:00
http . Error ( w , "use GET" , http . StatusMethodNotAllowed )
return
}
limit := 50
if limitStr := r . FormValue ( "limit" ) ; limitStr != "" {
l , err := strconv . Atoi ( limitStr )
if err != nil {
http . Error ( w , "parsing 'limit' parameter: " + err . Error ( ) , http . StatusBadRequest )
return
}
limit = int ( l )
}
updates , err := h . b . NetworkLockLog ( limit )
if err != nil {
http . Error ( w , "reading log failed: " + err . Error ( ) , http . StatusInternalServerError )
return
}
j , err := json . MarshalIndent ( updates , "" , "\t" )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "JSON encoding error" , http . StatusInternalServerError )
2022-11-14 23:04:10 +00:00
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
w . Write ( j )
}
2023-03-01 20:47:29 +00:00
func ( h * Handler ) serveTKAAffectedSigs ( w http . ResponseWriter , r * http . Request ) {
if r . Method != httpm . POST {
http . Error ( w , "use POST" , http . StatusMethodNotAllowed )
return
}
2023-08-23 16:42:44 +01:00
keyID , err := io . ReadAll ( http . MaxBytesReader ( w , r . Body , 2048 ) )
2023-03-01 20:47:29 +00:00
if err != nil {
http . Error ( w , "reading body" , http . StatusBadRequest )
return
}
sigs , err := h . b . NetworkLockAffectedSigs ( keyID )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
j , err := json . MarshalIndent ( sigs , "" , "\t" )
if err != nil {
http . Error ( w , "JSON encoding error" , http . StatusInternalServerError )
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
w . Write ( j )
}
2023-07-18 23:13:36 +01:00
func ( h * Handler ) serveTKAGenerateRecoveryAUM ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "access denied" , http . StatusForbidden )
return
}
if r . Method != httpm . POST {
http . Error ( w , "use POST" , http . StatusMethodNotAllowed )
return
}
type verifyRequest struct {
Keys [ ] tkatype . KeyID
ForkFrom string
}
var req verifyRequest
if err := json . NewDecoder ( r . Body ) . Decode ( & req ) ; err != nil {
http . Error ( w , "invalid JSON for verifyRequest body" , http . StatusBadRequest )
return
}
var forkFrom tka . AUMHash
if req . ForkFrom != "" {
if err := forkFrom . UnmarshalText ( [ ] byte ( req . ForkFrom ) ) ; err != nil {
http . Error ( w , "decoding fork-from: " + err . Error ( ) , http . StatusBadRequest )
return
}
}
res , err := h . b . NetworkLockGenerateRecoveryAUM ( req . Keys , forkFrom )
if err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
2023-07-18 23:13:36 +01:00
return
}
w . Header ( ) . Set ( "Content-Type" , "application/octet-stream" )
w . Write ( res . Serialize ( ) )
}
func ( h * Handler ) serveTKACosignRecoveryAUM ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "access denied" , http . StatusForbidden )
return
}
if r . Method != httpm . POST {
http . Error ( w , "use POST" , http . StatusMethodNotAllowed )
return
}
body := io . LimitReader ( r . Body , 1024 * 1024 )
2023-08-23 16:42:44 +01:00
aumBytes , err := io . ReadAll ( body )
2023-07-18 23:13:36 +01:00
if err != nil {
http . Error ( w , "reading AUM" , http . StatusBadRequest )
return
}
var aum tka . AUM
if err := aum . Unserialize ( aumBytes ) ; err != nil {
http . Error ( w , "decoding AUM" , http . StatusBadRequest )
return
}
res , err := h . b . NetworkLockCosignRecoveryAUM ( & aum )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
w . Header ( ) . Set ( "Content-Type" , "application/octet-stream" )
w . Write ( res . Serialize ( ) )
}
func ( h * Handler ) serveTKASubmitRecoveryAUM ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "access denied" , http . StatusForbidden )
return
}
if r . Method != httpm . POST {
http . Error ( w , "use POST" , http . StatusMethodNotAllowed )
return
}
body := io . LimitReader ( r . Body , 1024 * 1024 )
2023-08-23 16:42:44 +01:00
aumBytes , err := io . ReadAll ( body )
2023-07-18 23:13:36 +01:00
if err != nil {
http . Error ( w , "reading AUM" , http . StatusBadRequest )
return
}
var aum tka . AUM
if err := aum . Unserialize ( aumBytes ) ; err != nil {
http . Error ( w , "decoding AUM" , http . StatusBadRequest )
return
}
if err := h . b . NetworkLockSubmitRecoveryAUM ( & aum ) ; err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
w . WriteHeader ( http . StatusOK )
}
2022-11-10 21:38:22 +00:00
// serveProfiles serves profile switching-related endpoints. Supported methods
// and paths are:
// - GET /profiles/: list all profiles (JSON-encoded array of ipn.LoginProfiles)
// - PUT /profiles/: add new profile (no response). A separate
// StartLoginInteractive() is needed to populate and persist the new profile.
// - GET /profiles/current: current profile (JSON-ecoded ipn.LoginProfile)
// - GET /profiles/<id>: output profile (JSON-ecoded ipn.LoginProfile)
// - POST /profiles/<id>: switch to profile (no response)
// - DELETE /profiles/<id>: delete profile (no response)
func ( h * Handler ) serveProfiles ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "profiles access denied" , http . StatusForbidden )
return
}
2023-02-01 21:43:06 +00:00
suffix , ok := strings . CutPrefix ( r . URL . EscapedPath ( ) , "/localapi/v0/profiles/" )
2022-11-10 21:38:22 +00:00
if ! ok {
2022-11-18 18:13:14 +00:00
http . Error ( w , "misconfigured" , http . StatusInternalServerError )
return
2022-11-10 21:38:22 +00:00
}
if suffix == "" {
switch r . Method {
2023-01-27 03:35:26 +00:00
case httpm . GET :
2022-11-10 21:38:22 +00:00
w . Header ( ) . Set ( "Content-Type" , "application/json" )
json . NewEncoder ( w ) . Encode ( h . b . ListProfiles ( ) )
2023-01-27 03:35:26 +00:00
case httpm . PUT :
2022-11-10 21:38:22 +00:00
err := h . b . NewProfile ( )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
w . WriteHeader ( http . StatusCreated )
default :
http . Error ( w , "use GET or PUT" , http . StatusMethodNotAllowed )
}
return
}
suffix , err := url . PathUnescape ( suffix )
if err != nil {
http . Error ( w , "bad profile ID" , http . StatusBadRequest )
return
}
if suffix == "current" {
switch r . Method {
2023-01-27 03:35:26 +00:00
case httpm . GET :
2022-11-10 21:38:22 +00:00
w . Header ( ) . Set ( "Content-Type" , "application/json" )
json . NewEncoder ( w ) . Encode ( h . b . CurrentProfile ( ) )
default :
http . Error ( w , "use GET" , http . StatusMethodNotAllowed )
}
return
}
profileID := ipn . ProfileID ( suffix )
switch r . Method {
2023-01-27 03:35:26 +00:00
case httpm . GET :
2022-11-10 21:38:22 +00:00
profiles := h . b . ListProfiles ( )
profileIndex := slices . IndexFunc ( profiles , func ( p ipn . LoginProfile ) bool {
return p . ID == profileID
} )
if profileIndex == - 1 {
http . Error ( w , "Profile not found" , http . StatusNotFound )
return
}
w . Header ( ) . Set ( "Content-Type" , "application/json" )
json . NewEncoder ( w ) . Encode ( profiles [ profileIndex ] )
2023-01-27 03:35:26 +00:00
case httpm . POST :
2022-11-10 21:38:22 +00:00
err := h . b . SwitchProfile ( profileID )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
w . WriteHeader ( http . StatusNoContent )
2023-01-27 03:35:26 +00:00
case httpm . DELETE :
2022-11-10 21:38:22 +00:00
err := h . b . DeleteProfile ( profileID )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
w . WriteHeader ( http . StatusNoContent )
default :
http . Error ( w , "use POST or DELETE" , http . StatusMethodNotAllowed )
}
}
2023-08-02 15:56:18 +01:00
// serveQueryFeature makes a request to the "/machine/feature/query"
// Noise endpoint to get instructions on how to enable a feature, such as
// Funnel, for the node's tailnet.
//
// This request itself does not directly enable the feature on behalf of
// the node, but rather returns information that can be presented to the
// acting user about where/how to enable the feature. If relevant, this
// includes a control URL the user can visit to explicitly consent to
// using the feature.
//
// See tailcfg.QueryFeatureResponse for full response structure.
func ( h * Handler ) serveQueryFeature ( w http . ResponseWriter , r * http . Request ) {
feature := r . FormValue ( "feature" )
switch {
case ! h . PermitRead :
http . Error ( w , "access denied" , http . StatusForbidden )
return
case r . Method != httpm . POST :
http . Error ( w , "use POST" , http . StatusMethodNotAllowed )
return
case feature == "" :
http . Error ( w , "missing feature" , http . StatusInternalServerError )
return
}
nm := h . b . NetMap ( )
if nm == nil {
http . Error ( w , "no netmap" , http . StatusServiceUnavailable )
return
}
b , err := json . Marshal ( & tailcfg . QueryFeatureRequest {
NodeKey : nm . NodeKey ,
Feature : feature ,
} )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
req , err := http . NewRequestWithContext ( r . Context ( ) ,
"POST" , "https://unused/machine/feature/query" , bytes . NewReader ( b ) )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
resp , err := h . b . DoNoiseRequest ( req )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
defer resp . Body . Close ( )
w . Header ( ) . Set ( "Content-Type" , "application/json" )
w . WriteHeader ( resp . StatusCode )
if _ , err := io . Copy ( w , resp . Body ) ; err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
}
2021-03-19 04:07:58 +00:00
func defBool ( a string , def bool ) bool {
if a == "" {
return def
}
v , err := strconv . ParseBool ( a )
if err != nil {
return def
}
return v
2021-03-19 02:34:59 +00:00
}
2022-12-09 22:21:53 +00:00
2023-01-19 22:28:49 +00:00
func ( h * Handler ) serveDebugCapture ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitWrite {
http . Error ( w , "debug access denied" , http . StatusForbidden )
return
}
if r . Method != "POST" {
http . Error ( w , "POST required" , http . StatusMethodNotAllowed )
return
}
2024-02-05 17:34:41 +00:00
w . WriteHeader ( http . StatusOK )
2023-01-19 22:28:49 +00:00
w . ( http . Flusher ) . Flush ( )
h . b . StreamDebugCapture ( r . Context ( ) , w )
}
2023-03-21 23:16:25 +00:00
func ( h * Handler ) serveDebugLog ( w http . ResponseWriter , r * http . Request ) {
if ! h . PermitRead {
http . Error ( w , "debug-log access denied" , http . StatusForbidden )
return
}
if r . Method != httpm . POST {
http . Error ( w , "only POST allowed" , http . StatusMethodNotAllowed )
return
}
defer h . b . TryFlushLogs ( ) // kick off upload after we're done logging
type logRequestJSON struct {
Lines [ ] string
Prefix string
}
var logRequest logRequestJSON
if err := json . NewDecoder ( r . Body ) . Decode ( & logRequest ) ; err != nil {
2023-10-13 23:40:10 +01:00
http . Error ( w , "invalid JSON body" , http . StatusBadRequest )
2023-03-21 23:16:25 +00:00
return
}
prefix := logRequest . Prefix
if prefix == "" {
prefix = "debug-log"
}
logf := logger . WithPrefix ( h . logf , prefix + ": " )
// We can write logs too fast for logtail to handle, even when
// opting-out of rate limits. Limit ourselves to at most one message
// per 20ms and a burst of 60 log lines, which should be fast enough to
// not block for too long but slow enough that we can upload all lines.
2023-07-27 20:41:31 +01:00
logf = logger . SlowLoggerWithClock ( r . Context ( ) , logf , 20 * time . Millisecond , 60 , h . clock . Now )
2023-03-21 23:16:25 +00:00
for _ , line := range logRequest . Lines {
logf ( "%s" , line )
}
w . WriteHeader ( http . StatusNoContent )
}
2023-11-09 21:00:47 +00:00
// serveUpdateCheck returns the ClientVersion from Status, which contains
// information on whether an update is available, and if so, what version,
// *if* we support auto-updates on this platform. If we don't, this endpoint
// always returns a ClientVersion saying we're running the newest version.
// Effectively, it tells us whether serveUpdateInstall will be able to install
// an update for us.
func ( h * Handler ) serveUpdateCheck ( w http . ResponseWriter , r * http . Request ) {
if r . Method != "GET" {
http . Error ( w , "only GET allowed" , http . StatusMethodNotAllowed )
return
}
2023-12-06 18:40:50 +00:00
if ! clientupdate . CanAutoUpdate ( ) {
2023-11-09 21:00:47 +00:00
// if we don't support auto-update, just say that we're up to date
2023-12-06 18:40:50 +00:00
json . NewEncoder ( w ) . Encode ( tailcfg . ClientVersion { RunningLatest : true } )
2023-11-09 21:00:47 +00:00
return
}
cv := h . b . StatusWithoutPeers ( ) . ClientVersion
// ipnstate.Status documentation notes that ClientVersion may be nil on some
// platforms where this information is unavailable. In that case, return a
// ClientVersion that says we're up to date, since we have no information on
// whether an update is possible.
if cv == nil {
cv = & tailcfg . ClientVersion { RunningLatest : true }
}
json . NewEncoder ( w ) . Encode ( cv )
}
// serveUpdateInstall sends a request to the LocalBackend to start a Tailscale
// self-update. A successful response does not indicate whether the update
// succeeded, only that the request was accepted. Clients should use
// serveUpdateProgress after pinging this endpoint to check how the update is
// going.
func ( h * Handler ) serveUpdateInstall ( w http . ResponseWriter , r * http . Request ) {
if r . Method != "POST" {
http . Error ( w , "only POST allowed" , http . StatusMethodNotAllowed )
return
}
w . WriteHeader ( http . StatusAccepted )
go h . b . DoSelfUpdate ( )
}
// serveUpdateProgress returns the status of an in-progress Tailscale self-update.
// This is provided as a slice of ipnstate.UpdateProgress structs with various
// log messages in order from oldest to newest. If an update is not in progress,
// the returned slice will be empty.
func ( h * Handler ) serveUpdateProgress ( w http . ResponseWriter , r * http . Request ) {
if r . Method != "GET" {
http . Error ( w , "only GET allowed" , http . StatusMethodNotAllowed )
return
}
ups := h . b . GetSelfUpdateProgress ( )
json . NewEncoder ( w ) . Encode ( ups )
}
2024-02-09 17:26:43 +00:00
// serveTailFSFileServerAddr handles updates of the tailfs file server address.
func ( h * Handler ) serveTailFSFileServerAddr ( w http . ResponseWriter , r * http . Request ) {
2024-02-02 18:45:32 +00:00
if r . Method != "PUT" {
http . Error ( w , "only PUT allowed" , http . StatusMethodNotAllowed )
return
}
b , err := io . ReadAll ( r . Body )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusBadRequest )
return
}
2024-02-09 17:26:43 +00:00
h . b . TailFSSetFileServerAddr ( string ( b ) )
2024-02-02 18:45:32 +00:00
w . WriteHeader ( http . StatusCreated )
}
// serveShares handles the management of tailfs shares.
2024-03-08 16:43:32 +00:00
//
// PUT - adds or updates an existing share
// DELETE - removes a share
// GET - gets a list of all shares, sorted by name
// POST - renames an existing share
2024-02-02 18:45:32 +00:00
func ( h * Handler ) serveShares ( w http . ResponseWriter , r * http . Request ) {
2024-02-09 17:26:43 +00:00
if ! h . b . TailFSSharingEnabled ( ) {
2024-03-08 16:43:32 +00:00
http . Error ( w , ` tailfs sharing not enabled, please add the attribute "tailfs:share" to this node in your ACLs' "nodeAttrs" section ` , http . StatusForbidden )
2024-02-02 18:45:32 +00:00
return
}
switch r . Method {
case "PUT" :
var share tailfs . Share
err := json . NewDecoder ( r . Body ) . Decode ( & share )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusBadRequest )
return
}
share . Path = path . Clean ( share . Path )
fi , err := os . Stat ( share . Path )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusBadRequest )
return
}
if ! fi . IsDir ( ) {
http . Error ( w , "not a directory" , http . StatusBadRequest )
return
}
if tailfs . AllowShareAs ( ) {
// share as the connected user
username , err := h . getUsername ( )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
share . As = username
}
2024-03-08 16:43:32 +00:00
err = h . b . TailFSSetShare ( & share )
2024-02-02 18:45:32 +00:00
if err != nil {
2024-03-08 16:43:32 +00:00
if errors . Is ( err , ipnlocal . ErrInvalidShareName ) {
http . Error ( w , "invalid share name" , http . StatusBadRequest )
return
}
2024-02-02 18:45:32 +00:00
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
w . WriteHeader ( http . StatusCreated )
case "DELETE" :
2024-03-08 16:43:32 +00:00
b , err := io . ReadAll ( r . Body )
2024-02-02 18:45:32 +00:00
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusBadRequest )
return
}
2024-03-08 16:43:32 +00:00
err = h . b . TailFSRemoveShare ( string ( b ) )
2024-02-02 18:45:32 +00:00
if err != nil {
if os . IsNotExist ( err ) {
http . Error ( w , "share not found" , http . StatusNotFound )
return
}
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
w . WriteHeader ( http . StatusNoContent )
2024-03-08 16:43:32 +00:00
case "POST" :
var names [ 2 ] string
err := json . NewDecoder ( r . Body ) . Decode ( & names )
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusBadRequest )
return
}
err = h . b . TailFSRenameShare ( names [ 0 ] , names [ 1 ] )
if err != nil {
if os . IsNotExist ( err ) {
http . Error ( w , "share not found" , http . StatusNotFound )
return
}
if os . IsExist ( err ) {
http . Error ( w , "share name already used" , http . StatusBadRequest )
return
}
if errors . Is ( err , ipnlocal . ErrInvalidShareName ) {
http . Error ( w , "invalid share name" , http . StatusBadRequest )
return
}
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
w . WriteHeader ( http . StatusNoContent )
2024-02-02 18:45:32 +00:00
case "GET" :
2024-03-07 16:56:11 +00:00
shares := h . b . TailFSGetShares ( )
err := json . NewEncoder ( w ) . Encode ( shares )
2024-02-02 18:45:32 +00:00
if err != nil {
http . Error ( w , err . Error ( ) , http . StatusInternalServerError )
return
}
default :
http . Error ( w , "unsupported method" , http . StatusMethodNotAllowed )
}
}
2022-12-09 22:21:53 +00:00
var (
metricInvalidRequests = clientmetric . NewCounter ( "localapi_invalid_requests" )
// User-visible LocalAPI endpoints.
metricFilePutCalls = clientmetric . NewCounter ( "localapi_file_put" )
)