File: utils.go

package info (click to toggle)
mirrorbits 0.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 984 kB
  • sloc: sh: 675; makefile: 93
file content (68 lines) | stat: -rw-r--r-- 1,882 bytes parent folder | download | duplicates (2)
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
// Copyright (c) 2014-2019 Ludovic Fauvet
// Licensed under the MIT license

package network

import (
	"net"
	"strings"
)

// LookupMirrorIP returns the IP address of a mirror and returns an error
// if the DNS has more than one address
func LookupMirrorIP(host string) (string, error) {
	addrs, err := net.LookupIP(host)
	if err != nil {
		return "", err
	}
	// A mirror with multiple IP address is a problem
	// since we can't determine the exact position of
	// the server.
	if len(addrs) > 1 {
		err = ErrMultipleAddresses
	}

	return addrs[0].String(), err
}

// RemoteIPFromAddr removes the port from a remote address (x.x.x.x:yyyy)
func RemoteIPFromAddr(remoteAddr string) string {
	return remoteAddr[:strings.LastIndex(remoteAddr, ":")]
}

// ExtractRemoteIP extracts the remote IP from an X-Forwarded-For header
func ExtractRemoteIP(XForwardedFor string) string {
	addresses := strings.Split(XForwardedFor, ",")
	if len(addresses) > 0 {
		// The left-most address is supposed to be the original client address.
		// Each successive are added by proxies. In most cases we should probably
		// take the last address but in case of optimization services this will
		// probably not work. For now we'll always take the original one.
		return strings.TrimSpace(addresses[0])
	}
	return ""
}

// IsPrimaryCountry returns true if the clientInfo country is the primary country
func IsPrimaryCountry(clientInfo GeoIPRecord, list []string) bool {
	if !clientInfo.IsValid() {
		return false
	}
	if len(list) > 0 && list[0] == clientInfo.CountryCode {
		return true
	}
	return false
}

// IsAdditionalCountry returns true if the clientInfo country is in list
func IsAdditionalCountry(clientInfo GeoIPRecord, list []string) bool {
	if !clientInfo.IsValid() {
		return false
	}
	for i, b := range list {
		if i > 0 && b == clientInfo.CountryCode {
			return true
		}
	}
	return false
}