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"
|
|
|
|
"log"
|
|
|
|
"net"
|
|
|
|
"os"
|
|
|
|
|
2023-09-20 03:05:44 +02:00
|
|
|
"github.com/quexten/goldwarden/ipc/messages"
|
2023-08-21 13:52:06 +02: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 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) {
|
|
|
|
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 03:05:44 +02:00
|
|
|
message, err := messages.IPCMessageFromPayload(request)
|
2023-08-21 13:52:06 +02:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2023-09-20 03:05:44 +02:00
|
|
|
messageJson, err := json.Marshal(message)
|
2023-08-21 13:52:06 +02:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = c.Write(messageJson)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal("write error:", err)
|
|
|
|
}
|
|
|
|
result := reader(c)
|
2023-09-20 03:05:44 +02:00
|
|
|
return messages.ParsePayload(result.(messages.IPCMessage)), nil
|
2023-08-21 13:52:06 +02:00
|
|
|
}
|