Checkpoint. Code does not run. Still converting over to new

event loop model.  Streams, stream filters, and sockets are
converted.  Client proxies are almost converted.  CServer is
in progress.  Removed all HTTP code.  Haven't converted the
necessary win32 arch stuff.
This commit is contained in:
crs
2004-02-01 21:09:22 +00:00
parent 618aa7fedd
commit 848aee7a3a
64 changed files with 2581 additions and 2942 deletions

View File

@@ -13,27 +13,24 @@
*/
#include "CClientProxy.h"
#include "IInputStream.h"
#include "IOutputStream.h"
#include "IStream.h"
//
// CClientProxy
//
CClientProxy::CClientProxy(IServer* server, const CString& name,
IInputStream* input, IOutputStream* output) :
CClientProxy::CClientProxy(IServer* server,
const CString& name, IStream* stream) :
m_server(server),
m_name(name),
m_input(input),
m_output(output)
m_stream(stream)
{
// do nothing
}
CClientProxy::~CClientProxy()
{
delete m_output;
delete m_input;
delete m_stream;
}
IServer*
@@ -42,16 +39,10 @@ CClientProxy::getServer() const
return m_server;
}
IInputStream*
CClientProxy::getInputStream() const
IStream*
CClientProxy::getStream() const
{
return m_input;
}
IOutputStream*
CClientProxy::getOutputStream() const
{
return m_output;
return m_stream;
}
CString

View File

@@ -19,8 +19,7 @@
#include "CMutex.h"
#include "CString.h"
class IInputStream;
class IOutputStream;
class IStream;
class IServer;
//! Generic proxy for client
@@ -29,9 +28,7 @@ public:
/*!
\c name is the name of the client.
*/
CClientProxy(IServer* server, const CString& name,
IInputStream* adoptedInput,
IOutputStream* adoptedOutput);
CClientProxy(IServer* server, const CString& name, IStream* adoptedStream);
~CClientProxy();
//! @name accessors
@@ -43,17 +40,11 @@ public:
*/
IServer* getServer() const;
//! Get input stream
//! Get stream
/*!
Returns the input stream passed to the c'tor.
Returns the stream passed to the c'tor.
*/
IInputStream* getInputStream() const;
//! Get output stream
/*!
Returns the output stream passed to the c'tor.
*/
IOutputStream* getOutputStream() const;
IStream* getStream() const;
//@}
@@ -98,8 +89,7 @@ private:
CMutex m_mutex;
IServer* m_server;
CString m_name;
IInputStream* m_input;
IOutputStream* m_output;
IStream* m_stream;
};
#endif

View File

