goldwarden-vaultwarden-bitw.../client/unixsocketclient.go

92 lines
1.9 KiB
Go
Raw Normal View History

2023-08-21 13:52:06 +02:00
package client
import (
2023-09-20 03:05:44 +02:00
"encoding/json"
2023-08-21 13:52:06 +02:00
"io"
"net"
2023-12-30 18:53:01 +01:00
"github.com/quexten/goldwarden/agent/config"
2023-09-20 03:05:44 +02:00
"github.com/quexten/goldwarden/ipc/messages"
2023-08-21 13:52:06 +02:00
)
2024-02-17 11:30:16 +01:00
const READ_BUFFER = 4 * 1024 * 1024 // 16MB
2023-08-21 13:52:06 +02:00
type UnixSocketClient struct {
2023-12-30 18:53:01 +01:00
runtimeConfig *config.RuntimeConfig
2023-08-21 13:52:06 +02:00
}
2024-02-09 00:24:28 +01:00
type UnixSocketConnection struct {
conn net.Conn
}
2023-12-30 18:53:01 +01:00
func NewUnixSocketClient(runtimeConfig *config.RuntimeConfig) UnixSocketClient {
return UnixSocketClient{
runtimeConfig: runtimeConfig,
}
2023-08-21 13:52:06 +02:00
}
2024-02-09 00:24:28 +01:00
func Reader(r io.Reader) interface{} {
2023-08-21 13:52:06 +02:00
buf := make([]byte, READ_BUFFER)
for {
n, err := r.Read(buf[:])
if err != nil {
return nil
}
2023-09-20 03:05:44 +02:00
var message messages.IPCMessage
err = json.Unmarshal(buf[0:n], &message)
2023-08-21 13:52:06 +02:00
if err != nil {
panic(err)
}
return message
}
}
func (client UnixSocketClient) SendToAgent(request interface{}) (interface{}, error) {
2024-02-09 00:24:28 +01:00
c, err := client.Connect()
2023-08-21 13:52:06 +02:00
if err != nil {
return nil, err
}
defer c.Close()
2024-02-09 00:24:28 +01:00
return c.SendCommand(request)
}
2023-08-21 13:52:06 +02:00
2024-02-09 00:24:28 +01:00
func (client UnixSocketClient) Connect() (UnixSocketConnection, error) {
c, err := net.Dial("unix", client.runtimeConfig.GoldwardenSocketPath)
2023-08-21 13:52:06 +02:00
if err != nil {
2024-02-09 00:24:28 +01:00
return UnixSocketConnection{}, err
2023-08-21 13:52:06 +02:00
}
2024-02-09 00:24:28 +01:00
return UnixSocketConnection{conn: c}, nil
}
func (conn UnixSocketConnection) SendCommand(request interface{}) (interface{}, error) {
err := conn.WriteMessage(request)
2023-08-21 13:52:06 +02:00
if err != nil {
2024-02-09 00:24:28 +01:00
return nil, err
2023-08-21 13:52:06 +02:00
}
2024-02-09 00:24:28 +01:00
return conn.ReadMessage(), nil
}
func (conn UnixSocketConnection) ReadMessage() interface{} {
result := Reader(conn.conn)
payload := messages.ParsePayload(result.(messages.IPCMessage))
return payload
}
2023-08-21 13:52:06 +02:00
2024-02-09 00:24:28 +01:00
func (conn UnixSocketConnection) WriteMessage(message interface{}) error {
messagePacket, err := messages.IPCMessageFromPayload(message)
2023-08-21 13:52:06 +02:00
if err != nil {
2024-02-09 00:24:28 +01:00
panic(err)
2023-08-21 13:52:06 +02:00
}
2024-02-09 00:24:28 +01:00
messageJson, err := json.Marshal(messagePacket)
if err != nil {
panic(err)
}
_, err = conn.conn.Write(messageJson)
return err
}
func (conn UnixSocketConnection) Close() {
conn.conn.Close()
2023-08-21 13:52:06 +02:00
}