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 {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
2021-10-07 22:01:52 +02:00
|
|
|
var sessions map[string]*session.Session = make(map[string]*session.Session)
|
|
|
|
|
2021-08-26 15:08:24 +02:00
|
|
|
for {
|
|
|
|
conn, err := listener.Accept()
|
|
|
|
if err != nil {
|
|
|
|
log.Println("Failed accepting connection ", err)
|
|
|
|
}
|
2021-10-07 22:01:52 +02:00
|
|
|
handleConnection(conn, sessions)
|
2021-08-26 15:08:24 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-07 22:01:52 +02:00
|
|
|
func handleConnection(con net.Conn, sessions map[string]*session.Session) {
|
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-07 22:01:52 +02:00
|
|
|
// TODO
|
|
|
|
panic(err)
|
2021-09-28 12:30:32 +02:00
|
|
|
}
|
2021-10-07 22:01:52 +02:00
|
|
|
|
|
|
|
var sess *session.Session
|
|
|
|
if(conReq.ConnectPakcet.ClientId != nil) {
|
|
|
|
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 {
|
|
|
|
newSess := session.NewSession(conReq)
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|