This commit is contained in:
Bel LaPointe
2021-12-10 07:19:31 -07:00
parent e6a71d692e
commit dad1b3042c
152 changed files with 21753 additions and 9433 deletions

14
vendor/local/args/.gitignore vendored Normal file
View File

@@ -0,0 +1,14 @@
.*.go
vendor
*.swp
*.swo
testdata
fireflyiii
*.db
*.ldb
*.log
*.bak
CURRENT
LOCK
LOG
MANIFEST-*

222
vendor/local/args/arg.go vendored Normal file
View File

@@ -0,0 +1,222 @@
package args
import (
"fmt"
"math"
"strconv"
"strings"
"time"
)
type Arg struct {
Env string
Flag string
Help string
Default interface{}
Value interface{}
ArgType Type
}
func NewArg(argType Type, key, help string, def interface{}) *Arg {
return &Arg{
Env: strings.ToUpper(key),
Flag: strings.ToLower(key),
Help: help,
Default: def,
Value: def,
ArgType: argType,
}
}
func (a *Arg) String() string {
return fmt.Sprintf("[%s $%s/-%s, %v from %v, help %v]",
a.ArgType,
a.Env,
a.Flag,
a.Value,
a.Default,
a.Help,
)
}
func (a *Arg) Get() interface{} {
return a.Value
}
func (a *Arg) GetInt() int {
if a.ArgType != INT {
return -1
}
if _, ok := a.Value.(int); !ok {
return -1
}
return a.Value.(int)
}
func (a *Arg) GetString() string {
if a.ArgType != STRING {
return ""
}
if _, ok := a.Value.(string); !ok {
return ""
}
return a.Value.(string)
}
func (a *Arg) GetBool() bool {
if a.ArgType != BOOL {
return false
}
if _, ok := a.Value.(bool); !ok {
return false
}
return a.Value.(bool)
}
func (a *Arg) GetDuration() time.Duration {
if a.ArgType != DURATION {
return time.Duration(-1)
}
if _, ok := a.Value.(time.Duration); !ok {
return time.Duration(-1)
}
return a.Value.(time.Duration)
}
func (a *Arg) GetTime() time.Time {
if a.ArgType != TIME {
return time.Date(1995, 1, 1, 0, 0, 0, 0, time.UTC)
}
if _, ok := a.Value.(time.Time); !ok {
return time.Date(1995, 1, 1, 0, 0, 0, 0, time.UTC)
}
return a.Value.(time.Time)
}
func (a *Arg) GetFloat() float32 {
if a.ArgType != FLOAT {
return float32(-1)
}
if _, ok := a.Value.(float32); !ok {
return float32(-1)
}
return a.Value.(float32)
}
func (a *Arg) Set(value interface{}) error {
err := fmt.Errorf("incompatible set of type %T for arg $%v/-%v type %v", value, a.Env, a.Flag, a.ArgType)
switch a.ArgType {
case INT:
switch value.(type) {
case int:
a.Value = value.(int)
err = nil
case string:
s := value.(string)
var i int
if i, err = strconv.Atoi(s); err == nil {
a.Value = i
err = nil
}
case float64:
f := value.(float64)
if f-float64(int(f)) == 0 {
a.Value = int(f)
err = nil
}
}
case STRING:
i, ok := value.(string)
if ok {
a.Value = i
err = nil
}
case BOOL:
i, ok := value.(bool)
if ok {
a.Value = i
err = nil
} else if s, ok := value.(string); !ok {
} else if i, err = strconv.ParseBool(s); err == nil {
a.Value = i
err = nil
}
case DURATION:
i, ok := value.(time.Duration)
if ok {
a.Value = i
err = nil
} else if s, ok := value.(string); !ok {
} else if i, err = time.ParseDuration(s); err == nil {
a.Value = i
err = nil
}
case TIME:
if i, ok := value.(time.Duration); ok {
a.Value = time.Now().Add(i)
err = nil
} else if j, ok := value.(time.Time); ok {
a.Value = j
err = nil
} else if s, ok := value.(string); !ok {
} else if i, err = time.ParseDuration(s); err == nil {
a.Value = time.Now().Add(i)
err = nil
} else {
layouts := []string{
"01-02-2006",
"01/02/2006",
"01-02-06",
"01/02/06",
"2006-01-02",
"2006/01/02",
"06-01-02",
"06/01/02",
"2006-01-02 15:04:05.999999999 -0700 MST",
"15:04:05.999999999 -0700 MST",
"15:04:05 -0700 MST",
"15:04 -0700 MST",
"15:04",
}
for k := range layouts {
if j, err = time.Parse(layouts[k], s); err == nil {
a.Value = j
err = nil
break
}
}
if err == nil && s != "" {
j, _ := a.Value.(time.Time)
if j.Year() < 1980 {
n := time.Now()
j = j.AddDate(n.Year()-j.Year(), int(n.Month()-j.Month()), n.Day()-j.Day())
j = j.In(time.Local)
t := time.Date(2000, 02, 02, 12, 02, 02, 02, time.UTC)
l := t.Local()
tzDiff := int(math.Abs(float64(t.Hour() - l.Hour())))
j = j.Add(time.Hour * time.Duration(tzDiff))
}
a.Value = j
}
}
case FLOAT:
if i, ok := value.(float32); ok {
a.Value = i
err = nil
} else if j, ok := value.(float64); ok {
a.Value = float32(j)
err = nil
} else if k, ok := value.(int); ok {
a.Value = float32(k)
err = nil
} else if s, ok := value.(string); !ok {
} else if j, err = strconv.ParseFloat(s, 32); err == nil {
a.Value = float32(j)
err = nil
} else if k, err = strconv.Atoi(s); err == nil {
a.Value = float32(k)
err = nil
}
}
return err
}

