maeqtt/main.go

91 lines
1.9 KiB
Go
Raw Normal View History

2021-08-26 15:08:24 +02:00
package main
import (
"log"
"net"
2021-09-28 12:30:32 +02:00
"runtime/debug"
2021-08-26 15:08:24 +02:00
"badat.dev/maeqtt/v2/mqtt/packets"
2021-10-01 22:18:48 +02:00
"badat.dev/maeqtt/v2/session"
2021-08-26 15:08:24 +02:00
)
func main() {
2021-10-17 20:58:16 +02:00
listenAddr := ":1883"
listener, err := net.Listen("tcp", listenAddr)
2021-08-26 15:08:24 +02:00
if err != nil {
2021-10-17 20:58:16 +02:00
log.Fatalf("Coulde't start a listener on tcp %v. Error: %e", listenAddr, err)
2021-08-26 15:08:24 +02:00
}
2021-10-07 22:01:52 +02:00
var sessions map[string]*session.Session = make(map[string]*session.Session)
2021-10-16 23:38:23 +02:00
removeSessChan := make(session.RemoveSessionChannel)
connChan := make(chan net.Conn)
go func() {
for {
conn, err := listener.Accept()
if err != nil {
log.Println("Failed accepting connection ", err)
} else {
connChan <- conn
}
}
}()
2021-10-07 22:01:52 +02:00
2021-08-26 15:08:24 +02:00
for {
2021-10-16 23:38:23 +02:00
select {
2021-10-17 20:58:16 +02:00
case con := <-connChan:
2021-10-16 23:38:23 +02:00
handleConnection(con, sessions, removeSessChan)
2021-10-17 20:58:16 +02:00
case sesID := <-removeSessChan:
delete(sessions, sesID)
2021-08-26 15:08:24 +02:00
}
}
}
2021-10-16 23:38:23 +02:00
func handleConnection(con net.Conn, sessions map[string]*session.Session, rmSessChan session.RemoveSessionChannel) {
2021-10-01 22:18:48 +02:00
defer handlePanic(con)
2021-08-26 15:08:24 +02:00
2021-10-07 22:01:52 +02:00
conReq, err := session.NewConnection(con)
2021-09-28 12:30:32 +02:00
if err != nil {
2021-10-16 23:38:23 +02:00
log.Println("Failed to create connection ", err)
return
2021-09-28 12:30:32 +02:00
}
2021-10-07 22:01:52 +02:00
var sess *session.Session
2021-10-08 22:45:39 +02:00
if conReq.ConnectPakcet.ClientId != nil {
exists := false
sess, exists = sessions[*conReq.ConnectPakcet.ClientId]
2021-10-07 22:01:52 +02:00
if exists {
log.Printf("Resuming session %v", *sess.ClientID)
2021-10-07 22:01:52 +02:00
sess.ConnecionChannel <- conReq
2021-10-01 22:18:48 +02:00
}
2021-08-26 15:08:24 +02:00
}
2021-10-07 22:01:52 +02:00
if sess == nil {
2021-10-16 23:38:23 +02:00
newSess := session.NewSession(conReq, rmSessChan)
2021-10-07 22:01:52 +02:00
sess = &newSess
sessions[*sess.ClientID] = sess
log.Printf("New session %v", *sess.ClientID)
2021-10-07 22:01:52 +02:00
go func() {
defer handlePanic(con)
sess.HandlerLoop()
}()
}
2021-08-26 15:08:24 +02:00
}
2021-10-01 22:18:48 +02:00
func handlePanic(con net.Conn) {
2021-09-28 12:30:32 +02:00
if r := recover(); r != nil {
log.Println("Recovering from panic:", r)
log.Println("Stack Trace:")
debug.PrintStack()
2021-10-01 22:18:48 +02:00
err := packets.DisconnectPacket{
ReasonCode: packets.DisconnectReasonCodeImplErorr,
}.Write(con)
if err != nil {
log.Println("Failed to send a disconnect packet after recovering from panic", err)
}
2021-08-26 15:08:24 +02:00
}
}