Repository navigation
Expand file tree
/
Copy pathfriends.go
More file actions
349 lines (329 loc) · 9.92 KB
/
Copy pathfriends.go
File metadata and controls
349 lines (329 loc) · 9.92 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"strings"
"time"
"wanctl/internal/admission"
"wanctl/internal/relay"
)
const friendsHelp = `wanctl friends subcommands:
friends list friends and pending requests
friends add <namespace> send a friend request
friends accept <namespace> accept an incoming request
friends decline <namespace> decline an incoming request
friends remove <namespace> remove a friend and revoke shares in both directions`
const shareHelp = `wanctl share subcommands:
share list
share grant --device DEV --to NS [--manage]
share manage --device DEV --to NS on|off
share revoke --device DEV --to NS`
type relayHTTPError struct {
StatusCode int
Status string
Body string
}
func (e *relayHTTPError) Error() string {
if e.Body == "" {
return e.Status
}
return e.Status + ": " + e.Body
}
func userRequest(ctx context.Context, method, path string, body, out any) error {
base, err := relayBase()
if err != nil {
return err
}
token, err := relayToken()
if err != nil {
return err
}
var reader io.Reader
if body != nil {
raw, err := json.Marshal(body)
if err != nil {
return err
}
reader = bytes.NewReader(raw)
}
req, err := http.NewRequestWithContext(ctx, method, base+path, reader)
if err != nil {
return err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
admission.SetBearer(req, token)
resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
raw, _ := io.ReadAll(resp.Body)
return &relayHTTPError{
StatusCode: resp.StatusCode,
Status: resp.Status,
Body: strings.TrimSpace(string(raw)),
}
}
if out == nil {
return nil
}
return json.NewDecoder(resp.Body).Decode(out)
}
func cmdFriends(ctx context.Context, args []string) error {
if len(args) == 0 {
return friendsList(ctx)
}
if args[0] == "-h" || args[0] == "--help" || args[0] == "help" {
fmt.Println(friendsHelp)
return nil
}
if len(args) != 2 {
return fmt.Errorf("%s", friendsHelp)
}
peer := args[1]
switch args[0] {
case "add":
var result struct {
Status string `json:"status"`
}
err := userRequest(ctx, http.MethodPost, "/u/friends/request", map[string]string{"namespace": peer}, &result)
if isRelayError(err, http.StatusNotFound, "no-such-user") {
return fmt.Errorf("对方还没注册 wanctl:%s", peer)
}
if err != nil {
return err
}
if result.Status == "accepted" {
fmt.Printf("✓ %s 也已请求添加你,现已成为好友\n", peer)
} else {
fmt.Printf("✓ 已向 %s 发送好友请求\n", peer)
}
return nil
case "accept":
if err := friendPost(ctx, "/u/friends/accept", peer); err != nil {
return err
}
fmt.Printf("✓ 已接受 %s 的好友请求\n", peer)
return nil
case "decline":
if err := friendPost(ctx, "/u/friends/decline", peer); err != nil {
return err
}
fmt.Printf("✓ 已拒绝 %s 的好友请求\n", peer)
return nil
case "remove":
if err := friendPost(ctx, "/u/friends/remove", peer); err != nil {
return err
}
fmt.Printf("✓ 已删除好友 %s,并撤销双方之间的所有设备共享\n", peer)
return nil
default:
return fmt.Errorf("unknown subcommand %q\n%s", args[0], friendsHelp)
}
}
func friendPost(ctx context.Context, path, peer string) error {
err := userRequest(ctx, http.MethodPost, path, map[string]string{"namespace": peer}, nil)
if isRelayError(err, http.StatusNotFound, "no-such-friend") {
return fmt.Errorf("没有匹配的好友关系或待处理请求:%s", peer)
}
return err
}
func isRelayError(err error, status int, body string) bool {
httpErr, ok := err.(*relayHTTPError)
return ok && httpErr.StatusCode == status && httpErr.Body == body
}
func friendsList(ctx context.Context) error {
var result struct {
Friends []relay.Friend `json:"friends"`
}
if err := userRequest(ctx, http.MethodGet, "/u/friends", nil, &result); err != nil {
return err
}
printFriendSection("好友", result.Friends, func(friend relay.Friend) bool {
return friend.Status == "accepted"
})
printFriendSection("待你接受", result.Friends, func(friend relay.Friend) bool {
return friend.Status == "pending" && friend.Direction == "incoming"
})
printFriendSection("等待对方接受", result.Friends, func(friend relay.Friend) bool {
return friend.Status == "pending" && friend.Direction == "outgoing"
})
return nil
}
func printFriendSection(title string, friends []relay.Friend, include func(relay.Friend) bool) {
fmt.Println(title + ":")
count := 0
for _, friend := range friends {
if !include(friend) {
continue
}
fmt.Printf(" %-24s %s\n", friend.Namespace, friend.Since.Local().Format("2006-01-02 15:04"))
count++
}
if count == 0 {
fmt.Println(" (无)")
}
}
func cmdShare(ctx context.Context, args []string) error {
if len(args) == 0 {
return fmt.Errorf("%s", shareHelp)
}
switch args[0] {
case "list":
if len(args) != 1 {
return fmt.Errorf("usage: wanctl share list")
}
return shareList(ctx)
case "grant":
return shareGrant(ctx, args[1:])
case "manage":
return shareManage(ctx, args[1:])
case "revoke":
return shareRevoke(ctx, args[1:])
case "-h", "--help", "help":
fmt.Println(shareHelp)
return nil
default:
return fmt.Errorf("unknown subcommand %q\n%s", args[0], shareHelp)
}
}
func shareGrant(ctx context.Context, args []string) error {
fs := withHelp(flag.NewFlagSet("share grant", flag.ContinueOnError))
device := fs.String("device", "", "device name")
to := fs.String("to", "", "friend namespace")
manage := fs.Bool("manage", false, "also let them administer the device (approvals, rules, mode)")
if err := fs.Parse(args); err != nil {
return err
}
if *device == "" || *to == "" || fs.NArg() != 0 {
return fmt.Errorf("usage: wanctl share grant --device DEV --to NS [--manage]")
}
var result struct {
ID int `json:"id"`
}
err := userRequest(ctx, http.MethodPost, "/u/shares/grant", map[string]any{
"device": *device, "grantee": *to, "manage": *manage,
}, &result)
if isRelayError(err, http.StatusForbidden, "not-friends") {
return fmt.Errorf("%s 还不是你的好友;请先运行 `wanctl friends add %s`", *to, *to)
}
if err != nil {
return err
}
fmt.Printf("✓ 已将设备 %s 共享给 %s(授权 #%d)。对方对这台设备的使用权限与你相同%s。解绑和撤销共享仍然只有你能做。\n",
*device, *to, result.ID, manageSuffix(*manage))
return nil
}
// shareManage flips management on a share that already exists. Revoking and
// re-sharing would do the same thing, at the cost of making the grantee pair
// with the device again.
func shareManage(ctx context.Context, args []string) error {
device, to, manage, err := parseShareManage(args)
if err != nil {
return err
}
if err := userRequest(ctx, http.MethodPost, "/u/shares/manage", map[string]any{
"device": device, "grantee": to, "manage": manage,
}, nil); err != nil {
return err
}
if manage {
fmt.Printf("✓ %s 现在可以管理设备 %s(审批、规则、模式)\n", to, device)
} else {
fmt.Printf("✓ %s 不再能管理设备 %s,仍然可以使用它\n", to, device)
}
return nil
}
// parseShareManage reads `--device DEV --to NS on|off`. The switch is a word
// rather than a flag because it is the thing being set, and because `--manage`
// and `--no-manage` would be two ways to say one thing.
func parseShareManage(args []string) (device, to string, manage bool, err error) {
usage := fmt.Errorf("usage: wanctl share manage --device DEV --to NS on|off")
fs := withHelp(flag.NewFlagSet("share manage", flag.ContinueOnError))
fs.SetOutput(io.Discard)
dev := fs.String("device", "", "device name")
grantee := fs.String("to", "", "friend namespace")
if err := fs.Parse(args); err != nil {
return "", "", false, err
}
if *dev == "" || *grantee == "" || fs.NArg() != 1 {
return "", "", false, usage
}
switch fs.Arg(0) {
case "on":
manage = true
case "off":
manage = false
default:
return "", "", false, usage
}
return *dev, *grantee, manage, nil
}
// manageLabel names the one thing a share varies, in both listings.
func manageLabel(manage bool) string {
if manage {
return "可管理"
}
return "仅使用"
}
func manageSuffix(manage bool) string {
if manage {
return ",并且可以管理这台设备(审批、规则、模式)"
}
return ",但不能管理这台设备(审批、规则、模式)"
}
func shareRevoke(ctx context.Context, args []string) error {
fs := withHelp(flag.NewFlagSet("share revoke", flag.ContinueOnError))
device := fs.String("device", "", "device name")
to := fs.String("to", "", "friend namespace")
if err := fs.Parse(args); err != nil {
return err
}
if *device == "" || *to == "" || fs.NArg() != 0 {
return fmt.Errorf("usage: wanctl share revoke --device DEV --to NS")
}
if err := userRequest(ctx, http.MethodPost, "/u/shares/revoke", map[string]string{
"device": *device, "grantee": *to,
}, nil); err != nil {
return err
}
fmt.Printf("✓ 已撤销 %s 对设备 %s 的访问\n", *to, *device)
return nil
}
func shareList(ctx context.Context) error {
var result struct {
Given []struct {
ID int `json:"id"`
Device string `json:"device"`
Grantee string `json:"grantee"`
Manage bool `json:"manage"`
} `json:"given"`
Received []relay.ReceivedShare `json:"received"`
}
if err := userRequest(ctx, http.MethodGet, "/u/shares", nil, &result); err != nil {
return err
}
fmt.Println("我授出的共享:")
if len(result.Given) == 0 {
fmt.Println(" (无)")
}
for _, share := range result.Given {
fmt.Printf(" %-20s -> %-20s %-8s (#%d)\n", share.Device, share.Grantee, manageLabel(share.Manage), share.ID)
}
fmt.Println("好友授给我的共享:")
if len(result.Received) == 0 {
fmt.Println(" (无)")
}
for _, share := range result.Received {
fmt.Printf(" %-20s / %-20s %s\n", share.Owner, share.Device, manageLabel(share.Manage))
}
return nil
}