portingtools/src/server.cpp

61 lines
1.6 KiB
C++

#include "server.hpp"
#include "data.hpp"
#include "mappings.hpp"
#include "resourceloc.hpp"
#include <algorithm>
#include <boost/log/trivial.hpp>
#include <cstdlib>
#include <cstring>
#include <string>
#include <sys/ipc.h>
#include <sys/msg.h>
namespace server {
void sendToClient(int msqid, std::string msg) {
data::ResponseMapMsg pkt;
pkt.msgtype = data::clientbound_msg;
pkt.datalen = msg.size();
std::copy(msg.begin(), msg.end(), pkt.data);
if (msgsnd(msqid, &pkt, sizeof(data::ResponseMapMsg) - sizeof(long), 0) < 0) {
BOOST_LOG_TRIVIAL(error) << "failed to send response " << strerror(errno);
}
}
void run(key_t key) {
BOOST_LOG_TRIVIAL(info) << "starting server";
auto msqid = msgget(key, 0664 | IPC_CREAT);
if (msqid < 0) {
throw std::runtime_error("msgget fail");
}
BOOST_LOG_TRIVIAL(info) << "msqid " << msqid;
auto mappings = mappings::Mappings::load();
data::RequestMapMsg msg;
for (;;) {
if (msgrcv(
msqid,
&msg,
sizeof(data::RequestMapMsg) - sizeof(long),
data::serverbound_msg,
0
)
< 0) {
BOOST_LOG_TRIVIAL(error) << "receive error " << strerror(errno);
continue;
}
std::string s(msg.data, msg.datalen);
BOOST_LOG_TRIVIAL(info) << "got request to map '" << s << "'";
sendToClient(msqid, mappings.map(s));
}
}
}