wasm play

See:

* https://twitter.com/bradfitz/status/1450916922288005122
* https://twitter.com/bradfitz/status/1451423386777751561
* https://twitter.com/bradfitz/status/1457830780550275075

Updates #3157

Change-Id: I7f5a1b1bc1b8a4af0a700834c3fe09c8c791f6dc
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
This commit is contained in:
Brad Fitzpatrick 2021-10-21 09:12:31 -07:00
parent cc91a05686
commit cd54f07bd9
10 changed files with 1398 additions and 3 deletions

View File

@ -16,7 +16,6 @@
"path/filepath"
"runtime"
"strings"
"syscall"
"github.com/peterbourgon/ff/v3/ffcli"
"inet.af/netaddr"
@ -116,7 +115,7 @@ func runSSH(ctx context.Context, args []string) error {
log.Printf("Running: %q, %q ...", ssh, argv)
}
if runtime.GOOS == "windows" {
if runtime.GOOS == "windows" || runtime.GOOS == "js" {
// Don't use syscall.Exec on Windows.
cmd := exec.Command(ssh, argv[1:]...)
cmd.Stdin = os.Stdin
@ -130,7 +129,7 @@ func runSSH(ctx context.Context, args []string) error {
return err
}
if err := syscall.Exec(ssh, argv, os.Environ()); err != nil {
if err := syscallExec(ssh, argv, os.Environ()); err != nil {
return err
}
return errors.New("unreachable")

View File

@ -0,0 +1,8 @@
//go:build !js
// +build !js
package cli
import "syscall"
var syscallExec = syscall.Exec

View File

@ -0,0 +1,5 @@
package cli
var syscallExec = func(argv0 string, argv []string, envv []string) (err error) {
panic("unreachable")
}

8
go.sum
View File

@ -289,6 +289,7 @@ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
github.com/github/fakeca v0.1.0 h1:Km/MVOFvclqxPM9dZBC4+QE564nU4gz4iZ0D9pMw28I=
github.com/github/fakeca v0.1.0/go.mod h1:+bormgoGMMuamOscx7N91aOuUST7wdaJ2rNjeohylyo=
@ -331,6 +332,8 @@ github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD87
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY=
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
github.com/go-redis/redis v6.15.8+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
@ -368,6 +371,8 @@ github.com/gobwas/pool v0.2.0 h1:QEmUOlnSjWtnpRGHF3SauEiOsy82Cup83Vf2LcMlnc8=
github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.0.2 h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo=
github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo=
github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/godbus/dbus/v5 v5.0.6 h1:mkgN1ofwASrYnJ5W6U/BxG15eXXXjirgZc7CLqkcaro=
@ -821,6 +826,8 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJ
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
github.com/moricho/tparallel v0.2.1 h1:95FytivzT6rYzdJLdtfn6m1bfFJylOJK41+lgv/EHf4=
@ -1119,6 +1126,7 @@ github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVM
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
github.com/ulikunitz/xz v0.5.7/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/ulikunitz/xz v0.5.10 h1:t92gobL9l3HE202wg3rlk19F6X+JOxl9BBrCCMYEYd8=

3
wasmtest/Makefile Normal file
View File

@ -0,0 +1,3 @@
run:
GOROOT=/home/bradfitz/hack/go GOOS=js GOARCH=wasm /home/bradfitz/hack/go/bin/go build -o test.wasm ./wasmmod/
go run serve.go

48
wasmtest/index.html Normal file
View File

@ -0,0 +1,48 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<html>
<head>
<meta charset="utf-8"/>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha256-/SIrNqv8h6QGKDuNoLGA4iret+kyesCkHGzVUUV0shc=" crossorigin="anonymous"></script>
<script src="https://use.fontawesome.com/47de3a5ce8.js"></script>
<script src="wasm_exec.js"></script>
<script>
const go = new Go();
WebAssembly.instantiateStreaming(fetch("test.wasm"), go.importObject).then((result) => {
go.run(result.instance);
});
</script>
</head>
<body>
<form id=topbar style='padding: 5px'>
<input type=button value="Start" onclick='startClicked()'>
<input type=button value="Logout" onclick='logoutClicked()'>
<input type=button value="Goroutines" onclick='seeGoroutines()'>
<input type=button value="StartLoginInteractive" onclick='startLoginInteractive()'>
<input type=button value="authkey" onclick='startAuthKey(prompt("auth key:", ""))'>
</form>
<div><b>Backend state: </b><span id='state'>(wasm loading)</span> <span id='loginURL'></span></div>
<div class="term" style='width: 100%; height: 25em;'>
<div class="inner"></div>
</div>
<div id=netmap></div>
<link rel="stylesheet" href="https://unpkg.com/xterm@4.15.0-beta.10/css/xterm.css" />
<style>
.xterm-viewport.xterm-viewport {
scrollbar-width: thin;
}
.xterm-viewport::-webkit-scrollbar {
width: 10px;
}
.xterm-viewport::-webkit-scrollbar-track {
opacity: 0;
}
.xterm-viewport::-webkit-scrollbar-thumb {
min-height: 20px;
background-color: #ffffff20;
}
</style>
<script src="https://unpkg.com/xterm@4.15.0-beta.10/lib/xterm.js"></script>
<script src="https://unpkg.com/xterm-addon-webgl@0.12.0-beta.15/lib/xterm-addon-webgl.js"></script>
<script src="term.js"></script>
</body>
</html>

15
wasmtest/serve.go Normal file
View File

@ -0,0 +1,15 @@
package main
import (
"log"
"net/http"
)
func main() {
log.Printf("listening on :9090")
err := http.ListenAndServe(":9090", http.FileServer(http.Dir(".")))
if err != nil {
log.Fatal(err)
return
}
}

265
wasmtest/term.js Normal file
View File

@ -0,0 +1,265 @@
// Hacked up version of https://xtermjs.org/js/demo.js
// for now.
$(function () {
// Custom theme to match style of xterm.js logo
var baseTheme = {
foreground: '#F8F8F8',
background: '#2D2E2C',
selection: '#5DA5D533',
black: '#1E1E1D',
brightBlack: '#262625',
red: '#CE5C5C',
brightRed: '#FF7272',
green: '#5BCC5B',
brightGreen: '#72FF72',
yellow: '#CCCC5B',
brightYellow: '#FFFF72',
blue: '#5D5DD3',
brightBlue: '#7279FF',
magenta: '#BC5ED1',
brightMagenta: '#E572FF',
cyan: '#5DA5D5',
brightCyan: '#72F0FF',
white: '#F8F8F8',
brightWhite: '#FFFFFF'
};
// vscode-snazzy https://github.com/Tyriar/vscode-snazzy
var otherTheme = {
foreground: '#eff0eb',
background: '#282a36',
selection: '#97979b33',
black: '#282a36',
brightBlack: '#686868',
red: '#ff5c57',
brightRed: '#ff5c57',
green: '#5af78e',
brightGreen: '#5af78e',
yellow: '#f3f99d',
brightYellow: '#f3f99d',
blue: '#57c7ff',
brightBlue: '#57c7ff',
magenta: '#ff6ac1',
brightMagenta: '#ff6ac1',
cyan: '#9aedfe',
brightCyan: '#9aedfe',
white: '#f1f1f0',
brightWhite: '#eff0eb'
};
var isBaseTheme = true;
var term = new window.Terminal({
fontFamily: '"Cascadia Code", Menlo, monospace',
theme: baseTheme,
cursorBlink: true
});
term.open(document.querySelector('.term .inner'));
theTerminal = term;
var isWebglEnabled = false;
try {
const webgl = new window.WebglAddon.WebglAddon();
term.loadAddon(webgl);
isWebglEnabled = true;
} catch (e) {
console.warn('WebGL addon threw an exception during load', e);
}
// Cancel wheel events from scrolling the page if the terminal has scrollback
document.querySelector('.xterm').addEventListener('wheel', e => {
if (term.buffer.active.baseY > 0) {
e.preventDefault();
}
});
function runFakeTerminal() {
if (term._initialized) {
return;
}
term._initialized = true;
term.prompt = () => {
term.write('\r\n$ ');
};
// TODO: Use a nicer default font
term.writeln('Tailscale js/wasm demo; try running `help`.');
prompt(term);
term.onData(e => {
switch (e) {
case '\u0003': // Ctrl+C
term.write('^C');
prompt(term);
break;
case '\r': // Enter
runCommand(term, command);
command = '';
break;
case '\u007F': // Backspace (DEL)
// Do not delete the prompt
if (term._core.buffer.x > 2) {
term.write('\b \b');
if (command.length > 0) {
command = command.substr(0, command.length - 1);
}
}
break;
default: // Print all other characters for demo
if (e >= String.fromCharCode(0x20) && e <= String.fromCharCode(0x7B) || e >= '\u00a0') {
command += e;
term.write(e);
}
}
});
// Create a very simple link provider which hardcodes links for certain lines
term.registerLinkProvider({
provideLinks(bufferLineNumber, callback) {
switch (bufferLineNumber) {
case 2:
callback([
{
text: 'VS Code',
range: { start: { x: 28, y: 2 }, end: { x: 34, y: 2 } },
activate() {
window.open('https://github.com/microsoft/vscode', '_blank');
}
},
{
text: 'Hyper',
range: { start: { x: 37, y: 2 }, end: { x: 41, y: 2 } },
activate() {
window.open('https://github.com/vercel/hyper', '_blank');
}
},
{
text: 'Theia',
range: { start: { x: 47, y: 2 }, end: { x: 51, y: 2 } },
activate() {
window.open('https://github.com/eclipse-theia/theia', '_blank');
}
}
]);
return;
case 8:
callback([
{
text: 'WebGL renderer',
range: { start: { x: 54, y: 8 }, end: { x: 67, y: 8 } },
activate() {
window.open('https://npmjs.com/package/xterm-addon-webgl', '_blank');
}
}
]);
return;
case 14:
callback([
{
text: 'Links',
range: { start: { x: 45, y: 14 }, end: { x: 49, y: 14 } },
activate() {
window.alert('You can handle links any way you want');
}
},
{
text: 'themes',
range: { start: { x: 52, y: 14 }, end: { x: 57, y: 14 } },
activate() {
isBaseTheme = !isBaseTheme;
term.setOption('theme', isBaseTheme ? baseTheme : otherTheme);
document.querySelector('.demo .inner').classList.toggle('other-theme', !isBaseTheme);
term.write(`\r\nActivated ${isBaseTheme ? 'xterm.js' : 'snazzy'} theme`);
prompt(term);
}
},
{
text: 'addons',
range: { start: { x: 60, y: 14 }, end: { x: 65, y: 14 } },
activate() {
window.open('/docs/guides/using-addons/', '_blank');
}
},
{
text: 'typed API',
range: { start: { x: 68, y: 14 }, end: { x: 76, y: 14 } },
activate() {
window.open('https://github.com/xtermjs/xterm.js/blob/master/typings/xterm.d.ts', '_blank');
}
},
]);
return;
}
callback(undefined);
}
});
}
function prompt(term) {
command = '';
term.write('\r\n$ ');
}
var command = '';
var commands = {
help: {
f: () => {
term.writeln([
'Welcome to Tailscale js/wasm! Try some of the commands below.',
'',
...Object.keys(commands).map(e => ` ${e.padEnd(10)} ${commands[e].description}`)
].join('\n\r'));
prompt(term);
},
description: 'Prints this help message',
},
ssh: {
f: () => {
term.writeln("TODO(bradfitz): hook up golang.org/x/crypto/ssh");
term.prompt(term);
},
description: 'SSH to a Tailscale peer'
},
tailscale: {
f: (line) => {
//term.writeln("TODO(bradfitz): run the tailscale command: "+line);
runTailscaleCLI(line, function () { term.prompt(term) });
},
description: 'run cmd/tailscale'
},
http: {
f: (line) => {
runFakeCURL(line, function () { term.prompt(term) });
},
description: 'fetch a URL'
},
ssh: {
f: (line) => {
runSSH(line, function () { term.prompt(term) });
},
description: 'SSH to host'
},
goroutines: {
f: () => {
seeGoroutines();
},
description: 'dump goroutines'
}
};
function runCommand(term, text) {
const command = text.trim().split(' ')[0];
if (command.length > 0) {
term.writeln('');
if (command in commands) {
commands[command].f(text);
return;
}
term.writeln(`${command}: command not found`);
}
prompt(term);
}
runFakeTerminal();
});

629
wasmtest/wasm_exec.js Normal file
View File

@ -0,0 +1,629 @@
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
(() => {
// Map multiple JavaScript environments to a single common API,
// preferring web standards over Node.js API.
//
// Environments considered:
// - Browsers
// - Node.js
// - Electron
// - Parcel
// - Webpack
if (typeof global !== "undefined") {
// global already exists
} else if (typeof window !== "undefined") {
window.global = window;
} else if (typeof self !== "undefined") {
self.global = self;
} else {
throw new Error("cannot export Go (neither global, window nor self is defined)");
}
if (!global.require && typeof require !== "undefined") {
global.require = require;
}
if (!global.fs && global.require) {
const fs = require("fs");
if (typeof fs === "object" && fs !== null && Object.keys(fs).length !== 0) {
global.fs = fs;
}
}
const enosys = () => {
const err = new Error("not implemented");
err.code = "ENOSYS";
return err;
};
if (!global.fs) {
let outputBuf = "";
global.fs = {
constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused
writeSync(fd, buf) {
outputBuf += decoder.decode(buf);
const nl = outputBuf.lastIndexOf("\n");
if (nl != -1) {
console.log(outputBuf.substr(0, nl));
outputBuf = outputBuf.substr(nl + 1);
}
return buf.length;
},
write(fd, buf, offset, length, position, callback) {
if (offset !== 0 || length !== buf.length || position !== null) {
callback(enosys());
return;
}
const n = this.writeSync(fd, buf);
callback(null, n);
},
chmod(path, mode, callback) { callback(enosys()); },
chown(path, uid, gid, callback) { callback(enosys()); },
close(fd, callback) { callback(enosys()); },
fchmod(fd, mode, callback) { callback(enosys()); },
fchown(fd, uid, gid, callback) { callback(enosys()); },
fstat(fd, callback) { callback(enosys()); },
fsync(fd, callback) { callback(null); },
ftruncate(fd, length, callback) { callback(enosys()); },
lchown(path, uid, gid, callback) { callback(enosys()); },
link(path, link, callback) { callback(enosys()); },
lstat(path, callback) { callback(enosys()); },
mkdir(path, perm, callback) { callback(enosys()); },
open(path, flags, mode, callback) { callback(enosys()); },
read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
readdir(path, callback) { callback(enosys()); },
readlink(path, callback) { callback(enosys()); },
rename(from, to, callback) { callback(enosys()); },
rmdir(path, callback) { callback(enosys()); },
stat(path, callback) { callback(enosys()); },
symlink(path, link, callback) { callback(enosys()); },
truncate(path, length, callback) { callback(enosys()); },
unlink(path, callback) { callback(enosys()); },
utimes(path, atime, mtime, callback) { callback(enosys()); },
};
}
if (!global.process) {
global.process = {
getuid() { return -1; },
getgid() { return -1; },
geteuid() { return -1; },
getegid() { return -1; },
getgroups() { throw enosys(); },
pid: -1,
ppid: -1,
umask() { throw enosys(); },
cwd() { throw enosys(); },
chdir() { throw enosys(); },
}
}
if (!global.crypto && global.require) {
const nodeCrypto = require("crypto");
global.crypto = {
getRandomValues(b) {
nodeCrypto.randomFillSync(b);
},
};
}
if (!global.crypto) {
throw new Error("global.crypto is not available, polyfill required (getRandomValues only)");
}
if (!global.performance) {
global.performance = {
now() {
const [sec, nsec] = process.hrtime();
return sec * 1000 + nsec / 1000000;
},
};
}
if (!global.TextEncoder && global.require) {
global.TextEncoder = require("util").TextEncoder;
}
if (!global.TextEncoder) {
throw new Error("global.TextEncoder is not available, polyfill required");
}
if (!global.TextDecoder && global.require) {
global.TextDecoder = require("util").TextDecoder;
}
if (!global.TextDecoder) {
throw new Error("global.TextDecoder is not available, polyfill required");
}
// End of polyfills for common API.
const encoder = new TextEncoder("utf-8");
const decoder = new TextDecoder("utf-8");
global.Go = class {
constructor() {
this.argv = ["js"];
this.env = {};
this.exit = (code) => {
// if (code !== 0) {
console.warn("exit code:", code);
//}
};
this._exitPromise = new Promise((resolve) => {
this._resolveExitPromise = resolve;
});
this._pendingEvent = null;
this._scheduledTimeouts = new Map();
this._nextCallbackTimeoutID = 1;
const setInt64 = (addr, v) => {
this.mem.setUint32(addr + 0, v, true);
this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
}
const getInt64 = (addr) => {
const low = this.mem.getUint32(addr + 0, true);
const high = this.mem.getInt32(addr + 4, true);
return low + high * 4294967296;
}
const loadValue = (addr) => {
const f = this.mem.getFloat64(addr, true);
if (f === 0) {
return undefined;
}
if (!isNaN(f)) {
return f;
}
const id = this.mem.getUint32(addr, true);
return this._values[id];
}
const storeValue = (addr, v) => {
const nanHead = 0x7FF80000;
if (typeof v === "number" && v !== 0) {
if (isNaN(v)) {
this.mem.setUint32(addr + 4, nanHead, true);
this.mem.setUint32(addr, 0, true);
return;
}
this.mem.setFloat64(addr, v, true);
return;
}
if (v === undefined) {
this.mem.setFloat64(addr, 0, true);
return;
}
let id = this._ids.get(v);
if (id === undefined) {
id = this._idPool.pop();
if (id === undefined) {
id = this._values.length;
}
this._values[id] = v;
this._goRefCounts[id] = 0;
this._ids.set(v, id);
}
this._goRefCounts[id]++;
let typeFlag = 0;
switch (typeof v) {
case "object":
if (v !== null) {
typeFlag = 1;
}
break;
case "string":
typeFlag = 2;
break;
case "symbol":
typeFlag = 3;
break;
case "function":
typeFlag = 4;
break;
}
this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
this.mem.setUint32(addr, id, true);
}
const loadSlice = (addr) => {
const array = getInt64(addr + 0);
const len = getInt64(addr + 8);
return new Uint8Array(this._inst.exports.mem.buffer, array, len);
}
const loadSliceOfValues = (addr) => {
const array = getInt64(addr + 0);
const len = getInt64(addr + 8);
const a = new Array(len);
for (let i = 0; i < len; i++) {
a[i] = loadValue(array + i * 8);
}
return a;
}
const loadString = (addr) => {
const saddr = getInt64(addr + 0);
const len = getInt64(addr + 8);
return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
}
const timeOrigin = Date.now() - performance.now();
this.importObject = {
go: {
// Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
// may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
// function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
// This changes the SP, thus we have to update the SP used by the imported function.
// func wasmExit(code int32)
"runtime.wasmExit": (sp) => {
sp >>>= 0;
const code = this.mem.getInt32(sp + 8, true);
this.exited = true;
delete this._inst;
delete this._values;
delete this._goRefCounts;
delete this._ids;
delete this._idPool;
this.exit(code);
},
// func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
"runtime.wasmWrite": (sp) => {
sp >>>= 0;
const fd = getInt64(sp + 8);
const p = getInt64(sp + 16);
const n = this.mem.getInt32(sp + 24, true);
fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
},
// func resetMemoryDataView()
"runtime.resetMemoryDataView": (sp) => {
sp >>>= 0;
this.mem = new DataView(this._inst.exports.mem.buffer);
},
// func nanotime1() int64
"runtime.nanotime1": (sp) => {
sp >>>= 0;
setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
},
// func walltime() (sec int64, nsec int32)
"runtime.walltime": (sp) => {
sp >>>= 0;
const msec = (new Date).getTime();
setInt64(sp + 8, msec / 1000);
this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
},
// func scheduleTimeoutEvent(delay int64) int32
"runtime.scheduleTimeoutEvent": (sp) => {
sp >>>= 0;
const id = this._nextCallbackTimeoutID;
this._nextCallbackTimeoutID++;
this._scheduledTimeouts.set(id, setTimeout(
() => {
this._resume();
while (this._scheduledTimeouts.has(id)) {
// for some reason Go failed to register the timeout event, log and try again
// (temporary workaround for https://github.com/golang/go/issues/28975)
console.warn("scheduleTimeoutEvent: missed timeout event");
this._resume();
}
},
getInt64(sp + 8) + 1, // setTimeout has been seen to fire up to 1 millisecond early
));
this.mem.setInt32(sp + 16, id, true);
},
// func clearTimeoutEvent(id int32)
"runtime.clearTimeoutEvent": (sp) => {
sp >>>= 0;
const id = this.mem.getInt32(sp + 8, true);
clearTimeout(this._scheduledTimeouts.get(id));
this._scheduledTimeouts.delete(id);
},
// func getRandomData(r []byte)
"runtime.getRandomData": (sp) => {
sp >>>= 0;
crypto.getRandomValues(loadSlice(sp + 8));
},
// func finalizeRef(v ref)
"syscall/js.finalizeRef": (sp) => {
sp >>>= 0;
const id = this.mem.getUint32(sp + 8, true);
this._goRefCounts[id]--;
if (this._goRefCounts[id] === 0) {
const v = this._values[id];
this._values[id] = null;
this._ids.delete(v);
this._idPool.push(id);
}
},
// func stringVal(value string) ref
"syscall/js.stringVal": (sp) => {
sp >>>= 0;
storeValue(sp + 24, loadString(sp + 8));
},
// func valueGet(v ref, p string) ref
"syscall/js.valueGet": (sp) => {
sp >>>= 0;
const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 32, result);
},
// func valueSet(v ref, p string, x ref)
"syscall/js.valueSet": (sp) => {
sp >>>= 0;
Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
},
// func valueDelete(v ref, p string)
"syscall/js.valueDelete": (sp) => {
sp >>>= 0;
Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
},
// func valueIndex(v ref, i int) ref
"syscall/js.valueIndex": (sp) => {
sp >>>= 0;
storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
},
// valueSetIndex(v ref, i int, x ref)
"syscall/js.valueSetIndex": (sp) => {
sp >>>= 0;
Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
},
// func valueCall(v ref, m string, args []ref) (ref, bool)
"syscall/js.valueCall": (sp) => {
sp >>>= 0;
try {
const v = loadValue(sp + 8);
const m = Reflect.get(v, loadString(sp + 16));
const args = loadSliceOfValues(sp + 32);
const result = Reflect.apply(m, v, args);
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 56, result);
this.mem.setUint8(sp + 64, 1);
} catch (err) {
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 56, err);
this.mem.setUint8(sp + 64, 0);
}
},
// func valueInvoke(v ref, args []ref) (ref, bool)
"syscall/js.valueInvoke": (sp) => {
sp >>>= 0;
try {
const v = loadValue(sp + 8);
const args = loadSliceOfValues(sp + 16);
const result = Reflect.apply(v, undefined, args);
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, result);
this.mem.setUint8(sp + 48, 1);
} catch (err) {
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, err);
this.mem.setUint8(sp + 48, 0);
}
},
// func valueNew(v ref, args []ref) (ref, bool)
"syscall/js.valueNew": (sp) => {
sp >>>= 0;
try {
const v = loadValue(sp + 8);
const args = loadSliceOfValues(sp + 16);
const result = Reflect.construct(v, args);
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, result);
this.mem.setUint8(sp + 48, 1);
} catch (err) {
sp = this._inst.exports.getsp() >>> 0; // see comment above
storeValue(sp + 40, err);
this.mem.setUint8(sp + 48, 0);
}
},
// func valueLength(v ref) int
"syscall/js.valueLength": (sp) => {
sp >>>= 0;
setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
},
// valuePrepareString(v ref) (ref, int)
"syscall/js.valuePrepareString": (sp) => {
sp >>>= 0;
const str = encoder.encode(String(loadValue(sp + 8)));
storeValue(sp + 16, str);
setInt64(sp + 24, str.length);
},
// valueLoadString(v ref, b []byte)
"syscall/js.valueLoadString": (sp) => {
sp >>>= 0;
const str = loadValue(sp + 8);
loadSlice(sp + 16).set(str);
},
// func valueInstanceOf(v ref, t ref) bool
"syscall/js.valueInstanceOf": (sp) => {
sp >>>= 0;
this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
},
// func copyBytesToGo(dst []byte, src ref) (int, bool)
"syscall/js.copyBytesToGo": (sp) => {
sp >>>= 0;
const dst = loadSlice(sp + 8);
const src = loadValue(sp + 32);
if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
this.mem.setUint8(sp + 48, 0);
return;
}
const toCopy = src.subarray(0, dst.length);
dst.set(toCopy);
setInt64(sp + 40, toCopy.length);
this.mem.setUint8(sp + 48, 1);
},
// func copyBytesToJS(dst ref, src []byte) (int, bool)
"syscall/js.copyBytesToJS": (sp) => {
sp >>>= 0;
const dst = loadValue(sp + 8);
const src = loadSlice(sp + 16);
if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
this.mem.setUint8(sp + 48, 0);
return;
}
const toCopy = src.subarray(0, dst.length);
dst.set(toCopy);
setInt64(sp + 40, toCopy.length);
this.mem.setUint8(sp + 48, 1);
},
"debug": (value) => {
console.log(value);
},
}
};
}
async run(instance) {
if (!(instance instanceof WebAssembly.Instance)) {
throw new Error("Go.run: WebAssembly.Instance expected");
}
this._inst = instance;
this.mem = new DataView(this._inst.exports.mem.buffer);
this._values = [ // JS values that Go currently has references to, indexed by reference id
NaN,
0,
null,
true,
false,
global,
this,
];
this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
this._ids = new Map([ // mapping from JS values to reference ids
[0, 1],
[null, 2],
[true, 3],
[false, 4],
[global, 5],
[this, 6],
]);
this._idPool = []; // unused ids that have been garbage collected
this.exited = false; // whether the Go program has exited
// Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
let offset = 4096;
const strPtr = (str) => {
const ptr = offset;
const bytes = encoder.encode(str + "\0");
new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
offset += bytes.length;
if (offset % 8 !== 0) {
offset += 8 - (offset % 8);
}
return ptr;
};
const argc = this.argv.length;
const argvPtrs = [];
this.argv.forEach((arg) => {
argvPtrs.push(strPtr(arg));
});
argvPtrs.push(0);
const keys = Object.keys(this.env).sort();
keys.forEach((key) => {
argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
});
argvPtrs.push(0);
const argv = offset;
argvPtrs.forEach((ptr) => {
this.mem.setUint32(offset, ptr, true);
this.mem.setUint32(offset + 4, 0, true);
offset += 8;
});
this._inst.exports.run(argc, argv);
if (this.exited) {
this._resolveExitPromise();
}
await this._exitPromise;
}
_resume() {
if (this.exited) {
throw new Error("Go program has already exited");
}
this._inst.exports.resume();
if (this.exited) {
this._resolveExitPromise();
}
}
_makeFuncWrapper(id) {
const go = this;
return function () {
const event = { id: id, this: this, args: arguments };
go._pendingEvent = event;
go._resume();
return event.result;
};
}
}
if (
typeof module !== "undefined" &&
global.require &&
global.require.main === module &&
global.process &&
global.process.versions &&
!global.process.versions.electron
) {
if (process.argv.length < 3) {
console.error("usage: go_js_wasm_exec [wasm binary] [arguments]");
process.exit(1);
}
const go = new Go();
go.argv = process.argv.slice(2);
go.env = Object.assign({ TMPDIR: require("os").tmpdir() }, process.env);
go.exit = process.exit;
WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => {
process.on("exit", (code) => { // Node.js exits if no event handler is pending
if (code === 0 && !go.exited) {
// deadlock, make Go print error and stack traces
go._pendingEvent = { id: 0 };
go._resume();
}
});
return go.run(result.instance);
}).catch((err) => {
console.error(err);
process.exit(1);
});
}
})();

