aboutsummaryrefslogtreecommitdiffstats
path: root/lib/pinentry/pinentry.go
blob: 51b5492016b17206f6c3f58f6af11e5089a73b9a (plain) (blame)
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
package pinentry

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
	"sync/atomic"

	"git.sr.ht/~rjarry/aerc/config"
	"git.sr.ht/~rjarry/aerc/lib/log"
	"git.sr.ht/~rjarry/aerc/lib/ui"
)

var pinentryMode int32 = 0

func Enable() {
	if !config.General.UsePinentry {
		return
	}
	if atomic.SwapInt32(&pinentryMode, 1) == 1 {
		// cannot enter pinentry mode twice
		return
	}
	ui.SuspendScreen()
}

func Disable() {
	if atomic.SwapInt32(&pinentryMode, 0) == 0 {
		// not in pinentry mode
		return
	}
	ui.ResumeScreen()
}

func SetCmdEnv(cmd *exec.Cmd) {
	if cmd == nil || atomic.LoadInt32(&pinentryMode) == 0 {
		return
	}

	env := cmd.Env
	if env == nil {
		env = os.Environ()
	}

	hasTerm := false
	hasGPGTTY := false
	for _, e := range env {
		switch {
		case strings.HasPrefix(strings.ToUpper(e), "TERM="):
			log.Debugf("pinentry: use %v", e)
			hasTerm = true
		case strings.HasPrefix(strings.ToUpper(e), "GPG_TTY="):
			log.Debugf("pinentry: use %v", e)
			hasGPGTTY = true
		}
	}

	if !hasTerm {
		env = append(env, "TERM=xterm-256color")
		log.Debugf("pinentry: set TERM=xterm-256color")
	}

	if !hasGPGTTY {
		tty := ttyname()
		env = append(env, fmt.Sprintf("GPG_TTY=%s", tty))
		log.Debugf("pinentry: set GPG_TTY=%s", tty)
	}

	cmd.Env = env
}