maeqtt/main.go

87 lines
1.8 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() {
listen_addr := ":1883"
listener, err := net.Listen("tcp", listen_addr)
if err != nil {
2021-10-16 23:38:23 +02:00
log.Fatalf("Coulde't start a listener on tcp %v. Error: %e", listen_addr, 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 {
case con := <- connChan:
handleConnection(con, sessions, removeSessChan)
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 {
2021-10-07 22:01:52 +02:00
sess, exists := sessions[*conReq.ConnectPakcet.ClientId]
if exists {
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
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
}
}