-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
261 lines (246 loc) · 6.63 KB
/
main.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
package main
import (
"bufio"
"encoding/json"
"fmt"
"github.com/go-routeros/routeros"
"github.com/jessevdk/go-flags"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
type Opts struct {
Router string `long:"router" description:"IP or DNS name router RouterOS" required:"true"`
User string `long:"user" description:"User for router RouterOS" required:"true"`
Password string `long:"password" description:"Password for router RouterOS" required:"true"`
Port string `long:"port" description:"Port API" default:"8728"`
SSL bool `long:"ssl" description:"Required SSL user for API"`
List string `long:"list" description:"Address-List Name" required:"true"`
ASN string `long:"ASN" description:"ASN list one or more, delimeter(,)" required:"true"`
Verbose bool `long:"verbose" description:"Show verbose debug information"`
Cachettl int `logn:"cachettl" description:"Time To live cache for ASN" default:"86400"`
Cachepath string `long:"cachepath" description:"Path to save cache" default:"./tmp"`
Author bool `long:"author" description:"Vasilev Kirill\nhttps://vasilevkirill.ru"`
}
var options Opts
var parser = flags.NewParser(&options, flags.Default)
type ASjson struct {
Status string `json:"status"`
Status_message string `json:"status_message"`
Data ASjson_data `json:"data"`
}
type ASjson_data struct {
Ipv4_prefixes []Prefix_IPv4 `json:"ipv4_prefixes"`
}
type Prefix_IPv4 struct {
Ip string `json:"ip"`
Cidr int `json:"cidr"`
}
func main() {
if _, err := parser.Parse(); err != nil {
if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp {
os.Exit(0)
} else {
os.Exit(1)
}
}
if options.Cachettl == 0 {
options.Cachettl = 86400
}
CheckCashPath(options.Cachepath)
asns := strings.Split(options.ASN, ",")
for _, as := range asns {
Verb("Start for ASN: " + as)
c := CacheLive(as)
if c == false {
if UpdateCache(as) == false {
Verb("ASN " + as + "Update False")
continue
}
}
err := ROSUpdate(as)
if err != nil {
Verb("ASN " + as + "Update False")
Verb("ASN " + as + err.Error())
continue
}
}
}
func ROSUpdate(as string) (err error) {
Verb("Connect to Router")
c, err := dial()
if err != nil {
return err
}
defer c.Close()
namelist := "ASN" + as
Verb("Get Current list " + namelist)
reply, err := c.Run("/ip/firewall/address-list/print", "?list="+options.List, "?comment="+namelist, "=.proplist=address")
if err != nil {
return err
}
var curentlist []string
for _, re := range reply.Re {
curentlist = append(curentlist, re.List[0].Value)
}
file, err := os.Open(options.Cachepath + "/" + as + ".asn")
if err != nil {
return err
}
defer file.Close()
var needlist []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
needlist = append(needlist, scanner.Text())
}
needremove := compare(curentlist, needlist)
needadd := compare(needlist, curentlist)
Verb("Need Remove count: " + strconv.Itoa(len(needremove)))
Verb("Need Add count: " + strconv.Itoa(len(needadd)))
for _, l := range needremove {
r, err := c.Run("/ip/firewall/address-list/print", "?list="+options.List, "?comment="+namelist, "?address="+l, "=.proplist=.id")
if err != nil {
return err
}
_, err = c.Run("/ip/firewall/address-list/remove", "=.id="+r.Re[0].List[0].Value)
if err != nil {
return err
}
Verb("Remove address " + l + " From List " + namelist)
}
for _, l := range needadd {
_, err := c.Run("/ip/firewall/address-list/add", "=list="+options.List, "=address="+l, "=comment="+namelist)
if err != nil {
return err
}
Verb("Add address " + l + " To List " + namelist)
}
return nil
}
func dial() (*routeros.Client, error) {
adr := options.Router + ":" + options.Port
if options.SSL == true {
return routeros.DialTLS(adr, options.User, options.Password, nil)
}
return routeros.Dial(adr, options.User, options.Password)
}
func CacheLive(asn string) bool {
file := options.Cachepath + "/" + asn + ".asn"
if fileExists(file) == false {
Verb("File Not Exist: " + file)
return false
}
filet, err := os.Stat(file)
if err != nil {
Verb("Error get info file: " + file)
fmt.Println(err)
return false
}
modifiedtime := filet.ModTime()
Verb("ASN " + asn + " Cache File Time Info: " + modifiedtime.String())
now := time.Now()
secNow := now.Unix()
secF := modifiedtime.Unix()
ageseccach := secNow - secF
Verb("ASN " + asn + " CacheTTL: " + strconv.Itoa(options.Cachettl) + " Second ")
if ageseccach > int64(options.Cachettl) {
Verb("ASN " + asn + " Cache old, need Update")
return false
}
Verb("ASN " + asn + " Cache Good")
return true
}
func UpdateCache(asn string) bool {
url := "https://api.bgpview.io/asn/" + asn + "/prefixes"
spaceClient := http.Client{
Timeout: time.Second * 5,
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
return false
}
req.Header.Set("User-Agent", "spacecount-tutorial")
res, getErr := spaceClient.Do(req)
if getErr != nil {
log.Fatal(getErr)
return false
}
Verb("ASN " + asn + " Get Info From " + url)
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
log.Fatal(readErr)
return false
}
js := ASjson{}
jsonErr := json.Unmarshal(body, &js)
if jsonErr != nil {
log.Fatal(jsonErr)
return false
}
fln := options.Cachepath + "/" + asn + ".asn"
if fileExists(fln) == false {
emptyFile, err := os.Create(fln)
if err != nil {
log.Fatal(err)
return false
}
Verb("ASN " + asn + " Create file " + fln)
err = emptyFile.Close()
if err != nil {
log.Fatal(err)
return false
}
}
fo, _ := os.OpenFile(fln, os.O_WRONLY, 0644)
err = fo.Truncate(0)
if err != nil {
log.Fatal(err)
return false
}
defer fo.Close()
for _, s := range js.Data.Ipv4_prefixes {
str := s.Ip + "/" + strconv.Itoa(s.Cidr)
fmt.Fprintln(fo, str)
}
return true
}
//CheckCashPath Проверка существования директории и при необходимости создаём её.
func CheckCashPath(path string) {
if _, err := os.Stat(path); os.IsNotExist(err) {
Verb("Directory for cache not exist")
Verb("Create Directory " + path)
err := os.Mkdir(path, 0777)
if err != nil {
Verb("Fatal error not create directory " + path)
log.Fatal("MkdirAll %q: %s", path, err)
}
}
}
func Verb(str string) {
if options.Verbose {
log.Printf(str)
}
}
func fileExists(filename string) bool {
_, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return true
}
func compare(a, b []string) []string {
for i := len(a) - 1; i >= 0; i-- {
for _, vD := range b {
if a[i] == vD {
a = append(a[:i], a[i+1:]...)
break
}
}
}
return a
}