watchman/client/remote/remote.go

96 lines
2.2 KiB
Go
Executable File

package remote
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"local/encryptor"
"local/system/sysconf"
"local/watchman/client/watchman"
"net/http"
"strings"
)
type Remote struct {
enc encryptor.Encryptor
client *http.Client
url string
}
func New() (*Remote, error) {
r := &Remote{
url: "https://localhost:" + strings.Split(sysconf.Get("watchmans").Port, ",")[1],
client: &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
},
enc: encryptor.NewEncryptor("", ""),
}
body, err := r.request("getpub", sysconf.Get("watchmans").Name)
if err != nil {
return nil, errors.New("can't contact watchmans")
}
r.enc.SetPublic(string(body))
return r, nil
}
func (r *Remote) request(path string, body string) ([]byte, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%v/%v", r.url, path), bytes.NewBuffer([]byte(body)))
if err != nil {
return nil, err
}
resp, err := r.client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, errors.New("error when accessing " + path + ": http status " + resp.Status)
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
func (r *Remote) Push(pack *watchman.Package) error {
b, err := json.Marshal(pack)
if err != nil {
return err
}
if len(b) == 0 {
return nil
}
encrypted := r.enc.Encrypt(string(b))
_, err = r.request("push", encrypted)
return err
}
func (r *Remote) Pull(pack *watchman.Package) (*watchman.Package, error) {
transactionKey := encryptor.NewEncryptor("", "").GetPublic()
transactionKey = transactionKey[len(transactionKey)/2:]
transactionKey = transactionKey[:20]
pack.Packs = [][]byte{[]byte(encryptor.NewEncryptor("", "").GetPublic())}
dec := encryptor.NewEncryptor("", "")
dec.SetSymmetric(string(pack.Packs[0]))
b, err := json.Marshal(pack)
if err != nil {
return nil, err
}
if len(b) == 0 {
return nil, nil
}
encrypted := r.enc.Encrypt(string(b))
var ret watchman.Package
b, err = r.request("pull", encrypted)
if err != nil {
return nil, err
}
b = []byte(dec.Decrypt(string(b)))
if err := json.Unmarshal(b, &ret); err != nil {
return nil, err
}
return &ret, nil
}