209
vendor/local/args/argset.go vendored Normal file
View File

@@ -0,0 +1,209 @@
package args
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
"time"
yaml "gopkg.in/yaml.v2"
)
type ArgSet struct {
parsed bool
args []*Arg
configFiles []string
}
func NewArgSet(configFiles ...string) *ArgSet {
return &ArgSet{
args: []*Arg{},
configFiles: configFiles,
}
}
func (as *ArgSet) String() string {
s := "{"
for _, arg := range as.args {
if len(s) > 2 {
s += ", "
}
s += fmt.Sprintf("%s:%v", arg.Flag, arg.Value)
}
s += "}"
return s
}
func (as *ArgSet) Append(argType Type, key, help string, def interface{}) {
as.args = append(as.args, NewArg(argType, key, help, def))
}
func (as *ArgSet) Get(key string) *Arg {
if !as.parsed {
return nil
}
for i := range as.args {
if as.args[i].Env == key || as.args[i].Flag == key {
return as.args[i]
}
}
return nil
}
func (as *ArgSet) GetFloat(key string) float32 {
a := as.Get(key)
return a.GetFloat()
}
func (as *ArgSet) GetInt(key string) int {
a := as.Get(key)
return a.GetInt()
}
func (as *ArgSet) GetBool(key string) bool {
a := as.Get(key)
return a.GetBool()
}
func (as *ArgSet) GetDuration(key string) time.Duration {
a := as.Get(key)
return a.GetDuration()
}
func (as *ArgSet) GetString(key string) string {
a := as.Get(key)
return a.GetString()
}
func (as *ArgSet) Parse() error {
if as.parsed {
return nil
}
defer func() {
as.parsed = true
}()
if err := as.setValueFromDefaults(); err != nil {
return err
}
if err := as.setValueFromFiles(); err != nil {
return err
}
if err := as.setValueFromEnv(); err != nil {
return err
}
if err := as.setValueFromFlags(); err != nil {
return err
}
return nil
}
func (as *ArgSet) setValueFromDefaults() error {
for i := range as.args {
if err := as.args[i].Set(as.args[i].Default); err != nil {
return err
}
}
return nil
}
func (as *ArgSet) setValueFromEnv() error {
for i := range as.args {
key := as.args[i].Env
key = strings.ReplaceAll(key, "-", "_")
if v, ok := os.LookupEnv(key); ok {
if err := as.args[i].Set(v); err != nil {
return err
}
}
}
return nil
}
func (as *ArgSet) setValueFromFlags() error {
var err error
fs := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
for i := range as.args {
arg := as.args[i]
switch arg.ArgType {
case INT:
arg.Default = fs.Int(arg.Flag, arg.Value.(int), arg.Help)
case STRING:
arg.Default = fs.String(arg.Flag, arg.Value.(string), arg.Help)
case BOOL:
arg.Default = fs.Bool(arg.Flag, arg.Value.(bool), arg.Help)
case DURATION:
arg.Default = fs.Duration(arg.Flag, arg.Value.(time.Duration), arg.Help)
case TIME:
arg.Default = fs.String(arg.Flag, arg.Value.(time.Time).Format("2006-01-02"), arg.Help)
case FLOAT:
arg.Default = fs.Float64(arg.Flag, float64(arg.Value.(float32)), arg.Help)
default:
return errors.New("unknown type, cannot set from flag")
}
}
if err := fs.Parse(os.Args[1:]); err != nil {
return err
}
for i := range as.args {
arg := as.args[i]
switch arg.ArgType {
case INT:
arg.Value = *arg.Default.(*int)
case STRING:
arg.Value = *arg.Default.(*string)
case BOOL:
arg.Value = *arg.Default.(*bool)
case DURATION:
arg.Value = *arg.Default.(*time.Duration)
case TIME:
arg.Value = *arg.Default.(*string)
err = arg.Set(arg.Value)
case FLOAT:
arg.Value = *arg.Default.(*float64)
err = arg.Set(arg.Value)
}
}
return err
}
func (as *ArgSet) setValueFromFiles() error {
for _, file := range as.configFiles {
if err := as.setValueFromFile(file); err != nil {
return err
}
}
return nil
}
func (as *ArgSet) setValueFromFile(path string) error {
b, err := ioutil.ReadFile(path)
if err != nil {
return err
}
var config map[string]interface{}
if strings.HasSuffix(path, ".json") {
err = json.Unmarshal(b, &config)
} else if strings.HasSuffix(path, ".yaml") {
err = yaml.Unmarshal(b, &config)
} else {
err = fmt.Errorf("unknown config file suffix: %s", path)
}
if err != nil {
return err
}
for i := range as.args {
key := as.args[i].Flag
if v, ok := config[key]; ok {
if err := as.args[i].Set(v); err != nil {
return err
}
}
}
return nil
}

