CSI-ES-2324/Projs/PD1/internal/server/server.go
2024-04-20 00:55:16 +01:00

84 lines
2.3 KiB
Go

package server
import (
"PD1/internal/protocol"
"PD1/internal/utils/cryptoUtils"
"PD1/internal/utils/networking"
"fmt"
)
func clientHandler(connection networking.Connection[protocol.Packet], dataStore DataStore) {
defer connection.Conn.Close()
//Get certificate sent by user
clientCert := connection.GetPeerCertificate()
//Get the OID values
oidMap := cryptoUtils.ExtractAllOIDValues(clientCert)
//Get the UID of this user
UID := oidMap["2.5.4.65"]
if UID == "" {
panic("User certificate does not specify it's PSEUDONYM")
}
dataStore.storeUserCertIfNotExists(UID, *clientCert)
F:
for {
pac, active := connection.Receive()
if !active {
break F
}
switch pac.Flag {
case protocol.ReqUserCertPkt:
reqUserCert := protocol.UnmarshalRequestUserCertPacket(pac.Body)
userCertPacket := dataStore.GetUserCertificate(reqUserCert.UID)
if active := connection.Send(userCertPacket); !active {
break F
}
case protocol.ReqMsgsQueue:
_ = protocol.UnmarshalRequestMsgsQueuePacket(pac.Body)
messages := dataStore.GetUnreadMessagesInfoQueue(UID)
fmt.Printf("Number of unread messages by user %v is %v\n",UID,len(messages))
for _, message := range messages {
if !connection.Send(message) {
break
}
}
case protocol.ReqMsgPkt:
reqMsg := protocol.UnmarshalRequestMsgPacket(pac.Body)
message := dataStore.GetMessage(UID, reqMsg.Num)
if active := connection.Send(message); !active {
break F
}
dataStore.MarkMessageInQueueAsRead(UID, reqMsg.Num)
case protocol.SubmitMsgPkt:
submitMsg := protocol.UnmarshalSubmitMessagePacket(pac.Body)
if submitMsg.ToUID != UID && dataStore.userExists(submitMsg.ToUID) {
dataStore.AddMessageToQueue(UID, submitMsg)
}
}
}
}
func Run(port int) {
//Open connection to DB
dataStore := OpenDB()
defer dataStore.db.Close()
//FIX: Get the server's keystore path instead of hardcoding it
//Read server keystore
password := AskServerPassword()
serverKeyStore := cryptoUtils.LoadKeyStore("certs/server/server.p12", password)
//Create server listener
server := networking.NewServer[protocol.Packet](&serverKeyStore, port)
go server.ListenLoop()
for {
//Receive Connection via channel
conn := <-server.C
//Launch client handler via clientHandler
go clientHandler(conn, dataStore)
}
}