MoteHost: Improve error checking when daemonizing
[remote/remote-mci.git] / diku_mcs / HostListener.cc
blob1416f9ccd2e1de7cd75997128fd9eb180596b480
1 #include "HostListener.h"
3 namespace remote { namespace diku_mcs {
5 HostListener::HostListener(unsigned int port)
6 : FileDescriptor(
7 openServerSocket( server,
8 port,
9 5,
10 5 )),
11 hosts()
13 log("Listening for host connections on port %u.\n",port);
16 HostListener::~HostListener()
18 deleteAllHosts();
21 void HostListener::handleEvent(short events)
23 struct sockaddr_in client;
24 int hostfd;
26 if (events & POLLIN || events & POLLPRI) {
27 hostfd = nextClient(fd, client);
28 if (hostfd >= 0) {
29 log("New host connection\n");
30 if (!createHostByConnection(hostfd,client)) {
31 log("Host connection denied!\n");
32 close(hostfd);
38 bool HostListener::createHostByConnection(int p_fd, sockaddr_in& client)
40 mysqlpp::Connection& sqlConn = dbConn.getConnection();
41 // look up the host in the database, get the host id
42 std::string ip(inet_ntoa(client.sin_addr));
43 log("Looking up ip %s in host list\n", ip.c_str());
44 mysqlpp::ResUse res;
45 mysqlpp::Row row;
46 mysqlpp::Query query = sqlConn.query();
48 query << "select id from host where ip = " << mysqlpp::quote << ip;
50 res = query.use();
51 res.disable_exceptions();
52 row = res.fetch_row();
53 if (row && !row.empty()) {
54 dbkey_t host_id = (dbkey_t) (row["id"]);
55 hostmapbykey_t::iterator i = hosts.find(host_id);
56 if (i == hosts.end()) {
57 new Host(p_fd, host_id, ip, hosts);
58 return true;
60 } else {
61 // only one connection per host, deny connection
62 return false;
65 } else {
66 // if the host was not found in the database, deny host connection
67 return false;
71 void HostListener::deleteAllHosts()
73 hostmapbykey_t::iterator hI;
75 for (hI = hosts.begin(); hI != hosts.end(); hI++) {
76 hI->second->destroy(true);