@@ -17,46 +17,189 @@
#include "CClipboard.h"
#include "CProtocolUtil.h"
#include "XSynergy.h"
#include "IInputStream.h"
#include "IOutputStream.h"
#include "IStream.h"
#include "CLock.h"
#include "CThread.h"
#include "CLog.h"
#include "CStopwatch.h"
#include "IEventQueue.h"
#include "TMethodEventJob.h"
#include <cstring>
//
// CClientProxy1_0
//
CClientProxy1_0::CClientProxy1_0(IServer* server, const CString& name,
IInputStream* input, IOutputStream* output) :
CClientProxy(server, name, input, output),
m_heartRate(kHeartRate),
m_heartDeath(kHeartRate * kHeartBeatsUntilDeath)
CClientProxy1_0::CClientProxy1_0(IServer* server,
const CString& name, IStream* stream) :
CClientProxy(server, name, stream),
m_heartbeatAlarm(kHeartRate * kHeartBeatsUntilDeath),
m_heartbeatTimer(NULL)
{
for (UInt32 i = 0; i < kClipboardEnd; ++i) {
m_clipboardDirty[i] = true;
}
// install event handlers
EVENTQUEUE->adoptHandler(IStream::getInputReadyEvent(),
stream->getEventTarget(),
new TMethodEventJob<CClientProxy1_0>(this,
&CClientProxy1_0::handleData, NULL));
EVENTQUEUE->adoptHandler(IStream::getOutputErrorEvent(),
stream->getEventTarget(),
new TMethodEventJob<CClientProxy1_0>(this,
&CClientProxy1_0::handleWriteError, NULL));
EVENTQUEUE->adoptHandler(IStream::getInputShutdownEvent(),
stream->getEventTarget(),
new TMethodEventJob<CClientProxy1_0>(this,
&CClientProxy1_0::handleDisconnect, NULL));
EVENTQUEUE->adoptHandler(IStream::getOutputShutdownEvent(),
stream->getEventTarget(),
new TMethodEventJob<CClientProxy1_0>(this,
&CClientProxy1_0::handleWriteError, NULL));
EVENTQUEUE->adoptHandler(CEvent::kTimer, this,
new TMethodEventJob<CClientProxy1_0>(this,
&CClientProxy1_0::handleFlatline, NULL));
// FIXME -- open() replacement must install initial heartbeat timer
}
CClientProxy1_0::~CClientProxy1_0()
{
// do nothing
removeHandlers();
}
void
CClientProxy1_0::disconnect()
{
CLock lock(getMutex());
removeHandlers();
// FIXME -- send disconnect event (server should be listening for this)
getStream()->flush();
getStream()->close();
}
void
CClientProxy1_0::removeHandlers()
{
// uninstall event handlers
EVENTQUEUE->removeHandler(IStream::getInputReadyEvent(),
getStream()->getEventTarget());
EVENTQUEUE->removeHandler(IStream::getOutputErrorEvent(),
getStream()->getEventTarget());
EVENTQUEUE->removeHandler(IStream::getInputShutdownEvent(),
getStream()->getEventTarget());
EVENTQUEUE->removeHandler(IStream::getOutputShutdownEvent(),
getStream()->getEventTarget());
EVENTQUEUE->removeHandler(CEvent::kTimer, this);
// remove timer
removeHeartbeatTimer();
}
void
CClientProxy1_0::addHeartbeatTimer()
{
CLock lock(getMutex());
if (m_heartbeatAlarm > 0.0) {
m_heartbeatTimer = EVENTQUEUE->newOneShotTimer(m_heartbeatAlarm, this);
}
}
void
CClientProxy1_0::removeHeartbeatTimer()
{
CLock lock(getMutex());
if (m_heartbeatTimer != NULL) {
EVENTQUEUE->deleteTimer(m_heartbeatTimer);
m_heartbeatTimer = NULL;
}
}
void
CClientProxy1_0::handleData(const CEvent&, void*)
{
// handle messages until there are no more. first read message code.
UInt8 code[4];
UInt32 n = getStream()->read(code, 4);
while (n != 0) {
// verify we got an entire code
if (n != 4) {
LOG((CLOG_ERR "incomplete message from \"%s\": %d bytes", getName().c_str(), n));
disconnect();
return;
}
// parse message
LOG((CLOG_DEBUG2 "msg from \"%s\": %c%c%c%c", getName().c_str(), code[0], code[1], code[2], code[3]));
if (!parseMessage(code)) {
LOG((CLOG_ERR "invalid message from client \"%s\"", getName().c_str()));
disconnect();
return;
}
// next message
n = getStream()->read(code, 4);
}
// restart heartbeat timer
removeHeartbeatTimer();
addHeartbeatTimer();
}
bool
CClientProxy1_0::parseMessage(const UInt8* code)
{
if (memcmp(code, kMsgDInfo, 4) == 0) {
return recvInfo(true);
}
else if (memcmp(code, kMsgCNoop, 4) == 0) {
// discard no-ops
LOG((CLOG_DEBUG2 "no-op from", getName().c_str()));
return true;
}
else if (memcmp(code, kMsgCClipboard, 4) == 0) {
return recvGrabClipboard();
}
else if (memcmp(code, kMsgDClipboard, 4) == 0) {
return recvClipboard();
}
return false;
}
void
CClientProxy1_0::handleDisconnect(const CEvent&, void*)
{
LOG((CLOG_NOTE "client \"%s\" disconnected", getName().c_str()));
disconnect();
}
void
CClientProxy1_0::handleWriteError(const CEvent&, void*)
{
LOG((CLOG_ERR "error writing to client \"%s\"", getName().c_str()));
disconnect();
}
void
CClientProxy1_0::handleFlatline(const CEvent&, void*)
{
// didn't get a heartbeat fast enough. assume client is dead.
LOG((CLOG_NOTE "client \"%s\" is dead", getName().c_str()));
disconnect();
}
// FIXME -- replace this
void
CClientProxy1_0::open()
{
// send request
LOG((CLOG_DEBUG1 "querying client \"%s\" info", getName().c_str()));
CProtocolUtil::writef(getOutputStream(), kMsgQInfo);
getOutputStream()->flush();
CProtocolUtil::writef(getStream(), kMsgQInfo);
getStream()->flush();
// wait for and verify reply
UInt8 code[4];
for (;;) {
UInt32 n = getInputStream()->read(code, 4, -1.0);
UInt32 n = getStream()->read(code, 4);
if (n == 4) {
if (memcmp(code, kMsgCNoop, 4) == 0) {
// discard heartbeats
@@ -73,79 +216,15 @@ CClientProxy1_0::open()
recvInfo(false);
}
void
CClientProxy1_0::mainLoop()
{
// handle messages until the client hangs up or stops sending heartbeats
CStopwatch heartTimer;
for (;;) {
CThread::testCancel();
// wait for a message
UInt8 code[4];
UInt32 n = getInputStream()->read(code, 4, m_heartRate);
CThread::testCancel();
// check if client hungup
if (n == 0) {
LOG((CLOG_NOTE "client \"%s\" disconnected", getName().c_str()));
return;
}
// check if client has stopped sending heartbeats
if (n == (UInt32)-1) {
if (m_heartDeath >= 0.0 && heartTimer.getTime() > m_heartDeath) {
LOG((CLOG_NOTE "client \"%s\" is dead", getName().c_str()));
return;
}
continue;
}
// got a message so reset heartbeat monitor
heartTimer.reset();
// verify we got an entire code
if (n != 4) {
LOG((CLOG_ERR "incomplete message from \"%s\": %d bytes", getName().c_str(), n));
// client sent an incomplete message
throw XBadClient();
}
// parse message
LOG((CLOG_DEBUG2 "msg from \"%s\": %c%c%c%c", getName().c_str(), code[0], code[1], code[2], code[3]));
if (memcmp(code, kMsgDInfo, 4) == 0) {
recvInfo(true);
}
else if (memcmp(code, kMsgCNoop, 4) == 0) {
// discard no-ops
LOG((CLOG_DEBUG2 "no-op from", getName().c_str()));
continue;
}
else if (memcmp(code, kMsgCClipboard, 4) == 0) {
recvGrabClipboard();
}
else if (memcmp(code, kMsgDClipboard, 4) == 0) {
recvClipboard();
}
// note -- more message handlers go here
else {
LOG((CLOG_ERR "invalid message from client \"%s\"", getName().c_str()));
// unknown message
throw XBadClient();
}
}
}
// FIXME -- replace this
void
CClientProxy1_0::close()
{
LOG((CLOG_DEBUG1 "send close to \"%s\"", getName().c_str()));
CProtocolUtil::writef(getOutputStream(), kMsgCClose);
CProtocolUtil::writef(getStream(), kMsgCClose);
// force the close to be sent before we return
getOutputStream()->flush();
getStream()->flush();
}
void
@@ -153,7 +232,7 @@ CClientProxy1_0::enter(SInt32 xAbs, SInt32 yAbs,
UInt32 seqNum, KeyModifierMask mask, bool)
{
LOG((CLOG_DEBUG1 "send enter to \"%s\", %d,%d %d %04x", getName().c_str(), xAbs, yAbs, seqNum, mask));
CProtocolUtil::writef(getOutputStream(), kMsgCEnter,
CProtocolUtil::writef(getStream(), kMsgCEnter,
xAbs, yAbs, seqNum, mask);
}
@@ -161,7 +240,7 @@ bool
CClientProxy1_0::leave()
{
LOG((CLOG_DEBUG1 "send leave to \"%s\"", getName().c_str()));
CProtocolUtil::writef(getOutputStream(), kMsgCLeave);
CProtocolUtil::writef(getStream(), kMsgCLeave);
// we can never prevent the user from leaving
return true;
@@ -177,7 +256,7 @@ CClientProxy1_0::setClipboard(ClipboardID id, const CString& data)
m_clipboardDirty[id] = false;
LOG((CLOG_DEBUG "send clipboard %d to \"%s\" size=%d", id, getName().c_str(), data.size()));
CProtocolUtil::writef(getOutputStream(), kMsgDClipboard, id, 0, &data);
CProtocolUtil::writef(getStream(), kMsgDClipboard, id, 0, &data);
}
}
@@ -185,7 +264,7 @@ void
CClientProxy1_0::grabClipboard(ClipboardID id)
{
LOG((CLOG_DEBUG "send grab clipboard %d to \"%s\"", id, getName().c_str()));
CProtocolUtil::writef(getOutputStream(), kMsgCClipboard, id, 0);
CProtocolUtil::writef(getStream(), kMsgCClipboard, id, 0);
// this clipboard is now dirty
CLock lock(getMutex());
@@ -203,7 +282,7 @@ void
CClientProxy1_0::keyDown(KeyID key, KeyModifierMask mask, KeyButton)
{
LOG((CLOG_DEBUG1 "send key down to \"%s\" id=%d, mask=0x%04x", getName().c_str(), key, mask));
CProtocolUtil::writef(getOutputStream(), kMsgDKeyDown1_0, key, mask);
CProtocolUtil::writef(getStream(), kMsgDKeyDown1_0, key, mask);
}
void
@@ -211,78 +290,81 @@ CClientProxy1_0::keyRepeat(KeyID key, KeyModifierMask mask,
SInt32 count, KeyButton)
{
LOG((CLOG_DEBUG1 "send key repeat to \"%s\" id=%d, mask=0x%04x, count=%d", getName().c_str(), key, mask, count));
CProtocolUtil::writef(getOutputStream(), kMsgDKeyRepeat1_0, key, mask, count);
CProtocolUtil::writef(getStream(), kMsgDKeyRepeat1_0, key, mask, count);
}
void
CClientProxy1_0::keyUp(KeyID key, KeyModifierMask mask, KeyButton)
{
LOG((CLOG_DEBUG1 "send key up to \"%s\" id=%d, mask=0x%04x", getName().c_str(), key, mask));
CProtocolUtil::writef(getOutputStream(), kMsgDKeyUp1_0, key, mask);
CProtocolUtil::writef(getStream(), kMsgDKeyUp1_0, key, mask);
}
void
CClientProxy1_0::mouseDown(ButtonID button)
{
LOG((CLOG_DEBUG1 "send mouse down to \"%s\" id=%d", getName().c_str(), button));
CProtocolUtil::writef(getOutputStream(), kMsgDMouseDown, button);
CProtocolUtil::writef(getStream(), kMsgDMouseDown, button);
}
void
CClientProxy1_0::mouseUp(ButtonID button)
{
LOG((CLOG_DEBUG1 "send mouse up to \"%s\" id=%d", getName().c_str(), button));
CProtocolUtil::writef(getOutputStream(), kMsgDMouseUp, button);
CProtocolUtil::writef(getStream(), kMsgDMouseUp, button);
}
void
CClientProxy1_0::mouseMove(SInt32 xAbs, SInt32 yAbs)
{
LOG((CLOG_DEBUG2 "send mouse move to \"%s\" %d,%d", getName().c_str(), xAbs, yAbs));
CProtocolUtil::writef(getOutputStream(), kMsgDMouseMove, xAbs, yAbs);
CProtocolUtil::writef(getStream(), kMsgDMouseMove, xAbs, yAbs);
}
void
CClientProxy1_0::mouseWheel(SInt32 delta)
{
LOG((CLOG_DEBUG2 "send mouse wheel to \"%s\" %+d", getName().c_str(), delta));
CProtocolUtil::writef(getOutputStream(), kMsgDMouseWheel, delta);
CProtocolUtil::writef(getStream(), kMsgDMouseWheel, delta);
}
void
CClientProxy1_0::screensaver(bool on)
{
LOG((CLOG_DEBUG1 "send screen saver to \"%s\" on=%d", getName().c_str(), on ? 1 : 0));
CProtocolUtil::writef(getOutputStream(), kMsgCScreenSaver, on ? 1 : 0);
CProtocolUtil::writef(getStream(), kMsgCScreenSaver, on ? 1 : 0);
}
void
CClientProxy1_0::resetOptions()
{
LOG((CLOG_DEBUG1 "send reset options to \"%s\"", getName().c_str()));
CProtocolUtil::writef(getOutputStream(), kMsgCResetOptions);
CProtocolUtil::writef(getStream(), kMsgCResetOptions);
// reset heart rate and death
CLock lock(getMutex());
m_heartRate = kHeartRate;
m_heartDeath = kHeartRate * kHeartBeatsUntilDeath;
m_heartbeatAlarm = kHeartRate * kHeartBeatsUntilDeath;
removeHeartbeatTimer();
addHeartbeatTimer();
}
void
CClientProxy1_0::setOptions(const COptionsList& options)
{
LOG((CLOG_DEBUG1 "send set options to \"%s\" size=%d", getName().c_str(), options.size()));
CProtocolUtil::writef(getOutputStream(), kMsgDSetOptions, &options);
CProtocolUtil::writef(getStream(), kMsgDSetOptions, &options);
// check options
CLock lock(getMutex());
for (UInt32 i = 0, n = options.size(); i < n; i += 2) {
if (options[i] == kOptionHeartbeat) {
m_heartRate = 1.0e-3 * static_cast<double>(options[i + 1]);
if (m_heartRate <= 0.0) {
m_heartRate = -1.0;
double rate = 1.0e-3 * static_cast<double>(options[i + 1]);
if (rate <= 0.0) {
rate = -1.0;
}
m_heartDeath = m_heartRate * kHeartBeatsUntilDeath;
m_heartbeatAlarm = rate * kHeartBeatsUntilDeath;
removeHeartbeatTimer();
addHeartbeatTimer();
}
}
}
@@ -318,7 +400,7 @@ CClientProxy1_0::getCursorCenter(SInt32& x, SInt32& y) const
y = m_info.m_my;
}
void
bool
CClientProxy1_0::recvInfo(bool notify)
{
{
@@ -326,16 +408,18 @@ CClientProxy1_0::recvInfo(bool notify)
// parse the message
SInt16 x, y, w, h, zoneSize, mx, my;
CProtocolUtil::readf(getInputStream(), kMsgDInfo + 4,
&x, &y, &w, &h, &zoneSize, &mx, &my);
if (!CProtocolUtil::readf(getStream(), kMsgDInfo + 4,
&x, &y, &w, &h, &zoneSize, &mx, &my)) {
return false;
}
LOG((CLOG_DEBUG "received client \"%s\" info shape=%d,%d %dx%d, zone=%d, pos=%d,%d", getName().c_str(), x, y, w, h, zoneSize, mx, my));
// validate
if (w <= 0 || h <= 0 || zoneSize < 0) {
throw XBadClient();
return false;
}
if (mx < x || my < y || mx >= x + w || my >= y + h) {
throw XBadClient();
return false;
}
// save
@@ -355,44 +439,52 @@ CClientProxy1_0::recvInfo(bool notify)
// acknowledge receipt
LOG((CLOG_DEBUG1 "send info ack to \"%s\"", getName().c_str()));
CProtocolUtil::writef(getOutputStream(), kMsgCInfoAck);
CProtocolUtil::writef(getStream(), kMsgCInfoAck);
return true;
}
void
bool
CClientProxy1_0::recvClipboard()
{
// parse message
ClipboardID id;
UInt32 seqNum;
CString data;
CProtocolUtil::readf(getInputStream(), kMsgDClipboard + 4, &id, &seqNum, &data);
if (!CProtocolUtil::readf(getStream(),
kMsgDClipboard + 4, &id, &seqNum, &data)) {
return false;
}
LOG((CLOG_DEBUG "received client \"%s\" clipboard %d seqnum=%d, size=%d", getName().c_str(), id, seqNum, data.size()));
// validate
if (id >= kClipboardEnd) {
throw XBadClient();
return false;
}
// send update. this calls us back to reset our clipboard dirty flag
// so don't hold a lock during the call.
getServer()->onClipboardChanged(id, seqNum, data);
return true;
}
void
bool
CClientProxy1_0::recvGrabClipboard()
{
// parse message
ClipboardID id;
UInt32 seqNum;
CProtocolUtil::readf(getInputStream(), kMsgCClipboard + 4, &id, &seqNum);
if (!CProtocolUtil::readf(getStream(), kMsgCClipboard + 4, &id, &seqNum)) {
return false;
}
LOG((CLOG_DEBUG "received client \"%s\" grabbed clipboard %d seqnum=%d", getName().c_str(), id, seqNum));
// validate
if (id >= kClipboardEnd) {
throw XBadClient();
return false;
}
// send update. this calls us back to reset our clipboard dirty flag
// so don't hold a lock during the call.
getServer()->onGrabClipboard(getName(), id, seqNum);
return true;
}

View File

@@ -18,12 +18,14 @@
#include "CClientProxy.h"
#include "ProtocolTypes.h"
class CEvent;
class CEventQueueTimer;
//! Proxy for client implementing protocol version 1.0
class CClientProxy1_0 : public CClientProxy {
public:
CClientProxy1_0(IServer* server, const CString& name,
IInputStream* adoptedInput,
IOutputStream* adoptedOutput);
IStream* adoptedStream);
~CClientProxy1_0();
// IClient overrides
@@ -54,16 +56,29 @@ public:
virtual void getCursorPos(SInt32& x, SInt32& y) const;
virtual void getCursorCenter(SInt32& x, SInt32& y) const;
protected:
virtual bool parseMessage(const UInt8* code);
private:
void recvInfo(bool notify);
void recvClipboard();
void recvGrabClipboard();
void disconnect();
void removeHandlers();
void addHeartbeatTimer();
void removeHeartbeatTimer();
void handleData(const CEvent&, void*);
void handleDisconnect(const CEvent&, void*);
void handleWriteError(const CEvent&, void*);
void handleFlatline(const CEvent&, void*);
bool recvInfo(bool notify);
bool recvClipboard();
bool recvGrabClipboard();
private:
CClientInfo m_info;
bool m_clipboardDirty[kClipboardEnd];
double m_heartRate;
double m_heartDeath;
double m_heartbeatAlarm;
CEventQueueTimer* m_heartbeatTimer;
};
#endif

View File

@@ -21,9 +21,9 @@
// CClientProxy1_1
//
CClientProxy1_1::CClientProxy1_1(IServer* server, const CString& name,
IInputStream* input, IOutputStream* output) :
CClientProxy1_0(server, name, input, output)
CClientProxy1_1::CClientProxy1_1(IServer* server,
const CString& name, IStream* stream) :
CClientProxy1_0(server, name, stream)
{
// do nothing
}
@@ -37,7 +37,7 @@ void
CClientProxy1_1::keyDown(KeyID key, KeyModifierMask mask, KeyButton button)
{
LOG((CLOG_DEBUG1 "send key down to \"%s\" id=%d, mask=0x%04x, button=0x%04x", getName().c_str(), key, mask, button));
CProtocolUtil::writef(getOutputStream(), kMsgDKeyDown, key, mask, button);
CProtocolUtil::writef(getStream(), kMsgDKeyDown, key, mask, button);
}
void
@@ -45,12 +45,12 @@ CClientProxy1_1::keyRepeat(KeyID key, KeyModifierMask mask,
SInt32 count, KeyButton button)
{
LOG((CLOG_DEBUG1 "send key repeat to \"%s\" id=%d, mask=0x%04x, count=%d, button=0x%04x", getName().c_str(), key, mask, count, button));
CProtocolUtil::writef(getOutputStream(), kMsgDKeyRepeat, key, mask, count, button);
CProtocolUtil::writef(getStream(), kMsgDKeyRepeat, key, mask, count, button);
}
void
CClientProxy1_1::keyUp(KeyID key, KeyModifierMask mask, KeyButton button)
{
LOG((CLOG_DEBUG1 "send key up to \"%s\" id=%d, mask=0x%04x, button=0x%04x", getName().c_str(), key, mask, button));
CProtocolUtil::writef(getOutputStream(), kMsgDKeyUp, key, mask, button);
CProtocolUtil::writef(getStream(), kMsgDKeyUp, key, mask, button);
}

View File

@@ -21,8 +21,7 @@
class CClientProxy1_1 : public CClientProxy1_0 {
public:
CClientProxy1_1(IServer* server, const CString& name,
IInputStream* adoptedInput,
IOutputStream* adoptedOutput);
IStream* adoptedStream);
~CClientProxy1_1();
// IClient overrides

View File

@@ -239,12 +239,6 @@ CConfig::setSynergyAddress(const CNetworkAddress& addr)
m_synergyAddress = addr;
}
void
CConfig::setHTTPAddress(const CNetworkAddress& addr)
{
m_httpAddress = addr;
}
bool
CConfig::addOption(const CString& name, OptionID option, OptionValue value)
{
@@ -430,12 +424,6 @@ CConfig::getSynergyAddress() const
return m_synergyAddress;
}
const CNetworkAddress&
CConfig::getHTTPAddress() const
{
return m_httpAddress;
}
const CConfig::CScreenOptions*
CConfig::getOptions(const CString& name) const
{
@@ -462,9 +450,6 @@ CConfig::operator==(const CConfig& x) const
if (m_synergyAddress != x.m_synergyAddress) {
return false;
}
if (m_httpAddress != x.m_httpAddress) {
return false;
}
*/
if (m_map.size() != x.m_map.size()) {
return false;
@@ -782,14 +767,6 @@ CConfig::readSectionOptions(std::istream& s)
throw XConfigRead("invalid address argument");
}
}
else if (name == "http") {
try {
m_httpAddress = CNetworkAddress(value, kDefaultPort + 1);
}
catch (XSocketAddress&) {
throw XConfigRead("invalid http argument");
}
}
else if (name == "heartbeat") {
addOption("", kOptionHeartbeat, parseInt(value));
}
@@ -1063,10 +1040,6 @@ operator<<(std::ostream& s, const CConfig& config)
s << "\taddress = " <<
config.m_synergyAddress.getHostname().c_str() << std::endl;
}
if (config.m_httpAddress.isValid()) {
s << "\thttp = " <<
config.m_httpAddress.getHostname().c_str() << std::endl;
}
s << "end" << std::endl;
// screens section

View File

@@ -175,13 +175,6 @@ public:
*/
void setSynergyAddress(const CNetworkAddress&);
//! Set HTTP server address
/*!
Set the HTTP listen addresses. There is no default address so
this must be called to run an HTTP server using this configuration.
*/
void setHTTPAddress(const CNetworkAddress&);
//! Add a screen option
/*!
Adds an option and its value to the named screen. Replaces the
@@ -255,8 +248,6 @@ public:
//! Get the server address
const CNetworkAddress& getSynergyAddress() const;
//! Get the HTTP server address
const CNetworkAddress& getHTTPAddress() const;
//! Get the screen options
/*!
@@ -308,7 +299,6 @@ private:
CCellMap m_map;
CNameMap m_nameToCanonicalName;
CNetworkAddress m_synergyAddress;
CNetworkAddress m_httpAddress;
CScreenOptions m_globalOptions;
};

View File

@@ -1,799 +0,0 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file COPYING that should have accompanied this file.
*
* This package 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.
*/
#include "CHTTPServer.h"
#include "CConfig.h"
#include "CHTTPProtocol.h"
#include "CServer.h"
#include "XHTTP.h"
#include "IDataSocket.h"
#include "XThread.h"
#include "CLog.h"
#include "stdset.h"
#include "stdsstream.h"
//
// CHTTPServer
//
// maximum size of an HTTP request. this should be large enough to
// handle any reasonable request but small enough to prevent a
// malicious client from causing us to use too much memory.
const UInt32 CHTTPServer::s_maxRequestSize = 32768;
CHTTPServer::CHTTPServer(
CServer* server) :
m_server(server)
{
// do nothing
}
CHTTPServer::~CHTTPServer()
{
// do nothing
}
void
CHTTPServer::processRequest(IDataSocket* socket)
{
assert(socket != NULL);
CHTTPRequest* request = NULL;
try {
// parse request
request = CHTTPProtocol::readRequest(
socket->getInputStream(), s_maxRequestSize);
if (request == NULL) {
throw XHTTP(400);
}
// if absolute uri then strip off scheme and host
if (request->m_uri[0] != '/') {
CString::size_type n = request->m_uri.find('/');
if (n == CString::npos) {
throw XHTTP(404);
}
request->m_uri = request->m_uri.substr(n);
}
// prepare reply
CHTTPReply reply;
reply.m_majorVersion = request->m_majorVersion;
reply.m_minorVersion = request->m_minorVersion;
reply.m_status = 200;
reply.m_reason = "OK";
reply.m_method = request->m_method;
// process
doProcessRequest(*request, reply);
// send reply
CHTTPProtocol::reply(socket->getOutputStream(), reply);
LOG((CLOG_INFO "HTTP reply %d for %s %s", reply.m_status, request->m_method.c_str(), request->m_uri.c_str()));
// clean up
delete request;
}
catch (XHTTP& e) {
LOG((CLOG_WARN "returning HTTP error %d %s for %s", e.getStatus(), e.getReason().c_str(), (request != NULL) ? request->m_uri.c_str() : "<unknown>"));
// clean up
delete request;
// return error
CHTTPReply reply;
reply.m_majorVersion = 1;
reply.m_minorVersion = 0;
reply.m_status = e.getStatus();
reply.m_reason = e.getReason();
reply.m_method = "GET";
// FIXME -- use a nicer error page
reply.m_headers.push_back(std::make_pair(CString("Content-Type"),
CString("text/plain")));
reply.m_body = e.getReason();
e.addHeaders(reply);
CHTTPProtocol::reply(socket->getOutputStream(), reply);
}
catch (...) {
// ignore other exceptions
RETHROW_XTHREAD
}
}
void
CHTTPServer::doProcessRequest(CHTTPRequest& request, CHTTPReply& reply)
{
// switch based on uri
if (request.m_uri == "/editmap") {
if (request.m_method == "GET" || request.m_method == "HEAD") {
doProcessGetEditMap(request, reply);
reply.m_headers.push_back(std::make_pair(
CString("Content-Type"),
CString("text/html")));
}
else if (request.m_method == "POST") {
doProcessPostEditMap(request, reply);
reply.m_headers.push_back(std::make_pair(
CString("Content-Type"),
CString("text/html")));
}
else {
throw XHTTPAllow("GET, HEAD, POST");
}
}
else {
// unknown page
throw XHTTP(404);
}
}
void
CHTTPServer::doProcessGetEditMap(CHTTPRequest& /*request*/, CHTTPReply& reply)
{
static const char* s_editMapProlog1 =
"<html>\r\n"
"<head>\r\n"
" <title>Synergy -- Edit Screens</title>\r\n"
"</head>\r\n"
"<body>\r\n"
" <form method=\"POST\" action=\"editmap\" "
"enctype=\"multipart/form-data\">\r\n"
" <input type=hidden name=\"size\" value=\"";
static const char* s_editMapProlog2 =
"\">\r\n";
static const char* s_editMapEpilog =
" <input type=submit name=\"submit\">\r\n"
" <input type=reset>\r\n"
" <br>\r\n"
" </form>\r\n"
"</body>\r\n"
"</html>\r\n";
static const char* s_editMapTableProlog =
"<table border=\"1\" cellspacing=\"0\" cellpadding=\"0\"><tr><td>"
" <table border=\"0\" cellspacing=\"2\" cellpadding=\"6\">\r\n";
static const char* s_editMapTableEpilog =
" </table>"
"</td></tr></table>\r\n";
static const char* s_editMapRowProlog =
"<tr align=\"center\" valign=\"top\">\r\n";
static const char* s_editMapRowEpilog =
"</tr>\r\n";
static const char* s_editMapScreenDummy =
"<td>";
static const char* s_editMapScreenPrimary =
"<td bgcolor=\"#2222288\"><input type=\"text\" readonly value=\"";
static const char* s_editMapScreenLive =
"<td bgcolor=\"#cccccc\"><input type=\"text\" value=\"";
static const char* s_editMapScreenDead =
"<td><input type=\"text\" value=\"";
static const char* s_editMapScreenLiveDead1 =
"\" size=\"16\" maxlength=\"64\" name=\"";
static const char* s_editMapScreenLiveDead2 =
"\">";
static const char* s_editMapScreenEnd =
"</td>\r\n";
std::ostringstream s;
// convert screen map into a temporary screen map
CScreenArray screens;
{
CConfig config;
m_server->getConfig(&config);
screens.convertFrom(config);
// FIXME -- note to user if config couldn't be exactly represented
}
// insert blank columns and rows around array (to allow the user
// to insert new screens)
screens.insertColumn(0);
screens.insertColumn(screens.getWidth());
screens.insertRow(0);
screens.insertRow(screens.getHeight());
// get array size
const SInt32 w = screens.getWidth();
const SInt32 h = screens.getHeight();
// construct reply
reply.m_body += s_editMapProlog1;
s << w << "x" << h;
reply.m_body += s.str();
reply.m_body += s_editMapProlog2;
// add screen map for editing
const CString primaryName = m_server->getPrimaryScreenName();
reply.m_body += s_editMapTableProlog;
for (SInt32 y = 0; y < h; ++y) {
reply.m_body += s_editMapRowProlog;
for (SInt32 x = 0; x < w; ++x) {
s.str("");
if (!screens.isAllowed(x, y) && screens.get(x, y) != primaryName) {
s << s_editMapScreenDummy;
}
else {
if (!screens.isSet(x, y)) {
s << s_editMapScreenDead;
}
else if (screens.get(x, y) == primaryName) {
s << s_editMapScreenPrimary;
}
else {
s << s_editMapScreenLive;
}
s << screens.get(x, y) <<
s_editMapScreenLiveDead1 <<
"n" << x << "x" << y <<
s_editMapScreenLiveDead2;
}
s << s_editMapScreenEnd;
reply.m_body += s.str();
}
reply.m_body += s_editMapRowEpilog;
}
reply.m_body += s_editMapTableEpilog;
reply.m_body += s_editMapEpilog;
}
void
CHTTPServer::doProcessPostEditMap(CHTTPRequest& request, CHTTPReply& reply)
{
typedef std::vector<CString> ScreenArray;
typedef std::set<CString> ScreenSet;
// parse the result
CHTTPProtocol::CFormParts parts;
if (!CHTTPProtocol::parseFormData(request, parts)) {
LOG((CLOG_WARN "editmap: cannot parse form data"));
throw XHTTP(400);
}
try {
std::ostringstream s;
// convert post data into a temporary screen map. also check
// that no screen name is invalid or used more than once.
SInt32 w, h;
CHTTPProtocol::CFormParts::iterator index = parts.find("size");
if (index == parts.end() ||
!parseXY(index->second, w, h) ||
w <= 0 || h <= 0) {
LOG((CLOG_WARN "editmap: cannot parse size or size is invalid"));
throw XHTTP(400);
}
ScreenSet screenNames;
CScreenArray screens;
screens.resize(w, h);
for (SInt32 y = 0; y < h; ++y) {
for (SInt32 x = 0; x < w; ++x) {
// find part
s.str("");
s << "n" << x << "x" << y;
index = parts.find(s.str());
if (index == parts.end()) {
// FIXME -- screen is missing. error?
continue;
}
// skip blank names
const CString& name = index->second;
if (name.empty()) {
continue;
}
// check name. name must be legal and must not have
// already been seen.
if (screenNames.count(name)) {
// FIXME -- better error message
LOG((CLOG_WARN "editmap: duplicate name %s", name.c_str()));
throw XHTTP(400);
}
// FIXME -- check that name is legal
// save name. if we've already seen the name then
// report an error.
screens.set(x, y, name);
screenNames.insert(name);
}
}
// if new map is invalid then return error. map is invalid if:
// there are no screens, or
// the screens are not 4-connected.
if (screenNames.empty()) {
// no screens
// FIXME -- need better no screens
LOG((CLOG_WARN "editmap: no screens"));
throw XHTTP(400);
}
if (!screens.isValid()) {
// FIXME -- need better unconnected screens error
LOG((CLOG_WARN "editmap: unconnected screens"));
throw XHTTP(400);
}
// convert temporary screen map into a regular map
CConfig config;
m_server->getConfig(&config);
screens.convertTo(config);
// set new screen map on server
m_server->setConfig(config);
// now reply with current map
doProcessGetEditMap(request, reply);
}
catch (XHTTP&) {
// FIXME -- construct a more meaningful error?
throw;
}
}
bool
CHTTPServer::parseXY(const CString& xy, SInt32& x, SInt32& y)
{
std::istringstream s(xy);
char delimiter;
s >> x;
s.get(delimiter);
s >> y;
return (!!s && delimiter == 'x');
}
//
// CHTTPServer::CScreenArray
//
CHTTPServer::CScreenArray::CScreenArray() :
m_w(0),
m_h(0)
{
// do nothing
}
CHTTPServer::CScreenArray::~CScreenArray()
{
// do nothing
}
void
CHTTPServer::CScreenArray::resize(SInt32 w, SInt32 h)
{
m_screens.clear();
m_screens.resize(w * h);
m_w = w;
m_h = h;
}
void
CHTTPServer::CScreenArray::insertRow(SInt32 i)
{
assert(i >= 0 && i <= m_h);
CNames newScreens;
newScreens.resize(m_w * (m_h + 1));
for (SInt32 y = 0; y < i; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
newScreens[x + y * m_w] = m_screens[x + y * m_w];
}
}
for (SInt32 y = i; y < m_h; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
newScreens[x + (y + 1) * m_w] = m_screens[x + y * m_w];
}
}
m_screens.swap(newScreens);
++m_h;
}
void
CHTTPServer::CScreenArray::insertColumn(SInt32 i)
{
assert(i >= 0 && i <= m_w);
CNames newScreens;
newScreens.resize((m_w + 1) * m_h);
for (SInt32 y = 0; y < m_h; ++y) {
for (SInt32 x = 0; x < i; ++x) {
newScreens[x + y * (m_w + 1)] = m_screens[x + y * m_w];
}
for (SInt32 x = i; x < m_w; ++x) {
newScreens[(x + 1) + y * (m_w + 1)] = m_screens[x + y * m_w];
}
}
m_screens.swap(newScreens);
++m_w;
}
void
CHTTPServer::CScreenArray::eraseRow(SInt32 i)
{
assert(i >= 0 && i < m_h);
CNames newScreens;
newScreens.resize(m_w * (m_h - 1));
for (SInt32 y = 0; y < i; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
newScreens[x + y * m_w] = m_screens[x + y * m_w];
}
}
for (SInt32 y = i + 1; y < m_h; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
newScreens[x + (y - 1) * m_w] = m_screens[x + y * m_w];
}
}
m_screens.swap(newScreens);
--m_h;
}
void
CHTTPServer::CScreenArray::eraseColumn(SInt32 i)
{
assert(i >= 0 && i < m_w);
CNames newScreens;
newScreens.resize((m_w - 1) * m_h);
for (SInt32 y = 0; y < m_h; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
newScreens[x + y * (m_w - 1)] = m_screens[x + y * m_w];
}
for (SInt32 x = i + 1; x < m_w; ++x) {
newScreens[(x - 1) + y * (m_w - 1)] = m_screens[x + y * m_w];
}
}
m_screens.swap(newScreens);
--m_w;
}
void
CHTTPServer::CScreenArray::rotateRows(SInt32 i)
{
// nothing to do if no rows
if (m_h == 0) {
return;
}
// convert to canonical form
if (i < 0) {
i = m_h - ((-i) % m_h);
}
else {
i %= m_h;
}
if (i == 0 || i == m_h) {
return;
}
while (i > 0) {
// rotate one row
for (SInt32 x = 0; x < m_w; ++x) {
CString tmp = m_screens[x];
for (SInt32 y = 1; y < m_h; ++y) {
m_screens[x + (y - 1) * m_w] = m_screens[x + y * m_w];
}
m_screens[x + (m_h - 1) * m_w] = tmp;
}
}
}
void
CHTTPServer::CScreenArray::rotateColumns(SInt32 i)
{
// nothing to do if no columns
if (m_h == 0) {
return;
}
// convert to canonical form
if (i < 0) {
i = m_w - ((-i) % m_w);
}
else {
i %= m_w;
}
if (i == 0 || i == m_w) {
return;
}
while (i > 0) {
// rotate one column
for (SInt32 y = 0; y < m_h; ++y) {
CString tmp = m_screens[0 + y * m_w];
for (SInt32 x = 1; x < m_w; ++x) {
m_screens[x - 1 + y * m_w] = m_screens[x + y * m_w];
}
m_screens[m_w - 1 + y * m_w] = tmp;
}
}
}
void
CHTTPServer::CScreenArray::remove(SInt32 x, SInt32 y)
{
set(x, y, CString());
}
void
CHTTPServer::CScreenArray::set(SInt32 x, SInt32 y, const CString& name)
{
assert(x >= 0 && x < m_w);
assert(y >= 0 && y < m_h);
m_screens[x + y * m_w] = name;
}
bool
CHTTPServer::CScreenArray::isAllowed(SInt32 x, SInt32 y) const
{
assert(x >= 0 && x < m_w);
assert(y >= 0 && y < m_h);
if (x > 0 && !m_screens[(x - 1) + y * m_w].empty()) {
return true;
}
if (x < m_w - 1 && !m_screens[(x + 1) + y * m_w].empty()) {
return true;
}
if (y > 0 && !m_screens[x + (y - 1) * m_w].empty()) {
return true;
}
if (y < m_h - 1 && !m_screens[x + (y + 1) * m_w].empty()) {
return true;
}
return false;
}
bool
CHTTPServer::CScreenArray::isSet(SInt32 x, SInt32 y) const
{
assert(x >= 0 && x < m_w);
assert(y >= 0 && y < m_h);
return !m_screens[x + y * m_w].empty();
}
CString
CHTTPServer::CScreenArray::get(SInt32 x, SInt32 y) const
{
assert(x >= 0 && x < m_w);
assert(y >= 0 && y < m_h);
return m_screens[x + y * m_w];
}
bool
CHTTPServer::CScreenArray::find(const CString& name,
SInt32& xOut, SInt32& yOut) const
{
for (SInt32 y = 0; y < m_h; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
if (m_screens[x + y * m_w] == name) {
xOut = x;
yOut = y;
return true;
}
}
}
return false;
}
bool
CHTTPServer::CScreenArray::isValid() const
{
SInt32 count = 0, isolated = 0;
for (SInt32 y = 0; y < m_h; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
if (isSet(x, y)) {
++count;
if (!isAllowed(x, y)) {
++isolated;
}
}
}
}
return (count <= 1 || isolated == 0);
}
bool
CHTTPServer::CScreenArray::convertFrom(const CConfig& config)
{
typedef std::set<CString> ScreenSet;
// insert the first screen
CConfig::const_iterator index = config.begin();
if (index == config.end()) {
// no screens
resize(0, 0);
return true;
}
CString name = *index;
resize(1, 1);
set(0, 0, name);
// flood fill state
CNames screenStack;
ScreenSet doneSet;
// put all but the first screen on the stack
// note -- if all screens are 4-connected then we can skip this
while (++index != config.end()) {
screenStack.push_back(*index);
}
// put the first screen on the stack last so we process it first
screenStack.push_back(name);
// perform a flood fill using the stack as the seeds
while (!screenStack.empty()) {
// get next screen from stack
CString name = screenStack.back();
screenStack.pop_back();
// skip screen if we've seen it before
if (doneSet.count(name) > 0) {
continue;
}
// add this screen to doneSet so we don't process it again
doneSet.insert(name);
// find the screen. if it's not found then not all of the
// screens are 4-connected. discard disconnected screens.
SInt32 x, y;
if (!find(name, x, y)) {
continue;
}
// insert the screen's neighbors
// FIXME -- handle edge wrapping
CString neighbor;
neighbor = config.getNeighbor(name, kLeft);
if (!neighbor.empty() && doneSet.count(neighbor) == 0) {
// insert left neighbor, adding a column if necessary
if (x == 0 || get(x - 1, y) != neighbor) {
++x;
insertColumn(x - 1);
set(x - 1, y, neighbor);
}
screenStack.push_back(neighbor);
}
neighbor = config.getNeighbor(name, kRight);
if (!neighbor.empty() && doneSet.count(neighbor) == 0) {
// insert right neighbor, adding a column if necessary
if (x == m_w - 1 || get(x + 1, y) != neighbor) {
insertColumn(x + 1);
set(x + 1, y, neighbor);
}
screenStack.push_back(neighbor);
}
neighbor = config.getNeighbor(name, kTop);
if (!neighbor.empty() && doneSet.count(neighbor) == 0) {
// insert top neighbor, adding a row if necessary
if (y == 0 || get(x, y - 1) != neighbor) {
++y;
insertRow(y - 1);
set(x, y - 1, neighbor);
}
screenStack.push_back(neighbor);
}
neighbor = config.getNeighbor(name, kBottom);
if (!neighbor.empty() && doneSet.count(neighbor) == 0) {
// insert bottom neighbor, adding a row if necessary
if (y == m_h - 1 || get(x, y + 1) != neighbor) {
insertRow(y + 1);
set(x, y + 1, neighbor);
}
screenStack.push_back(neighbor);
}
}
// check symmetry
// FIXME -- handle edge wrapping
for (index = config.begin(); index != config.end(); ++index) {
const CString& name = *index;
SInt32 x, y;
if (!find(name, x, y)) {
return false;
}
CString neighbor;
neighbor = config.getNeighbor(name, kLeft);
if ((x == 0 && !neighbor.empty()) ||
(x > 0 && get(x - 1, y) != neighbor)) {
return false;
}
neighbor = config.getNeighbor(name, kRight);
if ((x == m_w - 1 && !neighbor.empty()) ||
(x < m_w - 1 && get(x + 1, y) != neighbor)) {
return false;
}
neighbor = config.getNeighbor(name, kTop);
if ((y == 0 && !neighbor.empty()) ||
(y > 0 && get(x, y - 1) != neighbor)) {
return false;
}
neighbor = config.getNeighbor(name, kBottom);
if ((y == m_h - 1 && !neighbor.empty()) ||
(y < m_h - 1 && get(x, y + 1) != neighbor)) {
return false;
}
}
return true;
}
void
CHTTPServer::CScreenArray::convertTo(CConfig& config) const
{
config.removeAllScreens();
// add screens and find smallest box containing all screens
SInt32 x0 = m_w, x1 = 0, y0 = m_h, y1 = 0;
for (SInt32 y = 0; y < m_h; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
if (isSet(x, y)) {
config.addScreen(get(x, y));
if (x < x0) {
x0 = x;
}
if (x > x1) {
x1 = x;
}
if (y < y0) {
y0 = y;
}
if (y > y1) {
y1 = y;
}
}
}
}
// make connections between screens
// FIXME -- add support for wrapping
// FIXME -- mark topmost and leftmost screens
for (SInt32 y = 0; y < m_h; ++y) {
for (SInt32 x = 0; x < m_w; ++x) {
if (!isSet(x, y)) {
continue;
}
if (x > x0 && isSet(x - 1, y)) {
config.connect(get(x, y), kLeft, get(x - 1, y));
}
if (x < x1 && isSet(x + 1, y)) {
config.connect(get(x, y), kRight, get(x + 1, y));
}
if (y > y0 && isSet(x, y - 1)) {
config.connect(get(x, y), kTop, get(x, y - 1));
}
if (y < y1 && isSet(x, y + 1)) {
config.connect(get(x, y), kBottom, get(x, y + 1));
}
}
}
}

