2023-01-27 21:37:20 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
2022-06-07 21:24:22 +00:00
|
|
|
|
|
|
|
// The wasm package builds a WebAssembly module that provides a subset of
|
|
|
|
// Tailscale APIs to JavaScript.
|
|
|
|
//
|
|
|
|
// When run in the browser, a newIPN(config) function is added to the global JS
|
|
|
|
// namespace. When called it returns an ipn object with the methods
|
|
|
|
// run(callbacks), login(), logout(), and ssh(...).
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"context"
|
|
|
|
"encoding/hex"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"math/rand"
|
|
|
|
"net"
|
2022-08-02 23:47:43 +00:00
|
|
|
"net/http"
|
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
|
|
|
"net/netip"
|
2022-06-07 21:24:22 +00:00
|
|
|
"strings"
|
|
|
|
"syscall/js"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"golang.org/x/crypto/ssh"
|
|
|
|
"tailscale.com/control/controlclient"
|
|
|
|
"tailscale.com/ipn"
|
|
|
|
"tailscale.com/ipn/ipnlocal"
|
|
|
|
"tailscale.com/ipn/ipnserver"
|
|
|
|
"tailscale.com/ipn/store/mem"
|
2022-08-03 23:15:21 +00:00
|
|
|
"tailscale.com/logpolicy"
|
|
|
|
"tailscale.com/logtail"
|
2022-06-07 21:24:22 +00:00
|
|
|
"tailscale.com/net/netns"
|
|
|
|
"tailscale.com/net/tsdial"
|
|
|
|
"tailscale.com/safesocket"
|
|
|
|
"tailscale.com/tailcfg"
|
2023-05-03 20:57:17 +00:00
|
|
|
"tailscale.com/tsd"
|
2022-06-07 21:24:22 +00:00
|
|
|
"tailscale.com/wgengine"
|
|
|
|
"tailscale.com/wgengine/netstack"
|
|
|
|
"tailscale.com/words"
|
|
|
|
)
|
|
|
|
|
2022-08-04 17:37:19 +00:00
|
|
|
// ControlURL defines the URL to be used for connection to Control.
|
|
|
|
var ControlURL = ipn.DefaultControlURL
|
|
|
|
|
2022-06-07 21:24:22 +00:00
|
|
|
func main() {
|
2023-04-17 22:38:24 +00:00
|
|
|
js.Global().Set("newIPN", js.FuncOf(func(this js.Value, args []js.Value) any {
|
2022-06-07 21:24:22 +00:00
|
|
|
if len(args) != 1 {
|
|
|
|
log.Fatal("Usage: newIPN(config)")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return newIPN(args[0])
|
|
|
|
}))
|
|
|
|
// Keep Go runtime alive, otherwise it will be shut down before newIPN gets
|
|
|
|
// called.
|
|
|
|
<-make(chan bool)
|
|
|
|
}
|
|
|
|
|
|
|
|
func newIPN(jsConfig js.Value) map[string]any {
|
|
|
|
netns.SetEnabled(false)
|
2022-08-03 23:15:21 +00:00
|
|
|
|
|
|
|
var store ipn.StateStore
|
2022-09-12 18:51:19 +00:00
|
|
|
if jsStateStorage := jsConfig.Get("stateStorage"); !jsStateStorage.IsUndefined() {
|
2022-08-03 23:15:21 +00:00
|
|
|
store = &jsStateStore{jsStateStorage}
|
2022-09-12 18:51:19 +00:00
|
|
|
} else {
|
|
|
|
store = new(mem.Store)
|
2022-08-03 23:15:21 +00:00
|
|
|
}
|
|
|
|
|
2022-08-24 01:05:23 +00:00
|
|
|
controlURL := ControlURL
|
2022-09-12 18:51:19 +00:00
|
|
|
if jsControlURL := jsConfig.Get("controlURL"); jsControlURL.Type() == js.TypeString {
|
2022-08-24 01:05:23 +00:00
|
|
|
controlURL = jsControlURL.String()
|
|
|
|
}
|
|
|
|
|
2022-08-09 20:07:01 +00:00
|
|
|
var authKey string
|
2022-09-12 18:51:19 +00:00
|
|
|
if jsAuthKey := jsConfig.Get("authKey"); jsAuthKey.Type() == js.TypeString {
|
2022-08-09 20:07:01 +00:00
|
|
|
authKey = jsAuthKey.String()
|
|
|
|
}
|
|
|
|
|
2022-09-12 18:51:19 +00:00
|
|
|
var hostname string
|
|
|
|
if jsHostname := jsConfig.Get("hostname"); jsHostname.Type() == js.TypeString {
|
|
|
|
hostname = jsHostname.String()
|
|
|
|
} else {
|
|
|
|
hostname = generateHostname()
|
|
|
|
}
|
|
|
|
|
2022-08-03 23:15:21 +00:00
|
|
|
lpc := getOrCreateLogPolicyConfig(store)
|
|
|
|
c := logtail.Config{
|
|
|
|
Collection: lpc.Collection,
|
|
|
|
PrivateID: lpc.PrivateID,
|
|
|
|
// NewZstdEncoder is intentionally not passed in, compressed requests
|
|
|
|
// set HTTP headers that are not supported by the no-cors fetching mode.
|
|
|
|
HTTPC: &http.Client{Transport: &noCORSTransport{http.DefaultTransport}},
|
|
|
|
}
|
|
|
|
logtail := logtail.NewLogger(c, log.Printf)
|
|
|
|
logf := logtail.Logf
|
2022-06-07 21:24:22 +00:00
|
|
|
|
2023-05-03 20:57:17 +00:00
|
|
|
sys := new(tsd.System)
|
|
|
|
sys.Set(store)
|
2022-09-30 21:15:17 +00:00
|
|
|
dialer := &tsdial.Dialer{Logf: logf}
|
2022-06-07 21:24:22 +00:00
|
|
|
eng, err := wgengine.NewUserspaceEngine(logf, wgengine.Config{
|
2023-05-10 04:14:41 +00:00
|
|
|
Dialer: dialer,
|
|
|
|
SetSubsystem: sys.Set,
|
2022-06-07 21:24:22 +00:00
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2023-05-03 20:57:17 +00:00
|
|
|
sys.Set(eng)
|
2022-06-07 21:24:22 +00:00
|
|
|
|
2023-05-03 20:57:17 +00:00
|
|
|
ns, err := netstack.Create(logf, sys.Tun.Get(), eng, sys.MagicSock.Get(), dialer, sys.DNSManager.Get())
|
2022-06-07 21:24:22 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("netstack.Create: %v", err)
|
|
|
|
}
|
|
|
|
ns.ProcessLocalIPs = true
|
|
|
|
ns.ProcessSubnets = true
|
2022-12-23 18:22:39 +00:00
|
|
|
|
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
|
|
|
dialer.UseNetstackForIP = func(ip netip.Addr) bool {
|
2022-06-07 21:24:22 +00:00
|
|
|
return true
|
|
|
|
}
|
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
|
|
|
dialer.NetstackDialTCP = func(ctx context.Context, dst netip.AddrPort) (net.Conn, error) {
|
2022-06-07 21:24:22 +00:00
|
|
|
return ns.DialContextTCP(ctx, dst)
|
|
|
|
}
|
2023-05-03 20:57:17 +00:00
|
|
|
sys.NetstackRouter.Set(true)
|
2022-06-07 21:24:22 +00:00
|
|
|
|
2023-03-23 17:49:56 +00:00
|
|
|
logid := lpc.PublicID
|
2023-04-17 23:01:41 +00:00
|
|
|
srv := ipnserver.New(logf, logid, nil /* no netMon */)
|
2023-05-03 20:57:17 +00:00
|
|
|
lb, err := ipnlocal.NewLocalBackend(logf, logid, sys, controlclient.LoginEphemeral)
|
2022-06-07 21:24:22 +00:00
|
|
|
if err != nil {
|
2022-11-27 21:07:41 +00:00
|
|
|
log.Fatalf("ipnlocal.NewLocalBackend: %v", err)
|
2022-06-07 21:24:22 +00:00
|
|
|
}
|
2022-12-23 18:22:39 +00:00
|
|
|
if err := ns.Start(lb); err != nil {
|
|
|
|
log.Fatalf("failed to start netstack: %v", err)
|
|
|
|
}
|
2022-11-27 21:07:41 +00:00
|
|
|
srv.SetLocalBackend(lb)
|
2022-06-07 21:24:22 +00:00
|
|
|
|
|
|
|
jsIPN := &jsIPN{
|
2022-08-24 01:05:23 +00:00
|
|
|
dialer: dialer,
|
|
|
|
srv: srv,
|
|
|
|
lb: lb,
|
|
|
|
controlURL: controlURL,
|
|
|
|
authKey: authKey,
|
2022-09-12 18:51:19 +00:00
|
|
|
hostname: hostname,
|
2022-06-07 21:24:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return map[string]any{
|
2023-04-17 22:38:24 +00:00
|
|
|
"run": js.FuncOf(func(this js.Value, args []js.Value) any {
|
2022-06-07 21:24:22 +00:00
|
|
|
if len(args) != 1 {
|
|
|
|
log.Fatal(`Usage: run({
|
|
|
|
notifyState(state: int): void,
|
|
|
|
notifyNetMap(netMap: object): void,
|
|
|
|
notifyBrowseToURL(url: string): void,
|
2022-07-27 22:11:17 +00:00
|
|
|
notifyPanicRecover(err: string): void,
|
2022-06-07 21:24:22 +00:00
|
|
|
})`)
|
|
|
|
return nil
|
|
|
|
}
|
2022-08-24 01:05:23 +00:00
|
|
|
jsIPN.run(args[0])
|
2022-06-07 21:24:22 +00:00
|
|
|
return nil
|
|
|
|
}),
|
2023-04-17 22:38:24 +00:00
|
|
|
"login": js.FuncOf(func(this js.Value, args []js.Value) any {
|
2022-06-07 21:24:22 +00:00
|
|
|
if len(args) != 0 {
|
|
|
|
log.Printf("Usage: login()")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
jsIPN.login()
|
|
|
|
return nil
|
|
|
|
}),
|
2023-04-17 22:38:24 +00:00
|
|
|
"logout": js.FuncOf(func(this js.Value, args []js.Value) any {
|
2022-06-07 21:24:22 +00:00
|
|
|
if len(args) != 0 {
|
|
|
|
log.Printf("Usage: logout()")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
jsIPN.logout()
|
|
|
|
return nil
|
|
|
|
}),
|
2023-04-17 22:38:24 +00:00
|
|
|
"ssh": js.FuncOf(func(this js.Value, args []js.Value) any {
|
2022-07-29 18:37:17 +00:00
|
|
|
if len(args) != 3 {
|
|
|
|
log.Printf("Usage: ssh(hostname, userName, termConfig)")
|
2022-06-07 21:24:22 +00:00
|
|
|
return nil
|
|
|
|
}
|
2022-08-02 00:41:55 +00:00
|
|
|
return jsIPN.ssh(
|
2022-06-07 21:24:22 +00:00
|
|
|
args[0].String(),
|
2022-07-29 18:37:17 +00:00
|
|
|
args[1].String(),
|
|
|
|
args[2])
|
2022-06-07 21:24:22 +00:00
|
|
|
}),
|
2023-04-17 22:38:24 +00:00
|
|
|
"fetch": js.FuncOf(func(this js.Value, args []js.Value) any {
|
2022-08-02 23:47:43 +00:00
|
|
|
if len(args) != 1 {
|
|
|
|
log.Printf("Usage: fetch(url)")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
url := args[0].String()
|
|
|
|
return jsIPN.fetch(url)
|
|
|
|
}),
|
2022-06-07 21:24:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type jsIPN struct {
|
2022-08-24 01:05:23 +00:00
|
|
|
dialer *tsdial.Dialer
|
|
|
|
srv *ipnserver.Server
|
|
|
|
lb *ipnlocal.LocalBackend
|
|
|
|
controlURL string
|
|
|
|
authKey string
|
2022-09-12 18:51:19 +00:00
|
|
|
hostname string
|
2022-08-24 01:05:23 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var jsIPNState = map[ipn.State]string{
|
|
|
|
ipn.NoState: "NoState",
|
|
|
|
ipn.InUseOtherUser: "InUseOtherUser",
|
|
|
|
ipn.NeedsLogin: "NeedsLogin",
|
|
|
|
ipn.NeedsMachineAuth: "NeedsMachineAuth",
|
|
|
|
ipn.Stopped: "Stopped",
|
|
|
|
ipn.Starting: "Starting",
|
|
|
|
ipn.Running: "Running",
|
|
|
|
}
|
|
|
|
|
|
|
|
var jsMachineStatus = map[tailcfg.MachineStatus]string{
|
|
|
|
tailcfg.MachineUnknown: "MachineUnknown",
|
|
|
|
tailcfg.MachineUnauthorized: "MachineUnauthorized",
|
|
|
|
tailcfg.MachineAuthorized: "MachineAuthorized",
|
|
|
|
tailcfg.MachineInvalid: "MachineInvalid",
|
2022-06-07 21:24:22 +00:00
|
|
|
}
|
|
|
|
|
2022-08-24 01:05:23 +00:00
|
|
|
func (i *jsIPN) run(jsCallbacks js.Value) {
|
2022-06-07 21:24:22 +00:00
|
|
|
notifyState := func(state ipn.State) {
|
2022-08-24 01:05:23 +00:00
|
|
|
jsCallbacks.Call("notifyState", jsIPNState[state])
|
2022-06-07 21:24:22 +00:00
|
|
|
}
|
|
|
|
notifyState(ipn.NoState)
|
|
|
|
|
|
|
|
i.lb.SetNotifyCallback(func(n ipn.Notify) {
|
2022-07-27 22:11:17 +00:00
|
|
|
// Panics in the notify callback are likely due to be due to bugs in
|
|
|
|
// this bridging module (as opposed to actual bugs in Tailscale) and
|
|
|
|
// thus may be recoverable. Let the UI know, and allow the user to
|
|
|
|
// choose if they want to reload the page.
|
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
fmt.Println("Panic recovered:", r)
|
|
|
|
jsCallbacks.Call("notifyPanicRecover", fmt.Sprint(r))
|
|
|
|
}
|
|
|
|
}()
|
2022-06-07 21:24:22 +00:00
|
|
|
log.Printf("NOTIFY: %+v", n)
|
|
|
|
if n.State != nil {
|
|
|
|
notifyState(*n.State)
|
|
|
|
}
|
2022-08-04 21:18:47 +00:00
|
|
|
if nm := n.NetMap; nm != nil {
|
2022-06-07 21:24:22 +00:00
|
|
|
jsNetMap := jsNetMap{
|
|
|
|
Self: jsNetMapSelfNode{
|
|
|
|
jsNetMapNode: jsNetMapNode{
|
|
|
|
Name: nm.Name,
|
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
|
|
|
Addresses: mapSlice(nm.Addresses, func(a netip.Prefix) string { return a.Addr().String() }),
|
2022-06-07 21:24:22 +00:00
|
|
|
NodeKey: nm.NodeKey.String(),
|
|
|
|
MachineKey: nm.MachineKey.String(),
|
|
|
|
},
|
2022-08-24 01:05:23 +00:00
|
|
|
MachineStatus: jsMachineStatus[nm.MachineStatus],
|
2022-06-07 21:24:22 +00:00
|
|
|
},
|
2023-08-18 14:57:44 +00:00
|
|
|
Peers: mapSlice(nm.Peers, func(p tailcfg.NodeView) jsNetMapPeerNode {
|
|
|
|
name := p.Name()
|
2022-07-29 18:37:17 +00:00
|
|
|
if name == "" {
|
|
|
|
// In practice this should only happen for Hello.
|
2023-08-18 14:57:44 +00:00
|
|
|
name = p.Hostinfo().Hostname()
|
|
|
|
}
|
|
|
|
addrs := make([]string, p.Addresses().Len())
|
|
|
|
for i := range p.Addresses().LenIter() {
|
|
|
|
addrs[i] = p.Addresses().At(i).Addr().String()
|
2022-07-29 18:37:17 +00:00
|
|
|
}
|
2022-06-07 21:24:22 +00:00
|
|
|
return jsNetMapPeerNode{
|
|
|
|
jsNetMapNode: jsNetMapNode{
|
2022-07-29 18:37:17 +00:00
|
|
|
Name: name,
|
2023-08-18 14:57:44 +00:00
|
|
|
Addresses: addrs,
|
|
|
|
MachineKey: p.Machine().String(),
|
|
|
|
NodeKey: p.Key().String(),
|
2022-06-07 21:24:22 +00:00
|
|
|
},
|
2023-08-18 14:57:44 +00:00
|
|
|
Online: p.Online(),
|
|
|
|
TailscaleSSHEnabled: p.Hostinfo().TailscaleSSHEnabled(),
|
2022-06-07 21:24:22 +00:00
|
|
|
}
|
|
|
|
}),
|
2023-08-21 17:53:57 +00:00
|
|
|
LockedOut: nm.TKAEnabled && nm.SelfNode.KeySignature().Len() == 0,
|
2022-06-07 21:24:22 +00:00
|
|
|
}
|
|
|
|
if jsonNetMap, err := json.Marshal(jsNetMap); err == nil {
|
|
|
|
jsCallbacks.Call("notifyNetMap", string(jsonNetMap))
|
|
|
|
} else {
|
|
|
|
log.Printf("Could not generate JSON netmap: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if n.BrowseToURL != nil {
|
|
|
|
jsCallbacks.Call("notifyBrowseToURL", *n.BrowseToURL)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
err := i.lb.Start(ipn.Options{
|
|
|
|
UpdatePrefs: &ipn.Prefs{
|
2022-08-24 01:05:23 +00:00
|
|
|
ControlURL: i.controlURL,
|
2022-06-07 21:24:22 +00:00
|
|
|
RouteAll: false,
|
|
|
|
AllowSingleHosts: true,
|
|
|
|
WantRunning: true,
|
2022-09-12 18:51:19 +00:00
|
|
|
Hostname: i.hostname,
|
2022-06-07 21:24:22 +00:00
|
|
|
},
|
2022-08-24 01:05:23 +00:00
|
|
|
AuthKey: i.authKey,
|
2022-06-07 21:24:22 +00:00
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Start error: %v", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
go func() {
|
2023-01-30 17:34:51 +00:00
|
|
|
ln, err := safesocket.Listen("")
|
2022-06-07 21:24:22 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("safesocket.Listen: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
err = i.srv.Run(context.Background(), ln)
|
|
|
|
log.Fatalf("ipnserver.Run exited: %v", err)
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (i *jsIPN) login() {
|
|
|
|
go i.lb.StartLoginInteractive()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (i *jsIPN) logout() {
|
|
|
|
if i.lb.State() == ipn.NoState {
|
|
|
|
log.Printf("Backend not running")
|
|
|
|
}
|
2023-08-31 01:33:58 +00:00
|
|
|
go func() {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
defer cancel()
|
2023-09-01 02:11:20 +00:00
|
|
|
i.lb.Logout(ctx)
|
2023-08-31 01:33:58 +00:00
|
|
|
}()
|
2022-06-07 21:24:22 +00:00
|
|
|
}
|
|
|
|
|
2022-08-02 00:41:55 +00:00
|
|
|
func (i *jsIPN) ssh(host, username string, termConfig js.Value) map[string]any {
|
|
|
|
jsSSHSession := &jsSSHSession{
|
|
|
|
jsIPN: i,
|
|
|
|
host: host,
|
|
|
|
username: username,
|
|
|
|
termConfig: termConfig,
|
|
|
|
}
|
|
|
|
|
|
|
|
go jsSSHSession.Run()
|
2022-07-29 18:37:17 +00:00
|
|
|
|
2022-08-02 00:41:55 +00:00
|
|
|
return map[string]any{
|
2023-04-17 22:38:24 +00:00
|
|
|
"close": js.FuncOf(func(this js.Value, args []js.Value) any {
|
2022-08-02 00:41:55 +00:00
|
|
|
return jsSSHSession.Close() != nil
|
|
|
|
}),
|
2023-04-17 22:38:24 +00:00
|
|
|
"resize": js.FuncOf(func(this js.Value, args []js.Value) any {
|
2022-08-02 00:41:55 +00:00
|
|
|
rows := args[0].Int()
|
|
|
|
cols := args[1].Int()
|
|
|
|
return jsSSHSession.Resize(rows, cols) != nil
|
|
|
|
}),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type jsSSHSession struct {
|
|
|
|
jsIPN *jsIPN
|
|
|
|
host string
|
|
|
|
username string
|
|
|
|
termConfig js.Value
|
|
|
|
session *ssh.Session
|
2022-09-08 01:22:35 +00:00
|
|
|
|
|
|
|
pendingResizeRows int
|
|
|
|
pendingResizeCols int
|
2022-08-02 00:41:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *jsSSHSession) Run() {
|
|
|
|
writeFn := s.termConfig.Get("writeFn")
|
2022-08-30 01:12:52 +00:00
|
|
|
writeErrorFn := s.termConfig.Get("writeErrorFn")
|
2022-08-02 00:41:55 +00:00
|
|
|
setReadFn := s.termConfig.Get("setReadFn")
|
|
|
|
rows := s.termConfig.Get("rows").Int()
|
|
|
|
cols := s.termConfig.Get("cols").Int()
|
2022-09-20 00:16:54 +00:00
|
|
|
timeoutSeconds := 5.0
|
|
|
|
if jsTimeoutSeconds := s.termConfig.Get("timeoutSeconds"); jsTimeoutSeconds.Type() == js.TypeNumber {
|
|
|
|
timeoutSeconds = jsTimeoutSeconds.Float()
|
|
|
|
}
|
2022-10-17 22:02:59 +00:00
|
|
|
onConnectionProgress := s.termConfig.Get("onConnectionProgress")
|
|
|
|
onConnected := s.termConfig.Get("onConnected")
|
2022-08-02 00:41:55 +00:00
|
|
|
onDone := s.termConfig.Get("onDone")
|
2022-06-07 21:24:22 +00:00
|
|
|
defer onDone.Invoke()
|
|
|
|
|
|
|
|
writeError := func(label string, err error) {
|
2022-08-30 01:12:52 +00:00
|
|
|
writeErrorFn.Invoke(fmt.Sprintf("%s Error: %v\r\n", label, err))
|
2022-06-07 21:24:22 +00:00
|
|
|
}
|
2022-10-17 22:02:59 +00:00
|
|
|
reportProgress := func(message string) {
|
|
|
|
onConnectionProgress.Invoke(message)
|
|
|
|
}
|
2022-06-07 21:24:22 +00:00
|
|
|
|
2022-09-20 00:16:54 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSeconds*float64(time.Second)))
|
2022-06-07 21:24:22 +00:00
|
|
|
defer cancel()
|
2022-10-17 22:02:59 +00:00
|
|
|
reportProgress(fmt.Sprintf("Connecting to %s…", strings.Split(s.host, ".")[0]))
|
2022-08-02 00:41:55 +00:00
|
|
|
c, err := s.jsIPN.dialer.UserDial(ctx, "tcp", net.JoinHostPort(s.host, "22"))
|
2022-06-07 21:24:22 +00:00
|
|
|
if err != nil {
|
|
|
|
writeError("Dial", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer c.Close()
|
|
|
|
|
|
|
|
config := &ssh.ClientConfig{
|
2022-10-17 22:02:59 +00:00
|
|
|
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
|
|
|
// Host keys are not used with Tailscale SSH, but we can use this
|
|
|
|
// callback to know that the connection has been established.
|
|
|
|
reportProgress("SSH connection established…")
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
User: s.username,
|
2022-06-07 21:24:22 +00:00
|
|
|
}
|
|
|
|
|
2022-10-17 22:02:59 +00:00
|
|
|
reportProgress("Starting SSH client…")
|
2022-08-02 00:41:55 +00:00
|
|
|
sshConn, _, _, err := ssh.NewClientConn(c, s.host, config)
|
2022-06-07 21:24:22 +00:00
|
|
|
if err != nil {
|
|
|
|
writeError("SSH Connection", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer sshConn.Close()
|
|
|
|
|
|
|
|
sshClient := ssh.NewClient(sshConn, nil, nil)
|
|
|
|
defer sshClient.Close()
|
|
|
|
|
|
|
|
session, err := sshClient.NewSession()
|
|
|
|
if err != nil {
|
|
|
|
writeError("SSH Session", err)
|
|
|
|
return
|
|
|
|
}
|
2022-08-02 00:41:55 +00:00
|
|
|
s.session = session
|
2022-06-07 21:24:22 +00:00
|
|
|
defer session.Close()
|
|
|
|
|
|
|
|
stdin, err := session.StdinPipe()
|
|
|
|
if err != nil {
|
|
|
|
writeError("SSH Stdin", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
session.Stdout = termWriter{writeFn}
|
|
|
|
session.Stderr = termWriter{writeFn}
|
|
|
|
|
2023-04-17 22:38:24 +00:00
|
|
|
setReadFn.Invoke(js.FuncOf(func(this js.Value, args []js.Value) any {
|
2022-06-07 21:24:22 +00:00
|
|
|
input := args[0].String()
|
|
|
|
_, err := stdin.Write([]byte(input))
|
|
|
|
if err != nil {
|
|
|
|
writeError("Write Input", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}))
|
|
|
|
|
2022-09-08 01:22:35 +00:00
|
|
|
// We might have gotten a resize notification since we started opening the
|
|
|
|
// session, pick up the latest size.
|
|
|
|
if s.pendingResizeRows != 0 {
|
|
|
|
rows = s.pendingResizeRows
|
|
|
|
}
|
|
|
|
if s.pendingResizeCols != 0 {
|
|
|
|
cols = s.pendingResizeCols
|
|
|
|
}
|
2022-06-07 21:24:22 +00:00
|
|
|
err = session.RequestPty("xterm", rows, cols, ssh.TerminalModes{})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
writeError("Pseudo Terminal", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
err = session.Shell()
|
|
|
|
if err != nil {
|
|
|
|
writeError("Shell", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-10-17 22:02:59 +00:00
|
|
|
onConnected.Invoke()
|
2022-06-07 21:24:22 +00:00
|
|
|
err = session.Wait()
|
|
|
|
if err != nil {
|
2022-08-02 00:41:55 +00:00
|
|
|
writeError("Wait", err)
|
2022-06-07 21:24:22 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-02 00:41:55 +00:00
|
|
|
func (s *jsSSHSession) Close() error {
|
2022-10-31 21:05:43 +00:00
|
|
|
if s.session == nil {
|
|
|
|
// We never had a chance to open the session, ignore the close request.
|
|
|
|
return nil
|
|
|
|
}
|
2022-08-02 00:41:55 +00:00
|
|
|
return s.session.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *jsSSHSession) Resize(rows, cols int) error {
|
2022-09-08 01:22:35 +00:00
|
|
|
if s.session == nil {
|
|
|
|
s.pendingResizeRows = rows
|
|
|
|
s.pendingResizeCols = cols
|
|
|
|
return nil
|
|
|
|
}
|
2022-08-02 00:41:55 +00:00
|
|
|
return s.session.WindowChange(rows, cols)
|
|
|
|
}
|
|
|
|
|
2022-08-02 23:47:43 +00:00
|
|
|
func (i *jsIPN) fetch(url string) js.Value {
|
|
|
|
return makePromise(func() (any, error) {
|
|
|
|
c := &http.Client{
|
|
|
|
Transport: &http.Transport{
|
|
|
|
DialContext: i.dialer.UserDial,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
res, err := c.Get(url)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return map[string]any{
|
|
|
|
"status": res.StatusCode,
|
|
|
|
"statusText": res.Status,
|
2023-04-17 22:38:24 +00:00
|
|
|
"text": js.FuncOf(func(this js.Value, args []js.Value) any {
|
2022-08-02 23:47:43 +00:00
|
|
|
return makePromise(func() (any, error) {
|
|
|
|
defer res.Body.Close()
|
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
if _, err := buf.ReadFrom(res.Body); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return buf.String(), nil
|
|
|
|
})
|
|
|
|
}),
|
|
|
|
// TODO: populate a more complete JS Response object
|
|
|
|
}, nil
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-06-07 21:24:22 +00:00
|
|
|
type termWriter struct {
|
|
|
|
f js.Value
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w termWriter) Write(p []byte) (n int, err error) {
|
|
|
|
r := bytes.Replace(p, []byte("\n"), []byte("\n\r"), -1)
|
|
|
|
w.f.Invoke(string(r))
|
|
|
|
return len(p), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type jsNetMap struct {
|
2023-03-03 21:28:23 +00:00
|
|
|
Self jsNetMapSelfNode `json:"self"`
|
|
|
|
Peers []jsNetMapPeerNode `json:"peers"`
|
|
|
|
LockedOut bool `json:"lockedOut"`
|
2022-06-07 21:24:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type jsNetMapNode struct {
|
2022-07-26 22:45:52 +00:00
|
|
|
Name string `json:"name"`
|
|
|
|
Addresses []string `json:"addresses"`
|
|
|
|
MachineKey string `json:"machineKey"`
|
|
|
|
NodeKey string `json:"nodeKey"`
|
2022-06-07 21:24:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type jsNetMapSelfNode struct {
|
|
|
|
jsNetMapNode
|
2022-08-24 01:05:23 +00:00
|
|
|
MachineStatus string `json:"machineStatus"`
|
2022-06-07 21:24:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type jsNetMapPeerNode struct {
|
|
|
|
jsNetMapNode
|
2022-07-27 22:11:17 +00:00
|
|
|
Online *bool `json:"online,omitempty"`
|
|
|
|
TailscaleSSHEnabled bool `json:"tailscaleSSHEnabled"`
|
2022-06-07 21:24:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type jsStateStore struct {
|
|
|
|
jsStateStorage js.Value
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *jsStateStore) ReadState(id ipn.StateKey) ([]byte, error) {
|
|
|
|
jsValue := s.jsStateStorage.Call("getState", string(id))
|
|
|
|
if jsValue.String() == "" {
|
|
|
|
return nil, ipn.ErrStateNotExist
|
|
|
|
}
|
|
|
|
return hex.DecodeString(jsValue.String())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *jsStateStore) WriteState(id ipn.StateKey, bs []byte) error {
|
|
|
|
s.jsStateStorage.Call("setState", string(id), hex.EncodeToString(bs))
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func mapSlice[T any, M any](a []T, f func(T) M) []M {
|
|
|
|
n := make([]M, len(a))
|
|
|
|
for i, e := range a {
|
|
|
|
n[i] = f(e)
|
|
|
|
}
|
|
|
|
return n
|
|
|
|
}
|
|
|
|
|
|
|
|
func filterSlice[T any](a []T, f func(T) bool) []T {
|
|
|
|
n := make([]T, 0, len(a))
|
|
|
|
for _, e := range a {
|
|
|
|
if f(e) {
|
|
|
|
n = append(n, e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return n
|
|
|
|
}
|
|
|
|
|
|
|
|
func generateHostname() string {
|
|
|
|
tails := words.Tails()
|
|
|
|
scales := words.Scales()
|
|
|
|
if rand.Int()%2 == 0 {
|
|
|
|
// JavaScript
|
|
|
|
tails = filterSlice(tails, func(s string) bool { return strings.HasPrefix(s, "j") })
|
|
|
|
scales = filterSlice(scales, func(s string) bool { return strings.HasPrefix(s, "s") })
|
|
|
|
} else {
|
|
|
|
// WebAssembly
|
|
|
|
tails = filterSlice(tails, func(s string) bool { return strings.HasPrefix(s, "w") })
|
|
|
|
scales = filterSlice(scales, func(s string) bool { return strings.HasPrefix(s, "a") })
|
|
|
|
}
|
|
|
|
|
|
|
|
tail := tails[rand.Intn(len(tails))]
|
|
|
|
scale := scales[rand.Intn(len(scales))]
|
|
|
|
return fmt.Sprintf("%s-%s", tail, scale)
|
|
|
|
}
|
2022-08-02 23:47:43 +00:00
|
|
|
|
|
|
|
// makePromise handles the boilerplate of wrapping goroutines with JS promises.
|
|
|
|
// f is run on a goroutine and its return value is used to resolve the promise
|
|
|
|
// (or reject it if an error is returned).
|
|
|
|
func makePromise(f func() (any, error)) js.Value {
|
2023-04-17 22:38:24 +00:00
|
|
|
handler := js.FuncOf(func(this js.Value, args []js.Value) any {
|
2022-08-02 23:47:43 +00:00
|
|
|
resolve := args[0]
|
|
|
|
reject := args[1]
|
|
|
|
go func() {
|
|
|
|
if res, err := f(); err == nil {
|
|
|
|
resolve.Invoke(res)
|
|
|
|
} else {
|
|
|
|
reject.Invoke(err.Error())
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
promiseConstructor := js.Global().Get("Promise")
|
|
|
|
return promiseConstructor.New(handler)
|
|
|
|
}
|
2022-08-03 23:15:21 +00:00
|
|
|
|
|
|
|
const logPolicyStateKey = "log-policy"
|
|
|
|
|
|
|
|
func getOrCreateLogPolicyConfig(state ipn.StateStore) *logpolicy.Config {
|
|
|
|
if configBytes, err := state.ReadState(logPolicyStateKey); err == nil {
|
|
|
|
if config, err := logpolicy.ConfigFromBytes(configBytes); err == nil {
|
|
|
|
return config
|
|
|
|
} else {
|
|
|
|
log.Printf("Could not parse log policy config: %v", err)
|
|
|
|
}
|
|
|
|
} else if err != ipn.ErrStateNotExist {
|
|
|
|
log.Printf("Could not get log policy config from state store: %v", err)
|
|
|
|
}
|
|
|
|
config := logpolicy.NewConfig(logtail.CollectionNode)
|
|
|
|
if err := state.WriteState(logPolicyStateKey, config.ToBytes()); err != nil {
|
|
|
|
log.Printf("Could not save log policy config to state store: %v", err)
|
|
|
|
}
|
|
|
|
return config
|
|
|
|
}
|
|
|
|
|
|
|
|
// noCORSTransport wraps a RoundTripper and forces the no-cors mode on requests,
|
|
|
|
// so that we can use it with non-CORS-aware servers.
|
|
|
|
type noCORSTransport struct {
|
|
|
|
http.RoundTripper
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *noCORSTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
|
|
req.Header.Set("js.fetch:mode", "no-cors")
|
|
|
|
resp, err := t.RoundTripper.RoundTrip(req)
|
|
|
|
if err == nil {
|
|
|
|
// In no-cors mode no response properties are returned. Populate just
|
|
|
|
// the status so that callers do not think this was an error.
|
|
|
|
resp.StatusCode = http.StatusOK
|
|
|
|
resp.Status = http.StatusText(http.StatusOK)
|
|
|
|
}
|
|
|
|
return resp, err
|
|
|
|
}
|