aboutsummaryrefslogtreecommitdiff
path: root/tun2/backend.go
blob: d94a1a8f61bba9459210e7024329455d6f0c45e4 (plain)
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
69
70
71
72
73
74
75
76
77
78
package tun2

import "time"

// Backend is the public state of an individual Connection.
type Backend struct {
	ID     string
	Proto  string
	User   string
	Domain string
	Phi    float32
	Host   string
	Usable bool
}

type backendMatcher func(*Connection) bool

func (s *Server) getBackendsForMatcher(bm backendMatcher) []Backend {
	s.connlock.Lock()
	defer s.connlock.Unlock()

	var result []Backend

	for _, c := range s.conns {
		if !bm(c) {
			continue
		}

		result = append(result, Backend{
			ID:     c.id,
			Proto:  c.conn.LocalAddr().Network(),
			User:   c.user,
			Domain: c.domain,
			Phi:    float32(c.detector.Phi(time.Now())),
			Host:   c.conn.RemoteAddr().String(),
			Usable: c.usable,
		})
	}

	return result
}

// KillBackend forcibly disconnects a given backend but doesn't offer a way to
// "ban" it from reconnecting.
func (s *Server) KillBackend(id string) error {
	s.connlock.Lock()
	defer s.connlock.Unlock()

	for _, c := range s.conns {
		if c.id == id {
			c.cancel()
			return nil
		}
	}

	return ErrNoSuchBackend
}

// GetBackendsForDomain fetches all backends connected to this server associated
// to a single public domain name.
func (s *Server) GetBackendsForDomain(domain string) []Backend {
	return s.getBackendsForMatcher(func(c *Connection) bool {
		return c.domain == domain
	})
}

// GetBackendsForUser fetches all backends connected to this server owned by a
// given user by username.
func (s *Server) GetBackendsForUser(uname string) []Backend {
	return s.getBackendsForMatcher(func(c *Connection) bool {
		return c.user == uname
	})
}

// GetAllBackends fetches every backend connected to this server.
func (s *Server) GetAllBackends() []Backend {
	return s.getBackendsForMatcher(func(*Connection) bool { return true })
}