/
conn.go
258 lines (214 loc) · 7.31 KB
/
conn.go
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/**********************************************************************************
* Copyright (c) 2009-2017 Misakai Ltd.
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Affero General Public License as published by the Free Software
* Foundation, either version 3 of the License, or(at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see<http://www.gnu.org/licenses/>.
************************************************************************************/
package broker
import (
"bufio"
"fmt"
"net"
"runtime/debug"
"sync"
"sync/atomic"
"time"
"github.com/emitter-io/emitter/broker/message"
"github.com/emitter-io/emitter/logging"
"github.com/emitter-io/emitter/network/address"
"github.com/emitter-io/emitter/network/mqtt"
"github.com/emitter-io/emitter/security"
)
// Conn represents an incoming connection.
type Conn struct {
sync.Mutex
tracked uint32 // Whether the connection was already tracked or not.
socket net.Conn // The transport used to read and write messages.
username string // The username provided by the client during MQTT connect.
luid security.ID // The locally unique id of the connection.
guid string // The globally unique id of the connection.
service *Service // The service for this connection.
subs *message.Counters // The subscriptions for this connection.
}
// NewConn creates a new connection.
func (s *Service) newConn(t net.Conn) *Conn {
c := &Conn{
tracked: 0,
luid: security.NewID(),
service: s,
socket: t,
subs: message.NewCounters(),
}
// Generate a globally unique id as well
c.guid = c.luid.Unique(uint64(address.Hardware()), "emitter")
logging.LogTarget("conn", "created", c.luid)
// Increment the connection counter
atomic.AddInt64(&s.connections, 1)
return c
}
// ID returns the unique identifier of the subsriber.
func (c *Conn) ID() string {
return c.guid
}
// Type returns the type of the subscriber
func (c *Conn) Type() message.SubscriberType {
return message.SubscriberDirect
}
// track tracks the connection by adding it to the metering.
func (c *Conn) track(contract security.Contract) {
if atomic.LoadUint32(&c.tracked) == 0 {
// We keep only the IP address for fair tracking
addr := c.socket.RemoteAddr().String()
if tcp, ok := c.socket.RemoteAddr().(*net.TCPAddr); ok {
addr = tcp.IP.String()
}
// Add the device to the stats and mark as done
contract.Stats().AddDevice(addr)
atomic.StoreUint32(&c.tracked, 1)
}
}
// Process processes the messages.
func (c *Conn) Process() error {
defer c.Close()
reader := bufio.NewReaderSize(c.socket, 65536)
for {
// Set read/write deadlines so we can close dangling connections
c.socket.SetDeadline(time.Now().Add(time.Second * 120))
// Decode an incoming MQTT packet
msg, err := mqtt.DecodePacket(reader)
if err != nil {
return err
}
switch msg.Type() {
// We got an attempt to connect to MQTT.
case mqtt.TypeOfConnect:
packet := msg.(*mqtt.Connect)
c.username = string(packet.Username)
// Write the ack
ack := mqtt.Connack{ReturnCode: 0x00}
if _, err := ack.EncodeTo(c.socket); err != nil {
return err
}
// We got an attempt to subscribe to a channel.
case mqtt.TypeOfSubscribe:
packet := msg.(*mqtt.Subscribe)
ack := mqtt.Suback{
MessageID: packet.MessageID,
Qos: make([]uint8, 0, len(packet.Subscriptions)),
}
// Subscribe for each subscription
for _, sub := range packet.Subscriptions {
if err := c.onSubscribe(sub.Topic); err != nil {
logging.LogError("conn", "subscribe received", err)
ack.Qos = append(ack.Qos, 0x80) // 0x80 indicate subscription failure
} else {
// Append the QoS
ack.Qos = append(ack.Qos, sub.Qos)
}
}
// Acknowledge the subscription
if _, err := ack.EncodeTo(c.socket); err != nil {
return err
}
// We got an attempt to unsubscribe from a channel.
case mqtt.TypeOfUnsubscribe:
packet := msg.(*mqtt.Unsubscribe)
ack := mqtt.Unsuback{MessageID: packet.MessageID}
// Unsubscribe from each subscription
for _, sub := range packet.Topics {
c.onUnsubscribe(sub.Topic) // TODO: Handle error or just ignore?
}
// Acknowledge the unsubscription
if _, err := ack.EncodeTo(c.socket); err != nil {
return err
}
// We got an MQTT ping response, respond appropriately.
case mqtt.TypeOfPingreq:
ack := mqtt.Pingresp{}
if _, err := ack.EncodeTo(c.socket); err != nil {
return err
}
case mqtt.TypeOfDisconnect:
return nil
case mqtt.TypeOfPublish:
packet := msg.(*mqtt.Publish)
if err := c.onPublish(packet.Topic, packet.Payload); err != nil {
logging.LogError("conn", "publish received", err)
// TODO: Handle Error
}
// Acknowledge the publication
if packet.Header.QOS > 0 {
ack := mqtt.Puback{MessageID: packet.MessageID}
if _, err := ack.EncodeTo(c.socket); err != nil {
return err
}
}
}
}
}
// Send forwards the message to the underlying client.
func (c *Conn) Send(m *message.Message) error {
packet := mqtt.Publish{
Header: &mqtt.StaticHeader{
QOS: 0, // TODO when we'll support more QoS
},
MessageID: 0, // TODO
Topic: m.Channel, // The channel for this message.
Payload: m.Payload, // The payload for this message.
}
// Acknowledge the publication
_, err := packet.EncodeTo(c.socket)
if err != nil {
logging.LogError("conn", "message send", err)
return err
}
return nil
}
// Subscribe subscribes to a particular channel.
func (c *Conn) Subscribe(ssid message.Ssid, channel []byte) {
c.Lock()
defer c.Unlock()
// Add the subscription
if first := c.subs.Increment(ssid, channel); first {
// Subscribe the subscriber
c.service.onSubscribe(ssid, c)
// Broadcast the subscription within our cluster
c.service.notifySubscribe(c, ssid, channel)
}
}
// Unsubscribe unsubscribes this client from a particular channel.
func (c *Conn) Unsubscribe(ssid message.Ssid, channel []byte) {
c.Lock()
defer c.Unlock()
// Decrement the counter and if there's no more subscriptions, notify everyone.
if last := c.subs.Decrement(ssid); last {
// Unsubscribe the subscriber
c.service.onUnsubscribe(ssid, c)
// Broadcast the unsubscription within our cluster
c.service.notifyUnsubscribe(c, ssid, channel)
}
}
// Close terminates the connection.
func (c *Conn) Close() error {
logging.LogTarget("conn", "closed", c.guid)
// Unsubscribe from everything, no need to lock since each Unsubscribe is
// already locked. Locking the 'Close()' would result in a deadlock.
for _, counter := range c.subs.All() {
c.service.onUnsubscribe(counter.Ssid, c)
c.service.notifyUnsubscribe(c, counter.Ssid, counter.Channel)
}
// Attempt to recover a panic
if r := recover(); r != nil {
logging.LogAction("closing", fmt.Sprintf("pancic recovered: %s \n %s", r, debug.Stack()))
}
// Close the transport and decrement the connection counter
atomic.AddInt64(&c.service.connections, -1)
return c.socket.Close()
}