View File

@@ -1,142 +0,0 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file COPYING that should have accompanied this file.
*
* This package 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.
*/
#ifndef CHTTPSERVER_H
#define CHTTPSERVER_H
#include "CString.h"
#include "BasicTypes.h"
#include "stdvector.h"
class CServer;
class CConfig;
class CHTTPRequest;
class CHTTPReply;
class IDataSocket;
//! Simple HTTP server
/*!
This class implements a simple HTTP server for interacting with the
synergy server.
*/
class CHTTPServer {
public:
CHTTPServer(CServer*);
virtual ~CHTTPServer();
//! @name manipulators
//@{
//! Process HTTP request
/*!
Synchronously processes an HTTP request on the given socket.
*/
void processRequest(IDataSocket*);
//@}
protected:
//! Process HTTP request
/*!
Processes a successfully read HTTP request. The reply is partially
filled in (version, method, status (200) and reason (OK)). This
method checks the URI and handles the request, filling in the rest
of the reply. If the request cannot be satisfied it throws an
appropriate XHTTP exception.
*/
virtual void doProcessRequest(CHTTPRequest&, CHTTPReply&);
//! Process request for map
virtual void doProcessGetEditMap(CHTTPRequest&, CHTTPReply&);
//! Process request for changing map
virtual void doProcessPostEditMap(CHTTPRequest&, CHTTPReply&);
//! Parse coordinate string
static bool parseXY(const CString&, SInt32& x, SInt32& y);
//! Screen map helper
/*!
This class represents the screen map as a resizable array. It's
used to handle map requests.
*/
class CScreenArray {
public:
CScreenArray();
~CScreenArray();
// resize the array. this also clears all the elements.
void resize(SInt32 w, SInt32 h);
// insert/remove a row/column. all elements in a new row/column
// are unset.
void insertRow(SInt32 insertedBeforeRow);
void insertColumn(SInt32 insertedBeforeColumn);
void eraseRow(SInt32 row);
void eraseColumn(SInt32 column);
// rotate rows or columns
void rotateRows(SInt32 rowsDown);
void rotateColumns(SInt32 columnsDown);
// remove/set a screen name. setting an empty name is the
// same as removing a name. names are not checked for
// validity.
void remove(SInt32 x, SInt32 y);
void set(SInt32 x, SInt32 y, const CString&);
// convert a CConfig to a CScreenArray. returns true iff
// all connections are symmetric and therefore exactly
// representable by a CScreenArray.
bool convertFrom(const CConfig&);
// accessors
// get the array size
SInt32 getWidth() const { return m_w; }
SInt32 getHeight() const { return m_h; }
// returns true iff the cell has a 4-connected neighbor
bool isAllowed(SInt32 x, SInt32 y) const;
// returns true iff the cell has a (non-empty) name
bool isSet(SInt32 x, SInt32 y) const;
// get a screen name
CString get(SInt32 x, SInt32 y) const;
// find a screen by name. returns true iff found.
bool find(const CString&, SInt32& x, SInt32& y) const;
// return true iff the overall array is valid. that means
// just zero or one screen or all screens are 4-connected
// to other screens.
bool isValid() const;
// convert this to a CConfig
void convertTo(CConfig&) const;
private:
typedef std::vector<CString> CNames;
SInt32 m_w, m_h;
CNames m_screens;
};
private:
CServer* m_server;
static const UInt32 s_maxRequestSize;
};
#endif

