goldwarden/client/unixsocketclient.go

65 lines
1.2 KiB
Go
Raw Normal View History

2023-08-21 14:52:06 +03:00
package client
import (
2023-09-20 04:05:44 +03:00
"encoding/json"
2023-08-21 14:52:06 +03:00
"io"
"log"
"net"
2023-12-30 20:53:01 +03:00
"github.com/quexten/goldwarden/agent/config"
2023-09-20 04:05:44 +03:00
"github.com/quexten/goldwarden/ipc/messages"
2023-08-21 14:52:06 +03:00
)
const READ_BUFFER = 1 * 1024 * 1024 // 1MB
type UnixSocketClient struct {
2023-12-30 20:53:01 +03:00
runtimeConfig *config.RuntimeConfig
2023-08-21 14:52:06 +03:00
}
2023-12-30 20:53:01 +03:00
func NewUnixSocketClient(runtimeConfig *config.RuntimeConfig) UnixSocketClient {
return UnixSocketClient{
runtimeConfig: runtimeConfig,
}
2023-08-21 14:52:06 +03:00
}
func reader(r io.Reader) interface{} {
buf := make([]byte, READ_BUFFER)
for {
n, err := r.Read(buf[:])
if err != nil {
return nil
}
2023-09-20 04:05:44 +03:00
var message messages.IPCMessage
err = json.Unmarshal(buf[0:n], &message)
2023-08-21 14:52:06 +03:00
if err != nil {
panic(err)
}
return message
}
}
func (client UnixSocketClient) SendToAgent(request interface{}) (interface{}, error) {
2023-12-30 20:53:01 +03:00
c, err := net.Dial("unix", client.runtimeConfig.GoldwardenSocketPath)
2023-08-21 14:52:06 +03:00
if err != nil {
return nil, err
}
defer c.Close()
2023-09-20 04:05:44 +03:00
message, err := messages.IPCMessageFromPayload(request)
2023-08-21 14:52:06 +03:00
if err != nil {
panic(err)
}
2023-09-20 04:05:44 +03:00
messageJson, err := json.Marshal(message)
2023-08-21 14:52:06 +03:00
if err != nil {
panic(err)
}
_, err = c.Write(messageJson)
if err != nil {
log.Fatal("write error:", err)
}
result := reader(c)
2023-09-20 04:05:44 +03:00
return messages.ParsePayload(result.(messages.IPCMessage)), nil
2023-08-21 14:52:06 +03:00
}