1package gumble
2
3import (
4	"net"
5	"time"
6
7	"github.com/golang/protobuf/proto"
8	"layeh.com/gumble/gumble/MumbleProto"
9)
10
11// BanList is a list of server ban entries.
12//
13// Whenever a ban is changed, it does not come into effect until the ban list
14// is sent back to the server.
15type BanList []*Ban
16
17// Add creates a new ban list entry with the given parameters.
18func (b *BanList) Add(address net.IP, mask net.IPMask, reason string, duration time.Duration) *Ban {
19	ban := &Ban{
20		Address:  address,
21		Mask:     mask,
22		Reason:   reason,
23		Duration: duration,
24	}
25	*b = append(*b, ban)
26	return ban
27}
28
29// Ban represents an entry in the server ban list.
30//
31// This type should not be initialized manually. Instead, create new ban
32// entries using BanList.Add().
33type Ban struct {
34	// The banned IP address.
35	Address net.IP
36	// The IP mask that the ban applies to.
37	Mask net.IPMask
38	// The name of the banned user.
39	Name string
40	// The certificate hash of the banned user.
41	Hash string
42	// The reason for the ban.
43	Reason string
44	// The start time from which the ban applies.
45	Start time.Time
46	// How long the ban is for.
47	Duration time.Duration
48
49	unban bool
50}
51
52// SetAddress sets the banned IP address.
53func (b *Ban) SetAddress(address net.IP) {
54	b.Address = address
55}
56
57// SetMask sets the IP mask that the ban applies to.
58func (b *Ban) SetMask(mask net.IPMask) {
59	b.Mask = mask
60}
61
62// SetReason changes the reason for the ban.
63func (b *Ban) SetReason(reason string) {
64	b.Reason = reason
65}
66
67// SetDuration changes the duration of the ban.
68func (b *Ban) SetDuration(duration time.Duration) {
69	b.Duration = duration
70}
71
72// Unban will unban the user from the server.
73func (b *Ban) Unban() {
74	b.unban = true
75}
76
77// Ban will ban the user from the server. This is only useful if Unban() was
78// called on the ban entry.
79func (b *Ban) Ban() {
80	b.unban = false
81}
82
83func (b BanList) writeMessage(client *Client) error {
84	packet := MumbleProto.BanList{
85		Query: proto.Bool(false),
86	}
87
88	for _, ban := range b {
89		if !ban.unban {
90			maskSize, _ := ban.Mask.Size()
91			packet.Bans = append(packet.Bans, &MumbleProto.BanList_BanEntry{
92				Address:  ban.Address,
93				Mask:     proto.Uint32(uint32(maskSize)),
94				Reason:   &ban.Reason,
95				Duration: proto.Uint32(uint32(ban.Duration / time.Second)),
96			})
97		}
98	}
99
100	return client.Conn.WriteProto(&packet)
101}
102