36
vendor/local/args/type.go vendored Normal file
View File

@@ -0,0 +1,36 @@
package args
import (
"fmt"
"time"
)
type Type int
const (
INT = Type(iota)
STRING = Type(iota)
BOOL = Type(iota)
DURATION = Type(iota)
TIME = Type(iota)
FLOAT = Type(iota)
)
func (t Type) String() string {
var i interface{} = nil
switch t {
case INT:
i = 1
case STRING:
i = ""
case BOOL:
i = false
case DURATION:
i = time.Duration(0)
case TIME:
i = time.Time{}
case FLOAT:
i = float32(0)
}
return fmt.Sprintf("%T", i)
}

View File

@@ -1,384 +0,0 @@
package encryptor
import (
"bytes"
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"io"
"io/ioutil"
"os"
"path"
"strings"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/packet"
// for openpgp
_ "golang.org/x/crypto/ripemd160"
)
const keylen = 32
// Encryptor interface
type Encryptor interface {
Encrypt(string) string
Decrypt(string) string
SetPublic(string)
GetPublic() string
SetSymmetric(string)
FromFiles(string, string) error
ToFiles(string, string) error
}
type encryptor struct {
entity *openpgp.Entity
writing *openpgp.Entity
symmetric string
b64 bool
}
func (e *encryptor) SetPublic(pub string) {
reader := b64dec(pub)
e.writing = entityFromPackets(nil, strToPubPack(reader))
}
func (e *encryptor) GetPublic() string {
bufpub := new(bytes.Buffer)
e.writing.Serialize(bufpub)
bufPu, err := ioutil.ReadAll(bufpub)
if err != nil {
panic(err)
}
return b64enc(string(bufPu))
}
func (e *encryptor) setPrivate(pri string) {
readerPri := b64dec(pri)
readerPub := b64dec(e.GetPublic())
e.entity = entityFromPackets(strToPriPack(readerPri), strToPubPack(readerPub))
}
func (e *encryptor) getPrivate() string {
bufpri := new(bytes.Buffer)
e.entity.SerializePrivate(bufpri, nil)
bufPr, err := ioutil.ReadAll(bufpri)
if err != nil {
panic(err)
}
return b64enc(string(bufPr))
}
// NewKeyPair generates a PGP private-public key pair.
func NewKeyPair() (string, string) {
entity, err := openpgp.NewEntity("", "", "", nil)
if err != nil {
panic(err)
}
en := &encryptor{
entity: entity,
writing: entity,
}
return en.getPrivate(), en.GetPublic()
}
func (e *encryptor) getPubPacket() *packet.PublicKey {
return e.writing.PrimaryKey
}
func (e *encryptor) getPriPacket() *packet.PrivateKey {
return e.entity.PrivateKey
}
func entityFromPackets(priKey *packet.PrivateKey, pubKey *packet.PublicKey) *openpgp.Entity {
config := packet.Config{
DefaultHash: crypto.SHA256,
DefaultCipher: packet.CipherAES256,
DefaultCompressionAlgo: packet.CompressionZLIB,
CompressionConfig: &packet.CompressionConfig{
Level: 9,
},
RSABits: 4096,
}
currentTime := config.Now()
uid := packet.NewUserId("", "", "")
e := openpgp.Entity{
PrimaryKey: pubKey,
PrivateKey: priKey,
Identities: make(map[string]*openpgp.Identity),
}
isPrimaryID := false
e.Identities[uid.Id] = &openpgp.Identity{
Name: uid.Name,
UserId: uid,
SelfSignature: &packet.Signature{
CreationTime: currentTime,
SigType: packet.SigTypePositiveCert,
PubKeyAlgo: packet.PubKeyAlgoRSA,
Hash: config.Hash(),
IsPrimaryId: &isPrimaryID,
FlagsValid: true,
FlagSign: true,
FlagCertify: true,
IssuerKeyId: &e.PrimaryKey.KeyId,
},
}
keyLifetimeSecs := uint32(86400 * 365)
e.Subkeys = make([]openpgp.Subkey, 1)
e.Subkeys[0] = openpgp.Subkey{
PublicKey: pubKey,
PrivateKey: priKey,
Sig: &packet.Signature{
CreationTime: currentTime,
SigType: packet.SigTypeSubkeyBinding,
PubKeyAlgo: packet.PubKeyAlgoRSA,
Hash: config.Hash(),
PreferredHash: []uint8{8}, // SHA-256
FlagsValid: true,
FlagEncryptStorage: true,
FlagEncryptCommunications: true,
IssuerKeyId: &e.PrimaryKey.KeyId,
KeyLifetimeSecs: &keyLifetimeSecs,
},
}
return &e
}
func strToPack(str string) interface{} {
reader := b64dec(str)
KeyRead := bytes.NewReader([]byte(reader))
PacketReader := packet.NewReader(KeyRead)
pkt, err := PacketReader.Next()
if err != nil {
panic(err)
}
return pkt
}
func strToPriPack(private string) *packet.PrivateKey {
priKeyPack, ok := strToPack(private).(*packet.PrivateKey)
if !ok {
panic(ok)
}
return priKeyPack
}
func strToPubPack(public string) *packet.PublicKey {
pubKeyPack, ok := strToPack(public).(*packet.PublicKey)
if !ok {
panic(ok)
}
return pubKeyPack
}
// NewEncryptor function
func NewEncryptor(private, public string, b64 ...bool) *encryptor {
backupPri, backupPub := NewKeyPair()
if private == "" {
private = backupPri
}
if public == "" {
public = backupPub
}
priKeyPack := strToPriPack(private)
pubKeyPack := strToPubPack(public)
b64payloads := len(b64) > 0 && b64[0]
return &encryptor{
entity: entityFromPackets(priKeyPack, pubKeyPack),
writing: entityFromPackets(nil, pubKeyPack),
b64: b64payloads,
}
}
func b64enc(msg string) string {
return base64.StdEncoding.EncodeToString([]byte(msg))
}
func b64dec(msg string) string {
decMe, err := base64.StdEncoding.DecodeString(msg)
if err != nil {
return msg
}
return string(decMe)
}
func (e *encryptor) SetSymmetric(key string) {
e.symmetric = key
}
func (e *encryptor) Encrypt(msg string) string {
if e.symmetric != "" {
return e.symEncrypt(msg)
}
return e.asymEncrypt(msg)
}
func (e *encryptor) Decrypt(msg string) string {
if e.symmetric != "" {
return e.symDecrypt(msg)
}
return e.asymDecrypt(msg)
}
func fixKey(key string) []byte {
return []byte(strings.Repeat("minkey"+string(key), keylen)[:keylen])
}
func pad(src []byte) []byte {
padding := aes.BlockSize - len(src)%aes.BlockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
func unpad(src []byte) ([]byte, error) {
length := len(src)
unpadding := int(src[length-1])
if unpadding > length {
return nil, errors.New("unpad error. This could happen when incorrect encryption key is used")
}
return src[:(length - unpadding)], nil
}
func (e *encryptor) symEncrypt(smsg string) string {
key := fixKey(e.symmetric)
block, err := aes.NewCipher(key)
if err != nil {
return ""
}
msg := pad([]byte(smsg))
ciphertext := make([]byte, aes.BlockSize+len(msg))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return ""
}
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], msg)
if e.b64 {
return b64enc(string(ciphertext))
}
return string(ciphertext)
}
func (e *encryptor) symDecrypt(msg string) string {
payload := []byte(msg)
if e.b64 {
payload = []byte(b64dec(msg))
}
if len(payload) == 0 {
return ""
}
key := fixKey(e.symmetric)
block, err := aes.NewCipher(key)
if err != nil {
return ""
}
if (len(payload) % aes.BlockSize) != 0 {
return ""
}
iv := payload[:aes.BlockSize]
bmsg := payload[aes.BlockSize:]
cfb := cipher.NewCFBDecrypter(block, iv)
cfb.XORKeyStream(bmsg, bmsg)
b, _ := unpad(bmsg)
return string(b)
}
// Encrypt function
func (e *encryptor) asymEncrypt(msg string) string {
// encrypt string
buf := new(bytes.Buffer)
w, err := openpgp.Encrypt(buf, []*openpgp.Entity{e.writing}, nil, nil, nil)
if err != nil {
return ""
}
_, err = w.Write([]byte(msg))
if err != nil {
return ""
}
err = w.Close()
if err != nil {
return ""
}
// Encode to b64
return b64enc(string(buf.Bytes()))
}
// Decrypt function
func (e *encryptor) asymDecrypt(msg string) string {
// Decode the b64 string
decMe := b64dec(msg)
KeyRead := bytes.NewReader([]byte(decMe))
md, err := openpgp.ReadMessage(KeyRead, openpgp.EntityList([]*openpgp.Entity{e.entity}), nil, nil)
if err != nil {
return ""
}
plaintext, err := ioutil.ReadAll(md.UnverifiedBody)
if err != nil {
return ""
}
return string(plaintext)
}
func (e *encryptor) FromFiles(privatePath, publicPath string) error {
priRaw, err := ioutil.ReadFile(privatePath)
if err != nil {
return err
}
pubRaw, err := ioutil.ReadFile(publicPath)
if err != nil {
return err
}
d := NewEncryptor(string(priRaw), string(pubRaw))
v := d.Encrypt("Hello")
if len(v) == 0 {
return errors.New("bad public-private key file pair")
}
v = d.Decrypt(v)
if len(v) == 0 {
return errors.New("bad public-private key file pair")
}
e.entity = d.entity
e.writing = d.entity
return nil
}
func (e *encryptor) ToFiles(privatePath, publicPath string) error {
d := &encryptor{
writing: e.entity,
entity: e.entity,
}
if err := os.MkdirAll(path.Dir(privatePath), os.ModePerm); err != nil {
return err
}
if err := ioutil.WriteFile(privatePath, []byte(d.getPrivate()), os.ModePerm); err != nil {
return err
}
if err := os.MkdirAll(path.Dir(publicPath), os.ModePerm); err != nil {
return err
}
return ioutil.WriteFile(publicPath, []byte(d.GetPublic()), os.ModePerm)
}

