-
Notifications
You must be signed in to change notification settings - Fork 0
/
signal-tty.go
127 lines (106 loc) · 2.28 KB
/
signal-tty.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package main
import (
"bufio"
"bytes"
"compress/zlib"
"context"
"fmt"
"io"
"math/big"
"os"
)
var _ SignalEgress = SignalTTY{}
var _ SignalIngress = SignalTTY{}
type SignalTTY struct {
in bufio.Reader
out io.Writer
}
func NewSignalTTY() SignalTTY {
return SignalTTY{
in: *bufio.NewReaderSize(os.Stdin, 10*1024),
out: os.Stdout,
}
}
func (s SignalTTY) SendOffer(ctx context.Context, offer string) (err error) {
s.out.Write([]byte("Offer:\n"))
return s.write(ctx, offer)
}
func (s SignalTTY) SendAnswer(ctx context.Context, answer string) (err error) {
s.out.Write([]byte("Answer:\n"))
return s.write(ctx, answer)
}
func (s SignalTTY) write(ctx context.Context, str string) (err error) {
done := make(chan struct{})
go func() {
defer chanSend(ctx, done, struct{}{})
var bu bytes.Buffer
w := zlib.NewWriter(&bu)
w.Write([]byte(str))
w.Close()
var i big.Int
b := []byte(i.SetBytes(bu.Bytes()).Text(62))
n, errw := s.out.Write(append(b, '\n'))
if errw != nil {
err = errw
return
}
if n < len(b) {
err = fmt.Errorf("incomplete write (%d) out of (%d)", n, len(b))
}
}()
if _, errr := chanRecv(ctx, done); errr != nil {
err = errr
}
return
}
func (s SignalTTY) RecvAnswer(ctx context.Context) (answer string, err error) {
s.out.Write([]byte("Peer's Answer?\n"))
return s.readLine(ctx)
}
func (s SignalTTY) RecvOffer(ctx context.Context) (offer string, err error) {
s.out.Write([]byte("Peer's Offer?\n"))
return s.readLine(ctx)
}
func (s SignalTTY) readLine(ctx context.Context) (line string, err error) {
done := make(chan struct{})
go func() {
defer chanSend(ctx, done, struct{}{})
for {
if ctx.Err() != nil {
return
}
b, errr := s.in.ReadBytes('\n')
if err != nil {
err = errr
return
}
var i big.Int
if _, ok := i.SetString(string(b[:len(b)-1]), 62); !ok {
err = fmt.Errorf("invalid base62 string: %v", string(b))
return
}
var bu bytes.Buffer
bu.Write(i.Bytes())
r, errw := zlib.NewReader(&bu)
if errw != nil {
err = errw
return
}
b, err = io.ReadAll(r)
if err != nil {
return
}
line = string(b)
if len(line) > 0 {
break
}
}
}()
if _, errr := chanRecv(ctx, done); errr != nil {
err = errr
}
return
}
func (s SignalTTY) Close() (err error) {
return
}