| 1 | |
| 2 | |
| 3 | |
| 4 | package osutil |
| 5 | |
| 6 | import ( |
| 7 | "fmt" |
| 8 | "net" |
| 9 | "strings" |
| 10 | |
| 11 | "github.com/lima-vm/lima/v2/pkg/sysprof" |
| 12 | ) |
| 13 | |
| 14 | func DNSAddresses() ([]string, error) { |
| 15 | nwData, err := sysprof.NetworkData() |
| 16 | if err != nil { |
| 17 | return nil, err |
| 18 | } |
| 19 | var addresses []string |
| 20 | |
| 21 | |
| 22 | for _, nw := range nwData { |
| 23 | if len(nw.IPv4.Addresses) > 0 { |
| 24 | addresses = nw.DNS.ServerAddresses |
| 25 | break |
| 26 | } |
| 27 | } |
| 28 | return addresses, nil |
| 29 | } |
| 30 | |
| 31 | func proxyURL(proxy string, port any) string { |
| 32 | if strings.Contains(proxy, "://") { |
| 33 | if portNumber, ok := port.(float64); ok && portNumber != 0 { |
| 34 | proxy = fmt.Sprintf("%s:%.0f", proxy, portNumber) |
| 35 | } else if portString, ok := port.(string); ok && portString != "" { |
| 36 | proxy = fmt.Sprintf("%s:%s", proxy, portString) |
| 37 | } |
| 38 | } else { |
| 39 | if portNumber, ok := port.(float64); ok && portNumber != 0 { |
| 40 | proxy = net.JoinHostPort(proxy, fmt.Sprintf("%.0f", portNumber)) |
| 41 | } else if portString, ok := port.(string); ok && portString != "" { |
| 42 | proxy = net.JoinHostPort(proxy, portString) |
| 43 | } |
| 44 | proxy = "http://" + proxy |
| 45 | } |
| 46 | return proxy |
| 47 | } |
| 48 | |
| 49 | func ProxySettings() (map[string]string, error) { |
| 50 | nwData, err := sysprof.NetworkData() |
| 51 | if err != nil { |
| 52 | return nil, err |
| 53 | } |
| 54 | env := make(map[string]string) |
| 55 | if len(nwData) > 0 { |
| 56 | |
| 57 | |
| 58 | var proxies sysprof.Proxies |
| 59 | for _, nw := range nwData { |
| 60 | if len(nw.IPv4.Addresses) > 0 { |
| 61 | proxies = nw.Proxies |
| 62 | break |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | |
| 67 | |
| 68 | if proxies.FTPEnable == "yes" && proxies.FTPUser == "" { |
| 69 | env["ftp_proxy"] = proxyURL(proxies.FTPProxy, proxies.FTPPort) |
| 70 | } |
| 71 | if proxies.HTTPEnable == "yes" && proxies.HTTPUser == "" { |
| 72 | env["http_proxy"] = proxyURL(proxies.HTTPProxy, proxies.HTTPPort) |
| 73 | } |
| 74 | if proxies.HTTPSEnable == "yes" && proxies.HTTPSUser == "" { |
| 75 | env["https_proxy"] = proxyURL(proxies.HTTPSProxy, proxies.HTTPSPort) |
| 76 | } |
| 77 | |
| 78 | |
| 79 | |
| 80 | } |
| 81 | return env, nil |
| 82 | } |