View File

@@ -1,102 +0,0 @@
package encryptor
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"golang.org/x/crypto/openpgp"
_ "golang.org/x/crypto/ripemd160"
)
// Encryptor interface
type Encryptor interface {
Encrypt(string) string
Decrypt() string
}
type encryptor struct {
entity *openpgp.Entity
}
// NewEncryptor function
func NewEncryptor(private, public string) *encryptor {
entity, err := openpgp.NewEntity("", "", "", nil)
if err != nil {
panic(err)
}
entity.PrimaryKey.PubKeyAlgo
entity.PrimaryKey.PublicKey
entity.PrivateKey.PubKeyAlgo
entity.PrivateKey.PrivateKey
fmt.Println(fmt.Sprintf("%T", entity.PrimaryKey.PublicKey))
bufpri := new(bytes.Buffer)
entity.SerializePrivate(bufpri, nil)
bufpub := new(bytes.Buffer)
entity.Serialize(bufpub)
bufPr, _ := b64enc(bufpri)
bufPu, _ := b64enc(bufpub)
fmt.Printf("PRIVATE: %v\nPUBLIC: %v\n", bufPr[10:20], bufPu[10:20])
return &encryptor{
entity: entity,
}
}
func b64enc(msg io.Reader) (string, error) {
bytes, err := ioutil.ReadAll(msg)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(bytes), nil
}
func b64dec(msg string) (io.Reader, error) {
decMe, err := base64.StdEncoding.DecodeString(msg)
if err != nil {
return nil, err
}
return bytes.NewBuffer(decMe), nil
}
// Encrypt function
func (e *encryptor) Encrypt(msg string) (string, error) {
// encrypt string
buf := new(bytes.Buffer)
w, err := openpgp.Encrypt(buf, []*openpgp.Entity{e.entity}, nil, nil, nil)
if err != nil {
return "", err
}
_, err = w.Write([]byte(msg))
if err != nil {
return "", err
}
err = w.Close()
if err != nil {
return "", err
}
// Encode to base64
return b64enc(buf)
}
// Decrypt function
func (e *encryptor) Decrypt(msg string) (string, error) {
// Decode the base64 string
decMe, err := b64dec(msg)
if err != nil {
panic(err)
}
md, err := openpgp.ReadMessage(decMe, openpgp.EntityList([]*openpgp.Entity{e.entity}), nil, nil)
if err != nil {
return "", err
}
plaintext, err := ioutil.ReadAll(md.UnverifiedBody)
if err != nil {
return "", err
}
return string(plaintext), nil
}