View File

@@ -13,7 +13,6 @@
*/
#include "CServer.h"
#include "CHTTPServer.h"
#include "CPrimaryClient.h"
#include "IScreenFactory.h"
#include "CInputPacketStream.h"
@@ -45,8 +44,6 @@
// CServer
//
const SInt32 CServer::s_httpMaxSimultaneousRequests = 3;
CServer::CServer(const CString& serverName) :
m_name(serverName),
m_error(false),
@@ -59,8 +56,6 @@ CServer::CServer(const CString& serverName) :
m_primaryClient(NULL),
m_seqNum(0),
m_activeSaver(NULL),
m_httpServer(NULL),
m_httpAvailable(&m_mutex, s_httpMaxSimultaneousRequests),
m_switchDir(kNoDirection),
m_switchScreen(NULL),
m_switchWaitDelay(0.0),
@@ -118,18 +113,15 @@ CServer::mainLoop()
setStatus(kNotRunning);
LOG((CLOG_NOTE "starting server"));
// FIXME -- started here
createClientListener();
// FIXME -- finished here
// start listening for new clients
m_acceptClientThread = new CThread(startThread(
new TMethodJob<CServer>(this,
&CServer::acceptClients)));
// start listening for HTTP requests
if (m_config.getHTTPAddress().isValid()) {
m_httpServer = new CHTTPServer(this);
startThread(new TMethodJob<CServer>(this,
&CServer::acceptHTTPClients));
}
// handle events
m_primaryClient->mainLoop();
@@ -144,8 +136,6 @@ CServer::mainLoop()
// bucket.
#define FINALLY do { \
stopThreads(); \
delete m_httpServer; \
m_httpServer = NULL; \
runStatusJobs(); \
} while (false)
FINALLY;
@@ -360,6 +350,16 @@ CServer::getConfig(CConfig* config) const
*config = m_config;
}
CString
CServer::getCanonicalName(const CString& name) const
{
CLock lock(&m_mutex);
if (m_config.isScreen(name)) {
return m_config.getCanonicalName(name);
}
return name;
}
void
CServer::runStatusJobs() const
{
@@ -411,11 +411,6 @@ CServer::onError()
// threads may be unable to proceed until this thread returns.
stopThreads(3.0);
// done with the HTTP server
CLock lock(&m_mutex);
delete m_httpServer;
m_httpServer = NULL;
// note -- we do not attempt to close down the primary screen
}
@@ -1673,23 +1668,6 @@ CServer::handshakeClient(IDataSocket* socket)
{
LOG((CLOG_DEBUG1 "negotiating with new client"));
// get the input and output streams
IInputStream* input = socket->getInputStream();
IOutputStream* output = socket->getOutputStream();
bool own = false;
// attach filters
if (m_streamFilterFactory != NULL) {
input = m_streamFilterFactory->createInput(input, own);
output = m_streamFilterFactory->createOutput(output, own);
own = true;
}
// attach the packetizing filters
input = new CInputPacketStream(input, own);
output = new COutputPacketStream(output, own);
own = true;
CClientProxy* proxy = NULL;
CString name("<unknown>");
try {
@@ -1810,111 +1788,6 @@ CServer::handshakeClient(IDataSocket* socket)
return NULL;
}
void
CServer::acceptHTTPClients(void*)
{
LOG((CLOG_DEBUG1 "starting to wait for HTTP clients"));
IListenSocket* listen = NULL;
try {
// create socket listener
listen = new CTCPListenSocket;
// bind to the desired port. keep retrying if we can't bind
// the address immediately.
CStopwatch timer;
for (;;) {
try {
LOG((CLOG_DEBUG1 "binding HTTP listen socket"));
listen->bind(m_config.getHTTPAddress());
break;
}
catch (XSocketBind& e) {
LOG((CLOG_DEBUG1 "bind HTTP failed: %s", e.what()));
// give up if we've waited too long
if (timer.getTime() >= m_bindTimeout) {
LOG((CLOG_DEBUG1 "waited too long to bind HTTP, giving up"));
throw;
}
// wait a bit before retrying
ARCH->sleep(5.0);
}
}
// accept connections and begin processing them
LOG((CLOG_DEBUG1 "waiting for HTTP connections"));
for (;;) {
// limit the number of HTTP requests being handled at once
{
CLock lock(&m_httpAvailable);
while (m_httpAvailable == 0) {
m_httpAvailable.wait();
}
assert(m_httpAvailable > 0);
m_httpAvailable = m_httpAvailable - 1;
}
// accept connection
CThread::testCancel();
IDataSocket* socket = listen->accept();
LOG((CLOG_NOTE "accepted HTTP connection"));
CThread::testCancel();
// handle HTTP request
startThread(new TMethodJob<CServer>(
this, &CServer::processHTTPRequest, socket));
}
// clean up
delete listen;
}
catch (XBase& e) {
LOG((CLOG_ERR "cannot listen for HTTP clients: %s", e.what()));
delete listen;
exitMainLoopWithError();
}
catch (...) {
delete listen;
throw;
}
}
void
CServer::processHTTPRequest(void* vsocket)
{
IDataSocket* socket = reinterpret_cast<IDataSocket*>(vsocket);
try {
// process the request and force delivery
m_httpServer->processRequest(socket);
socket->getOutputStream()->flush();
// wait a moment to give the client a chance to hangup first
ARCH->sleep(3.0);
// clean up
socket->close();
delete socket;
// increment available HTTP handlers
{
CLock lock(&m_httpAvailable);
m_httpAvailable = m_httpAvailable + 1;
m_httpAvailable.signal();
}
}
catch (...) {
delete socket;
{
CLock lock(&m_httpAvailable);
m_httpAvailable = m_httpAvailable + 1;
m_httpAvailable.signal();
}
throw;
}
}
void
CServer::sendOptions(IClient* client) const
{
@@ -2141,3 +2014,259 @@ CServer::CClipboardInfo::CClipboardInfo() :
{
// do nothing
}
// --- transitional ---
void
CServer::clientConnecting(const CEvent&, void*)
{
// accept client connection
IDataSocket* socket = m_listen->accept();
if (socket == NULL) {
return;
}
LOG((CLOG_NOTE "accepted client connection"));
// filter socket's streams then wrap the result in a new socket
IInputStream* input = socket->getInputStream();
IOutputStream* output = socket->getOutputStream();
bool own = false;
if (m_streamFilterFactory != NULL) {
input = m_streamFilterFactory->createInput(input, own);
output = m_streamFilterFactory->createOutput(output, own);
own = true;
}
input = new CInputPacketStream(input, own);
output = new COutputPacketStream(output, own);
socket = new CDataSocket(socket,
new CInputOutputStream(input, output, true));
// FIXME -- may want to move these event handlers (but not the
// handshake timer?) and the handshake into a new proxy object.
// we save this proxy as a provisional connection. it calls
// back to us (or maybe sends an event) to notify of failure or
// success. failure is socket failure or protocol error.
// success returns a new proxy of the appropriate version. we
// need to verify the validity of the client's name then remove
// the provisional connection and install a true connection.
// if we keep the timer then when it expires we just remove and
// delete the provisional connection. if we install a true
// connection then we remove the timer.
CProvisionalClient* client;
try {
client = new CProvisionalClient(this, socket);
}
catch (XBase&) {
delete socket;
// handle error
return;
}
// start timer for handshake
CEventQueueTimer* timer = EVENTQUEUE->newOneShotTimer(30.0, client);
// add client to client map
m_provisional.insert(client, timer);
}
void
CServer::recvClientHello(const CEvent&, void* vsocket)
{
IDataSocket* socket = reinterpret_cast<IDataSocket*>(vsocket);
LOG((CLOG_DEBUG1 "parsing hello reply"));
CClientProxy* proxy = NULL;
CString name("<unknown>");
try {
// limit the maximum length of the hello
UInt32 n = socket->getInputStream()->getSize();
if (n > kMaxHelloLength) {
LOG((CLOG_DEBUG1 "hello reply too long"));
throw XBadClient();
}
// parse the reply to hello
SInt16 major, minor;
CProtocolUtil::readf(socket->getInputStream(), kMsgHelloBack,
&major, &minor, &name);
// disallow invalid version numbers
if (major <= 0 || minor < 0) {
throw XIncompatibleClient(major, minor);
}
// convert name to canonical form (if any)
// FIXME -- need lock?
if (m_config.isScreen(name)) {
name = m_config.getCanonicalName(name);
}
// create client proxy for highest version supported by the client
LOG((CLOG_DEBUG1 "creating proxy for client \"%s\" version %d.%d", name.c_str(), major, minor));
if (major == 1) {
switch (minor) {
case 0:
// FIXME -- should pass socket, not input and output
proxy = new CClientProxy1_0(this, name, input, output);
break;
case 1:
// FIXME -- should pass socket, not input and output
proxy = new CClientProxy1_1(this, name, input, output);
break;
}
}
// hangup (with error) if version isn't supported
if (proxy == NULL) {
throw XIncompatibleClient(major, minor);
}
// the proxy now owns the socket
socket = NULL;
// add provisional client connection. this also checks if
// the client's name is okay (i.e. in the map and not in use).
addProvisionalClient(proxy);
// negotiate
// FIXME
// request the client's info and install a handler for it. note
// that the handshake timer is still going.
EVENTQUEUE->adoptHandler(IInputStream::getInputReadyEvent(),
socket->getInputStream(),
new TMethodEventJob<CServer>(this,
&CServer::recvClientInfo, socket));
LOG((CLOG_DEBUG1 "request info for client \"%s\"", name.c_str()));
// FIXME -- maybe should send this request some other way.
// could have the proxy itself handle the input. that makes sense
// but will have to check if that'll work. for one thing, the proxy
// will have to inform this object of any errors. it takes this
// object as a parameter so it probably can do that.
/*
proxy->open();
*/
return;
}
catch (XDuplicateClient& e) {
// client has duplicate name
LOG((CLOG_WARN "a client with name \"%s\" is already connected", e.getName().c_str()));
CProtocolUtil::writefNoError(proxy->getOutputStream(), kMsgEBusy);
}
catch (XUnknownClient& e) {
// client has unknown name
LOG((CLOG_WARN "a client with name \"%s\" is not in the map", e.getName().c_str()));
CProtocolUtil::writefNoError(proxy->getOutputStream(), kMsgEUnknown);
}
catch (XIncompatibleClient& e) {
// client is incompatible
LOG((CLOG_WARN "client \"%s\" has incompatible version %d.%d)", name.c_str(), e.getMajor(), e.getMinor()));
CProtocolUtil::writefNoError(socket->getOutputStream(),
kMsgEIncompatible,
kProtocolMajorVersion, kProtocolMinorVersion);
}
catch (XBadClient&) {
// client not behaving
LOG((CLOG_WARN "protocol error from client \"%s\"", name.c_str()));
CProtocolUtil::writefNoError(socket->getOutputStream(), kMsgEBad);
}
catch (XIO&) {
// client not behaving
LOG((CLOG_WARN "protocol error from client \"%s\"", name.c_str()));
CProtocolUtil::writefNoError(socket->getOutputStream(), kMsgEBad);
}
catch (XBase& e) {
// misc error
LOG((CLOG_WARN "error communicating with client \"%s\": %s", name.c_str(), e.what()));
}
// FIXME -- really clean up, including event handlers and timer.
// should have a method for this.
delete proxy;
delete socket;
}
void
CServer::recvClientInfo(const CEvent&, void* vsocket)
{
// FIXME -- get client's info and proxy becomes first class citizen.
// adopt new input handler aimed at clientInput. remove timer.
}
void
CServer::clientTimeout(const CEvent&, void* vsocket)
{
// FIXME -- client failed to connect fast enough. if client is
// already first class then just ignore this (that should never
// happen though because timer events are synthesized in the
// getEvent() so there can't be a race, so don't fuss over
// checking).
}
void
CServer::clientInput(const CEvent&, void* vsocket)
{
// FIXME -- client has sent a message
}
void
CServer::clientDisconnected(const CEvent&, void* vsocket)
{
// FIXME -- handle disconnection of client
}
void
CServer::createClientListener()
{
LOG((CLOG_DEBUG1 "creating socket to listen for clients"));
assert(m_socketFactory != NULL);
IListenSocket* listen = NULL;
try {
// create socket
listen = m_socketFactory->createListen();
// setup event handler
EVENTQUEUE->adoptHandler(IListenSocket::getConnectingEvent(), listen,
new TMethodEventJob<CServer>(this,
&CServer::clientConnecting));
// bind listen address
LOG((CLOG_DEBUG1 "binding listen socket"));
listen->bind(m_config.getSynergyAddress());
}
catch (XSocketAddressInUse& e) {
if (listen != NULL) {
EVENTQUEUE->removeHandler(
IListenSocket::getConnectingEvent(), listen);
delete listen;
}
setStatus(kError, e.what());
LOG((CLOG_WARN "bind failed: %s", e.what()));
// FIXME -- throw retry in X seconds object. the caller should
// catch this and optionally wait X seconds and try again.
// alternatively we could install a timer and retry automatically.
throw;
}
catch (...) {
if (listen != NULL) {
EVENTQUEUE->removeHandler(
IListenSocket::getConnectingEvent(), listen);
delete listen;
}
/* FIXME -- set some status and log error
setStatus(kNotRunning);
setStatus(kError, e.what());
LOG((CLOG_ERR "cannot listen for clients: %s", e.what()));
*/
throw;
}
m_listen = listen;
setStatus(kRunning);
LOG((CLOG_DEBUG1 "waiting for client connections"));
}

View File

@@ -29,7 +29,6 @@
#include "stdvector.h"
class CClientProxy;
class CHTTPServer;
class CPrimaryClient;
class IClient;
class IDataSocket;
@@ -151,6 +150,12 @@ public:
*/
void getConfig(CConfig*) const;
//! Get canonical screen name
/*!
Returns the canonical version of a screen name.
*/
CString getCanonicalName(const CString& name) const;
//! Get name
/*!
Returns the server's name passed to the c'tor
@@ -295,12 +300,6 @@ private:
void runClient(void*);
CClientProxy* handshakeClient(IDataSocket*);
// thread method to accept incoming HTTP connections
void acceptHTTPClients(void*);
// thread method to process HTTP requests
void processHTTPRequest(void*);
// connection list maintenance
void addConnection(IClient*);
void removeConnection(const CString& name);
@@ -381,11 +380,6 @@ private:
IClient* m_activeSaver;
SInt32 m_xSaver, m_ySaver;
// HTTP request processing stuff
CHTTPServer* m_httpServer;
CCondVar<SInt32> m_httpAvailable;
static const SInt32 s_httpMaxSimultaneousRequests;
// common state for screen switch tests. all tests are always
// trying to reach the same screen in the same direction.
EDirection m_switchDir;
@@ -408,6 +402,15 @@ private:
CJobList m_statusJobs;
EStatus m_status;
CString m_statusMessage;
//---
/*
IListenSocket* m_listen;
typedef std::map<CProvisionalClient*,
CEventQueueTimer*> CProvisionalClients;
CProvisionalClients m_provisional;
*/
};
#endif

View File

@@ -29,15 +29,15 @@ libserver_a_SOURCES = \
CClientProxy1_0.cpp \
CClientProxy1_1.cpp \
CConfig.cpp \
CHTTPServer.cpp \
CPrimaryClient.cpp \
CProvisionalClient.cpp \
CServer.cpp \
CClientProxy.h \
CClientProxy1_0.h \
CClientProxy1_1.h \
CConfig.h \
CHTTPServer.h \
CPrimaryClient.h \
CProvisionalClient.h \
CServer.h \
$(NULL)
INCLUDES = \
@@ -46,7 +46,6 @@ INCLUDES = \
-I$(VDEPTH)/lib/base \
-I$(VDEPTH)/lib/mt \
-I$(VDEPTH)/lib/io \
-I$(VDEPTH)/lib/http \
-I$(VDEPTH)/lib/net \
-I$(VDEPTH)/lib/synergy \
-I$(VDEPTH)/lib/platform \