package bgptools
import (
"fmt"
"html"
"io"
"net"
"regexp"
"strings"
"github.com/google/uuid"
"github.com/imroc/req/v3"
)
type ASCard struct {
ASN string
Name string
Fill string
Stroke string
ID string
}
type Arrow struct {
From string
To string
}
type Upstream struct {
ASN string
Name string
Direct bool
Tier1 bool
Type string // 新增类型字段
}
type PoPResult struct {
TargetASN string
Upstreams []Upstream
Result string
}
var tier1Global = map[string]string{
"174": "Cogent",
"1299": "Arelion",
"3356": "Lumen",
"3257": "GTT",
"7018": "AT&T",
"701": "Verizon",
"2914": "NTT",
"6453": "Tata",
"3320": "DTAG",
"5511": "Orange",
"3491": "PCCW",
"6461": "Zayo",
"6830": "Liberty",
"6762": "Sparkle",
"12956": "Telxius",
}
func getISPAbbr(asn, name string) string {
if abbr, ok := tier1Global[asn]; ok {
return abbr
}
if idx := strings.Index(name, " "); idx != -1 {
return name[:idx]
}
return name
}
func getISPType(asn string, tier1 bool) string {
if tier1 {
if _, ok := tier1Global[asn]; ok {
return "Tier1 Global"
}
return "Tier1 Regional"
}
return "Direct"
}
func isValidIP(ip string) bool {
return net.ParseIP(ip) != nil
}
func getSVGPath(client *req.Client, ip string) (string, error) {
if !isValidIP(ip) {
return "", fmt.Errorf("invalid IP address: %s", ip)
}
url := fmt.Sprintf("https://bgp.tools/prefix/%s#connectivity", ip)
resp, err := client.R().Get(url)
if err != nil {
return "", fmt.Errorf("failed to fetch BGP info for IP %s: %w", ip, err)
}
if resp.StatusCode != 200 {
return "", fmt.Errorf("HTTP error %d when fetching BGP info for IP %s", resp.StatusCode, ip)
}
body := resp.String()
re := regexp.MustCompile(`]+id="pathimg"[^>]+src="([^"]+)"`)
matches := re.FindStringSubmatch(body)
if len(matches) < 2 {
return "", fmt.Errorf("SVG path not found for IP %s", ip)
}
return matches[1], nil
}
func downloadSVG(client *req.Client, svgPath string) (string, error) {
uuid := uuid.NewString()
url := fmt.Sprintf("https://bgp.tools%s?%s&loggedin", svgPath, uuid)
resp, err := client.R().Get(url)
if err != nil {
return "", fmt.Errorf("failed to download SVG: %w", err)
}
if resp.StatusCode != 200 {
return "", fmt.Errorf("HTTP error %d when downloading SVG", resp.StatusCode)
}
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("failed to read SVG response body: %w", err)
}
return string(bodyBytes), nil
}
func parseASAndEdges(svg string) ([]ASCard, []Arrow) {
svg = html.UnescapeString(svg)
var nodes []ASCard
var edges []Arrow
nodeRE := regexp.MustCompile(`(?s)