View File

@@ -1,156 +0,0 @@
package encryptor
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"github.com/jchavannes/go-pgp/pgp"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"
)
// Encryptor interface
type Encryptor interface {
Encrypt(string) string
Decrypt() string
}
type encryptor struct {
entity *openpgp.Entity
}
type readerWriter struct {
b []byte
}
func (rw *readerWriter) Write(b []byte) (int, error) {
rw.b = b[:]
return len(b), io.EOF
}
func (rw *readerWriter) Read(b []byte) (int, error) {
b = rw.b[:]
return len(b), io.EOF
}
func NewKeyPair() (string, string) {
entity, err := openpgp.NewEntity("a", "b", "c@d.e", nil)
if err != nil {
panic(err)
}
// Sign all the identities
for _, id := range entity.Identities {
err := id.SelfSignature.SignUserId(id.UserId.Id, entity.PrimaryKey, entity.PrivateKey, nil)
if err != nil {
panic(err)
}
}
rw := &readerWriter{b: make([]byte, 5000)}
b := make([]byte, 5000)
priW, err := armor.Encode(rw, openpgp.PrivateKeyType, nil)
if err != io.EOF {
fmt.Println(priW, rw)
panic(err)
}
if priW != nil {
defer priW.Close()
entity.SerializePrivate(priW, nil)
}
rw.Read(b)
pri := string(b)
pubW, err := armor.Encode(rw, openpgp.PublicKeyType, nil)
if err != io.EOF {
panic(err)
}
rw.Read(b)
pub := string(b)
if pubW != nil {
defer pubW.Close()
entity.Serialize(pubW)
}
fmt.Println(pri, pub)
return pri, pub
}
// NewEncryptor function
func NewEncryptor(private, public string) *encryptor {
pubKeyPack, err := pgp.GetPublicKeyPacket([]byte(public))
if err != nil {
panic(err)
}
priKeyPack, err := pgp.GetPrivateKeyPacket([]byte(private))
if err != nil {
panic(err)
}
entity, err := openpgp.NewEntity("", "", "", nil)
entity.PrimaryKey = pubKeyPack
entity.PrivateKey = priKeyPack
return &encryptor{
entity: entity,
}
}
func b64enc(msg io.Reader) (string, error) {
bytes, err := ioutil.ReadAll(msg)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(bytes), nil
}
func b64dec(msg string) (io.Reader, error) {
decMe, err := base64.StdEncoding.DecodeString(msg)
if err != nil {
return nil, err
}
return bytes.NewBuffer(decMe), nil
}
// Encrypt function
func (e *encryptor) Encrypt(msg string) (string, error) {
// encrypt string
buf := new(bytes.Buffer)
w, err := openpgp.Encrypt(buf, []*openpgp.Entity{e.entity}, nil, nil, nil)
if err != nil {
return "", err
}
_, err = w.Write([]byte(msg))
if err != nil {
return "", err
}
err = w.Close()
if err != nil {
return "", err
}
// Encode to base64
return b64enc(buf)
}
// Decrypt function
func (e *encryptor) Decrypt(msg string) (string, error) {
// Decode the base64 string
decMe, err := b64dec(msg)
if err != nil {
panic(err)
}
md, err := openpgp.ReadMessage(decMe, openpgp.EntityList([]*openpgp.Entity{e.entity}), nil, nil)
if err != nil {
return "", err
}
plaintext, err := ioutil.ReadAll(md.UnverifiedBody)
if err != nil {
return "", err
}
return string(plaintext), nil
}

