cloudflare/cloudflared

Public

mirrored from https://github.com/cloudflare/cloudflaredAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
2020.5.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

edgediscovery/allregions/region.go

84lines · modecode

1package allregions
2
3import (
4 "net"
5
6 "github.com/sirupsen/logrus"
7)
8
9// Region contains cloudflared edge addresses. The edge is partitioned into several regions for
10// redundancy purposes.
11type Region struct {
12 connFor map[*net.TCPAddr]UsedBy
13}
14
15// NewRegion creates a region with the given addresses, which are all unused.
16func NewRegion(addrs []*net.TCPAddr) Region {
17 // The zero value of UsedBy is Unused(), so we can just initialize the map's values with their
18 // zero values.
19 m := make(map[*net.TCPAddr]UsedBy)
20 for _, addr := range addrs {
21 m[addr] = Unused()
22 }
23 return Region{connFor: m}
24}
25
26// AddrUsedBy finds the address used by the given connection in this region.
27// Returns nil if the connection isn't using any IP.
28func (r *Region) AddrUsedBy(connID int) *net.TCPAddr {
29 for addr, used := range r.connFor {
30 if used.Used && used.ConnID == connID {
31 return addr
32 }
33 }
34 return nil
35}
36
37// AvailableAddrs counts how many unused addresses this region contains.
38func (r Region) AvailableAddrs() int {
39 n := 0
40 for _, usedby := range r.connFor {
41 if !usedby.Used {
42 n++
43 }
44 }
45 return n
46}
47
48// GetUnusedIP returns a random unused address in this region.
49// Returns nil if all addresses are in use.
50func (r Region) GetUnusedIP(excluding *net.TCPAddr) *net.TCPAddr {
51 for addr, usedby := range r.connFor {
52 if !usedby.Used && addr != excluding {
53 return addr
54 }
55 }
56 return nil
57}
58
59// Use the address, assigning it to a proxy connection.
60func (r Region) Use(addr *net.TCPAddr, connID int) {
61 if addr == nil {
62 logrus.Errorf("Attempted to use nil address for connection %d", connID)
63 return
64 }
65 r.connFor[addr] = InUse(connID)
66}
67
68// GetAnyAddress returns an arbitrary address from the region.
69func (r Region) GetAnyAddress() *net.TCPAddr {
70 for addr := range r.connFor {
71 return addr
72 }
73 return nil
74}
75
76// GiveBack the address, ensuring it is no longer assigned to an IP.
77// Returns true if the address is in this region.
78func (r Region) GiveBack(addr *net.TCPAddr) (ok bool) {
79 if _, ok := r.connFor[addr]; !ok {
80 return false
81 }
82 r.connFor[addr] = Unused()
83 return true
84}
85