This repository has been archived by the owner on Jun 23, 2023. It is now read-only.
forked from jda/routeros-api-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprotocol.go
133 lines (115 loc) · 2.46 KB
/
protocol.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
128
129
130
131
132
133
// Package routeros provides a programmatic interface to the Mikrotik RouterOS API
package routeros
import (
"fmt"
"io"
"strings"
)
// Encode and send a single line
func (c *Client) send(word string) error {
bword := []byte(word)
prefix := prefixlen(len(bword))
_, err := c.conn.Write(prefix.Bytes())
if err != nil {
return err
}
_, err = c.conn.Write(bword)
if err != nil {
return err
}
return nil
}
// Get reply
func (c *Client) receive() (reply Reply, err error) {
defer func() {
r := recover()
if r == nil {
return
}
e, ok := r.(mtbyteprotoError)
if ok {
err = e
return
}
panic(r)
}()
re := false
done := false
trap := false
subReply := make(map[string]string, 1)
for {
length := c.getlen()
if length == 0 && done {
break
}
inbuf := make([]byte, length)
n, err := io.ReadAtLeast(c.conn, inbuf, int(length))
// We don't actually care about EOF, but things like ErrUnspectedEOF we would
if err != nil && err != io.EOF {
return reply, err
}
// be annoying about reading exactly the correct number of bytes
if int64(n) != length {
return reply, fmt.Errorf("incorrect number of bytes read")
}
word := string(inbuf)
if word == "!done" {
done = true
continue
}
if word == "!trap" { // error reply
trap = true
continue
}
if word == "!re" { // new term so start a new pair
if len(subReply) > 0 {
// we've already used this subreply because it has stuff in it
// so we need to close it out and make a new one
reply.SubPairs = append(reply.SubPairs, subReply)
subReply = make(map[string]string, 1)
} else {
re = true
}
continue
}
if strings.Contains(word, "=") {
parts := strings.SplitN(word, "=", 3)
var key, val string
if len(parts) == 3 {
key = parts[1]
val = parts[2]
} else {
key = parts[1]
}
if re {
if key != "" {
subReply[key] = val
}
} else {
var p Pair
p.Key = key
p.Value = val
reply.Pairs = append(reply.Pairs, p)
}
}
}
if len(subReply) > 0 {
reply.SubPairs = append(reply.SubPairs, subReply)
}
// if we got a error flag from routeros, look for a message and signal err
if trap {
trapMesasge := ""
for _, v := range reply.Pairs {
if v.Key == "message" {
trapMesasge = v.Value
continue
}
}
if trapMesasge == "" {
return reply, fmt.Errorf("routeros: unknown error")
} else {
return reply, fmt.Errorf("routeros: %s", trapMesasge)
}
}
return reply, nil
}