View File

@@ -1,98 +0,0 @@
package logger
import (
"errors"
"fmt"
"os"
"time"
)
var outfile *os.File
var outfileB *os.File
var lastWasReturn = false
var ErrCantConfigLog = errors.New("cannot configure log")
func Config(path string) error {
if path == "" {
return nil
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return ErrCantConfigLog
}
outfile = f
return nil
}
func Logf(args ...interface{}) {
if outfile == nil {
outfile = os.Stderr
}
defer outfile.Sync()
if len(args) == 0 {
fmt.Fprintln(outfile, "")
return
}
v := fmt.Sprintf(args[0].(string), args[1:]...)
if v[len(v)-1] == '\n' {
v = v[:len(v)-1]
}
thisWasReturn := v[0] == '\r'
if lastWasReturn && !thisWasReturn {
fmt.Println()
}
if thisWasReturn {
fmt.Fprintf(outfile, "\r%s%v", prefix(), v[1:])
} else {
fmt.Fprintf(outfile, "%s%v\n", prefix(), v)
}
lastWasReturn = thisWasReturn
}
func Fatalf(args ...interface{}) {
Logf(args...)
if len(args) > 0 {
panic(args[0])
} else {
panic("Panic from logger.fatal()")
}
}
func Fatal(args ...interface{}) {
Log(args...)
if len(args) > 0 {
panic(args[0])
} else {
panic("Panic from logger.fatal()")
}
}
func Log(args ...interface{}) {
if lastWasReturn {
fmt.Println()
}
if outfile == nil {
outfile = os.Stderr
}
v := fmt.Sprintf("%v", args)
v = v[1 : len(v)-1]
fmt.Fprintf(outfile, "%s%v\n", prefix(), v)
outfile.Sync()
lastWasReturn = false
}
func LogB(args ...interface{}) {
if outfileB == nil {
outfileB = os.Stderr
}
v := fmt.Sprintf("%v", args)
v = v[1 : len(v)-1]
fmt.Fprintf(outfileB, "%s%v\n", prefix(), v)
outfileB.Sync()
}
func prefix() string {
return time.Now().Format("20060102-150405") + " : "
}

View File

