-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathclients.go
109 lines (104 loc) · 2.5 KB
/
clients.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
package main
import (
"bufio"
"fmt"
"os"
"github.com/urfave/cli/v2"
)
const FPS_FILENAME = "authorized_fingerprints"
var ClientCommands = []*cli.Command{
{
Name: "add",
Usage: "add one or more clients",
Action: addClients,
}, {
Name: "remove",
Usage: "remove one or more clients",
Action: removeClients,
}, {
Name: "list",
Usage: "list clients",
Action: listClients,
},
}
func addClients(c *cli.Context) error {
file, err := os.OpenFile(ConfPath(FPS_FILENAME), os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("Failed to open authorized_fingerprints: %s", err)
}
defer file.Close()
for _, fp := range c.Args().Slice() {
if _, err := file.WriteString(fp + "\n"); err != nil {
return fmt.Errorf("Failed to write to authorized_fingerprints: %s", err)
}
}
return nil
}
func removeClients(c *cli.Context) error {
file, err := os.OpenFile(ConfPath(FPS_FILENAME), os.O_RDWR, 0644)
if err != nil {
return fmt.Errorf("Failed to open authorized_fingerprints: %s", err)
}
defer file.Close()
// read the file
scanner := bufio.NewScanner(file)
var fps []string
for scanner.Scan() {
fps = append(fps, scanner.Text())
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("Failed to read authorized_fingerprints: %s", err)
}
// remove the fp
var post []string
for _, t := range fps {
found := false
for _, arg := range c.Args().Slice() {
if t == arg {
found = true
break
}
}
if !found {
post = append(post, t)
}
}
// write the file
if err := file.Truncate(0); err != nil {
return fmt.Errorf("Failed to truncate authorized_fingerprints: %s", err)
}
if _, err := file.Seek(0, 0); err != nil {
return fmt.Errorf("Failed to seek authorized_fingerprints: %s", err)
}
for _, t := range post {
if _, err := file.WriteString(t + "\n"); err != nil {
return fmt.Errorf("Failed to write to authorized_fingerprints: %s", err)
}
}
return nil
}
func listClients(c *cli.Context) error {
file, err := os.Open(ConfPath(FPS_FILENAME))
if err != nil {
return fmt.Errorf("Failed to open authorized_fingerprints: %s", err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
fmt.Println("Authorized fingerprints:")
for scanner.Scan() {
line := scanner.Text()
// skip empty lines
if len(line) == 0 {
continue
}
// skip comments
if line[0] == '#' {
continue
}
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("Failed to read authorized_fingerprints: %s", err)
}
return nil
}