summaryrefslogtreecommitdiffstats
path: root/src/Server/ConnectionManager.cpp
blob: a15a5161e9637410d84077bff584ffd57e9976a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/*
 * ConnectionManager.cpp
 *
 * Copyright (C) 2008 Matthias Schiffer <matthias@gamezock.de>
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "ConnectionManager.h"
#include <Core/ConfigEntry.h>
#include <Core/ConfigManager.h>
#include <Core/Logger.h>
#include <Common/RequestHandlers/FSInfoRequestHandler.h>
#include <Common/RequestHandlers/StatusRequestHandler.h>
#include "Requests/DaemonStateUpdateRequest.h"
#include "RequestHandlers/DaemonListRequestHandler.h"
//#include "RequestHandlers/GSSAPIAuthRequestHandler.h"
#include "RequestHandlers/IdentifyRequestHandler.h"
#include "RequestHandlers/LogRequestHandler.h"
#include "RequestHandlers/DaemonRequestHandlerGroup.h"
#include "RequestHandlers/UserRequestHandlerGroup.h"
#include <Net/Packet.h>
#include <Net/Listener.h>

#include <unistd.h>
#include <algorithm>

namespace Mad {
namespace Server {

ConnectionManager ConnectionManager::connectionManager;

bool ConnectionManager::ServerConnection::send(const Net::Packet &packet) {
  return connection->send(packet);
}

ConnectionManager::ServerConnection::ServerConnection(boost::shared_ptr<Net::Connection> connection0)
: connection(connection0), type(UNKNOWN), hostInfo(0) {
  connection->connectSignalReceive(boost::bind(&ServerConnection::receive, this, _1));
}

bool ConnectionManager::ServerConnection::isConnected() const {
  return connection->isConnected();
}

bool ConnectionManager::ServerConnection::disconnect() {
  connection->disconnect();

  return true;
}

/*void* ConnectionManager::ServerConnection::getCertificate(size_t *size) const {
  const gnutls_datum_t *cert = connection->getCertificate();

  *size = cert->size;
  return cert->data;
}

void* ConnectionManager::ServerConnection::getPeerCertificate(size_t *size) const {
  const gnutls_datum_t *cert = connection->getPeerCertificate();

  *size = cert->size;
  return cert->data;
}*/

void ConnectionManager::updateState(Common::HostInfo *hostInfo, Common::HostInfo::State state) {
  hostInfo->setState(state);


  for(std::set<boost::shared_ptr<ServerConnection> >::iterator con = connections.begin(); con != connections.end(); ++con) {
    if((*con)->getConnectionType() == ServerConnection::CLIENT) {
      boost::shared_ptr<Requests::DaemonStateUpdateRequest> request(new Requests::DaemonStateUpdateRequest(hostInfo->getName(), state));
      Common::RequestManager::get()->sendRequest(con->get(), request);
    }
  }
}

bool ConnectionManager::handleConfigEntry(const Core::ConfigEntry &entry, bool handled) {
  if(handled)
    return false;

  if(entry[0].getKey().matches("Listen") && entry[1].empty()) {
    try {
      listenerAddresses.push_back(boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string(entry[0][0]), 6666));
    }
    catch(Core::Exception &e) {
      // TODO Log error
    }

    return true;
  }
  else if(entry[0].getKey().matches("X509TrustFile") && entry[1].empty()) {
    x509TrustFile = entry[0][0];

    return true;
  }
  else if(entry[0].getKey().matches("X509CrlFile") && entry[1].empty()) {
    x509CrlFile = entry[0][0];

    return true;
  }
  else if(entry[0].getKey().matches("X509CertFile") && entry[1].empty()) {
    x509CertFile = entry[0][0];

    return true;
  }
  else if(entry[0].getKey().matches("X509KeyFile") && entry[1].empty()) {
    x509KeyFile = entry[0][0];

    return true;
  }
  else if(entry[0].getKey().matches("Daemon")) {
    if(entry[0].getSize() == 1) {
      if(entry[1].empty()) {
        daemonInfo.insert(std::make_pair(entry[0][0], Common::HostInfo(entry[0][0])));

        return true;
      }
      else if(entry[1].getKey().matches("IpAddress") && entry[2].empty()) {
        daemonInfo[entry[0][0]].setIP(entry[1][0]);

        return true;
      }
    }
  }

  return false;
}