@@ -1,77 +0,0 @@
[
{
"Name": "watchmans",
"Port": "9988,9998"
},
{
"Name": "ytubespdrun",
"Port": "29687",
"Log": "/volume1/video/Bel/YouTube/Speedrun/"
},
{
"Name": "emailmonitor",
"Log": "breellocaldev@gmail.com",
"Timeout": "15m"
},
{
"Name": "vpntorfeed",
"Port": "29688",
"DB": "magnets",
"IP2": "http://192.168.0.86:9091/transmission/rpc",
"Pub": "X-Transmission-Session-Id"
},
{
"Name": "broadcaster",
"Timeout": "5s",
"IP": "localhost"
},
{
"Name": "jbt-serve",
"Timeout": "5s",
"IP": "localhost",
"Port": "59998"
},
{
"Name": "jbt-client",
"Timeout": "5s",
"IP": "localhost"
},
{
"Name": "nat-serve",
"Timeout": "5s",
"IP": "localhost",
"Port": "59997"
},
{
"Name": "Coordinator",
"Port": "50000"
},
{
"Name": "rss-monitor",
"Timeout": "5s",
"IP": "localhost",
"Port": "28686",
"Log": "./alt5.log",
"DB": "./alt5.db",
"Measure": false,
"Intervalunit": "1s",
"ConfFile": "./conf.json",
"Overwrite": true
},
{
"Name": "sev-alerts",
"IP": "https://qualtrics.atlassian.net/sr/jira.issueviews:searchrequest-rss/44938/SearchRequest-44938.xml?tempMax=1000",
"Port": "YnJlZWxAcXVhbHRyaWNzLmNvbTpeKllycGl6Y3cmNTRPd3Yw",
"Timeout": "720h",
"Intervalunit": "30m"
},
{
"Name": "email",
"Log": "breellocaldev@gmail.com",
"IP": "smtp.gmail.com:465",
"IP2": "pop.gmail.com:995",
"Port": "ML3WQRFSqe9rQ8qNkm",
"DB": "mailto:3852010864@txt.att.net",
"Pub": "xsBNBFsn3DkBCADFA7dD+urJE82QrqsTK9cPS4S1stfCglnh4kpFQRO98cX2FRYlIlWJYnVr8IUTI+fAb0XymB+kLOUYtgMQp7vK7MbbowG6sUBc7Eb4TNOOYm+LuUq4ECDvWJIuT4EWt4aeY9g7IR0Llbm5ec7pe8hfABVUABrz8ZnFOufD5Gkd0/O3aATaKmZJ3K3aPQO7jnfVOzn4US5lo0C+Dt1B/HFEKOeRnaeOPqRNm1cn9Vq+Vw+9l9E8SPU1mGZbELMaY19A/BRGTOhliWosTKzcG9u8QG3eNb1/jG9xduS0QWaCEHjYgPqYvNJ1pHcKEdrGZj69RLWgQOkc2mitAR+gkzYLABEBAAHNAMLAYgQTAQgAFgUCWyfcOQkQVnaLXPzpsa4CGwMCGQEAAFj2CAAtVKdj+SPvG1Rd7bXXv6i3mjEyfwkV1XSxda8nVkx72MK6utYXATLM5BNVkCCeK7CTaOnpNwfUZ+TqPlmr2G+cWGfPEDApBS1ajuK65sKeppZ7tQEocZLKCdUcqqLaPycOVNW1ZoNqrCurHQPJdWEJAtplYFDKOptMfcwFX3AkR27eYV286b1Kk+LM26h+SAJUEZ78Ixf6vkp5nfTle1wBANhASZ7XhUWyxWrJ7gNW/1N82ThlkHr+FxrhMfGyIoihtpaFdMnh3RLgnNs3pfnMGNOdTVo1DVh294EQagG+CW1Lt68LekHSxUbFvXVwUHdufLTO8+6SI3iSquuR6NR1zsBNBFsn3DkBCAC8Kg61Gu/lu91QM/Ze/bzAP3IqNIaQjjgB23UEM1XoHgyMcDCTnuwx0IFjak/a7LxEBiaUWC6oaRqdwuPa5lNr2KrpoBsh4hUBwySRTRQrHymwYFBI8qBYfdoO8jP7C70RoiOCXX9j5I/V0g3gneFxbIOiixrILDIZj5jlSkMpSGG0vDOsC8GpqWRMOs4/F5zSN0UKzq4Vr67zizcDnfD9/9qrfAxOw0GOohl97ePxfgFoVZckkRgAOJylGgGQ3ihwt7MBf8LOL3shY0wMYqvxSc2UcJPbPH3kfKfMi+XhAlwCAdnlRdKEOCn1svhAvcxv5FDVnTiS7I1HGH7AfCP5ABEBAAHCwF8EGAEIABMFAlsn3DkJEFZ2i1z86bGuAhsMAACxFwgAFR3jG0f+tqgGxzgGsSDhcZC9h1QfWvh1nw/q0EZzwI8+lAsEfBeVNOjZttZI+RMyO9NBTwJErq4EeuemNCqu93zJOf3i45G0+jGV9/XMga5641CfIuFPKkcWBMR67iiEu2/vG7e9l1IkR74pBJhp2ub8aaivWvNS1lloYESee0euGu/TOXe7FO6V6E1KVw+17A78NlG09WCO5c5SZdDI9YCXxEeqHzNH4j2RrAxNsYZ3M6L0+JbVqwWFN73OUi6EM7fQFdpXCryKV6OEKnYKeGPW2TRUrT+gBgLnJV0crVTibaOSXdq+vyuHszKdT0lcLmEj2F3i73vmvUKYMh/shA=="
}
]

