goldwarden/client/unixsocketclient.go

67 lines
1.1 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"
"os"
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 {
}
func NewUnixSocketClient() UnixSocketClient {
return UnixSocketClient{}
}
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) {
home, err := os.UserHomeDir()
if err != nil {
panic(err)
}
c, err := net.Dial("unix", home+"/.goldwarden.sock")
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
}