File: threadkeyring.go

package info (click to toggle)
ssh-tpm-agent 0.8.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 420 kB
  • sloc: makefile: 72
file content (95 lines) | stat: -rw-r--r-- 1,748 bytes parent folder | download
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
package keyring

import (
	"context"
	"runtime"
	"sync"
)

// ThreadKeyring runs Keyring in a dedicated OS Thread
type ThreadKeyring struct {
	wg        sync.WaitGroup
	addkey    chan *addkeyMsg
	removekey chan *removekeyMsg
	readkey   chan *readkeyMsg
}

type addkeyMsg struct {
	name string
	key  []byte
	cb   chan error
}

type removekeyMsg struct {
	name string
	cb   chan error
}

type readkeyRet struct {
	key *Key
	err error
}

type readkeyMsg struct {
	name string
	cb   chan *readkeyRet
}

func (tk *ThreadKeyring) Wait() {
	tk.wg.Wait()
}

func (tk *ThreadKeyring) AddKey(name string, key []byte) error {
	cb := make(chan error)
	tk.addkey <- &addkeyMsg{name, key, cb}
	return <-cb
}

func (tk *ThreadKeyring) RemoveKey(name string) error {
	cb := make(chan error)
	tk.removekey <- &removekeyMsg{name, cb}
	return <-cb
}

func (tk *ThreadKeyring) ReadKey(name string) (*Key, error) {
	cb := make(chan *readkeyRet)
	tk.readkey <- &readkeyMsg{name, cb}
	ret := <-cb
	if ret.err != nil {
		return nil, ret.err
	}
	return ret.key, nil
}

func NewThreadKeyring(ctx context.Context, keyring *Keyring) (*ThreadKeyring, error) {
	var err error
	var tk ThreadKeyring

	tk.addkey = make(chan *addkeyMsg)
	tk.removekey = make(chan *removekeyMsg)
	tk.readkey = make(chan *readkeyMsg)

	tk.wg.Add(1)
	go func() {
		var ak *Keyring
		runtime.LockOSThread()
		ak, err = keyring.CreateKeyring()
		if err != nil {
			return
		}
		for {
			select {
			case msg := <-tk.addkey:
				msg.cb <- ak.AddKey(msg.name, msg.key)
			case msg := <-tk.readkey:
				key, err := ak.ReadKey(msg.name)
				msg.cb <- &readkeyRet{key, err}
			case msg := <-tk.removekey:
				msg.cb <- ak.RemoveKey(msg.name)
			case <-ctx.Done():
				return
			}
		}
	}()
	return &tk, err
}