View File

@@ -1,166 +0,0 @@
package sysconf
import (
"encoding/json"
"fmt"
"io/ioutil"
"local/logger"
"os"
"path"
"strconv"
"strings"
"time"
)
type Conf struct {
Name string
Pub string
Port string
IP string
IP2 string
TimeOut time.Duration
Timeout string
Log string
DB string
Measure bool
IntervalUnit time.Duration
Intervalunit string
Overwrite bool
ConfFile string
}
var configs map[string]Conf
func (c Conf) String() string {
kv := make(map[string]interface{})
kv["name"] = c.Name
kv["port"] = c.Port
kv["IP"] = c.IP
kv["IP2"] = c.IP2
out := ""
for k, v := range kv {
out += fmt.Sprintf("%v:%v ", k, v)
}
return out
}
func Get(name string) Conf {
if configs == nil {
open()
}
if _, ok := configs[name]; !ok {
panic("Unknown service " + name)
}
logger.Log("config: got", name, "config: ", configs[name])
return configs[name]
}
func open() {
f, err := ioutil.ReadFile(path.Join(os.Getenv("GOPATH"), "src", "local1", "system", "sysconf", "conf.json"))
if err != nil {
panic(err)
}
var jsonConfs []Conf
err = json.Unmarshal([]byte(string(f)), &jsonConfs)
if err != nil {
panic(err)
}
configs = make(map[string]Conf)
ports := make(map[string]bool)
initPort := 28685
thisPort := 0
for i := range jsonConfs {
portstr := jsonConfs[i].Port
portlist := strings.Split(portstr, ",")
for j := range portlist {
ports[portlist[j]] = true
}
}
for i := range jsonConfs {
if jsonConfs[i].Timeout != "" {
jsonConfs[i].TimeOut, err = time.ParseDuration(jsonConfs[i].Timeout)
if err != nil {
panic(err)
}
}
if jsonConfs[i].Intervalunit != "" {
jsonConfs[i].IntervalUnit, err = time.ParseDuration(jsonConfs[i].Intervalunit)
if err != nil {
panic(err)
}
}
if jsonConfs[i].Port == "" {
thisPort += 1
port := strconv.Itoa(initPort + thisPort)
for _, ok := ports[port]; ok; _, ok = ports[port] {
port = strconv.Itoa(initPort + thisPort)
thisPort++
}
jsonConfs[i].Port = port
ports[jsonConfs[i].Port] = true
}
if jsonConfs[i].Log != "" && jsonConfs[i].Log[0] == '.' {
jsonConfs[i].Log = os.Getenv("MNT") + jsonConfs[i].Log
}
if jsonConfs[i].DB != "" && jsonConfs[i].DB[0] == '.' {
jsonConfs[i].DB = os.Getenv("MNT") + jsonConfs[i].DB
}
if jsonConfs[i].ConfFile != "" && jsonConfs[i].ConfFile[0] == '.' {
jsonConfs[i].ConfFile = os.Getenv("MNT") + jsonConfs[i].ConfFile
}
configs[jsonConfs[i].Name] = jsonConfs[i]
}
}
/*
var (
Broadcaster = Conf{
Name: "broadcaster",
Port: "28688",
Timeout: time.Second * 5,
IP: "localhost",
}
JBTServe = Conf{
Name: "jbt-serve",
Port: "28080",
Timeout: time.Second * 5,
IP: "localhost",
}
JBTClient = Conf{
Name: "jbt-client",
Port: "28081",
Timeout: time.Second * 5,
IP: "localhost",
}
NATServe = Conf{
Name: "nat-serve",
Port: "28447",
Timeout: time.Second * 5,
IP: "localhost",
}
RSSMon = Conf{
Name: "rss-monitor",
Port: "28686",
Timeout: time.Second * 5,
IP: "localhost",
Log: "./my.log",
DB: "./my.db",
Measure: false,
IntervalUnit: time.Second,
}
SevAlerts = Conf{
Name: "sev-alerts",
IP: "https://qualtrics.atlassian.net/sr/jira.issueviews:searchrequest-rss/44938/SearchRequest-44938.xml?tempMax=1000",
Port: "YnJlZWxAcXVhbHRyaWNzLmNvbTpeKllycGl6Y3cmNTRPd3Yw",
Timeout: time.Minute * 60,
IntervalUnit: time.Minute * 15,
}
Email = Conf{
Name: "bbarl64@gmail.com",
IP: "smtp.gmail.com:465",
Port: ">_w2Xeq\"tvJkv5y\\",
DB: "3852010864@txt.att.net",
}
)
*/

View File

@@ -1,5 +0,0 @@
package sysconf
var (
RSSFeedItem = "rssFeedItem."
)