-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
agent.go
104 lines (81 loc) · 1.88 KB
/
agent.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"time"
whisper "github.com/ysmood/whisper/lib"
"github.com/ysmood/whisper/lib/secure"
)
func agent() whisper.AgentClient {
return whisper.NewAgentClient(WHISPER_AGENT_ADDR)
}
func runAsAgentServer() {
fmt.Fprintf(os.Stderr, "whisper agent started on %s, version: %s\n", WHISPER_AGENT_ADDR, whisper.APIVersion)
whisper.NewAgentServer().Serve(WHISPER_AGENT_ADDR)
}
func isAgentServerRunning() bool {
running, err := agent().IsServerRunning(whisper.APIVersion)
if err != nil {
exit(err)
}
return running
}
func launchAgentServer() {
if isAgentServerRunning() {
return
}
exePath, err := os.Executable()
if err != nil {
exit(err)
}
cmd := exec.Command(exePath, "-"+AS_AGENT_FLAG)
err = cmd.Start()
if err != nil {
exit(err)
}
err = cmd.Process.Release()
if err != nil {
exit(err)
}
fmt.Fprintln(os.Stderr, "wait for background whisper agent to start ...")
for {
if isAgentServerRunning() {
break
}
time.Sleep(time.Millisecond * 100)
}
fmt.Fprintln(os.Stderr, "background whisper agent started")
}
func agentCheckPassphrase(prv whisper.PrivateKey) bool {
r, err := agent().IsPassphraseRight(prv)
if err != nil {
exit(err)
}
return r
}
func agentWhisper(conf whisper.Config, in io.ReadCloser, out io.WriteCloser) error {
defer func() { _ = in.Close() }()
defer func() { _ = out.Close() }()
err := agent().Whisper(conf, in, out)
if conf.Sign == nil && errors.Is(err, secure.ErrSignMismatch) {
return nil
}
return err
}
var ErrWrongPassphrase = errors.New("wrong passphrase")
func agentAddPassphrase(path string) {
launchAgentServer()
prv, err := whisper.ReadKey(path)
if err != nil {
exit(fmt.Errorf("failed to read private key: %w", err))
}
if !agentCheckPassphrase(whisper.PrivateKey{
Data: prv,
Passphrase: getPassphrase(path),
}) {
exit(ErrWrongPassphrase)
}
}