Initial commit
[remote/remote-mci.git] / diku_mcs / HostListener.cc
blob0315a969b997b5c449dc750c3eeb500693e8a4db
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 )
28 hostfd = nextClient(fd,client);
29 if ( hostfd >= 0 )
31 log("New host connection: ");
32 if ( ! createHostByConnection(hostfd,client) )
34 log("Host connection denied!\n");
35 close(hostfd);
41 bool HostListener::createHostByConnection(int p_fd, sockaddr_in& client)
43 mysqlpp::Connection& sqlConn = dbConn.getConnection();
44 // look up the host in the database, get the host id
45 std::string ip(inet_ntoa(client.sin_addr));
46 log("Looking up ip %s in host list\n",ip.c_str());
47 mysqlpp::ResUse res;
48 mysqlpp::Row row;
49 mysqlpp::Query query = sqlConn.query();
50 query << "select id from host where ip='%0:ip'";
51 query.parse();
52 query.def["ip"] = ip;
54 res = query.use();
55 res.disable_exceptions();
56 row = res.fetch_row();
57 if ( row && !row.empty() )
59 dbkey_t host_id = (dbkey_t)(row["id"]);
60 hostmapbykey_t::iterator i = hosts.find(host_id);
61 if (i==hosts.end())
63 new Host(p_fd,host_id,ip,hosts);
64 return true;
66 else
68 // only one connection per host, deny connection
69 return false;
72 else
74 // if the host was not found in the database, deny host connection
75 return false;
79 void HostListener::deleteAllHosts()
81 hostmapbykey_t::iterator hI;
83 for ( hI = hosts.begin(); hI != hosts.end(); hI++ )
85 hI->second->destroy(true);