maeqtt/main.go

72 lines
1.4 KiB
Go
Raw Normal View History

2021-08-26 15:08:24 +02:00
package main
import (
"bufio"
"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 {
log.Fatal(err)
}
for {
conn, err := listener.Accept()
if err != nil {
log.Println("Failed accepting connection ", err)
}
go handleConnection(conn)
}
}
func handleConnection(con net.Conn) {
2021-10-01 22:18:48 +02:00
defer handlePanic(con)
2021-08-26 15:08:24 +02:00
2021-09-28 12:30:32 +02:00
reader := bufio.NewReader(con)
packet, err := packets.ReadPacket(reader)
if err != nil {
log.Println("Error reading packet ", err)
return
}
connect, isConn := (*packet).(packets.ConnectPacket)
if !isConn {
2021-10-01 22:18:48 +02:00
log.Println("Didn't recieve a connect packet")
err := packets.DisconnectPacket{
ReasonCode: packets.DisconnectReasonCodeProtocolError,
}.Write(con)
if err != nil {
log.Println("Failed to disconnect after not recieving a connect packet", err)
}
return
2021-08-26 15:08:24 +02:00
}
2021-10-01 22:18:48 +02:00
conn := session.NewConnection(connect, con)
sess := session.NewSession(&conn, connect)
2021-09-28 12:30:32 +02:00
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
}
}