2024-06-12 02:42:10 +02:00
|
|
|
// Copyright 2024, Command Line Inc.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
|
|
|
package web
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
2024-07-18 03:42:49 +02:00
|
|
|
"net"
|
2024-06-12 02:42:10 +02:00
|
|
|
"net/http"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
"github.com/gorilla/websocket"
|
2024-09-05 23:25:45 +02:00
|
|
|
"github.com/wavetermdev/waveterm/pkg/authkey"
|
|
|
|
"github.com/wavetermdev/waveterm/pkg/eventbus"
|
2024-11-21 03:05:13 +01:00
|
|
|
"github.com/wavetermdev/waveterm/pkg/panichandler"
|
2024-09-05 23:25:45 +02:00
|
|
|
"github.com/wavetermdev/waveterm/pkg/web/webcmd"
|
|
|
|
"github.com/wavetermdev/waveterm/pkg/wshrpc"
|
|
|
|
"github.com/wavetermdev/waveterm/pkg/wshutil"
|
2024-06-12 02:42:10 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
const wsReadWaitTimeout = 15 * time.Second
|
|
|
|
const wsWriteWaitTimeout = 10 * time.Second
|
|
|
|
const wsPingPeriodTickTime = 10 * time.Second
|
|
|
|
const wsInitialPingTime = 1 * time.Second
|
|
|
|
|
2024-06-21 01:01:55 +02:00
|
|
|
const DefaultCommandTimeout = 2 * time.Second
|
|
|
|
|
2024-10-18 21:05:20 +02:00
|
|
|
var GlobalLock = &sync.Mutex{}
|
|
|
|
var RouteToConnMap = map[string]string{} // routeid => connid
|
|
|
|
|
2024-07-18 03:42:49 +02:00
|
|
|
func RunWebSocketServer(listener net.Listener) {
|
2024-06-12 02:42:10 +02:00
|
|
|
gr := mux.NewRouter()
|
|
|
|
gr.HandleFunc("/ws", HandleWs)
|
|
|
|
server := &http.Server{
|
|
|
|
ReadTimeout: HttpReadTimeout,
|
|
|
|
WriteTimeout: HttpWriteTimeout,
|
|
|
|
MaxHeaderBytes: HttpMaxHeaderBytes,
|
|
|
|
Handler: gr,
|
|
|
|
}
|
|
|
|
server.SetKeepAlivesEnabled(false)
|
2024-10-18 08:42:55 +02:00
|
|
|
log.Printf("[websocket] running websocket server on %s\n", listener.Addr())
|
2024-07-18 03:42:49 +02:00
|
|
|
err := server.Serve(listener)
|
2024-06-12 02:42:10 +02:00
|
|
|
if err != nil {
|
2024-10-18 08:42:55 +02:00
|
|
|
log.Printf("[websocket] error trying to run websocket server: %v\n", err)
|
2024-06-12 02:42:10 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var WebSocketUpgrader = websocket.Upgrader{
|
|
|
|
ReadBufferSize: 4 * 1024,
|
|
|
|
WriteBufferSize: 32 * 1024,
|
|
|
|
HandshakeTimeout: 1 * time.Second,
|
|
|
|
CheckOrigin: func(r *http.Request) bool { return true },
|
|
|
|
}
|
|
|
|
|
|
|
|
func HandleWs(w http.ResponseWriter, r *http.Request) {
|
|
|
|
err := HandleWsInternal(w, r)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func getMessageType(jmsg map[string]any) string {
|
|
|
|
if str, ok := jmsg["type"].(string); ok {
|
|
|
|
return str
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
func getStringFromMap(jmsg map[string]any, key string) string {
|
|
|
|
if str, ok := jmsg[key].(string); ok {
|
|
|
|
return str
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2024-07-18 00:24:43 +02:00
|
|
|
func processWSCommand(jmsg map[string]any, outputCh chan any, rpcInputCh chan []byte) {
|
2024-06-12 23:18:03 +02:00
|
|
|
var rtnErr error
|
|
|
|
defer func() {
|
2024-11-21 03:05:13 +01:00
|
|
|
panicErr := panichandler.PanicHandler("processWSCommand")
|
|
|
|
if panicErr != nil {
|
|
|
|
rtnErr = panicErr
|
2024-06-12 23:18:03 +02:00
|
|
|
}
|
|
|
|
if rtnErr == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
rtn := map[string]any{"type": "error", "error": rtnErr.Error()}
|
|
|
|
outputCh <- rtn
|
|
|
|
}()
|
|
|
|
wsCommand, err := webcmd.ParseWSCommandMap(jmsg)
|
|
|
|
if err != nil {
|
|
|
|
rtnErr = fmt.Errorf("cannot parse wscommand: %v", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
switch cmd := wsCommand.(type) {
|
|
|
|
case *webcmd.SetBlockTermSizeWSCommand:
|
2024-07-18 00:24:43 +02:00
|
|
|
data := wshrpc.CommandBlockInputData{
|
|
|
|
BlockId: cmd.BlockId,
|
2024-06-12 23:18:03 +02:00
|
|
|
TermSize: &cmd.TermSize,
|
|
|
|
}
|
2024-07-18 00:24:43 +02:00
|
|
|
rpcMsg := wshutil.RpcMessage{
|
2024-07-26 22:30:11 +02:00
|
|
|
Command: wshrpc.Command_ControllerInput,
|
2024-07-18 00:24:43 +02:00
|
|
|
Data: data,
|
|
|
|
}
|
|
|
|
msgBytes, err := json.Marshal(rpcMsg)
|
2024-06-21 01:01:55 +02:00
|
|
|
if err != nil {
|
2024-07-18 00:24:43 +02:00
|
|
|
// this really should never fail since we just unmarshalled this value
|
2024-10-18 08:42:55 +02:00
|
|
|
log.Printf("[websocket] error marshalling rpc message: %v\n", err)
|
2024-07-18 00:24:43 +02:00
|
|
|
return
|
2024-06-21 01:01:55 +02:00
|
|
|
}
|
2024-07-18 00:24:43 +02:00
|
|
|
rpcInputCh <- msgBytes
|
|
|
|
|
2024-06-18 07:38:48 +02:00
|
|
|
case *webcmd.BlockInputWSCommand:
|
2024-07-18 00:24:43 +02:00
|
|
|
data := wshrpc.CommandBlockInputData{
|
|
|
|
BlockId: cmd.BlockId,
|
2024-06-18 07:38:48 +02:00
|
|
|
InputData64: cmd.InputData64,
|
|
|
|
}
|
2024-07-18 00:24:43 +02:00
|
|
|
rpcMsg := wshutil.RpcMessage{
|
2024-07-26 22:30:11 +02:00
|
|
|
Command: wshrpc.Command_ControllerInput,
|
2024-07-18 00:24:43 +02:00
|
|
|
Data: data,
|
|
|
|
}
|
|
|
|
msgBytes, err := json.Marshal(rpcMsg)
|
|
|
|
if err != nil {
|
|
|
|
// this really should never fail since we just unmarshalled this value
|
2024-10-18 08:42:55 +02:00
|
|
|
log.Printf("[websocket] error marshalling rpc message: %v\n", err)
|
2024-07-18 00:24:43 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
rpcInputCh <- msgBytes
|
|
|
|
|
|
|
|
case *webcmd.WSRpcCommand:
|
|
|
|
rpcMsg := cmd.Message
|
|
|
|
if rpcMsg == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
msgBytes, err := json.Marshal(rpcMsg)
|
2024-06-21 01:01:55 +02:00
|
|
|
if err != nil {
|
2024-07-18 00:24:43 +02:00
|
|
|
// this really should never fail since we just unmarshalled this value
|
|
|
|
return
|
2024-06-21 01:01:55 +02:00
|
|
|
}
|
2024-07-18 00:24:43 +02:00
|
|
|
rpcInputCh <- msgBytes
|
2024-06-12 23:18:03 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-18 00:24:43 +02:00
|
|
|
func processMessage(jmsg map[string]any, outputCh chan any, rpcInputCh chan []byte) {
|
2024-06-12 23:18:03 +02:00
|
|
|
wsCommand := getStringFromMap(jmsg, "wscommand")
|
2024-08-14 01:52:35 +02:00
|
|
|
if wsCommand == "" {
|
2024-06-12 02:42:10 +02:00
|
|
|
return
|
|
|
|
}
|
2024-08-14 01:52:35 +02:00
|
|
|
processWSCommand(jmsg, outputCh, rpcInputCh)
|
2024-06-12 02:42:10 +02:00
|
|
|
}
|
|
|
|
|
2024-10-18 08:42:55 +02:00
|
|
|
func ReadLoop(conn *websocket.Conn, outputCh chan any, closeCh chan any, rpcInputCh chan []byte, routeId string) {
|
2024-06-12 02:42:10 +02:00
|
|
|
readWait := wsReadWaitTimeout
|
|
|
|
conn.SetReadLimit(64 * 1024)
|
|
|
|
conn.SetReadDeadline(time.Now().Add(readWait))
|
|
|
|
defer close(closeCh)
|
|
|
|
for {
|
|
|
|
_, message, err := conn.ReadMessage()
|
|
|
|
if err != nil {
|
2024-10-18 08:42:55 +02:00
|
|
|
log.Printf("[websocket] ReadPump error (%s): %v\n", routeId, err)
|
2024-06-12 02:42:10 +02:00
|
|
|
break
|
|
|
|
}
|
|
|
|
jmsg := map[string]any{}
|
|
|
|
err = json.Unmarshal(message, &jmsg)
|
|
|
|
if err != nil {
|
2024-10-18 08:42:55 +02:00
|
|
|
log.Printf("[websocket] error unmarshalling json: %v\n", err)
|
2024-06-12 02:42:10 +02:00
|
|
|
break
|
|
|
|
}
|
|
|
|
conn.SetReadDeadline(time.Now().Add(readWait))
|
|
|
|
msgType := getMessageType(jmsg)
|
|
|
|
if msgType == "pong" {
|
|
|
|
// nothing
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if msgType == "ping" {
|
|
|
|
now := time.Now()
|
|
|
|
pongMessage := map[string]interface{}{"type": "pong", "stime": now.UnixMilli()}
|
|
|
|
outputCh <- pongMessage
|
|
|
|
continue
|
|
|
|
}
|
2024-07-18 00:24:43 +02:00
|
|
|
go processMessage(jmsg, outputCh, rpcInputCh)
|
2024-06-12 02:42:10 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func WritePing(conn *websocket.Conn) error {
|
|
|
|
now := time.Now()
|
|
|
|
pingMessage := map[string]interface{}{"type": "ping", "stime": now.UnixMilli()}
|
|
|
|
jsonVal, _ := json.Marshal(pingMessage)
|
|
|
|
_ = conn.SetWriteDeadline(time.Now().Add(wsWriteWaitTimeout)) // no error
|
|
|
|
err := conn.WriteMessage(websocket.TextMessage, jsonVal)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-10-18 08:42:55 +02:00
|
|
|
func WriteLoop(conn *websocket.Conn, outputCh chan any, closeCh chan any, routeId string) {
|
2024-06-12 02:42:10 +02:00
|
|
|
ticker := time.NewTicker(wsInitialPingTime)
|
|
|
|
defer ticker.Stop()
|
|
|
|
initialPing := true
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case msg := <-outputCh:
|
|
|
|
var barr []byte
|
|
|
|
var err error
|
|
|
|
if _, ok := msg.([]byte); ok {
|
|
|
|
barr = msg.([]byte)
|
|
|
|
} else {
|
|
|
|
barr, err = json.Marshal(msg)
|
|
|
|
if err != nil {
|
2024-10-18 08:42:55 +02:00
|
|
|
log.Printf("[websocket] cannot marshal websocket message: %v\n", err)
|
2024-06-12 02:42:10 +02:00
|
|
|
// just loop again
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
err = conn.WriteMessage(websocket.TextMessage, barr)
|
|
|
|
if err != nil {
|
|
|
|
conn.Close()
|
2024-10-18 08:42:55 +02:00
|
|
|
log.Printf("[websocket] WritePump error (%s): %v\n", routeId, err)
|
2024-06-12 02:42:10 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
case <-ticker.C:
|
|
|
|
err := WritePing(conn)
|
|
|
|
if err != nil {
|
2024-10-18 08:42:55 +02:00
|
|
|
log.Printf("[websocket] WritePump error (%s): %v\n", routeId, err)
|
2024-06-12 02:42:10 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if initialPing {
|
|
|
|
initialPing = false
|
|
|
|
ticker.Reset(wsPingPeriodTickTime)
|
|
|
|
}
|
|
|
|
|
|
|
|
case <-closeCh:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-18 21:05:20 +02:00
|
|
|
func registerConn(wsConnId string, routeId string, wproxy *wshutil.WshRpcProxy) {
|
|
|
|
GlobalLock.Lock()
|
|
|
|
defer GlobalLock.Unlock()
|
|
|
|
curConnId := RouteToConnMap[routeId]
|
|
|
|
if curConnId != "" {
|
|
|
|
log.Printf("[websocket] warning: replacing existing connection for route %q\n", routeId)
|
|
|
|
wshutil.DefaultRouter.UnregisterRoute(routeId)
|
|
|
|
}
|
|
|
|
RouteToConnMap[routeId] = wsConnId
|
2024-10-24 07:43:17 +02:00
|
|
|
wshutil.DefaultRouter.RegisterRoute(routeId, wproxy, true)
|
2024-10-18 21:05:20 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func unregisterConn(wsConnId string, routeId string) {
|
|
|
|
GlobalLock.Lock()
|
|
|
|
defer GlobalLock.Unlock()
|
|
|
|
curConnId := RouteToConnMap[routeId]
|
|
|
|
if curConnId != wsConnId {
|
|
|
|
// only unregister if we are the current connection (otherwise we were already removed)
|
|
|
|
log.Printf("[websocket] warning: trying to unregister connection %q for route %q but it is not the current connection (ignoring)\n", wsConnId, routeId)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
delete(RouteToConnMap, routeId)
|
|
|
|
wshutil.DefaultRouter.UnregisterRoute(routeId)
|
|
|
|
}
|
|
|
|
|
2024-06-12 02:42:10 +02:00
|
|
|
func HandleWsInternal(w http.ResponseWriter, r *http.Request) error {
|
2024-10-17 23:34:02 +02:00
|
|
|
tabId := r.URL.Query().Get("tabid")
|
|
|
|
if tabId == "" {
|
|
|
|
return fmt.Errorf("tabid is required")
|
2024-06-12 02:42:10 +02:00
|
|
|
}
|
2024-08-22 00:04:39 +02:00
|
|
|
err := authkey.ValidateIncomingRequest(r)
|
|
|
|
if err != nil {
|
2024-08-22 00:23:15 +02:00
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
2024-08-22 00:04:39 +02:00
|
|
|
w.Write([]byte(fmt.Sprintf("error validating authkey: %v", err)))
|
2024-10-18 08:42:55 +02:00
|
|
|
log.Printf("[websocket] error validating authkey: %v\n", err)
|
2024-08-22 00:04:39 +02:00
|
|
|
return err
|
|
|
|
}
|
2024-06-12 02:42:10 +02:00
|
|
|
conn, err := WebSocketUpgrader.Upgrade(w, r, nil)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("WebSocket Upgrade Failed: %v", err)
|
|
|
|
}
|
|
|
|
defer conn.Close()
|
|
|
|
wsConnId := uuid.New().String()
|
|
|
|
outputCh := make(chan any, 100)
|
|
|
|
closeCh := make(chan any)
|
2024-09-18 08:10:09 +02:00
|
|
|
var routeId string
|
2024-10-17 23:34:02 +02:00
|
|
|
if tabId == wshutil.ElectronRoute {
|
2024-09-18 08:10:09 +02:00
|
|
|
routeId = wshutil.ElectronRoute
|
|
|
|
} else {
|
2024-10-17 23:34:02 +02:00
|
|
|
routeId = wshutil.MakeTabRouteId(tabId)
|
2024-09-18 08:10:09 +02:00
|
|
|
}
|
2024-10-18 18:29:39 +02:00
|
|
|
log.Printf("[websocket] new connection: tabid:%s connid:%s routeid:%s\n", tabId, wsConnId, routeId)
|
2024-10-18 23:39:48 +02:00
|
|
|
eventbus.RegisterWSChannel(wsConnId, tabId, outputCh)
|
2024-10-18 21:05:20 +02:00
|
|
|
defer eventbus.UnregisterWSChannel(wsConnId)
|
|
|
|
wproxy := wshutil.MakeRpcProxy() // we create a wshproxy to handle rpc messages to/from the window
|
|
|
|
defer close(wproxy.ToRemoteCh)
|
|
|
|
registerConn(wsConnId, routeId, wproxy)
|
|
|
|
defer unregisterConn(wsConnId, routeId)
|
2024-06-12 02:42:10 +02:00
|
|
|
wg := &sync.WaitGroup{}
|
|
|
|
wg.Add(2)
|
2024-07-18 00:24:43 +02:00
|
|
|
go func() {
|
2024-11-21 03:05:13 +01:00
|
|
|
defer panichandler.PanicHandler("HandleWsInternal:outputCh")
|
2024-07-18 00:24:43 +02:00
|
|
|
// no waitgroup add here
|
|
|
|
// move values from rpcOutputCh to outputCh
|
2024-08-14 01:52:35 +02:00
|
|
|
for msgBytes := range wproxy.ToRemoteCh {
|
2024-07-18 00:24:43 +02:00
|
|
|
rpcWSMsg := map[string]any{
|
|
|
|
"eventtype": "rpc", // TODO don't hard code this (but def is in eventbus)
|
|
|
|
"data": json.RawMessage(msgBytes),
|
|
|
|
}
|
|
|
|
outputCh <- rpcWSMsg
|
|
|
|
}
|
|
|
|
}()
|
2024-06-12 02:42:10 +02:00
|
|
|
go func() {
|
2024-11-21 03:05:13 +01:00
|
|
|
defer panichandler.PanicHandler("HandleWsInternal:ReadLoop")
|
2024-06-12 02:42:10 +02:00
|
|
|
// read loop
|
|
|
|
defer wg.Done()
|
2024-10-18 08:42:55 +02:00
|
|
|
ReadLoop(conn, outputCh, closeCh, wproxy.FromRemoteCh, routeId)
|
2024-06-12 02:42:10 +02:00
|
|
|
}()
|
|
|
|
go func() {
|
2024-11-21 03:05:13 +01:00
|
|
|
defer panichandler.PanicHandler("HandleWsInternal:WriteLoop")
|
2024-06-12 02:42:10 +02:00
|
|
|
// write loop
|
|
|
|
defer wg.Done()
|
2024-10-18 08:42:55 +02:00
|
|
|
WriteLoop(conn, outputCh, closeCh, routeId)
|
2024-06-12 02:42:10 +02:00
|
|
|
}()
|
|
|
|
wg.Wait()
|
2024-08-14 01:52:35 +02:00
|
|
|
close(wproxy.FromRemoteCh)
|
2024-06-12 02:42:10 +02:00
|
|
|
return nil
|
|
|
|
}
|