-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
113 lines (89 loc) · 2.22 KB
/
main.go
File metadata and controls
113 lines (89 loc) · 2.22 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
package nc
import (
"bytes"
"context"
"fmt"
"net"
"github.com/scorify/schema"
)
type Schema struct {
Target string `key:"target"`
Port int `key:"port" default:"23"`
Command string `key:"command"`
ExpectedOutput string `key:"expected_output"`
}
func Validate(config string) error {
conf := Schema{}
err := schema.Unmarshal([]byte(config), &conf)
if err != nil {
return err
}
if conf.Target == "" {
return fmt.Errorf("target is required")
}
if conf.Port < 1 || conf.Port > 65535 {
return fmt.Errorf("port must be between 1 and 65535")
}
if conf.Command == "" {
return fmt.Errorf("command is required")
}
if conf.ExpectedOutput == "" {
return fmt.Errorf("expected_output is required")
}
return nil
}
func Run(ctx context.Context, config string) error {
conf := Schema{}
err := schema.Unmarshal([]byte(config), &conf)
if err != nil {
return err
}
connStr := fmt.Sprintf("%s:%d", conf.Target, conf.Port)
dialer := net.Dialer{}
conn, err := dialer.DialContext(ctx, "tcp", connStr)
if err != nil {
return fmt.Errorf("failed to connect to %q: %w", connStr, err)
}
defer conn.Close()
deadline, ok := ctx.Deadline()
if !ok {
return fmt.Errorf("failed to get deadline")
}
err = conn.SetDeadline(deadline)
if err != nil {
return fmt.Errorf("failed to set deadline: %w", err)
}
buffer := make([]byte, 2048)
// read until the buffer is not 2048 bytes
for ctx.Err() == nil {
i, err := conn.Read(buffer)
if err != nil {
return fmt.Errorf("failed to read from %q: %w", connStr, err)
}
if i < 2048 {
break
}
}
_, err = conn.Write([]byte(conf.Command + "\n"))
if err != nil {
return fmt.Errorf("failed to write to %q: %w", connStr, err)
}
output := bytes.NewBuffer(nil)
buffer = make([]byte, 2048)
// read until the buffer is not 2048 bytes
for ctx.Err() == nil {
i, err := conn.Read(buffer)
if err != nil {
return fmt.Errorf("failed to read from %q: %w", connStr, err)
}
fmt.Println(i, string(buffer[:i]))
output.Write(buffer[:i])
if i < 2048 {
break
}
}
if !bytes.Contains(output.Bytes(), []byte(conf.ExpectedOutput)) {
return fmt.Errorf("expected output %q not found in %q", conf.ExpectedOutput, output.String())
}
return nil
}