void ConnectionManager::configFinished() {
  if(listenerAddresses.empty()) {
    try {
      boost::shared_ptr<Net::Listener> listener(new Net::Listener(x509CertFile, x509KeyFile));
      listener->connectSignalNewConnection(boost::bind(&ConnectionManager::handleNewConnection, this, _1));
      listeners.push_back(listener);
    }
    catch(Core::Exception &e) {
      // TODO Log error
    }
  }
  else {
    for(std::vector<boost::asio::ip::tcp::endpoint>::const_iterator address = listenerAddresses.begin(); address != listenerAddresses.end(); ++address) {
      try {
        boost::shared_ptr<Net::Listener> listener(new Net::Listener(x509CertFile, x509KeyFile, *address));
        listener->connectSignalNewConnection(boost::bind(&ConnectionManager::handleNewConnection, this, _1));
        listeners.push_back(listener);
      }
      catch(Core::Exception &e) {
        // TODO Log error
      }
    }
  }
}

void ConnectionManager::handleNewConnection(boost::shared_ptr<Net::Connection> con) {
  boost::shared_ptr<ServerConnection> connection(new ServerConnection(con));
  con->connectSignalDisconnected(boost::bind(&ConnectionManager::handleDisconnect, this, connection));
  connections.insert(connection);

  Common::RequestManager::get()->registerConnection(connection.get());
}

void ConnectionManager::handleDisconnect(boost::shared_ptr<ServerConnection> con) {
  if(con->getHostInfo())
    updateState(con->getHostInfo(), Common::HostInfo::INACTIVE);

  connections.erase(con);

  Common::RequestManager::get()->unregisterConnection(con.get());
}

void ConnectionManager::doInit() {
  Common::RequestManager::get()->setServer(true);

  daemonRequestHandlerGroup.reset(new RequestHandlers::DaemonRequestHandlerGroup);
  userRequestHandlerGroup.reset(new RequestHandlers::UserRequestHandlerGroup);

  //Common::RequestManager::get()->registerPacketType<RequestHandlers::GSSAPIAuthRequestHandler>("AuthGSSAPI");
  //Common::RequestManager::get()->registerPacketType<RequestHandlers::DaemonCommandRequestHandler>("DaemonCommand");
  //Common::RequestManager::get()->registerPacketType<RequestHandlers::DaemonFSInfoRequestHandler>("DaemonFSInfo");
  Common::RequestManager::get()->registerPacketType<Common::RequestHandlers::FSInfoRequestHandler>("FSInfo");
  Common::RequestManager::get()->registerPacketType<Common::RequestHandlers::StatusRequestHandler>("GetStatus");
  //Common::RequestManager::get()->registerPacketType<RequestHandlers::DaemonStatusRequestHandler>("GetDaemonStatus");
  Common::RequestManager::get()->registerPacketType<RequestHandlers::IdentifyRequestHandler>("Identify");
  Common::RequestManager::get()->registerPacketType<RequestHandlers::DaemonListRequestHandler>("ListHosts");
  Common::RequestManager::get()->registerPacketType<RequestHandlers::LogRequestHandler>("Log");

  Common::RequestManager::get()->registerRequestHandlerGroup(daemonRequestHandlerGroup);
  Common::RequestManager::get()->registerRequestHandlerGroup(userRequestHandlerGroup);
}

