sing-box/experimental/libbox/command_close_connection.go

55 lines
1.3 KiB
Go
Raw Normal View History

2024-06-11 13:16:33 +00:00
package libbox
import (
"bufio"
"net"
"github.com/sagernet/sing-box/experimental/clashapi"
"github.com/sagernet/sing/common/binary"
E "github.com/sagernet/sing/common/exceptions"
2024-06-24 01:49:15 +00:00
"github.com/sagernet/sing/common/varbin"
2024-06-11 13:16:33 +00:00
"github.com/gofrs/uuid/v5"
)
func (c *CommandClient) CloseConnection(connId string) error {
conn, err := c.directConnect()
if err != nil {
return err
}
defer conn.Close()
2024-10-18 01:58:03 +00:00
err = binary.Write(conn, binary.BigEndian, uint8(CommandCloseConnection))
if err != nil {
return err
}
2024-06-11 13:16:33 +00:00
writer := bufio.NewWriter(conn)
2024-06-24 01:49:15 +00:00
err = varbin.Write(writer, binary.BigEndian, connId)
2024-06-11 13:16:33 +00:00
if err != nil {
return err
}
err = writer.Flush()
if err != nil {
return err
}
return readError(conn)
}
func (s *CommandServer) handleCloseConnection(conn net.Conn) error {
reader := bufio.NewReader(conn)
var connId string
2024-06-24 01:49:15 +00:00
err := varbin.Read(reader, binary.BigEndian, &connId)
2024-06-11 13:16:33 +00:00
if err != nil {
return E.Cause(err, "read connection id")
}
service := s.service
if service == nil {
return writeError(conn, E.New("service not ready"))
}
targetConn := service.clashServer.(*clashapi.Server).TrafficManager().Connection(uuid.FromStringOrNil(connId))
2024-06-11 13:16:33 +00:00
if targetConn == nil {
return writeError(conn, E.New("connection already closed"))
}
targetConn.Close()
return writeError(conn, nil)
}