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 pathapi.go
271 lines (234 loc) · 5.63 KB
/
api.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
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
package routeros
import (
"crypto/md5"
"crypto/tls"
"encoding/hex"
"errors"
"fmt"
"io"
"net"
"strings"
"time"
)
// A reply can contain multiple pairs. A pair is a string key->value.
// A reply can also contain subpairs, that is, a array of pair arrays.
type Reply struct {
Pairs []Pair
SubPairs []map[string]string
}
func (r *Reply) GetPairVal(key string) (string, error) {
for _, p := range r.Pairs {
if p.Key == key {
return p.Value, nil
}
}
return "", errors.New("key not found")
}
func (r *Reply) GetSubPairByName(key string) (map[string]string, error) {
for _, p := range r.SubPairs {
if _, ok := p["name"]; ok {
if p["name"] == key {
return p, nil
}
}
}
return nil, errors.New("key not found")
}
func GetPairVal(pairs []Pair, key string) (string, error) {
for _, p := range pairs {
if p.Key == key {
return p.Value, nil
}
}
return "", errors.New("key not found")
}
// Client is a RouterOS API client.
type Client struct {
// Network Address.
// E.g. "10.0.0.1:8728" or "router.example.com:8728"
address string
user string
password string
debug bool // debug logging enabled
ready bool // Ready for work (login ok and connection not terminated)
conn net.Conn // Connection to pass around
TLSConfig *tls.Config
}
// Pair is a Key-Value pair for RouterOS Attribute, Query, and Reply words
// use slices of pairs instead of map because we care about order
type Pair struct {
Key string
Value string
// Op is used for Query words to signify logical operations
// valid operators are -, =, <, >
// see http://wiki.mikrotik.com/wiki/Manual:API#Queries for details.
Op string
}
type Query struct {
Pairs []Pair
Op string
Proplist []string
}
func NewPair(key string, value string) *Pair {
p := new(Pair)
p.Key = key
p.Value = value
return p
}
// Create a new instance of the RouterOS API client
func New(address string) (*Client, error) {
// basic validation of host address
_, _, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
var c Client
c.address = address
return &c, nil
}
func (c *Client) Close() {
c.conn.Close()
}
func (c *Client) Connect(user string, password string, timeout time.Duration) error {
var err error
if c.TLSConfig != nil {
dialer := net.Dialer{Timeout: timeout}
c.conn, err = tls.DialWithDialer(&dialer, "tcp", c.address, c.TLSConfig)
} else {
c.conn, err = net.DialTimeout("tcp", c.address, timeout)
}
if err != nil {
return err
}
// if c.TLSConfig != nil {
// c.conn, err = tls.Dial("tcp", c.address, c.TLSConfig)
// } else {
// c.conn, err = net.Dial("tcp", c.address)
// }
err = c.conn.SetDeadline(time.Now().Add(timeout))
if err != nil {
return err
}
var loginParams []Pair
loginParams = append(loginParams, *NewPair("name", user))
loginParams = append(loginParams, *NewPair("password", password))
// try to log in again with challenge/response
res, err := c.Call("/login", loginParams)
if err != nil {
return err
}
if len(res.Pairs) > 0 {
return fmt.Errorf("Unexpected result on login: %+v", res)
}
return nil
}
func (c *Client) ConnectLegacy(user string, password string, timeout time.Duration) error {
var err error
if c.TLSConfig != nil {
dialer := net.Dialer{Timeout: timeout}
c.conn, err = tls.DialWithDialer(&dialer, "tcp", c.address, c.TLSConfig)
} else {
c.conn, err = net.DialTimeout("tcp", c.address, timeout)
}
if err != nil {
return err
}
// if c.TLSConfig != nil {
// c.conn, err = tls.Dial("tcp", c.address, c.TLSConfig)
// } else {
// c.conn, err = net.Dial("tcp", c.address)
// }
err = c.conn.SetDeadline(time.Now().Add(timeout))
if err != nil {
return err
}
// try to log in
res, err := c.Call("/login", nil)
if err != nil {
return err
}
// handle challenge/response
challengeEnc, err := res.GetPairVal("ret")
if err != nil {
return errors.New("Didn't get challenge from ROS")
}
challenge, err := hex.DecodeString(challengeEnc)
if err != nil {
return err
}
h := md5.New()
io.WriteString(h, "\000")
io.WriteString(h, password)
h.Write(challenge)
resp := fmt.Sprintf("00%x", h.Sum(nil))
var loginParams []Pair
loginParams = append(loginParams, *NewPair("name", user))
loginParams = append(loginParams, *NewPair("response", resp))
// try to log in again with challenge/response
res, err = c.Call("/login", loginParams)
if err != nil {
return err
}
if len(res.Pairs) > 0 {
return fmt.Errorf("Unexpected result on login: %+v", res)
}
return nil
}
func (c *Client) Query(command string, q Query) (Reply, error) {
err := c.send(command)
if err != nil {
return Reply{}, err
}
// Set property list if present
if len(q.Proplist) > 0 {
proplist := fmt.Sprintf("=.proplist=%s", strings.Join(q.Proplist, ","))
err = c.send(proplist)
if err != nil {
return Reply{}, err
}
}
// send params if we got them
if len(q.Pairs) > 0 {
for _, v := range q.Pairs {
word := fmt.Sprintf("?%s%s=%s", v.Op, v.Key, v.Value)
c.send(word)
}
if q.Op != "" {
word := fmt.Sprintf("?#%s", q.Op)
c.send(word)
}
}
// send terminator
err = c.send("")
if err != nil {
return Reply{}, err
}
res, err := c.receive()
if err != nil {
return Reply{}, err
}
return res, nil
}
func (c *Client) Call(command string, params []Pair) (Reply, error) {
err := c.send(command)
if err != nil {
return Reply{}, err
}
// send params if we got them
if len(params) > 0 {
for _, v := range params {
word := fmt.Sprintf("=%s=%s", v.Key, v.Value)
c.send(word)
}
}
// send terminator
err = c.send("")
if err != nil {
return Reply{}, err
}
res, err := c.receive()
if err != nil {
return Reply{}, err
}
return res, nil
}