View File

@ -0,0 +1,415 @@
// Copyright (c) 2021 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The wasmmod is a Tailscale-in-wasm proof of concept.
//
// See ../index.html and ../term.js for how it ties together.
package main
import (
"bufio"
"bytes"
"context"
"encoding/base64"
"fmt"
"html"
"io"
"log"
"net"
"net/http"
"os"
"runtime"
"strings"
"sync"
"syscall/js"
"time"
"github.com/skip2/go-qrcode"
"tailscale.com/cmd/tailscale/cli"
"tailscale.com/ipn"
"tailscale.com/ipn/ipnserver"
"tailscale.com/ipn/store/mem"
"tailscale.com/net/netns"
"tailscale.com/net/packet"
"tailscale.com/net/tsdial"
"tailscale.com/net/tstun"
"tailscale.com/safesocket"
"tailscale.com/types/logger"
"tailscale.com/wgengine"
"tailscale.com/wgengine/filter"
"tailscale.com/wgengine/netstack"
)
func main() {
netns.SetEnabled(false)
var logf logger.Logf = log.Printf
dialer := new(tsdial.Dialer)
eng, err := wgengine.NewUserspaceEngine(logf, wgengine.Config{
Dialer: dialer,
})
if err != nil {
log.Fatal(err)
}
tunDev, magicConn, dnsManager, ok := eng.(wgengine.InternalsGetter).GetInternals()
if !ok {
log.Fatalf("%T is not a wgengine.InternalsGetter", eng)
}
ns, err := netstack.Create(logf, tunDev, eng, magicConn, dialer, dnsManager)
if err != nil {
log.Fatalf("netstack.Create: %v", err)
}
ns.ProcessLocalIPs = true
ns.ProcessSubnets = true
ns.ForwardTCPIn = handleIncomingTCP
if err := ns.Start(); err != nil {
log.Fatalf("failed to start netstack: %v", err)
}
doc := js.Global().Get("document")
state := doc.Call("getElementById", "state")
topBar := doc.Call("getElementById", "topbar")
topBarStyle := topBar.Get("style")
netmapEle := doc.Call("getElementById", "netmap")
loginEle := doc.Call("getElementById", "loginURL")
netstackHandlePacket := tunDev.PostFilterIn
tunDev.PostFilterIn = func(p *packet.Parsed, t *tstun.Wrapper) filter.Response {
if p.IsEchoRequest() {
go func() {
topBarStyle.Set("background", "gray")
time.Sleep(100 * time.Millisecond)
topBarStyle.Set("background", "white")
}()
}
return netstackHandlePacket(p, t)
}
var store ipn.StateStore = new(mem.Store)
srv, err := ipnserver.New(log.Printf, "some-logid", store, eng, dialer, nil, ipnserver.Options{
SurviveDisconnects: true,
})
if err != nil {
log.Fatalf("ipnserver.New: %v", err)
}
lb := srv.LocalBackend()
state.Set("innerHTML", "ready")
lb.SetNotifyCallback(func(n ipn.Notify) {
log.Printf("NOTIFY: %+v", n)
if n.State != nil {
state.Set("innerHTML", fmt.Sprint(*n.State))
switch *n.State {
case ipn.Running, ipn.Starting:
loginEle.Set("innerHTML", "")
}
}
if nm := n.NetMap; nm != nil {
var buf bytes.Buffer
fmt.Fprintf(&buf, "<p>Name: <b>%s</b></p>\n", html.EscapeString(nm.Name))
fmt.Fprintf(&buf, "<p>Addresses: ")
for i, a := range nm.Addresses {
if i == 0 {
fmt.Fprintf(&buf, "<b>%s</b>", a.IP())
} else {
fmt.Fprintf(&buf, ", %s", a.IP())
}
}
fmt.Fprintf(&buf, "</p>")
fmt.Fprintf(&buf, "<p>Machine: <b>%v</b>, %v</p>\n", nm.MachineStatus, nm.MachineKey)
fmt.Fprintf(&buf, "<p>Nodekey: %v</p>\n", nm.NodeKey)
fmt.Fprintf(&buf, "<hr><table>")
for _, p := range nm.Peers {
var ip string
if len(p.Addresses) > 0 {
ip = p.Addresses[0].IP().String()
}
fmt.Fprintf(&buf, "<tr><td>%s</td><td>%s</td></tr>\n", ip, html.EscapeString(p.Name))
}
fmt.Fprintf(&buf, "</table>")
netmapEle.Set("innerHTML", buf.String())
}
if n.BrowseToURL != nil {
esc := html.EscapeString(*n.BrowseToURL)
pngBytes, _ := qrcode.Encode(*n.BrowseToURL, qrcode.Medium, 256)
qrDataURL := "data:image/png;base64," + base64.StdEncoding.EncodeToString(pngBytes)
loginEle.Set("innerHTML", fmt.Sprintf("<a href='%s' target=_blank>%s<br/><img src='%s' border=0></a>", esc, esc, qrDataURL))
}
})
start := func() {
err := lb.Start(ipn.Options{
Prefs: &ipn.Prefs{
// go run ./cmd/trunkd/ -remote-url=https://controlplane.tailscale.com
//ControlURL: "http://tsdev:8080",
ControlURL: "https://controlplane.tailscale.com",
RouteAll: false,
AllowSingleHosts: true,
WantRunning: true,
Hostname: "wasm",
},
})
log.Printf("Start error: %v", err)
}
js.Global().Set("startClicked", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
go start()
return nil
}))
js.Global().Set("logoutClicked", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
log.Printf("Logout clicked")
if lb.State() == ipn.NoState {
log.Printf("Backend not running")
return nil
}
go lb.Logout()
return nil
}))
js.Global().Set("startLoginInteractive", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
log.Printf("State: %v", lb.State)
go func() {
if lb.State() == ipn.NoState {
start()
}
lb.StartLoginInteractive()
}()
return nil
}))
js.Global().Set("seeGoroutines", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
full := make([]byte, 1<<20)
buf := full[:runtime.Stack(full, true)]
js.Global().Get("theTerminal").Call("reset")
withCR := make([]byte, 0, len(buf)+bytes.Count(buf, []byte{'\n'}))
for _, b := range buf {
if b == '\n' {
withCR = append(withCR, "\r\n"...)
} else {
withCR = append(withCR, b)
}
}
js.Global().Get("theTerminal").Call("write", string(withCR))
return nil
}))
js.Global().Set("startAuthKey", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
authKey := args[0].String()
log.Printf("got auth key")
go func() {
err := lb.Start(ipn.Options{
Prefs: &ipn.Prefs{
// go run ./cmd/trunkd/ -remote-url=https://controlplane.tailscale.com
//ControlURL: "http://tsdev:8080",
ControlURL: "https://controlplane.tailscale.com",
RouteAll: false,
AllowSingleHosts: true,
WantRunning: true,
Hostname: "wasm",
},
AuthKey: authKey,
})
log.Printf("Start error: %v", err)
}()
return nil
}))
var termOutOnce sync.Once
js.Global().Set("runTailscaleCLI", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
if len(args) < 1 {
log.Printf("missing args")
return nil
}
// TODO(bradfitz): enforce that we're only running one
// CLI command at a time, as we modify package cli
// globals below, like cli.Fatalf.
go func() {
if len(args) >= 2 {
onDone := args[1]
defer onDone.Invoke() // re-print the prompt
}
/*
fs := js.Global().Get("globalThis").Get("fs")
oldWriteSync := fs.Get("writeSync")
defer fs.Set("writeSync", oldWriteSync)
fs.Set("writeSync", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
if len(args) != 2 {
return nil
}
js.Global().Get("theTerminal").Call("write", fmt.Sprintf("Got a %T %v\r\n", args[1], args[1]))
return nil
}))
*/
line := args[0].String()
f := strings.Fields(line)
term := js.Global().Get("theTerminal")
termOutOnce.Do(func() {
cli.Stdout = termWriter{term}
cli.Stderr = termWriter{term}
})
cli.Fatalf = func(format string, a ...interface{}) {
term.Call("write", strings.ReplaceAll(fmt.Sprintf(format, a...), "\n", "\n\r"))
runtime.Goexit()
}
// TODO(bradfitz): add a cli package global logger and make that
// package use it, rather than messing with log.SetOutput.
log.SetOutput(cli.Stderr)
defer log.SetOutput(os.Stderr) // back to console
defer func() {
if e := recover(); e != nil {
term.Call("write", fmt.Sprintf("%s\r\n", e))
fmt.Fprintf(os.Stderr, "recovered panic from %q: %v", f, e)
}
}()
if err := cli.Run(f[1:]); err != nil {
fmt.Fprintf(os.Stderr, "CLI error on %q: %v\n", f, err)
term.Call("write", fmt.Sprintf("%v\r\n", err))
return
}
}()
return nil
}))
js.Global().Set("runFakeCURL", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
if len(args) < 2 {
log.Printf("missing args")
return nil
}
go func() {
onDone := args[1]
defer onDone.Invoke() // re-print the prompt
line := args[0].String()
f := strings.Fields(line)
if len(f) < 2 {
return
}
wantURL := f[1]
term := js.Global().Get("theTerminal")
c := &http.Client{
Transport: &http.Transport{
DialContext: dialer.UserDial,
},
}
res, err := c.Get(wantURL)
if err != nil {
term.Call("write", fmt.Sprintf("Error: %v\r\n", err))
return
}
defer res.Body.Close()
res.Write(termWriter{term})
}()
return nil
}))
js.Global().Set("runSSH", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
if len(args) < 2 {
log.Printf("missing args")
return nil
}
go func() {
onDone := args[1]
defer onDone.Invoke() // re-print the prompt
line := args[0].String()
f := strings.Fields(line)
host := f[1]
term := js.Global().Get("theTerminal")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
c, err := dialer.UserDial(ctx, "tcp", net.JoinHostPort(host, "22"))
if err != nil {
term.Call("write", fmt.Sprintf("Error: %v\r\n", err))
return
}
defer c.Close()
br := bufio.NewReader(c)
greet, err := br.ReadString('\n')
if err != nil {
term.Call("write", fmt.Sprintf("Error: %v\r\n", err))
return
}
term.Call("write", fmt.Sprintf("%v\r\n\r\nTODO(bradfitz): rest of the owl", strings.TrimSpace(greet)))
}()
return nil
}))
ln, _, err := safesocket.Listen("", 0)
if err != nil {
log.Fatal(err)
}
err = srv.Run(context.Background(), ln)
log.Fatalf("ipnserver.Run exited: %v", err)
}
type termWriter struct {
o js.Value
}
func (w termWriter) Write(p []byte) (n int, err error) {
r := bytes.Replace(p, []byte("\n"), []byte("\n\r"), -1)
w.o.Call("write", string(r))
return len(p), nil
}
func handleIncomingTCP(c net.Conn, port uint16) {
if port != 80 {
log.Printf("incoming conn on port %v; closing", port)
c.Close()
return
}
log.Printf("incoming conn on port %v", port)
s := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Got HTTP request: %+v", r)
if c := strings.TrimPrefix(r.URL.Path, "/"); c != "" {
body := js.Global().Get("document").Get("body")
body.Set("bgColor", c)
}
}),
}
err := s.Serve(&oneConnListener{conn: c})
log.Printf("http.Serve: %v", err)
}
type dummyAddr string
type oneConnListener struct {
conn net.Conn
}
func (l *oneConnListener) Accept() (c net.Conn, err error) {
c = l.conn
if c == nil {
err = io.EOF
return
}
err = nil
l.conn = nil
return
}
func (l *oneConnListener) Close() error { return nil }
func (l *oneConnListener) Addr() net.Addr { return dummyAddr("unused-address") }
func (a dummyAddr) Network() string { return string(a) }
func (a dummyAddr) String() string { return string(a) }