void ConnectionManager::doDeinit() {
  connections.clear();

  Common::RequestManager::get()->unregisterRequestHandlerGroup(userRequestHandlerGroup);
  Common::RequestManager::get()->unregisterRequestHandlerGroup(daemonRequestHandlerGroup);

  //Common::RequestManager::get()->unregisterPacketType("AuthGSSAPI");
  //Common::RequestManager::get()->unregisterPacketType("DaemonCommand");
  //Common::RequestManager::get()->unregisterPacketType("DaemonFSInfo");
  Common::RequestManager::get()->unregisterPacketType("FSInfo");
  Common::RequestManager::get()->unregisterPacketType("GetStatus");
  //Common::RequestManager::get()->unregisterPacketType("GetDaemonStatus");
  Common::RequestManager::get()->unregisterPacketType("Identify");
  Common::RequestManager::get()->unregisterPacketType("ListHosts");
  Common::RequestManager::get()->unregisterPacketType("Log");
}

boost::shared_ptr<Common::Connection> ConnectionManager::getDaemonConnection(const std::string &name) const throw (Core::Exception&) {
  const Common::HostInfo *hostInfo;

  try {
    hostInfo = &daemonInfo.at(name);
  }
  catch(std::out_of_range&) {
    throw Core::Exception(Core::Exception::UNKNOWN_DAEMON);
  }

  if(hostInfo->getState() != Common::HostInfo::INACTIVE) {
    for(std::set<boost::shared_ptr<ServerConnection> >::const_iterator it = connections.begin(); it != connections.end(); ++it) {
      if((*it)->getHostInfo() == hostInfo) {
        return *it;
      }
    }
  }

  throw Core::Exception(Core::Exception::NOT_AVAILABLE);
}

std::string ConnectionManager::getDaemonName(const Common::Connection *con) const throw (Core::Exception&) {
  const ServerConnection *connection = dynamic_cast<const ServerConnection*>(con);

  if(connection && connection->getConnectionType() == ServerConnection::DAEMON)
    return connection->getHostInfo()->getName();

  throw Core::Exception(Core::Exception::UNKNOWN_DAEMON);
}

void ConnectionManager::identifyDaemonConnection(Common::Connection *con, const std::string &name) throw (Core::Exception&) {
  // TODO Logging

  ServerConnection *connection = dynamic_cast<ServerConnection*>(con);

  if(!connection)
    throw Core::Exception(Core::Exception::INVALID_ACTION);

  if(connection->isIdentified())
    throw Core::Exception(Core::Exception::ALREADY_IDENTIFIED);

  if(daemonInfo.count(name) == 0)
    throw Core::Exception(Core::Exception::UNKNOWN_DAEMON);

  Common::HostInfo *hostInfo = &daemonInfo[name];

  if(hostInfo->getState() != Common::HostInfo::INACTIVE) {
    try {
      getDaemonConnection(name)->disconnect();
      Core::Logger::log(Core::Logger::WARNING, "Disconnecting old connection.");
    }
    catch(Core::Exception&) {}
  }

  connection->identify(hostInfo);
  updateState(hostInfo, Common::HostInfo::RUNNING);

  Core::Logger::logf("Identified as '%s'.", name.c_str());
}

void ConnectionManager::identifyClientConnection(Common::Connection *con) throw (Core::Exception&) {
  ServerConnection *connection = dynamic_cast<ServerConnection*>(con);

  if(!connection)
    throw Core::Exception(Core::Exception::INVALID_ACTION);

  if(connection->isIdentified())
    throw Core::Exception(Core::Exception::ALREADY_IDENTIFIED);

  connection->identify();
}

std::vector<Common::HostInfo> ConnectionManager::getDaemonList() const {
  std::vector<Common::HostInfo> ret;

  for(std::map<std::string,Common::HostInfo>::const_iterator daemon = daemonInfo.begin(); daemon != daemonInfo.end(); ++daemon) {
    ret.push_back(daemon->second);
  }

  return ret;
}

}
}