Debian Codegraph @

network/utils.go

raw
1 // Copyright (c) 2014-2019 Ludovic Fauvet
2 // Licensed under the MIT license
3
4 package network
5
6 import (
7 "net"
8 "strings"
9 )
10
11 // LookupMirrorIP returns the IP address of a mirror and returns an error
12 // if the DNS has more than one address
13 func LookupMirrorIP(host string) (string, error) {
14 addrs, err := net.LookupIP(host)
15 if err != nil {
16 return "", err
17 }
18 // A mirror with multiple IP address is a problem
19 // since we can't determine the exact position of
20 // the server.
21 if len(addrs) > 1 {
22 err = ErrMultipleAddresses
23 }
24
25 return addrs[0].String(), err
26 }
27
28 // RemoteIPFromAddr removes the port from a remote address (x.x.x.x:yyyy)
29 func RemoteIPFromAddr(remoteAddr string) string {
30 return remoteAddr[:strings.LastIndex(remoteAddr, ":")]
31 }
32
33 // ExtractRemoteIP extracts the remote IP from an X-Forwarded-For header
34 func ExtractRemoteIP(XForwardedFor string) string {
35 addresses := strings.Split(XForwardedFor, ",")
36 if len(addresses) > 0 {
37 // The left-most address is supposed to be the original client address.
38 // Each successive are added by proxies. In most cases we should probably
39 // take the last address but in case of optimization services this will
40 // probably not work. For now we'll always take the original one.
41 return strings.TrimSpace(addresses[0])
42 }
43 return ""
44 }
45
46 // IsPrimaryCountry returns true if the clientInfo country is the primary country
47 func IsPrimaryCountry(clientInfo GeoIPRecord, list []string) bool {
48 if !clientInfo.IsValid() {
49 return false
50 }
51 if len(list) > 0 && list[0] == clientInfo.CountryCode {
52 return true
53 }
54 return false
55 }
56
57 // IsAdditionalCountry returns true if the clientInfo country is in list
58 func IsAdditionalCountry(clientInfo GeoIPRecord, list []string) bool {
59 if !clientInfo.IsValid() {
60 return false
61 }
62 for i, b := range list {
63 if i > 0 && b == clientInfo.CountryCode {
64 return true
65 }
66 }
67 return false
68 }