-
Notifications
You must be signed in to change notification settings - Fork 11
/
quagga.go
358 lines (293 loc) · 8.74 KB
/
quagga.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
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
350
351
352
353
354
355
356
357
358
// Copyright (c) 2017 Pani Networks
// All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
// The package advertises list of networks by connecting to the instance
// of bgpd and executing `networl A.B.C.D/E` command for every network in
// a list.
package quagga
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
"net"
"os"
"sync"
"time"
router "github.com/romana/core/agent/router/publisher"
telnet "github.com/reiver/go-telnet"
)
func New(config router.Config) (router.Interface, error) {
quagga := QuaggaBgpRoutePublisher{Mutex: &sync.Mutex{}}
quagga.BgpdHost = config.SetDefault("bgpdHost", "localhost")
quagga.BgpdPort = config.SetDefault("bgpdPort", "2605")
quagga.UserPrompt = config.SetDefault("userPrompt", "bgpd> ")
quagga.AdminPrompt = config.SetDefault("adminPrompt", "bgpd# ")
quagga.ConfigPrompt = config.SetDefault("configPrompt", "bgpd(config)# ")
quagga.RouterPrompt = config.SetDefault("routerPrompt", "bgpd(config-router)# ")
if pass, ok := config["password"]; ok {
quagga.Password = pass
} else {
return nil, fmt.Errorf("Parameter missing `password`")
}
if enable, ok := config["enablePass"]; ok {
quagga.EnablePass = enable
} else {
return nil, fmt.Errorf("Parameter missing `enablePass`")
}
if localAS, ok := config["localAS"]; ok {
quagga.LocalAS = localAS
} else {
return nil, fmt.Errorf("Parameter missing `localAS`")
}
if debug, ok := config["debug"]; ok && debug != "false" {
quagga.Debug = true
}
return quagga, nil
}
// Default implementation of Interface that publishes routes via instance
// of bgpd managed by quagga.
type QuaggaBgpRoutePublisher struct {
// Connect to BGP
*sync.Mutex
// IP address or hostname bgpd listens on.
BgpdHost string
// bgpd port (defaul 2605)
BgpdPort string
// Quagga password. Required.
Password string
// Enable privilege password. Required.
EnablePass string
// User prompt to expect in telnet session. Optional.
UserPrompt string
// Admin prompt to expect in telnet session. Optional
AdminPrompt string
// Config prompt to expect in telnet session. Optional.
ConfigPrompt string
// Router prompt to expect in a telnet session. Optional.
RouterPrompt string
// LocalAS used to identify proper config context in bgpd
// `router bgp .LocalAS`. Required.
LocalAS string
// Extra output
Debug bool
// Internal.
Input bytes.Buffer
networks []net.IPNet
}
// Update implements Interact, it publishes provided networks with
// quagga managed bgp.
func (q QuaggaBgpRoutePublisher) Update(networks []net.IPNet, args map[string]interface{}) error {
q.Lock()
defer q.Unlock()
log.Printf("Starting bgp update at %s:%s", q.BgpdHost, q.BgpdPort)
q.networks = networks
q.Input.Reset()
telnet.DialToAndCall(fmt.Sprintf("%s:%s", q.BgpdHost, q.BgpdPort), q)
log.Printf("Finished bgp update at %s:%s", q.BgpdHost, q.BgpdPort)
return nil
}
func (q QuaggaBgpRoutePublisher) debug(format string, args ...interface{}) {
if q.Debug {
log.Printf(format, args...)
}
}
// CallTELNET implements telnet.Caller interface, this is a callback that gets called by telnet package.
func (caller QuaggaBgpRoutePublisher) CallTELNET(ctx telnet.Context, writer telnet.Writer, reader telnet.Reader) {
var bufferArray [1]byte
buffer := bufferArray[:]
go func(reader io.Reader) {
for {
// Read 1 byte, if read zero then skip
// if error, thenm break.
n, err := reader.Read(buffer)
if n <= 0 && err == nil {
continue
} else if n <= 0 && err != nil {
break
}
caller.Input.Write(buffer)
if caller.Debug {
os.Stdout.Write(buffer)
}
}
}(reader)
time.Sleep(time.Duration(1 * time.Second))
if bytes.HasSuffix(caller.Input.Bytes(), []byte("Password: ")) {
err := caller.Authentificate(writer)
if err != nil {
log.Printf("Error: when authentificating %s", err)
return
}
}
showConfigCmd := "show running-config\n"
_, err := writer.Write([]byte(showConfigCmd))
if err != nil {
log.Printf("Error when writing %s: %s", showConfigCmd, err)
return
}
time.Sleep(time.Duration(1 * time.Second))
// make a map of networks and their desired statuses
networks := make(map[string]string)
for _, network := range caller.parseCurrentNetworks() {
networks[network] = "remove"
}
for _, network := range caller.networks {
newNetwork := network.String()
if _, ok := networks[newNetwork]; ok {
networks[newNetwork] = "keep"
} else {
networks[newNetwork] = "add"
}
}
// turn map of statuses into lists by status
// ignore "keep" status
var addedNetworks, outdatedNetworks []string
for network, status := range networks {
if status == "add" {
addedNetworks = append(addedNetworks, network)
} else if status == "remove" {
outdatedNetworks = append(outdatedNetworks, network)
}
}
caller.debug("Networks to add %v, networks to delete %v", addedNetworks, outdatedNetworks)
err = caller.configMode(writer)
if err != nil {
log.Printf("Error: %s", err)
return
}
err = caller.updateAdvertisedNetworks(addedNetworks, outdatedNetworks, writer)
if err != nil {
log.Printf("Error: %s", err)
return
}
return
}
func (caller *QuaggaBgpRoutePublisher) updateAdvertisedNetworks(addedNetworks, outdatedNetworks []string, writer telnet.Writer) error {
var commands []interactCmd
for _, network := range outdatedNetworks {
commands = append(commands, interactCmd{
send: fmt.Sprintf("no network %s\n", network),
expect: caller.RouterPrompt,
})
}
for _, network := range addedNetworks {
commands = append(commands, interactCmd{
send: fmt.Sprintf("network %s\n", network),
expect: caller.RouterPrompt,
})
}
commands = append(commands, interactCmd{
send: "write file\n",
expect: caller.RouterPrompt,
})
err := caller.Interact(commands, writer)
if err != nil {
return fmt.Errorf("Failed to update advertised networks, err=(%s)", err)
}
return nil
}
func (caller *QuaggaBgpRoutePublisher) shutdownTelnet(writer telnet.Writer) error {
commands := []interactCmd{
{
send: "exit\n",
expect: caller.ConfigPrompt,
}, {
send: "exit\n",
expect: caller.AdminPrompt,
}, {
send: "exit\n",
expect: "",
},
}
err := caller.Interact(commands, writer)
if err != nil {
return fmt.Errorf("Failed to shutdown telnet session properly, err=(%s)", err)
}
return nil
}
func (caller *QuaggaBgpRoutePublisher) Authentificate(writer telnet.Writer) error {
commands := []interactCmd{
{
fmt.Sprintf("%s\n", caller.Password),
caller.UserPrompt,
}, {
"enable\n",
"Password: ",
}, {
fmt.Sprintf("%s\n", caller.EnablePass),
caller.AdminPrompt,
},
}
err := caller.Interact(commands, writer)
if err != nil {
return fmt.Errorf("Authentification failed, err=(%s)", err)
}
return nil
}
func (caller *QuaggaBgpRoutePublisher) configMode(writer telnet.Writer) error {
commands := []interactCmd{
{
"configure terminal\n",
caller.ConfigPrompt,
}, {
fmt.Sprintf("router bgp %s\n", caller.LocalAS),
caller.RouterPrompt,
},
}
err := caller.Interact(commands, writer)
if err != nil {
return fmt.Errorf("Config mode failed, err=(%s)", err)
}
return nil
}
// parseCurrentNetworks goes through current input buffer and returns
// a list of advertised networks.
func (caller *QuaggaBgpRoutePublisher) parseCurrentNetworks() []string {
var nets []string
scanner := bufio.NewScanner(&caller.Input)
for scanner.Scan() {
line := scanner.Bytes()
if bytes.HasPrefix(bytes.TrimSpace(line), []byte("network")) {
words := bytes.Split(line, []byte{' '})
nets = append(nets, string(words[len(words)-1]))
}
}
return nets
}
type interactCmd struct {
send string
expect string
}
func (caller *QuaggaBgpRoutePublisher) Interact(commands []interactCmd, writer telnet.Writer) error {
for _, command := range commands {
n, err := writer.Write([]byte(command.send))
if err != nil || n != len(command.send) {
// TODO, remove passwords from error message
return fmt.Errorf("interaction attempted to write %s, wrote %d out of %d chars, err=%s",
command.send,
n,
len(command.send),
err)
}
time.Sleep(time.Duration(1 * time.Second))
if !bytes.HasSuffix(caller.Input.Bytes(), []byte(command.expect)) {
return fmt.Errorf("interaction expected output %s, got %s",
command.expect,
caller.Input.Bytes()[caller.Input.Len()-len(command.expect):])
}
}
return nil
}