mirror of
https://github.com/shtorm-7/sing-box-extended.git
synced 2026-12-01 14:18:36 +00:00
Add Taildrop support
This commit is contained in:
@@ -79,7 +79,10 @@ func runAPITailscalePing(selector string) error {
|
||||
}()
|
||||
timer := time.NewTimer(commandAPITailscalePingTimeout)
|
||||
defer timer.Stop()
|
||||
var pongCount int
|
||||
var (
|
||||
pongCount int
|
||||
lastPeerRelay string
|
||||
)
|
||||
for pongCount < commandAPITailscalePingCount {
|
||||
var (
|
||||
response *daemon.TailscalePingResponse
|
||||
@@ -109,16 +112,23 @@ func runAPITailscalePing(selector string) error {
|
||||
if response.GetEndpoint() != "" {
|
||||
return nil
|
||||
}
|
||||
lastPeerRelay = response.GetPeerRelay()
|
||||
timer.Reset(commandAPITailscalePingTimeout)
|
||||
}
|
||||
os.Stdout.WriteString("direct connection not established\n")
|
||||
if lastPeerRelay != "" {
|
||||
os.Stdout.WriteString(F.ToString("direct connection not established, relayed by peer relay ", lastPeerRelay, "\n"))
|
||||
} else {
|
||||
os.Stdout.WriteString("direct connection not established\n")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func formatTailscalePong(peerName string, peerAddress string, response *daemon.TailscalePingResponse) string {
|
||||
via := response.GetEndpoint()
|
||||
if via == "" {
|
||||
if response.GetDerpRegionCode() != "" {
|
||||
if response.GetPeerRelay() != "" {
|
||||
via = F.ToString("peer relay ", response.GetPeerRelay())
|
||||
} else if response.GetDerpRegionCode() != "" {
|
||||
via = F.ToString("DERP(", response.GetDerpRegionCode(), ")")
|
||||
} else {
|
||||
via = F.ToString("DERP(", response.GetDerpRegionID(), ")")
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/daemon"
|
||||
F "github.com/sagernet/sing/common/format"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var commandAPITailscaleTaildrop = &cobra.Command{
|
||||
Use: "taildrop",
|
||||
Short: "Send and receive files over Tailscale",
|
||||
}
|
||||
|
||||
func init() {
|
||||
commandAPITailscaleTaildrop.PersistentFlags().StringVar(&commandAPITailscaleFlagEndpoint, "endpoint", "", commandAPITailscaleEndpointUsage)
|
||||
commandAPITailscale.AddCommand(commandAPITailscaleTaildrop)
|
||||
}
|
||||
|
||||
func fetchTaildropInbox(client daemon.StartedServiceClient, endpointTag string) (*daemon.TaildropInbox, error) {
|
||||
ctx, cancel := context.WithCancel(globalCtx)
|
||||
defer cancel()
|
||||
stream, err := client.SubscribeTaildropInbox(ctx, &daemon.SubscribeTaildropInboxRequest{
|
||||
EndpointTag: endpointTag,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return stream.Recv()
|
||||
}
|
||||
|
||||
func formatTaildropSize(size int64) string {
|
||||
switch {
|
||||
case size < 0:
|
||||
return "-"
|
||||
case size < 1000:
|
||||
return F.ToString(size, " B")
|
||||
case size < 1000*1000:
|
||||
return formatTaildropSizeUnit(size, 1000, "KB")
|
||||
case size < 1000*1000*1000:
|
||||
return formatTaildropSizeUnit(size, 1000*1000, "MB")
|
||||
default:
|
||||
return formatTaildropSizeUnit(size, 1000*1000*1000, "GB")
|
||||
}
|
||||
}
|
||||
|
||||
func formatTaildropSizeUnit(size int64, unit int64, unitName string) string {
|
||||
value := float64(size) / float64(unit)
|
||||
var precision int
|
||||
switch {
|
||||
case value < 10:
|
||||
precision = 2
|
||||
case value < 100:
|
||||
precision = 1
|
||||
}
|
||||
return strconv.FormatFloat(value, 'f', precision, 64) + " " + unitName
|
||||
}
|
||||
|
||||
func formatTaildropModifiedAt(timestamp int64) string {
|
||||
if timestamp == 0 {
|
||||
return ""
|
||||
}
|
||||
return time.Unix(timestamp, 0).Local().Format("2006-01-02 15:04")
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/sagernet/sing-box/daemon"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var commandAPITailscaleTaildropDelete = &cobra.Command{
|
||||
Use: "delete <name>...",
|
||||
Short: "Delete received files",
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return runAPITaildropDelete(args)
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
commandAPITailscaleTaildrop.AddCommand(commandAPITailscaleTaildropDelete)
|
||||
}
|
||||
|
||||
func runAPITaildropDelete(names []string) error {
|
||||
clientConn, client, err := createAPIClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer clientConn.Close()
|
||||
endpointTag, err := resolveTailscaleEndpointTag(client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, name := range names {
|
||||
_, err = client.DeleteTaildropFile(globalCtx, &daemon.DeleteTaildropFileRequest{
|
||||
EndpointTag: endpointTag,
|
||||
Name: name,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
|
||||
"github.com/sagernet/sing-box/daemon"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
F "github.com/sagernet/sing/common/format"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var commandAPITailscaleTaildropGet = &cobra.Command{
|
||||
Use: "get <name> [output]",
|
||||
Short: "Save a received file",
|
||||
Args: cobra.RangeArgs(1, 2),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
var outputPath string
|
||||
if len(args) > 1 {
|
||||
outputPath = args[1]
|
||||
}
|
||||
return runAPITaildropGet(args[0], outputPath)
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
commandAPITailscaleTaildrop.AddCommand(commandAPITailscaleTaildropGet)
|
||||
}
|
||||
|
||||
func runAPITaildropGet(name string, outputPath string) error {
|
||||
clientConn, client, err := createAPIClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer clientConn.Close()
|
||||
endpointTag, err := resolveTailscaleEndpointTag(client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if outputPath == "" {
|
||||
outputPath = name
|
||||
} else {
|
||||
information, statErr := os.Stat(outputPath)
|
||||
if statErr == nil && information.IsDir() {
|
||||
outputPath = filepath.Join(outputPath, name)
|
||||
}
|
||||
}
|
||||
ctx, cancel := signal.NotifyContext(globalCtx, os.Interrupt, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
stream, err := client.DownloadTaildropFile(ctx, &daemon.DownloadTaildropFileRequest{
|
||||
EndpointTag: endpointTag,
|
||||
Name: name,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
firstChunk, err := stream.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
totalSize := firstChunk.GetSize()
|
||||
var outputFile *os.File
|
||||
if outputPath == "-" {
|
||||
outputFile = os.Stdout
|
||||
} else {
|
||||
outputFile, err = os.OpenFile(outputPath, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var downloaded int64
|
||||
writeChunk := func(data []byte) error {
|
||||
if len(data) == 0 {
|
||||
return nil
|
||||
}
|
||||
_, writeErr := outputFile.Write(data)
|
||||
if writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
downloaded += int64(len(data))
|
||||
writeProgress(F.ToString(name, ": ", formatTaildropSize(downloaded), " / ", formatTaildropSize(totalSize), " "))
|
||||
return nil
|
||||
}
|
||||
err = writeChunk(firstChunk.GetData())
|
||||
for err == nil {
|
||||
var chunk *daemon.DownloadTaildropFileChunk
|
||||
chunk, err = stream.Recv()
|
||||
if err == io.EOF {
|
||||
err = nil
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
err = writeChunk(chunk.GetData())
|
||||
}
|
||||
if outputPath != "-" {
|
||||
closeErr := outputFile.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(outputPath)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return E.New("interrupted")
|
||||
}
|
||||
return err
|
||||
}
|
||||
writeProgress("")
|
||||
writeStderrLine(F.ToString("saved ", name, " (", formatTaildropSize(downloaded), ")"))
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var commandAPITailscaleTaildropList = &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List received files",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return runAPITaildropList()
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
commandAPITailscaleTaildrop.AddCommand(commandAPITailscaleTaildropList)
|
||||
}
|
||||
|
||||
func runAPITaildropList() error {
|
||||
clientConn, client, err := createAPIClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer clientConn.Close()
|
||||
endpointTag, err := resolveTailscaleEndpointTag(client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
inbox, err := fetchTaildropInbox(client, endpointTag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, file := range inbox.GetReceiving() {
|
||||
writeStderrLine("receiving " + file.GetName() + ": " + formatTaildropSize(file.GetReceivedBytes()) + " / " + formatTaildropSize(file.GetSize()))
|
||||
}
|
||||
table := tableWriter{
|
||||
header: []string{"NAME", "SIZE", "FROM", "RECEIVED"},
|
||||
emptyMessage: "no received files",
|
||||
}
|
||||
for _, file := range inbox.GetFiles() {
|
||||
sender := file.GetSenderName()
|
||||
if sender == "" {
|
||||
sender = "-"
|
||||
}
|
||||
table.addRow(
|
||||
file.GetName(),
|
||||
formatTaildropSize(file.GetSize()),
|
||||
sender,
|
||||
formatTaildropModifiedAt(file.GetModifiedAt()),
|
||||
)
|
||||
}
|
||||
table.flush()
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
|
||||
"github.com/sagernet/sing-box/daemon"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
F "github.com/sagernet/sing/common/format"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
var commandAPITailscaleTaildropSend = &cobra.Command{
|
||||
Use: "send <peer> <file>...",
|
||||
Short: "Send files to a Tailscale peer",
|
||||
Args: cobra.MinimumNArgs(2),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return runAPITaildropSend(args[0], args[1:])
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
commandAPITailscaleTaildrop.AddCommand(commandAPITailscaleTaildropSend)
|
||||
}
|
||||
|
||||
func runAPITaildropSend(selector string, filePaths []string) error {
|
||||
clientConn, client, err := createAPIClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer clientConn.Close()
|
||||
endpoint, err := fetchTailscaleEndpoint(client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !endpoint.GetCanShareFiles() {
|
||||
return E.New("file sharing not enabled by Tailscale admin")
|
||||
}
|
||||
entry, err := resolveTailscalePeer(tailscalePeerEntries(endpoint), selector)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if entry.self {
|
||||
return E.New("cannot send files to this device")
|
||||
}
|
||||
if !entry.peer.GetCanReceiveFiles() {
|
||||
return E.New("peer cannot receive files: ", tailscalePeerName(entry.peer))
|
||||
}
|
||||
|
||||
type outgoingFile struct {
|
||||
path string
|
||||
name string
|
||||
size int64
|
||||
}
|
||||
files := make([]outgoingFile, 0, len(filePaths))
|
||||
manifest := make([]*daemon.TaildropOutgoingFile, 0, len(filePaths))
|
||||
for _, filePath := range filePaths {
|
||||
information, statErr := os.Stat(filePath)
|
||||
if statErr != nil {
|
||||
return statErr
|
||||
}
|
||||
if information.IsDir() {
|
||||
return E.New("directories are not supported: ", filePath)
|
||||
}
|
||||
file := outgoingFile{
|
||||
path: filePath,
|
||||
name: filepath.Base(filePath),
|
||||
size: information.Size(),
|
||||
}
|
||||
files = append(files, file)
|
||||
manifest = append(manifest, &daemon.TaildropOutgoingFile{
|
||||
Name: file.name,
|
||||
Size: file.size,
|
||||
})
|
||||
}
|
||||
|
||||
ctx, cancel := signal.NotifyContext(globalCtx, os.Interrupt, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
stream, err := client.SendTaildropFiles(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = stream.Send(&daemon.TaildropSendClientMessage{
|
||||
Message: &daemon.TaildropSendClientMessage_Start{Start: &daemon.TaildropSendStart{
|
||||
EndpointTag: endpoint.GetEndpointTag(),
|
||||
PeerStableID: entry.peer.GetStableID(),
|
||||
Files: manifest,
|
||||
}},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var uploadErr error
|
||||
uploadDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(uploadDone)
|
||||
failUpload := func(cause error) {
|
||||
uploadErr = cause
|
||||
cancel()
|
||||
}
|
||||
buffer := make([]byte, daemon.TaildropChunkSize)
|
||||
for _, file := range files {
|
||||
sourceFile, openErr := os.Open(file.path)
|
||||
if openErr != nil {
|
||||
failUpload(openErr)
|
||||
return
|
||||
}
|
||||
for {
|
||||
n, readErr := sourceFile.Read(buffer)
|
||||
if n > 0 {
|
||||
sendErr := stream.Send(&daemon.TaildropSendClientMessage{
|
||||
Message: &daemon.TaildropSendClientMessage_Chunk{Chunk: &daemon.TaildropFileChunk{Data: buffer[:n]}},
|
||||
})
|
||||
if sendErr != nil {
|
||||
sourceFile.Close()
|
||||
failUpload(sendErr)
|
||||
return
|
||||
}
|
||||
}
|
||||
if readErr == io.EOF {
|
||||
break
|
||||
}
|
||||
if readErr != nil {
|
||||
sourceFile.Close()
|
||||
failUpload(readErr)
|
||||
return
|
||||
}
|
||||
}
|
||||
sourceFile.Close()
|
||||
sendErr := stream.Send(&daemon.TaildropSendClientMessage{
|
||||
Message: &daemon.TaildropSendClientMessage_FileDone{FileDone: &daemon.TaildropFileDone{}},
|
||||
})
|
||||
if sendErr != nil {
|
||||
failUpload(sendErr)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
peerName := tailscalePeerName(entry.peer)
|
||||
for {
|
||||
message, recvErr := stream.Recv()
|
||||
if recvErr != nil {
|
||||
cancel()
|
||||
<-uploadDone
|
||||
if uploadErr != nil && !E.IsCanceled(uploadErr) && status.Code(uploadErr) != codes.Canceled {
|
||||
return uploadErr
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return E.New("interrupted")
|
||||
}
|
||||
if recvErr == io.EOF {
|
||||
writeProgress("")
|
||||
writeStderrLine(F.ToString("sent ", len(files), " file(s) to ", peerName))
|
||||
return nil
|
||||
}
|
||||
return recvErr
|
||||
}
|
||||
progress := message.GetProgress()
|
||||
if progress == nil {
|
||||
continue
|
||||
}
|
||||
fileIndex := progress.FileIndex
|
||||
if fileIndex < 0 || int(fileIndex) >= len(files) {
|
||||
return E.New("invalid file index: ", fileIndex)
|
||||
}
|
||||
file := files[fileIndex]
|
||||
if progress.FileCompleted {
|
||||
writeProgress("")
|
||||
writeStderrLine(F.ToString(file.name, ": done"))
|
||||
} else {
|
||||
writeProgress(F.ToString(file.name, ": ", formatTaildropSize(progress.SentBytes), " / ", formatTaildropSize(file.size), " "))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var commandAPITailscaleTaildropTargets = &cobra.Command{
|
||||
Use: "targets",
|
||||
Short: "List peers that can receive files",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return runAPITaildropTargets()
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
commandAPITailscaleTaildrop.AddCommand(commandAPITailscaleTaildropTargets)
|
||||
}
|
||||
|
||||
func runAPITaildropTargets() error {
|
||||
clientConn, client, err := createAPIClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer clientConn.Close()
|
||||
endpoint, err := fetchTailscaleEndpoint(client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !endpoint.GetCanShareFiles() {
|
||||
return E.New("file sharing not enabled by Tailscale admin")
|
||||
}
|
||||
entries := tailscalePeerEntries(endpoint)
|
||||
if len(entries) > 0 && entries[0].self {
|
||||
entries = entries[1:]
|
||||
}
|
||||
sortTailscalePeerEntries(entries)
|
||||
table := tableWriter{
|
||||
header: []string{"DNS NAME", "IP", "ONLINE"},
|
||||
emptyMessage: "no file targets",
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if !entry.peer.GetCanReceiveFiles() {
|
||||
continue
|
||||
}
|
||||
table.addRow(
|
||||
tailscalePeerName(entry.peer),
|
||||
tailscalePeerAddress(entry.peer),
|
||||
formatYesNo(entry.peer.GetOnline()),
|
||||
)
|
||||
}
|
||||
table.flush()
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user