-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmsg_server.go
100 lines (86 loc) · 2.19 KB
/
msg_server.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
package sqrl
import (
"errors"
"fmt"
"strconv"
"strings"
)
// ServerMsg is used to represent the values
// sent from the server to the client.
type ServerMsg struct {
// TODO: should we remove Ver? Do package
// consumers actually need to be able to
// set this?
Ver []string
Nut Nut
Tif TIF
Qry string
URL string
// TODO: sin - Secret index
// TODO: suk - server unlock key
// TODO: ask - message text to display to user
// TODO: can - cancellation redirection URL
// TODO: additional parameters
}
// Encode writes the server message to a string
// ready for transmission to the client.
func (m *ServerMsg) Encode() (string, error) {
vals := []string{
"ver=" + strings.Join(m.Ver, ","),
"nut=" + string(m.Nut),
"tif=" + strconv.Itoa(int(m.Tif)),
"qry=" + m.Qry,
}
if m.URL != "" {
vals = append(vals, "url="+m.URL)
}
vals = append(vals, "") // Must end with a final newline
return Base64.EncodeToString([]byte(strings.Join(vals, "\r\n"))), nil
}
// Set adds the given transaction information flag
// to the server message.
func (m *ServerMsg) Set(flag TIF) *ServerMsg {
m.Tif |= flag
return m
}
// Unset removes the given transaction information
// flag from the server message.
func (m *ServerMsg) Unset(flag TIF) *ServerMsg {
m.Tif &^= flag
return m
}
// Is returns whether or not the server message
// includes the given transaction information flag.
func (m *ServerMsg) Is(flag TIF) bool {
return m.Tif&flag != 0
}
// ParseServer decodes the base64 encoded server
// parameter into the component parts.
func ParseServer(raw string) (*ServerMsg, error) {
vals, err := parseMsg(raw)
if err != nil {
return nil, err
}
if len(vals) < 4 {
return nil, errors.New("missing one or more required parameters (ver,nut,tif,qry)")
}
ver, err := parseVer(vals["ver"])
if err != nil {
return nil, err
}
tifstr := vals["tif"]
tif, err := strconv.Atoi(tifstr)
if err != nil {
return nil, fmt.Errorf("required value 'tif' is invalid: '%s'", tifstr)
}
// TODO: Ensure nut can be decoded correctly
nut := Nut(vals["nut"])
// TODO: Check supported version before parsing
return &ServerMsg{
Ver: ver,
Nut: nut,
Tif: TIF(tif),
Qry: vals["qry"],
URL: vals["url"],
}, nil
}