mirror of
https://github.com/schollz/croc.git
synced 2025-10-11 13:21:00 +02:00
add some more websocket stuff
This commit is contained in:
parent
639d4d4d3c
commit
e5bfe8530b
8 changed files with 947 additions and 107 deletions
2
go.mod
2
go.mod
|
@ -8,4 +8,6 @@ require (
|
||||||
github.com/gorilla/mux v1.7.3
|
github.com/gorilla/mux v1.7.3
|
||||||
github.com/gorilla/websocket v1.4.1
|
github.com/gorilla/websocket v1.4.1
|
||||||
github.com/schollz/logger v1.0.1
|
github.com/schollz/logger v1.0.1
|
||||||
|
github.com/schollz/pake/v2 v2.0.1
|
||||||
|
golang.org/x/crypto v0.0.0-20190907121410-71b5226ff739
|
||||||
)
|
)
|
||||||
|
|
10
go.sum
10
go.sum
|
@ -24,14 +24,24 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
|
||||||
github.com/schollz/croc v3.0.6+incompatible h1:rCfc8MGgcGjNW2/qSoulPh8CRGH+Ej4i3RWYOwhX9pE=
|
github.com/schollz/croc v3.0.6+incompatible h1:rCfc8MGgcGjNW2/qSoulPh8CRGH+Ej4i3RWYOwhX9pE=
|
||||||
github.com/schollz/logger v1.0.1 h1:BuBAU+euqphM0Ny9qFVScl4RSxatis4nCHIkOxO2cUU=
|
github.com/schollz/logger v1.0.1 h1:BuBAU+euqphM0Ny9qFVScl4RSxatis4nCHIkOxO2cUU=
|
||||||
github.com/schollz/logger v1.0.1/go.mod h1:P6F4/dGMGcx8wh+kG1zrNEd4vnNpEBY/mwEMd/vn6AM=
|
github.com/schollz/logger v1.0.1/go.mod h1:P6F4/dGMGcx8wh+kG1zrNEd4vnNpEBY/mwEMd/vn6AM=
|
||||||
|
github.com/schollz/pake v1.1.1 h1:QKeojDWzdAdtRC4m89b6HAxw/8gjqrVu7r4SAOxOFg8=
|
||||||
|
github.com/schollz/pake/v2 v2.0.1 h1:mvDqzFhKdYw2jG7Wk66DD6qtzkKepQ+Q6vd06rURY0E=
|
||||||
|
github.com/schollz/pake/v2 v2.0.1/go.mod h1:3uXB571UYJ8Eqh2EEohXe/aO32QID+Varb4GeYA//yw=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/tscholl2/siec v0.0.0-20180721101609-21667da05937 h1:lhssCpSe3TjKcbvUoPzFMuv9oUyZDgI3Cmgolfw2C90=
|
||||||
|
github.com/tscholl2/siec v0.0.0-20180721101609-21667da05937/go.mod h1:KL9+ubr1JZdaKjgAaHr+tCytEncXBa1pR6FjbTsOJnw=
|
||||||
github.com/ugorji/go v1.1.4 h1:j4s+tAvLfL3bZyefP2SEWmhBzmuIlH/eqNuPdFPgngw=
|
github.com/ugorji/go v1.1.4 h1:j4s+tAvLfL3bZyefP2SEWmhBzmuIlH/eqNuPdFPgngw=
|
||||||
github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
|
github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
|
||||||
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
golang.org/x/crypto v0.0.0-20190907121410-71b5226ff739 h1:Gc7JIyxvWgD6m+QmVryY0MstDORNYididDGxgZ6Tnpk=
|
||||||
|
golang.org/x/crypto v0.0.0-20190907121410-71b5226ff739/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
|
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b h1:ag/x1USPSsqHud38I9BAC88qdNLDHHtQ4mlgQIZPPNA=
|
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b h1:ag/x1USPSsqHud38I9BAC88qdNLDHHtQ4mlgQIZPPNA=
|
||||||
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
|
|
|
@ -210,5 +210,5 @@ func Run() (err error) {
|
||||||
log.Debugf("[%s] new connection %+v", room, c)
|
log.Debugf("[%s] new connection %+v", room, c)
|
||||||
s.readPump()
|
s.readPump()
|
||||||
})
|
})
|
||||||
return router.Run(":8000")
|
return router.Run(":8005")
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
<html>
|
<html>
|
||||||
|
|
||||||
<head>
|
<head>
|
||||||
|
|
||||||
<script src="https://cdn.jsdelivr.net/gh/emn178/js-md5/build/md5.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/gh/emn178/js-md5/build/md5.min.js"></script>
|
||||||
<style>
|
<style>
|
||||||
#byte_content {
|
#byte_content {
|
||||||
|
@ -19,7 +18,6 @@
|
||||||
</html>
|
</html>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
|
|
||||||
<input type="file" id="files" name="file" /> Read bytes:
|
<input type="file" id="files" name="file" /> Read bytes:
|
||||||
<span class="readBytesButtons">
|
<span class="readBytesButtons">
|
||||||
<button data-startbyte="0" data-endbyte="4">1-5</button>
|
<button data-startbyte="0" data-endbyte="4">1-5</button>
|
||||||
|
@ -31,118 +29,120 @@
|
||||||
<div id="byte_content"></div>
|
<div id="byte_content"></div>
|
||||||
Base64: <textarea id="remoteSessionDescription"></textarea> <br />
|
Base64: <textarea id="remoteSessionDescription"></textarea> <br />
|
||||||
<button onclick="startSession()"> Send Message </button> <br />
|
<button onclick="startSession()"> Send Message </button> <br />
|
||||||
|
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
function readBlob(opt_startByte, opt_stopByte) {
|
||||||
|
|
||||||
|
var files = document.getElementById('files').files;
|
||||||
|
if (!files.length) {
|
||||||
function readBlob(opt_startByte, opt_stopByte) {
|
alert('Please select a file!');
|
||||||
|
return;
|
||||||
var files = document.getElementById('files').files;
|
|
||||||
if (!files.length) {
|
|
||||||
alert('Please select a file!');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var file = files[0];
|
|
||||||
var start = parseInt(opt_startByte) || 0;
|
|
||||||
var stop = parseInt(opt_stopByte) || file.size - 1;
|
|
||||||
|
|
||||||
var reader = new FileReader();
|
|
||||||
|
|
||||||
// If we use onloadend, we need to check the readyState.
|
|
||||||
reader.onloadend = function (evt) {
|
|
||||||
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
|
|
||||||
document.getElementById('byte_content').textContent = evt.target.result;
|
|
||||||
document.getElementById('byte_range').textContent =
|
|
||||||
['Read bytes: ', start + 1, ' - ', stop + 1,
|
|
||||||
' of ', file.size, ' byte file'].join('');
|
|
||||||
sendMessage(evt.target.result);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
var blob = file.slice(start, stop + 1);
|
|
||||||
reader.readAsBinaryString(blob);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
document.querySelector('.readBytesButtons').addEventListener('click', function (evt) {
|
var file = files[0];
|
||||||
if (evt.target.tagName.toLowerCase() == 'button') {
|
var start = parseInt(opt_startByte) || 0;
|
||||||
var startByte = evt.target.getAttribute('data-startbyte');
|
var stop = parseInt(opt_stopByte) || file.size - 1;
|
||||||
var endByte = evt.target.getAttribute('data-endbyte');
|
|
||||||
readBlob(startByte, endByte);
|
var reader = new FileReader();
|
||||||
|
|
||||||
|
// If we use onloadend, we need to check the readyState.
|
||||||
|
reader.onloadend = function(evt) {
|
||||||
|
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
|
||||||
|
document.getElementById('byte_content').textContent = evt.target.result;
|
||||||
|
document.getElementById('byte_range').textContent = ['Read bytes: ', start + 1, ' - ', stop + 1,
|
||||||
|
' of ', file.size, ' byte file'
|
||||||
|
].join('');
|
||||||
|
sendMessage(evt.target.result);
|
||||||
}
|
}
|
||||||
}, false);
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
let pc = new RTCPeerConnection({
|
|
||||||
iceServers: [{
|
|
||||||
urls: 'stun:stun.l.google.com:19302'
|
|
||||||
}]
|
|
||||||
})
|
|
||||||
let log = msg => {
|
|
||||||
console.log(msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
pc.onsignalingstatechange = e => log(pc.signalingState)
|
|
||||||
pc.oniceconnectionstatechange = e => log(pc.iceConnectionState)
|
|
||||||
pc.onicecandidate = event => {
|
|
||||||
if (event.candidate === null) {
|
|
||||||
log(JSON.stringify(pc.localDescription))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
pc.ondatachannel = e => {
|
|
||||||
let dc = e.channel
|
|
||||||
log('New DataChannel ' + dc.label)
|
|
||||||
dc.onclose = () => log('dc has closed')
|
|
||||||
dc.onopen = () => {
|
|
||||||
log('dc has opened');
|
|
||||||
}
|
|
||||||
dc.onmessage = e => {
|
|
||||||
log(`Message from DataChannel '${dc.label}' payload '${e.data}'`)
|
|
||||||
}
|
|
||||||
window.sendMessage = e => {
|
|
||||||
let message = e;
|
|
||||||
if (message === '') {
|
|
||||||
return alert('Message must not be empty')
|
|
||||||
}
|
|
||||||
|
|
||||||
dc.send(message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
window.startSession = () => {
|
|
||||||
pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(atob(document.getElementById('remoteSessionDescription').value)))).catch(log)
|
|
||||||
pc.createAnswer().then(d => pc.setLocalDescription(d)).catch(log)
|
|
||||||
}
|
|
||||||
|
|
||||||
// websockets
|
|
||||||
var socket;
|
|
||||||
|
|
||||||
const socketMessageListener = (event) => {
|
|
||||||
log(event);
|
|
||||||
};
|
};
|
||||||
const socketOpenListener = (event) => {
|
|
||||||
log('Connected');
|
var blob = file.slice(start, stop + 1);
|
||||||
|
reader.readAsBinaryString(blob);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {
|
||||||
|
if (evt.target.tagName.toLowerCase() == 'button') {
|
||||||
|
var startByte = evt.target.getAttribute('data-startbyte');
|
||||||
|
var endByte = evt.target.getAttribute('data-endbyte');
|
||||||
|
readBlob(startByte, endByte);
|
||||||
}
|
}
|
||||||
const socketCloseListener = (event) => {
|
}, false);
|
||||||
if (socket) {
|
|
||||||
log('Disconnected.');
|
|
||||||
|
|
||||||
|
|
||||||
|
let pc = new RTCPeerConnection({
|
||||||
|
iceServers: [{
|
||||||
|
urls: 'stun:stun.l.google.com:19302'
|
||||||
|
}]
|
||||||
|
})
|
||||||
|
let log = msg => {
|
||||||
|
console.log(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
pc.onsignalingstatechange = e => log(pc.signalingState)
|
||||||
|
pc.oniceconnectionstatechange = e => log(pc.iceConnectionState)
|
||||||
|
pc.onicecandidate = event => {
|
||||||
|
if (event.candidate === null) {
|
||||||
|
log(JSON.stringify(pc.localDescription))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
pc.ondatachannel = e => {
|
||||||
|
let dc = e.channel
|
||||||
|
log('New DataChannel ' + dc.label)
|
||||||
|
dc.onclose = () => log('dc has closed')
|
||||||
|
dc.onopen = () => {
|
||||||
|
log('dc has opened');
|
||||||
|
}
|
||||||
|
dc.onmessage = e => {
|
||||||
|
log(`Message from DataChannel '${dc.label}' payload '${e.data}'`)
|
||||||
|
}
|
||||||
|
window.sendMessage = e => {
|
||||||
|
let message = e;
|
||||||
|
if (message === '') {
|
||||||
|
return alert('Message must not be empty')
|
||||||
}
|
}
|
||||||
// var ws_url = window.origin.replace("http", "ws") + '/ws/test1';
|
|
||||||
var ws_url = "ws://localhost:8000/ws/test1";
|
dc.send(message)
|
||||||
log(`connecting to '${ws_url}'`)
|
}
|
||||||
socket = new WebSocket(ws_url);
|
}
|
||||||
socket.addEventListener('open', socketOpenListener);
|
|
||||||
socket.addEventListener('message', socketMessageListener);
|
window.startSession = () => {
|
||||||
socket.addEventListener('close', socketCloseListener);
|
pc.setRemoteDescription(new RTCSessionDescription(JSON.parse(atob(document.getElementById('remoteSessionDescription').value)))).catch(log)
|
||||||
};
|
pc.createAnswer().then(d => pc.setLocalDescription(d)).catch(log)
|
||||||
socketCloseListener();
|
}
|
||||||
|
|
||||||
|
// websockets
|
||||||
|
var socket;
|
||||||
|
|
||||||
|
const socketMessageListener = (event) => {
|
||||||
|
log(event);
|
||||||
|
};
|
||||||
|
const socketOpenListener = (event) => {
|
||||||
|
log('Connected');
|
||||||
|
}
|
||||||
|
const socketCloseListener = (event) => {
|
||||||
|
if (socket) {
|
||||||
|
log('Disconnected.');
|
||||||
|
}
|
||||||
|
// var ws_url = window.origin.replace("http", "ws") + '/ws/test1';
|
||||||
|
var ws_url = "ws://localhost:8005/ws/test1";
|
||||||
|
log(`connecting to '${ws_url}'`)
|
||||||
|
socket = new WebSocket(ws_url);
|
||||||
|
socket.addEventListener('open', socketOpenListener);
|
||||||
|
socket.addEventListener('message', socketMessageListener);
|
||||||
|
socket.addEventListener('close', socketCloseListener);
|
||||||
|
};
|
||||||
|
socketCloseListener();
|
||||||
|
</script>
|
||||||
|
<script src="wasm_exec.js"></script>
|
||||||
|
<script>
|
||||||
|
const go = new Go();
|
||||||
|
WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((result) => {
|
||||||
|
go.run(result.instance);
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
|
|
||||||
|
|
263
src/webrtc/websend/main.go
Normal file
263
src/webrtc/websend/main.go
Normal file
|
@ -0,0 +1,263 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
//go:generate cp /usr/local/go/misc/wasm/wasm_exec.js .
|
||||||
|
|
||||||
|
// compile with
|
||||||
|
// GOOS=js GOARCH=wasm go build -o main.wasm
|
||||||
|
|
||||||
|
// to run
|
||||||
|
//
|
||||||
|
// bob = pakeInit("pass1","0");
|
||||||
|
// jane = pakeInit("pass1","1");
|
||||||
|
// jane = pakeUpdate(jane,pakePublic(bob));
|
||||||
|
// bob = pakeUpdate(bob,pakePublic(jane));
|
||||||
|
// jane = pakeUpdate(jane,pakePublic(bob));
|
||||||
|
// console.log(pakeSessionKey(bob))
|
||||||
|
// console.log(pakeSessionKey(jane))
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"compress/flate"
|
||||||
|
"crypto/aes"
|
||||||
|
"crypto/cipher"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"syscall/js"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/schollz/pake/v2"
|
||||||
|
"golang.org/x/crypto/pbkdf2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CompressWithOption returns compressed data using the specified level
|
||||||
|
func CompressWithOption(src []byte, level int) []byte {
|
||||||
|
compressedData := new(bytes.Buffer)
|
||||||
|
compress(src, compressedData, level)
|
||||||
|
return compressedData.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compress returns a compressed byte slice.
|
||||||
|
func Compress(src []byte) []byte {
|
||||||
|
compressedData := new(bytes.Buffer)
|
||||||
|
compress(src, compressedData, -2)
|
||||||
|
return compressedData.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decompress returns a decompressed byte slice.
|
||||||
|
func Decompress(src []byte) []byte {
|
||||||
|
compressedData := bytes.NewBuffer(src)
|
||||||
|
deCompressedData := new(bytes.Buffer)
|
||||||
|
decompress(compressedData, deCompressedData)
|
||||||
|
return deCompressedData.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
// compress uses flate to compress a byte slice to a corresponding level
|
||||||
|
func compress(src []byte, dest io.Writer, level int) {
|
||||||
|
compressor, _ := flate.NewWriter(dest, level)
|
||||||
|
compressor.Write(src)
|
||||||
|
compressor.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// compress uses flate to decompress an io.Reader
|
||||||
|
func decompress(src io.Reader, dest io.Writer) {
|
||||||
|
decompressor := flate.NewReader(src)
|
||||||
|
io.Copy(dest, decompressor)
|
||||||
|
decompressor.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ENCRYPTION
|
||||||
|
|
||||||
|
type Encryption struct {
|
||||||
|
key []byte
|
||||||
|
passphrase []byte
|
||||||
|
salt []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// New generates a new Encryption, using the supplied passphrase and
|
||||||
|
// an optional supplied salt.
|
||||||
|
// Passing nil passphrase will not use decryption.
|
||||||
|
func NewEncryption(passphrase []byte, salt []byte) (e Encryption, err error) {
|
||||||
|
if passphrase == nil {
|
||||||
|
e = Encryption{nil, nil, nil}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
e.passphrase = passphrase
|
||||||
|
if salt == nil {
|
||||||
|
e.salt = make([]byte, 8)
|
||||||
|
// http://www.ietf.org/rfc/rfc2898.txt
|
||||||
|
// Salt.
|
||||||
|
rand.Read(e.salt)
|
||||||
|
} else {
|
||||||
|
e.salt = salt
|
||||||
|
}
|
||||||
|
e.key = pbkdf2.Key([]byte(passphrase), e.salt, 100, 32, sha256.New)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e Encryption) Salt() []byte {
|
||||||
|
return e.salt
|
||||||
|
}
|
||||||
|
|
||||||
|
// Encrypt will generate an Encryption, prefixed with the IV
|
||||||
|
func (e Encryption) Encrypt(plaintext []byte) (encrypted []byte, err error) {
|
||||||
|
plaintext = Compress(plaintext)
|
||||||
|
if e.passphrase == nil {
|
||||||
|
encrypted = plaintext
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// generate a random iv each time
|
||||||
|
// http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
|
||||||
|
// Section 8.2
|
||||||
|
ivBytes := make([]byte, 12)
|
||||||
|
rand.Read(ivBytes)
|
||||||
|
b, err := aes.NewCipher(e.key)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
aesgcm, err := cipher.NewGCM(b)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
encrypted = aesgcm.Seal(nil, ivBytes, plaintext, nil)
|
||||||
|
encrypted = append(ivBytes, encrypted...)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decrypt an Encryption
|
||||||
|
func (e Encryption) Decrypt(encrypted []byte) (plaintext []byte, err error) {
|
||||||
|
if e.passphrase == nil {
|
||||||
|
plaintext = encrypted
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b, err := aes.NewCipher(e.key)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
aesgcm, err := cipher.NewGCM(b)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
plaintext, err = aesgcm.Open(nil, encrypted[:12], encrypted[12:], nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
plaintext = Decompress(plaintext)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// encrypt(message,password,salt)
|
||||||
|
func encrypt(this js.Value, inputs []js.Value) interface{} {
|
||||||
|
if len(inputs) != 3 {
|
||||||
|
return js.Global().Get("Error").New("not enough inputs")
|
||||||
|
}
|
||||||
|
e, err := NewEncryption([]byte(inputs[1].String()), []byte(inputs[2].String()))
|
||||||
|
if err != nil {
|
||||||
|
return js.Global().Get("Error").New(err.Error())
|
||||||
|
}
|
||||||
|
enc, err := e.Encrypt([]byte(inputs[0].String()))
|
||||||
|
if err != nil {
|
||||||
|
return js.Global().Get("Error").New(err.Error())
|
||||||
|
}
|
||||||
|
return base64.StdEncoding.EncodeToString(enc)
|
||||||
|
}
|
||||||
|
|
||||||
|
// decrypt(message,password,salt)
|
||||||
|
func decrypt(this js.Value, inputs []js.Value) interface{} {
|
||||||
|
e, err := NewEncryption([]byte(inputs[1].String()), []byte(inputs[2].String()))
|
||||||
|
if err != nil {
|
||||||
|
return js.Global().Get("Error").New(err.Error())
|
||||||
|
}
|
||||||
|
decBytes, err := base64.StdEncoding.DecodeString(inputs[0].String())
|
||||||
|
if err != nil {
|
||||||
|
return js.Global().Get("Error").New(err.Error())
|
||||||
|
}
|
||||||
|
dec, err := e.Decrypt(decBytes)
|
||||||
|
if err != nil {
|
||||||
|
return js.Global().Get("Error").New(err.Error())
|
||||||
|
}
|
||||||
|
return string(dec)
|
||||||
|
}
|
||||||
|
|
||||||
|
// initPake(weakPassphrase, role)
|
||||||
|
// returns: pakeBytes
|
||||||
|
func pakeInit(this js.Value, inputs []js.Value) interface{} {
|
||||||
|
// initialize sender P ("0" indicates sender)
|
||||||
|
if len(inputs) != 2 {
|
||||||
|
return js.Global().Get("Error").New("need weakPassphrase, role")
|
||||||
|
}
|
||||||
|
role := 0
|
||||||
|
if inputs[1].String() == "1" {
|
||||||
|
role = 1
|
||||||
|
}
|
||||||
|
P, err := pake.Init([]byte(inputs[0].String()), role, elliptic.P521(), 1*time.Millisecond)
|
||||||
|
if err != nil {
|
||||||
|
return js.Global().Get("Error").New(err.Error())
|
||||||
|
}
|
||||||
|
bJSON, _ := json.Marshal(P)
|
||||||
|
return string(bJSON)
|
||||||
|
}
|
||||||
|
|
||||||
|
// pakeUpdate(pakeBytes,otherPublicPakeBytes)
|
||||||
|
func pakeUpdate(this js.Value, inputs []js.Value) interface{} {
|
||||||
|
if len(inputs) != 2 {
|
||||||
|
return js.Global().Get("Error").New("need two input")
|
||||||
|
}
|
||||||
|
var P, Q *pake.Pake
|
||||||
|
err := json.Unmarshal([]byte(inputs[0].String()), &P)
|
||||||
|
P.SetCurve(elliptic.P521())
|
||||||
|
if err != nil {
|
||||||
|
return js.Global().Get("Error").New(err.Error())
|
||||||
|
}
|
||||||
|
err = json.Unmarshal([]byte(inputs[1].String()), &Q)
|
||||||
|
Q.SetCurve(elliptic.P521())
|
||||||
|
if err != nil {
|
||||||
|
return js.Global().Get("Error").New(err.Error())
|
||||||
|
}
|
||||||
|
P.Update(Q.Bytes())
|
||||||
|
bJSON, _ := json.Marshal(P)
|
||||||
|
return string(bJSON)
|
||||||
|
}
|
||||||
|
|
||||||
|
// pakePublic(pakeBytes)
|
||||||
|
func pakePublic(this js.Value, inputs []js.Value) interface{} {
|
||||||
|
var P *pake.Pake
|
||||||
|
err := json.Unmarshal([]byte(inputs[0].String()), &P)
|
||||||
|
P.SetCurve(elliptic.P521())
|
||||||
|
if err != nil {
|
||||||
|
return js.Global().Get("Error").New(err.Error())
|
||||||
|
}
|
||||||
|
return string(P.Public().Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
// pakeSessionKey(pakeBytes)
|
||||||
|
func pakeSessionKey(this js.Value, inputs []js.Value) interface{} {
|
||||||
|
var P *pake.Pake
|
||||||
|
err := json.Unmarshal([]byte(inputs[0].String()), &P)
|
||||||
|
P.SetCurve(elliptic.P521())
|
||||||
|
if err != nil {
|
||||||
|
return js.Global().Get("Error").New(err.Error())
|
||||||
|
}
|
||||||
|
key, err := P.SessionKey()
|
||||||
|
if err != nil {
|
||||||
|
return js.Global().Get("Error").New(err.Error())
|
||||||
|
}
|
||||||
|
return base64.StdEncoding.EncodeToString(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
c := make(chan bool)
|
||||||
|
fmt.Println("starting")
|
||||||
|
js.Global().Set("encrypt", js.FuncOf(encrypt))
|
||||||
|
js.Global().Set("decrypt", js.FuncOf(decrypt))
|
||||||
|
js.Global().Set("pakeInit", js.FuncOf(pakeInit))
|
||||||
|
js.Global().Set("pakePublic", js.FuncOf(pakePublic))
|
||||||
|
js.Global().Set("pakeUpdate", js.FuncOf(pakeUpdate))
|
||||||
|
js.Global().Set("pakeSessionKey", js.FuncOf(pakeSessionKey))
|
||||||
|
fmt.Println("Initiated")
|
||||||
|
<-c
|
||||||
|
}
|
BIN
src/webrtc/websend/main.wasm
Executable file
BIN
src/webrtc/websend/main.wasm
Executable file
Binary file not shown.
533
src/webrtc/websend/wasm_exec.js
Normal file
533
src/webrtc/websend/wasm_exec.js
Normal file
|
@ -0,0 +1,533 @@
|
||||||
|
// 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
|
||||||
|
|
||||||
|
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) {
|
||||||
|
global.fs = require("fs");
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
throw new Error("not implemented");
|
||||||
|
}
|
||||||
|
const n = this.writeSync(fd, buf);
|
||||||
|
callback(null, n);
|
||||||
|
},
|
||||||
|
open(path, flags, mode, callback) {
|
||||||
|
const err = new Error("not implemented");
|
||||||
|
err.code = "ENOSYS";
|
||||||
|
callback(err);
|
||||||
|
},
|
||||||
|
read(fd, buffer, offset, length, position, callback) {
|
||||||
|
const err = new Error("not implemented");
|
||||||
|
err.code = "ENOSYS";
|
||||||
|
callback(err);
|
||||||
|
},
|
||||||
|
fsync(fd, callback) {
|
||||||
|
callback(null);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!global.crypto) {
|
||||||
|
const nodeCrypto = require("crypto");
|
||||||
|
global.crypto = {
|
||||||
|
getRandomValues(b) {
|
||||||
|
nodeCrypto.randomFillSync(b);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!global.performance) {
|
||||||
|
global.performance = {
|
||||||
|
now() {
|
||||||
|
const [sec, nsec] = process.hrtime();
|
||||||
|
return sec * 1000 + nsec / 1000000;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!global.TextEncoder) {
|
||||||
|
global.TextEncoder = require("util").TextEncoder;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!global.TextDecoder) {
|
||||||
|
global.TextDecoder = require("util").TextDecoder;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 mem = () => {
|
||||||
|
// The buffer may change when requesting more memory.
|
||||||
|
return new DataView(this._inst.exports.mem.buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
const setInt64 = (addr, v) => {
|
||||||
|
mem().setUint32(addr + 0, v, true);
|
||||||
|
mem().setUint32(addr + 4, Math.floor(v / 4294967296), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
const getInt64 = (addr) => {
|
||||||
|
const low = mem().getUint32(addr + 0, true);
|
||||||
|
const high = mem().getInt32(addr + 4, true);
|
||||||
|
return low + high * 4294967296;
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadValue = (addr) => {
|
||||||
|
const f = mem().getFloat64(addr, true);
|
||||||
|
if (f === 0) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
if (!isNaN(f)) {
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = mem().getUint32(addr, true);
|
||||||
|
return this._values[id];
|
||||||
|
}
|
||||||
|
|
||||||
|
const storeValue = (addr, v) => {
|
||||||
|
const nanHead = 0x7FF80000;
|
||||||
|
|
||||||
|
if (typeof v === "number") {
|
||||||
|
if (isNaN(v)) {
|
||||||
|
mem().setUint32(addr + 4, nanHead, true);
|
||||||
|
mem().setUint32(addr, 0, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (v === 0) {
|
||||||
|
mem().setUint32(addr + 4, nanHead, true);
|
||||||
|
mem().setUint32(addr, 1, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
mem().setFloat64(addr, v, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (v) {
|
||||||
|
case undefined:
|
||||||
|
mem().setFloat64(addr, 0, true);
|
||||||
|
return;
|
||||||
|
case null:
|
||||||
|
mem().setUint32(addr + 4, nanHead, true);
|
||||||
|
mem().setUint32(addr, 2, true);
|
||||||
|
return;
|
||||||
|
case true:
|
||||||
|
mem().setUint32(addr + 4, nanHead, true);
|
||||||
|
mem().setUint32(addr, 3, true);
|
||||||
|
return;
|
||||||
|
case false:
|
||||||
|
mem().setUint32(addr + 4, nanHead, true);
|
||||||
|
mem().setUint32(addr, 4, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let ref = this._refs.get(v);
|
||||||
|
if (ref === undefined) {
|
||||||
|
ref = this._values.length;
|
||||||
|
this._values.push(v);
|
||||||
|
this._refs.set(v, ref);
|
||||||
|
}
|
||||||
|
let typeFlag = 0;
|
||||||
|
switch (typeof v) {
|
||||||
|
case "string":
|
||||||
|
typeFlag = 1;
|
||||||
|
break;
|
||||||
|
case "symbol":
|
||||||
|
typeFlag = 2;
|
||||||
|
break;
|
||||||
|
case "function":
|
||||||
|
typeFlag = 3;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
mem().setUint32(addr + 4, nanHead | typeFlag, true);
|
||||||
|
mem().setUint32(addr, ref, 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) => {
|
||||||
|
const code = mem().getInt32(sp + 8, true);
|
||||||
|
this.exited = true;
|
||||||
|
delete this._inst;
|
||||||
|
delete this._values;
|
||||||
|
delete this._refs;
|
||||||
|
this.exit(code);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
|
||||||
|
"runtime.wasmWrite": (sp) => {
|
||||||
|
const fd = getInt64(sp + 8);
|
||||||
|
const p = getInt64(sp + 16);
|
||||||
|
const n = mem().getInt32(sp + 24, true);
|
||||||
|
fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func nanotime() int64
|
||||||
|
"runtime.nanotime": (sp) => {
|
||||||
|
setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func walltime() (sec int64, nsec int32)
|
||||||
|
"runtime.walltime": (sp) => {
|
||||||
|
const msec = (new Date).getTime();
|
||||||
|
setInt64(sp + 8, msec / 1000);
|
||||||
|
mem().setInt32(sp + 16, (msec % 1000) * 1000000, true);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func scheduleTimeoutEvent(delay int64) int32
|
||||||
|
"runtime.scheduleTimeoutEvent": (sp) => {
|
||||||
|
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
|
||||||
|
));
|
||||||
|
mem().setInt32(sp + 16, id, true);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func clearTimeoutEvent(id int32)
|
||||||
|
"runtime.clearTimeoutEvent": (sp) => {
|
||||||
|
const id = mem().getInt32(sp + 8, true);
|
||||||
|
clearTimeout(this._scheduledTimeouts.get(id));
|
||||||
|
this._scheduledTimeouts.delete(id);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func getRandomData(r []byte)
|
||||||
|
"runtime.getRandomData": (sp) => {
|
||||||
|
crypto.getRandomValues(loadSlice(sp + 8));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func stringVal(value string) ref
|
||||||
|
"syscall/js.stringVal": (sp) => {
|
||||||
|
storeValue(sp + 24, loadString(sp + 8));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueGet(v ref, p string) ref
|
||||||
|
"syscall/js.valueGet": (sp) => {
|
||||||
|
const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
|
||||||
|
sp = this._inst.exports.getsp(); // see comment above
|
||||||
|
storeValue(sp + 32, result);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueSet(v ref, p string, x ref)
|
||||||
|
"syscall/js.valueSet": (sp) => {
|
||||||
|
Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueIndex(v ref, i int) ref
|
||||||
|
"syscall/js.valueIndex": (sp) => {
|
||||||
|
storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
|
||||||
|
},
|
||||||
|
|
||||||
|
// valueSetIndex(v ref, i int, x ref)
|
||||||
|
"syscall/js.valueSetIndex": (sp) => {
|
||||||
|
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) => {
|
||||||
|
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(); // see comment above
|
||||||
|
storeValue(sp + 56, result);
|
||||||
|
mem().setUint8(sp + 64, 1);
|
||||||
|
} catch (err) {
|
||||||
|
storeValue(sp + 56, err);
|
||||||
|
mem().setUint8(sp + 64, 0);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueInvoke(v ref, args []ref) (ref, bool)
|
||||||
|
"syscall/js.valueInvoke": (sp) => {
|
||||||
|
try {
|
||||||
|
const v = loadValue(sp + 8);
|
||||||
|
const args = loadSliceOfValues(sp + 16);
|
||||||
|
const result = Reflect.apply(v, undefined, args);
|
||||||
|
sp = this._inst.exports.getsp(); // see comment above
|
||||||
|
storeValue(sp + 40, result);
|
||||||
|
mem().setUint8(sp + 48, 1);
|
||||||
|
} catch (err) {
|
||||||
|
storeValue(sp + 40, err);
|
||||||
|
mem().setUint8(sp + 48, 0);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueNew(v ref, args []ref) (ref, bool)
|
||||||
|
"syscall/js.valueNew": (sp) => {
|
||||||
|
try {
|
||||||
|
const v = loadValue(sp + 8);
|
||||||
|
const args = loadSliceOfValues(sp + 16);
|
||||||
|
const result = Reflect.construct(v, args);
|
||||||
|
sp = this._inst.exports.getsp(); // see comment above
|
||||||
|
storeValue(sp + 40, result);
|
||||||
|
mem().setUint8(sp + 48, 1);
|
||||||
|
} catch (err) {
|
||||||
|
storeValue(sp + 40, err);
|
||||||
|
mem().setUint8(sp + 48, 0);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueLength(v ref) int
|
||||||
|
"syscall/js.valueLength": (sp) => {
|
||||||
|
setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
|
||||||
|
},
|
||||||
|
|
||||||
|
// valuePrepareString(v ref) (ref, int)
|
||||||
|
"syscall/js.valuePrepareString": (sp) => {
|
||||||
|
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) => {
|
||||||
|
const str = loadValue(sp + 8);
|
||||||
|
loadSlice(sp + 16).set(str);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueInstanceOf(v ref, t ref) bool
|
||||||
|
"syscall/js.valueInstanceOf": (sp) => {
|
||||||
|
mem().setUint8(sp + 24, loadValue(sp + 8) instanceof loadValue(sp + 16));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func copyBytesToGo(dst []byte, src ref) (int, bool)
|
||||||
|
"syscall/js.copyBytesToGo": (sp) => {
|
||||||
|
const dst = loadSlice(sp + 8);
|
||||||
|
const src = loadValue(sp + 32);
|
||||||
|
if (!(src instanceof Uint8Array)) {
|
||||||
|
mem().setUint8(sp + 48, 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const toCopy = src.subarray(0, dst.length);
|
||||||
|
dst.set(toCopy);
|
||||||
|
setInt64(sp + 40, toCopy.length);
|
||||||
|
mem().setUint8(sp + 48, 1);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func copyBytesToJS(dst ref, src []byte) (int, bool)
|
||||||
|
"syscall/js.copyBytesToJS": (sp) => {
|
||||||
|
const dst = loadValue(sp + 8);
|
||||||
|
const src = loadSlice(sp + 16);
|
||||||
|
if (!(dst instanceof Uint8Array)) {
|
||||||
|
mem().setUint8(sp + 48, 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const toCopy = src.subarray(0, dst.length);
|
||||||
|
dst.set(toCopy);
|
||||||
|
setInt64(sp + 40, toCopy.length);
|
||||||
|
mem().setUint8(sp + 48, 1);
|
||||||
|
},
|
||||||
|
|
||||||
|
"debug": (value) => {
|
||||||
|
console.log(value);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async run(instance) {
|
||||||
|
this._inst = instance;
|
||||||
|
this._values = [ // TODO: garbage collection
|
||||||
|
NaN,
|
||||||
|
0,
|
||||||
|
null,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
global,
|
||||||
|
this,
|
||||||
|
];
|
||||||
|
this._refs = new Map();
|
||||||
|
this.exited = false;
|
||||||
|
|
||||||
|
const mem = new DataView(this._inst.exports.mem.buffer)
|
||||||
|
|
||||||
|
// 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(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));
|
||||||
|
});
|
||||||
|
|
||||||
|
const keys = Object.keys(this.env).sort();
|
||||||
|
argvPtrs.push(keys.length);
|
||||||
|
keys.forEach((key) => {
|
||||||
|
argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
|
||||||
|
});
|
||||||
|
|
||||||
|
const argv = offset;
|
||||||
|
argvPtrs.forEach((ptr) => {
|
||||||
|
mem.setUint32(offset, ptr, true);
|
||||||
|
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 (
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})();
|
32
src/wsclient/wsclient.go
Normal file
32
src/wsclient/wsclient.go
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
package wsclient
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/url"
|
||||||
|
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
log "github.com/schollz/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Connect() (err error) {
|
||||||
|
|
||||||
|
u := url.URL{Scheme: "ws", Host: "localhost", Path: "/ws/test1"}
|
||||||
|
log.Debugf("connecting to %s", u.String())
|
||||||
|
|
||||||
|
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("dial:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer c.Close()
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
_, message, err := c.ReadMessage()
|
||||||
|
if err != nil {
|
||||||
|
log.Println("read:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("recv: %s", message)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
Loading…
Add table
Add a link
Reference in a new issue