80 lines
2.2 KiB
Go
80 lines
2.2 KiB
Go
package server
|
|
|
|
import (
|
|
"PD1/internal/protocol"
|
|
"PD1/internal/utils/cryptoUtils"
|
|
"PD1/internal/utils/networking"
|
|
)
|
|
|
|
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
|
|
}
|
|
switch pac.Flag {
|
|
case protocol.FlagGetUserCert:
|
|
reqUserCert := protocol.UnmarshalGetUserCert(pac.Body)
|
|
userCertPacket := dataStore.GetUserCertificate(reqUserCert.UID)
|
|
if active := connection.Send(userCertPacket); !active {
|
|
break F
|
|
}
|
|
case protocol.FlagGetUnreadMsgsInfo:
|
|
getUnreadMsgsInfo := protocol.UnmarshalGetUnreadMsgsInfo(pac.Body)
|
|
messages := dataStore.GetUnreadMsgsInfo(UID,getUnreadMsgsInfo.Page,getUnreadMsgsInfo.PageSize)
|
|
if !connection.Send(messages) {
|
|
break F
|
|
}
|
|
case protocol.FlagGetMsg:
|
|
reqMsg := protocol.UnmarshalGetMsg(pac.Body)
|
|
message := dataStore.GetMessage(UID, reqMsg.Num)
|
|
if active := connection.Send(message); !active {
|
|
break F
|
|
}
|
|
dataStore.MarkMessageInQueueAsRead(UID, reqMsg.Num)
|
|
case protocol.FlagSendMsg:
|
|
submitMsg := protocol.UnmarshalSendMsg(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)
|
|
}
|
|
}
|