maeqtt/session/session.go

246 lines
6.1 KiB
Go
Raw Normal View History

2021-10-01 22:18:48 +02:00
package session
2021-09-28 12:30:32 +02:00
import (
"encoding/base64"
"fmt"
2021-10-01 22:18:48 +02:00
"io"
2021-09-28 12:30:32 +02:00
"log"
"math/rand"
"time"
"badat.dev/maeqtt/v2/mqtt/packets"
2021-10-01 22:18:48 +02:00
"badat.dev/maeqtt/v2/subscription"
2021-09-28 12:30:32 +02:00
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func Auth(username string, password []byte) bool {
return true
}
type Session struct {
ClientID *string
// Nullable
Connection *Connection
SubscriptionChannel chan packets.PublishPacket
2021-10-08 22:45:39 +02:00
ConnecionChannel chan ConnectionRequest
2021-09-28 12:30:32 +02:00
2021-10-01 22:18:48 +02:00
ExpiryInterval time.Duration // TODO
expireTimer time.Timer // TODO
freePacketID uint16
2021-09-28 12:30:32 +02:00
}
2021-10-07 22:01:52 +02:00
type ConnectionRequest struct {
2021-10-08 22:45:39 +02:00
Connection *Connection
2021-10-07 22:01:52 +02:00
ConnectPakcet packets.ConnectPacket
}
func NewSession(req ConnectionRequest) Session {
2021-09-28 12:30:32 +02:00
sess := Session{}
sess.SubscriptionChannel = make(chan packets.PublishPacket)
2021-10-07 22:01:52 +02:00
sess.Connect(req)
2021-09-28 12:30:32 +02:00
return sess
}
2021-10-07 22:01:52 +02:00
func (s *Session) Connect(req ConnectionRequest) {
2021-09-28 12:30:32 +02:00
if s.Connection != nil {
2021-10-01 22:18:48 +02:00
s.Disconnect(packets.DisconnectReasonCodeSessionTakenOver)
2021-09-28 12:30:32 +02:00
}
connAck := packets.ConnackPacket{}
2021-10-07 22:01:52 +02:00
s.updateExpireTimer(req.ConnectPakcet.Properties.SessionExpiryInterval.Value)
2021-09-28 12:30:32 +02:00
2021-10-16 22:44:14 +02:00
if req.ConnectPakcet.ClientId == nil {
2021-09-28 12:30:32 +02:00
if s.ClientID == nil {
s.ClientID = genClientID()
}
connAck.Properties.AssignedClientIdentifier.Value = s.ClientID
2021-10-16 22:44:14 +02:00
} else if s.ClientID != nil && s.ClientID != req.ConnectPakcet.ClientId {
panic(fmt.Errorf("Session %s connect called with a connect packet with an ID: %s", *s.ClientID, *req.ConnectPakcet.ClientId))
} else {
s.ClientID = req.ConnectPakcet.ClientId
2021-09-28 12:30:32 +02:00
}
true := byte(1)
false := byte(0)
connAck.Properties.WildcardSubscriptionAvailable.Value = &true
connAck.Properties.RetainAvailable.Value = &false
connAck.Properties.SharedSubscriptionAvailable.Value = &false
2021-10-07 22:01:52 +02:00
s.Connection = req.Connection
2021-09-28 12:30:32 +02:00
err := s.Connection.sendPacket(connAck)
if err != nil {
2021-10-07 22:01:52 +02:00
// TODO
2021-09-28 12:30:32 +02:00
panic(err)
}
}
// Starts a loop the recieves and responds to packets
func (s *Session) HandlerLoop() {
2021-10-07 22:01:52 +02:00
go s.Connection.PacketReadLoop()
2021-09-28 12:30:32 +02:00
for s.Connection != nil {
select {
case packet := <-s.Connection.PacketChannel:
packet.Visit(s)
case _ = <-s.Connection.ClientDisconnectedChan:
2021-10-01 22:18:48 +02:00
s.onDisconnect()
2021-10-07 22:01:52 +02:00
case c := <-s.ConnecionChannel:
s.Connect(c)
2021-09-28 12:30:32 +02:00
case subMessage := <-s.SubscriptionChannel:
2021-10-08 22:45:39 +02:00
subMessage.QOSLevel = 0
subMessage.Dup = false
s.Connection.sendPacket(subMessage)
2021-09-28 12:30:32 +02:00
}
}
2021-10-08 22:44:02 +02:00
c := <-s.ConnecionChannel
s.Connect(c)
s.HandlerLoop()
2021-09-28 12:30:32 +02:00
}
2021-10-01 22:18:48 +02:00
func (s *Session) Disconnect(code packets.DisconnectReasonCode) error {
s.Connection.sendPacket(packets.DisconnectPacket{
ReasonCode: code,
})
2021-09-28 12:30:32 +02:00
err := s.Connection.close()
if err != nil {
return err
}
2021-10-01 22:18:48 +02:00
s.onDisconnect()
2021-09-28 12:30:32 +02:00
return nil
}
2021-10-01 22:18:48 +02:00
func (s *Session) onDisconnect() {
2021-09-28 12:30:32 +02:00
s.Connection = nil
s.resetExpireTimer()
log.Printf("Client disconnected, id: %s", *s.ClientID)
}
2021-10-01 22:18:48 +02:00
func (s *Session) expireSession() {
subscription.Subscriptions.RemoveSubsForChannel(s.SubscriptionChannel)
}
2021-09-28 12:30:32 +02:00
// newTime is nullable
func (s *Session) updateExpireTimer(newTime *uint32) {
var expiry = uint32(0)
if newTime != nil {
expiry = *newTime
} else {
expiry = uint32(0)
}
s.ExpiryInterval = time.Duration(expiry) * time.Second
if s.Connection == nil {
s.resetExpireTimer()
}
}
func (s *Session) resetExpireTimer() {
//s.expireTimer.Reset(s.ExpiryInterval)
}
func genClientID() *string {
buf := make([]byte, 32)
_, err := rand.Read(buf)
if err != nil {
// I don't think this can actually happen but just in case panic
panic(fmt.Errorf("Failed to generate a client id, %e", err))
}
id := "Client_rand_" + base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(buf)
return &id
}
func (s *Session) VisitConnect(_ packets.ConnectPacket) {
2021-10-01 22:18:48 +02:00
// Disconnect, we handle the connect packet in Connect,
// this means that we have an estabilished connection already
log.Println("WARN: Got a connect packet on an already estabilished connection")
s.Disconnect(packets.DisconnectReasonCodeProtocolError)
2021-09-28 12:30:32 +02:00
}
func (s *Session) VisitPublish(p packets.PublishPacket) {
2021-10-08 23:53:37 +02:00
subNodes := subscription.Subscriptions.GetSubscriptions(p.TopicName)
for _, subNode := range subNodes {
subNode.NodeLock.RLock()
defer subNode.NodeLock.RUnlock()
if p.QOSLevel == 0 {
if p.PacketId != nil {
log.Printf("Client: %v, Got publish with qos 0 and a packet id, ignoring\n", s.ClientID)
return
}
} else if p.QOSLevel == 1 {
var reason packets.PubackReasonCode = packets.PubackReasonCodeSuccess
ack := packets.PubackPacket{
PacketID: *p.PacketId,
Reason: reason,
}
s.Connection.sendPacket(ack)
} else if p.QOSLevel == 2 {
panic("UNIMPLEMENTED QOS level 2")
2021-10-01 22:18:48 +02:00
}
2021-09-28 12:30:32 +02:00
2021-10-08 23:53:37 +02:00
for _, sub := range subNode.Subscriptions {
if !(sub.NoLocal && sub.SubscriptionChannel == s.SubscriptionChannel) {
go func(sub subscription.Subscription) { sub.SubscriptionChannel <- p }(sub)
}
2021-10-01 22:18:48 +02:00
}
2021-09-28 12:30:32 +02:00
}
}
func (s *Session) VisitDisconnect(p packets.DisconnectPacket) {
2021-10-01 22:18:48 +02:00
err := s.Connection.close()
if err != nil && err != io.ErrClosedPipe {
log.Println("Error closing connection", err)
}
s.onDisconnect()
2021-09-28 12:30:32 +02:00
}
func (s *Session) VisitSubscribe(p packets.SubscribePacket) {
for _, filter := range p.TopicFilters {
2021-10-01 22:18:48 +02:00
subscription.Subscriptions.Subscribe(filter, s.SubscriptionChannel)
2021-09-28 12:30:32 +02:00
}
2021-10-01 22:18:48 +02:00
s.Connection.sendPacket(packets.SubAckPacket{
PacketID: p.PacketId,
Reason: packets.SubackReasonGrantedQoSTwo,
})
2021-09-28 12:30:32 +02:00
}
2021-10-01 22:18:48 +02:00
func (s *Session) VisitUnsubscribe(p packets.UnsubscribePacket) {
for _, topic := range p.Topics {
subscription.Subscriptions.Unsubscribe(topic, s.SubscriptionChannel)
}
s.Connection.sendPacket(packets.UnsubAckPacket{
PacketID: p.PacketID,
Reason: packets.UnsubackReasonSuccess,
})
2021-09-28 12:30:32 +02:00
}
func (s *Session) VisitPing(p packets.PingreqPacket) {
s.Connection.sendPacket(packets.PingrespPacket{})
}
func (s *Session) VisitPubackPacket(_ packets.PubackPacket) {
panic("not implemented") // TODO: Implement
}
func (s *Session) VisitPubrecPacket(_ packets.PubrecPacket) {
panic("not implemented") // TODO: Implement
}
func (s *Session) VisitPubrelPacket(_ packets.PubrelPacket) {
panic("not implemented") // TODO: Implement
}
func (s *Session) VisitPubcompPacket(_ packets.PubcompPacket) {
panic("not implemented") // TODO: Implement
}
2021-10-01 22:18:48 +02:00
func (s *Session) getFreePacketId() uint16 {
s.freePacketID += 1
return s.freePacketID
}