2024-08-14 03:36:11 +02:00
|
|
|
// Copyright 2024, Command Line Inc.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
|
|
|
package wshremote
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/base64"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2024-09-03 01:48:10 +02:00
|
|
|
"io/fs"
|
2024-08-14 03:36:11 +02:00
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2024-09-03 01:48:10 +02:00
|
|
|
"strings"
|
2024-08-14 03:36:11 +02:00
|
|
|
|
2024-09-05 23:25:45 +02:00
|
|
|
"github.com/wavetermdev/waveterm/pkg/util/utilfn"
|
|
|
|
"github.com/wavetermdev/waveterm/pkg/wavebase"
|
|
|
|
"github.com/wavetermdev/waveterm/pkg/wshrpc"
|
2024-08-14 03:36:11 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
const MaxFileSize = 50 * 1024 * 1024 // 10M
|
2024-08-19 20:02:40 +02:00
|
|
|
const MaxDirSize = 1024
|
|
|
|
const FileChunkSize = 16 * 1024
|
|
|
|
const DirChunkSize = 128
|
2024-08-14 03:36:11 +02:00
|
|
|
|
|
|
|
type ServerImpl struct {
|
|
|
|
LogWriter io.Writer
|
|
|
|
}
|
|
|
|
|
|
|
|
func (*ServerImpl) WshServerImpl() {}
|
|
|
|
|
|
|
|
func (impl *ServerImpl) Log(format string, args ...interface{}) {
|
|
|
|
if impl.LogWriter != nil {
|
|
|
|
fmt.Fprintf(impl.LogWriter, format, args...)
|
|
|
|
} else {
|
|
|
|
log.Printf(format, args...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (impl *ServerImpl) MessageCommand(ctx context.Context, data wshrpc.CommandMessageData) error {
|
|
|
|
impl.Log("[message] %q\n", data.Message)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func respErr(err error) wshrpc.RespOrErrorUnion[wshrpc.CommandRemoteStreamFileRtnData] {
|
|
|
|
return wshrpc.RespOrErrorUnion[wshrpc.CommandRemoteStreamFileRtnData]{Error: err}
|
|
|
|
}
|
|
|
|
|
|
|
|
type ByteRangeType struct {
|
|
|
|
All bool
|
|
|
|
Start int64
|
|
|
|
End int64
|
|
|
|
}
|
|
|
|
|
|
|
|
func parseByteRange(rangeStr string) (ByteRangeType, error) {
|
|
|
|
if rangeStr == "" {
|
|
|
|
return ByteRangeType{All: true}, nil
|
|
|
|
}
|
|
|
|
var start, end int64
|
|
|
|
_, err := fmt.Sscanf(rangeStr, "%d-%d", &start, &end)
|
|
|
|
if err != nil {
|
|
|
|
return ByteRangeType{}, errors.New("invalid byte range")
|
|
|
|
}
|
|
|
|
if start < 0 || end < 0 || start > end {
|
|
|
|
return ByteRangeType{}, errors.New("invalid byte range")
|
|
|
|
}
|
|
|
|
return ByteRangeType{Start: start, End: end}, nil
|
|
|
|
}
|
|
|
|
|
2024-08-19 20:02:40 +02:00
|
|
|
func (impl *ServerImpl) remoteStreamFileDir(ctx context.Context, path string, byteRange ByteRangeType, dataCallback func(fileInfo []*wshrpc.FileInfo, data []byte)) error {
|
2024-08-14 03:36:11 +02:00
|
|
|
innerFilesEntries, err := os.ReadDir(path)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("cannot open dir %q: %w", path, err)
|
|
|
|
}
|
|
|
|
if byteRange.All {
|
2024-08-19 20:02:40 +02:00
|
|
|
if len(innerFilesEntries) > MaxDirSize {
|
|
|
|
innerFilesEntries = innerFilesEntries[:MaxDirSize]
|
2024-08-14 03:36:11 +02:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if byteRange.Start >= int64(len(innerFilesEntries)) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
realEnd := byteRange.End
|
|
|
|
if realEnd > int64(len(innerFilesEntries)) {
|
|
|
|
realEnd = int64(len(innerFilesEntries))
|
|
|
|
}
|
|
|
|
innerFilesEntries = innerFilesEntries[byteRange.Start:realEnd]
|
|
|
|
}
|
2024-08-19 20:02:40 +02:00
|
|
|
var fileInfoArr []*wshrpc.FileInfo
|
2024-08-14 03:36:11 +02:00
|
|
|
parent := filepath.Dir(path)
|
2024-09-03 01:48:10 +02:00
|
|
|
parentFileInfo, err := impl.fileInfoInternal(parent, false)
|
2024-08-14 03:36:11 +02:00
|
|
|
if err == nil && parent != path {
|
|
|
|
parentFileInfo.Name = ".."
|
|
|
|
parentFileInfo.Size = -1
|
2024-08-19 20:02:40 +02:00
|
|
|
fileInfoArr = append(fileInfoArr, parentFileInfo)
|
2024-08-14 03:36:11 +02:00
|
|
|
}
|
|
|
|
for _, innerFileEntry := range innerFilesEntries {
|
|
|
|
if ctx.Err() != nil {
|
|
|
|
return ctx.Err()
|
|
|
|
}
|
|
|
|
innerFileInfoInt, err := innerFileEntry.Info()
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2024-09-20 21:25:46 +02:00
|
|
|
innerFileInfo := statToFileInfo(filepath.Join(path, innerFileInfoInt.Name()), innerFileInfoInt, false)
|
2024-09-03 01:48:10 +02:00
|
|
|
fileInfoArr = append(fileInfoArr, innerFileInfo)
|
2024-08-19 20:02:40 +02:00
|
|
|
if len(fileInfoArr) >= DirChunkSize {
|
|
|
|
dataCallback(fileInfoArr, nil)
|
|
|
|
fileInfoArr = nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(fileInfoArr) > 0 {
|
|
|
|
dataCallback(fileInfoArr, nil)
|
2024-08-14 03:36:11 +02:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-08-19 20:02:40 +02:00
|
|
|
// TODO make sure the read is in chunks of 3 bytes (so 4 bytes of base64) in order to make decoding more efficient
|
|
|
|
func (impl *ServerImpl) remoteStreamFileRegular(ctx context.Context, path string, byteRange ByteRangeType, dataCallback func(fileInfo []*wshrpc.FileInfo, data []byte)) error {
|
2024-08-14 03:36:11 +02:00
|
|
|
fd, err := os.Open(path)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("cannot open file %q: %w", path, err)
|
|
|
|
}
|
|
|
|
defer fd.Close()
|
|
|
|
var filePos int64
|
|
|
|
if !byteRange.All && byteRange.Start > 0 {
|
|
|
|
_, err := fd.Seek(byteRange.Start, io.SeekStart)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("seeking file %q: %w", path, err)
|
|
|
|
}
|
|
|
|
filePos = byteRange.Start
|
|
|
|
}
|
2024-08-19 20:02:40 +02:00
|
|
|
buf := make([]byte, FileChunkSize)
|
2024-08-14 03:36:11 +02:00
|
|
|
for {
|
|
|
|
if ctx.Err() != nil {
|
|
|
|
return ctx.Err()
|
|
|
|
}
|
|
|
|
n, err := fd.Read(buf)
|
|
|
|
if n > 0 {
|
|
|
|
if !byteRange.All && filePos+int64(n) > byteRange.End {
|
|
|
|
n = int(byteRange.End - filePos)
|
|
|
|
}
|
|
|
|
filePos += int64(n)
|
|
|
|
dataCallback(nil, buf[:n])
|
|
|
|
}
|
2024-08-19 23:37:52 +02:00
|
|
|
if !byteRange.All && filePos >= byteRange.End {
|
2024-08-14 03:36:11 +02:00
|
|
|
break
|
|
|
|
}
|
|
|
|
if errors.Is(err, io.EOF) {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("reading file %q: %w", path, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-08-19 20:02:40 +02:00
|
|
|
func (impl *ServerImpl) remoteStreamFileInternal(ctx context.Context, data wshrpc.CommandRemoteStreamFileData, dataCallback func(fileInfo []*wshrpc.FileInfo, data []byte)) error {
|
2024-08-14 03:36:11 +02:00
|
|
|
byteRange, err := parseByteRange(data.ByteRange)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-09-25 03:24:39 +02:00
|
|
|
path, err := wavebase.ExpandHomeDir(data.Path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-09-03 01:48:10 +02:00
|
|
|
finfo, err := impl.fileInfoInternal(path, true)
|
2024-08-14 03:36:11 +02:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("cannot stat file %q: %w", path, err)
|
|
|
|
}
|
2024-08-19 20:02:40 +02:00
|
|
|
dataCallback([]*wshrpc.FileInfo{finfo}, nil)
|
2024-08-14 03:36:11 +02:00
|
|
|
if finfo.NotFound {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if finfo.Size > MaxFileSize {
|
|
|
|
return fmt.Errorf("file %q is too large to read, use /wave/stream-file", path)
|
|
|
|
}
|
|
|
|
if finfo.IsDir {
|
|
|
|
return impl.remoteStreamFileDir(ctx, path, byteRange, dataCallback)
|
|
|
|
} else {
|
|
|
|
return impl.remoteStreamFileRegular(ctx, path, byteRange, dataCallback)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (impl *ServerImpl) RemoteStreamFileCommand(ctx context.Context, data wshrpc.CommandRemoteStreamFileData) chan wshrpc.RespOrErrorUnion[wshrpc.CommandRemoteStreamFileRtnData] {
|
|
|
|
ch := make(chan wshrpc.RespOrErrorUnion[wshrpc.CommandRemoteStreamFileRtnData], 16)
|
|
|
|
defer close(ch)
|
2024-08-19 20:02:40 +02:00
|
|
|
err := impl.remoteStreamFileInternal(ctx, data, func(fileInfo []*wshrpc.FileInfo, data []byte) {
|
2024-08-14 03:36:11 +02:00
|
|
|
resp := wshrpc.CommandRemoteStreamFileRtnData{}
|
|
|
|
resp.FileInfo = fileInfo
|
|
|
|
if len(data) > 0 {
|
2024-08-19 20:02:40 +02:00
|
|
|
resp.Data64 = base64.StdEncoding.EncodeToString(data)
|
2024-08-14 03:36:11 +02:00
|
|
|
}
|
|
|
|
ch <- wshrpc.RespOrErrorUnion[wshrpc.CommandRemoteStreamFileRtnData]{Response: resp}
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
ch <- respErr(err)
|
|
|
|
}
|
|
|
|
return ch
|
|
|
|
}
|
|
|
|
|
2024-09-20 21:25:46 +02:00
|
|
|
func statToFileInfo(fullPath string, finfo fs.FileInfo, extended bool) *wshrpc.FileInfo {
|
|
|
|
mimeType := utilfn.DetectMimeType(fullPath, finfo, extended)
|
2024-09-03 01:48:10 +02:00
|
|
|
rtn := &wshrpc.FileInfo{
|
|
|
|
Path: wavebase.ReplaceHomeDir(fullPath),
|
|
|
|
Dir: computeDirPart(fullPath, finfo.IsDir()),
|
2024-08-14 03:36:11 +02:00
|
|
|
Name: finfo.Name(),
|
|
|
|
Size: finfo.Size(),
|
|
|
|
Mode: finfo.Mode(),
|
|
|
|
ModeStr: finfo.Mode().String(),
|
|
|
|
ModTime: finfo.ModTime().UnixMilli(),
|
|
|
|
IsDir: finfo.IsDir(),
|
|
|
|
MimeType: mimeType,
|
2024-09-03 01:48:10 +02:00
|
|
|
}
|
|
|
|
if finfo.IsDir() {
|
|
|
|
rtn.Size = -1
|
|
|
|
}
|
|
|
|
return rtn
|
|
|
|
}
|
|
|
|
|
|
|
|
// fileInfo might be null
|
|
|
|
func checkIsReadOnly(path string, fileInfo fs.FileInfo, exists bool) bool {
|
|
|
|
if !exists || fileInfo.Mode().IsDir() {
|
|
|
|
dirName := filepath.Dir(path)
|
|
|
|
randHexStr, err := utilfn.RandomHexString(12)
|
|
|
|
if err != nil {
|
|
|
|
// we're not sure, just return false
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
tmpFileName := filepath.Join(dirName, "wsh-tmp-"+randHexStr)
|
2024-10-24 18:46:52 +02:00
|
|
|
fd, err := os.Create(tmpFileName)
|
2024-09-03 01:48:10 +02:00
|
|
|
if err != nil {
|
|
|
|
return true
|
|
|
|
}
|
2024-10-24 18:46:52 +02:00
|
|
|
fd.Close()
|
2024-09-03 01:48:10 +02:00
|
|
|
os.Remove(tmpFileName)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
// try to open for writing, if this fails then it is read-only
|
|
|
|
file, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0666)
|
|
|
|
if err != nil {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
file.Close()
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func computeDirPart(path string, isDir bool) string {
|
2024-09-25 03:24:39 +02:00
|
|
|
path = filepath.Clean(wavebase.ExpandHomeDirSafe(path))
|
2024-09-03 01:48:10 +02:00
|
|
|
path = filepath.ToSlash(path)
|
|
|
|
if path == "/" {
|
|
|
|
return "/"
|
|
|
|
}
|
|
|
|
path = strings.TrimSuffix(path, "/")
|
|
|
|
if isDir {
|
|
|
|
return path
|
|
|
|
}
|
|
|
|
return filepath.Dir(path)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (*ServerImpl) fileInfoInternal(path string, extended bool) (*wshrpc.FileInfo, error) {
|
2024-09-25 03:24:39 +02:00
|
|
|
cleanedPath := filepath.Clean(wavebase.ExpandHomeDirSafe(path))
|
2024-09-03 01:48:10 +02:00
|
|
|
finfo, err := os.Stat(cleanedPath)
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return &wshrpc.FileInfo{
|
|
|
|
Path: wavebase.ReplaceHomeDir(path),
|
|
|
|
Dir: computeDirPart(path, false),
|
|
|
|
NotFound: true,
|
|
|
|
ReadOnly: checkIsReadOnly(cleanedPath, finfo, false),
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("cannot stat file %q: %w", path, err)
|
|
|
|
}
|
2024-09-20 21:25:46 +02:00
|
|
|
rtn := statToFileInfo(cleanedPath, finfo, extended)
|
2024-09-03 01:48:10 +02:00
|
|
|
if extended {
|
|
|
|
rtn.ReadOnly = checkIsReadOnly(cleanedPath, finfo, true)
|
|
|
|
}
|
|
|
|
return rtn, nil
|
|
|
|
}
|
|
|
|
|
2024-09-04 06:08:51 +02:00
|
|
|
func resolvePaths(paths []string) string {
|
|
|
|
if len(paths) == 0 {
|
2024-09-25 03:24:39 +02:00
|
|
|
return wavebase.ExpandHomeDirSafe("~")
|
2024-09-04 06:08:51 +02:00
|
|
|
}
|
2024-09-25 03:24:39 +02:00
|
|
|
rtnPath := wavebase.ExpandHomeDirSafe(paths[0])
|
2024-09-04 06:08:51 +02:00
|
|
|
for _, path := range paths[1:] {
|
2024-09-25 03:24:39 +02:00
|
|
|
path = wavebase.ExpandHomeDirSafe(path)
|
2024-09-04 06:08:51 +02:00
|
|
|
if filepath.IsAbs(path) {
|
|
|
|
rtnPath = path
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
rtnPath = filepath.Join(rtnPath, path)
|
|
|
|
}
|
|
|
|
return rtnPath
|
|
|
|
}
|
|
|
|
|
|
|
|
func (impl *ServerImpl) RemoteFileJoinCommand(ctx context.Context, paths []string) (*wshrpc.FileInfo, error) {
|
|
|
|
rtnPath := resolvePaths(paths)
|
|
|
|
return impl.fileInfoInternal(rtnPath, true)
|
|
|
|
}
|
|
|
|
|
2024-09-03 01:48:10 +02:00
|
|
|
func (impl *ServerImpl) RemoteFileInfoCommand(ctx context.Context, path string) (*wshrpc.FileInfo, error) {
|
|
|
|
return impl.fileInfoInternal(path, true)
|
2024-08-14 03:36:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (*ServerImpl) RemoteWriteFileCommand(ctx context.Context, data wshrpc.CommandRemoteWriteFileData) error {
|
2024-09-25 03:24:39 +02:00
|
|
|
path, err := wavebase.ExpandHomeDir(data.Path)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-08-14 03:36:11 +02:00
|
|
|
createMode := data.CreateMode
|
|
|
|
if createMode == 0 {
|
|
|
|
createMode = 0644
|
|
|
|
}
|
|
|
|
dataSize := base64.StdEncoding.DecodedLen(len(data.Data64))
|
|
|
|
dataBytes := make([]byte, dataSize)
|
|
|
|
n, err := base64.StdEncoding.Decode(dataBytes, []byte(data.Data64))
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("cannot decode base64 data: %w", err)
|
|
|
|
}
|
|
|
|
err = os.WriteFile(path, dataBytes[:n], createMode)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("cannot write file %q: %w", path, err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2024-08-19 20:02:40 +02:00
|
|
|
|
|
|
|
func (*ServerImpl) RemoteFileDeleteCommand(ctx context.Context, path string) error {
|
2024-09-25 03:24:39 +02:00
|
|
|
expandedPath, err := wavebase.ExpandHomeDir(path)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("cannot delete file %q: %w", path, err)
|
|
|
|
}
|
|
|
|
cleanedPath := filepath.Clean(expandedPath)
|
|
|
|
err = os.Remove(cleanedPath)
|
2024-08-19 20:02:40 +02:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("cannot delete file %q: %w", path, err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|