lindows/lrss/main.cxx
2024-03-05 17:46:15 -05:00

104 lines
2.2 KiB
C++

#include <iostream>
#include <vector>
#include <unordered_map>
#include <sys/socket.h>
#include <sys/un.h>
#include <poll.h>
#include <signal.h>
#include <lindows/lrss.h>
class ConnectionState {
// -- general --
int socket;
public:
// -- constructors --
ConnectionState(int sock) : socket(sock) {};
};
int main() {
int tmp;
// Hi
std::cout << "Starting Lindows Registry Subsystem\n";
// Set up handshake socket (used to be used for a handshake, kept the name, sry)
struct sockaddr_un theSockAddr {
.sun_family = AF_UNIX,
.sun_path = {}
};
// Get the listening address
if (auto err = LrcSocketAddress(theSockAddr.sun_path)) {
std::cerr << "Failed to get LRSS socket address: " << err << std::endl;
return 1;
}
// Create the socket
int handshakeSocket = socket(AF_UNIX, SOCK_SEQPACKET, 0);
if (handshakeSocket < 0) {
perror("socket");
return 1;
}
// Configure the socket
tmp = 1;
if (setsockopt(handshakeSocket, SOL_SOCKET, SO_PASSCRED, &tmp, sizeof(tmp)) < 0) {
perror("setsockopt");
return 1;
}
// Bind to the socket
if (bind(handshakeSocket, reinterpret_cast<sockaddr*>(&theSockAddr), sizeof(theSockAddr)) < 0) {
perror("bind");
return 1;
}
// Listen on da socket
if (listen(handshakeSocket, 20) < 0) {
perror("listen");
return 1;
}
// Wait for LSMSS
raise(SIGSTOP);
// Main loop
std::unordered_map<int, ConnectionState> connections {};
std::vector<pollfd> pollfds {{ handshakeSocket, POLLIN, 0 }};
while (true) {
// Poll for whateversies
if (poll(pollfds.data(), pollfds.size(), -1) < 0) {
perror("poll");
return 1;
}
// First fd is our handshake socket
if (pollfds[0].revents) {
if (pollfds[0].revents & POLLIN) {
// Accept the connection and add it to our client list
int sock = accept(handshakeSocket, nullptr, nullptr);
if (sock < 0) {
perror("accept");
}
connections.emplace(sock, sock);
pollfds.emplace(pollfds.end(), sock, POLLIN | POLLHUP, 0);
}
pollfds[0].revents = 0;
}
// Iterate over client sockets
for (auto it = ++pollfds.begin(); it < pollfds.end(); it++) {
std::cout << it->fd << " " << it->revents << "\n";
it->revents = 0;
}
}
return 1;
}