This repository has been archived on 2024-10-20. You can view files and clone it, but cannot push or open issues or pull requests.
burgerbackup/lib/client/main.go

85 lines
1.9 KiB
Go
Raw Normal View History

2024-07-12 21:53:59 +01:00
package client
import (
"bytes"
"concord.hectabit.org/Hectabit/burgerbackup/lib/common"
"encoding/json"
"errors"
"golang.org/x/crypto/argon2"
2024-07-12 21:53:59 +01:00
"io"
"log"
"net/http"
"os"
)
func PerformBackup(fileLocation string, backupKey string, cryptoKey string, remoteURL string) (error, int) {
2024-07-12 21:53:59 +01:00
fileContent, err := os.ReadFile(fileLocation)
if err != nil {
log.Println("[CRITICAL] Unknown in performBackup() file read:", err)
return err, 0
}
cryptoKeyHashed := argon2.IDKey([]byte(cryptoKey), []byte("burgerbackup"), 1, 64*1024, 4, 32)
encryptedContent, err := common.EncryptAES(cryptoKeyHashed, fileContent)
2024-07-12 21:53:59 +01:00
if err != nil {
log.Println("[CRITICAL] Unknown in performBack() content encryption", err)
return err, 1
}
encryptedFile := io.NopCloser(bytes.NewReader(encryptedContent))
err, errCode := SendFileToServer(encryptedFile, backupKey, remoteURL)
if err != nil {
return err, errCode + 2
}
log.Println("[INFO] Backup completed at:")
return nil, -1
}
func SendFileToServer(file io.Reader, backupKey string, remoteURL string) (error, int) {
req, err := http.NewRequest("POST", remoteURL, file)
if err != nil {
return err, 0
}
salt, err := common.GenSalt(16)
hashedBackupKey, err := common.Hash(backupKey, salt)
if err != nil {
return err, 1
}
req.Header.Set("Authorization", hashedBackupKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err, 2
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Println("[ERROR] Error in sendFileToServer() response defer:", err)
}
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return err, 3
}
var response map[string]interface{}
err = json.Unmarshal(body, &response)
if err != nil {
return err, 4
}
if resp.StatusCode != 200 {
err, ok := response["goErr"].(string)
if !ok {
err = "error not sent by server"
}
return errors.New(err), 5
}
return nil, -1
}