moving 1.4 to trunk

This commit is contained in:
Nick Bolton
2012-06-10 16:50:54 +00:00
parent cdeb3a7824
commit 488241850c
1291 changed files with 425650 additions and 12 deletions

View File

@@ -0,0 +1,67 @@
# synergy -- mouse and keyboard sharing utility
# Copyright (C) 2009 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
set(inc
CNetworkAddress.h
CSocketMultiplexer.h
CTCPListenSocket.h
CTCPSocket.h
CTCPSocketFactory.h
IDataSocket.h
IListenSocket.h
ISocket.h
ISocketFactory.h
ISocketMultiplexerJob.h
TSocketMultiplexerMethodJob.h
XSocket.h
)
set(src
CNetworkAddress.cpp
CSocketMultiplexer.cpp
CTCPListenSocket.cpp
CTCPSocket.cpp
CTCPSocketFactory.cpp
IDataSocket.cpp
IListenSocket.cpp
ISocket.cpp
XSocket.cpp
)
if (WIN32)
list(APPEND src ${inc})
endif()
set(inc
../arch
../base
../common
../io
../mt
../synergy
)
if (UNIX)
list(APPEND inc
../../..
)
endif()
include_directories(${inc})
add_library(net STATIC ${src})
if (UNIX)
target_link_libraries(net mt io)
endif()

View File

@@ -0,0 +1,211 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* 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 "CNetworkAddress.h"
#include "XSocket.h"
#include "CArch.h"
#include "XArch.h"
#include <cstdlib>
//
// CNetworkAddress
//
// name re-resolution adapted from a patch by Brent Priddy.
CNetworkAddress::CNetworkAddress() :
m_address(NULL),
m_hostname(),
m_port(0)
{
// note -- make no calls to CNetwork socket interface here;
// we're often called prior to CNetwork::init().
}
CNetworkAddress::CNetworkAddress(int port) :
m_address(NULL),
m_hostname(),
m_port(port)
{
checkPort();
m_address = ARCH->newAnyAddr(IArchNetwork::kINET);
ARCH->setAddrPort(m_address, m_port);
}
CNetworkAddress::CNetworkAddress(const CNetworkAddress& addr) :
m_address(addr.m_address != NULL ? ARCH->copyAddr(addr.m_address) : NULL),
m_hostname(addr.m_hostname),
m_port(addr.m_port)
{
// do nothing
}
CNetworkAddress::CNetworkAddress(const CString& hostname, int port) :
m_address(NULL),
m_hostname(hostname),
m_port(port)
{
// check for port suffix
CString::size_type i = m_hostname.rfind(':');
if (i != CString::npos && i + 1 < m_hostname.size()) {
// found a colon. see if it looks like an IPv6 address.
bool colonNotation = false;
bool dotNotation = false;
bool doubleColon = false;
for (CString::size_type j = 0; j < i; ++j) {
if (m_hostname[j] == ':') {
colonNotation = true;
dotNotation = false;
if (m_hostname[j + 1] == ':') {
doubleColon = true;
}
}
else if (m_hostname[j] == '.' && colonNotation) {
dotNotation = true;
}
}
// port suffix is ambiguous with IPv6 notation if there's
// a double colon and the end of the address is not in dot
// notation. in that case we assume it's not a port suffix.
// the user can replace the double colon with zeros to
// disambiguate.
if ((!doubleColon || dotNotation) || !colonNotation) {
// parse port from hostname
char* end;
const char* chostname = m_hostname.c_str();
long suffixPort = strtol(chostname + i + 1, &end, 10);
if (end == chostname + i + 1 || *end != '\0') {
throw XSocketAddress(XSocketAddress::kBadPort,
m_hostname, m_port);
}
// trim port from hostname
m_hostname.erase(i);
// save port
m_port = static_cast<int>(suffixPort);
}
}
// check port number
checkPort();
}
CNetworkAddress::~CNetworkAddress()
{
if (m_address != NULL) {
ARCH->closeAddr(m_address);
}
}
CNetworkAddress&
CNetworkAddress::operator=(const CNetworkAddress& addr)
{
CArchNetAddress newAddr = NULL;
if (addr.m_address != NULL) {
newAddr = ARCH->copyAddr(addr.m_address);
}
if (m_address != NULL) {
ARCH->closeAddr(m_address);
}
m_address = newAddr;
m_hostname = addr.m_hostname;
m_port = addr.m_port;
return *this;
}
void
CNetworkAddress::resolve()
{
// discard previous address
if (m_address != NULL) {
ARCH->closeAddr(m_address);
m_address = NULL;
}
try {
// if hostname is empty then use wildcard address otherwise look
// up the name.
if (m_hostname.empty()) {
m_address = ARCH->newAnyAddr(IArchNetwork::kINET);
}
else {
m_address = ARCH->nameToAddr(m_hostname);
}
}
catch (XArchNetworkNameUnknown&) {
throw XSocketAddress(XSocketAddress::kNotFound, m_hostname, m_port);
}
catch (XArchNetworkNameNoAddress&) {
throw XSocketAddress(XSocketAddress::kNoAddress, m_hostname, m_port);
}
catch (XArchNetworkNameUnsupported&) {
throw XSocketAddress(XSocketAddress::kUnsupported, m_hostname, m_port);
}
catch (XArchNetworkName&) {
throw XSocketAddress(XSocketAddress::kUnknown, m_hostname, m_port);
}
// set port in address
ARCH->setAddrPort(m_address, m_port);
}
bool
CNetworkAddress::operator==(const CNetworkAddress& addr) const
{
return ARCH->isEqualAddr(m_address, addr.m_address);
}
bool
CNetworkAddress::operator!=(const CNetworkAddress& addr) const
{
return !operator==(addr);
}
bool
CNetworkAddress::isValid() const
{
return (m_address != NULL);
}
const CArchNetAddress&
CNetworkAddress::getAddress() const
{
return m_address;
}
int
CNetworkAddress::getPort() const
{
return m_port;
}
CString
CNetworkAddress::getHostname() const
{
return m_hostname;
}
void
CNetworkAddress::checkPort()
{
// check port number
if (m_port <= 0 || m_port > 65535) {
throw XSocketAddress(XSocketAddress::kBadPort, m_hostname, m_port);
}
}

View File

@@ -0,0 +1,125 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CNETWORKADDRESS_H
#define CNETWORKADDRESS_H
#include "CString.h"
#include "BasicTypes.h"
#include "IArchNetwork.h"
//! Network address type
/*!
This class represents a network address.
*/
class CNetworkAddress {
public:
/*!
Constructs the invalid address
*/
CNetworkAddress();
/*!
Construct the wildcard address with the given port. \c port must
not be zero.
*/
CNetworkAddress(int port);
/*!
Construct the network address for the given \c hostname and \c port.
If \c hostname can be parsed as a numerical address then that's how
it's used, otherwise it's used as a host name. If \c hostname ends
in ":[0-9]+" then that suffix is extracted and used as the port,
overridding the port parameter. The resulting port must be a valid
port number (zero is not a valid port number) otherwise \c XSocketAddress
is thrown with an error of \c XSocketAddress::kBadPort. The hostname
is not resolved by the c'tor; use \c resolve to do that.
*/
CNetworkAddress(const CString& hostname, int port);
CNetworkAddress(const CNetworkAddress&);
~CNetworkAddress();
CNetworkAddress& operator=(const CNetworkAddress&);
//! @name manipulators
//@{
//! Resolve address
/*!
Resolves the hostname to an address. This can be done any number of
times and is done automatically by the c'tor taking a hostname.
Throws XSocketAddress if resolution is unsuccessful, after which
\c isValid returns false until the next call to this method.
*/
void resolve();
//@}
//! @name accessors
//@{
//! Check address equality
/*!
Returns true if this address is equal to \p address.
*/
bool operator==(const CNetworkAddress& address) const;
//! Check address inequality
/*!
Returns true if this address is not equal to \p address.
*/
bool operator!=(const CNetworkAddress& address) const;
//! Check address validity
/*!
Returns true if this is not the invalid address.
*/
bool isValid() const;
//! Get address
/*!
Returns the address in the platform's native network address
structure.
*/
const CArchNetAddress& getAddress() const;
//! Get port
/*!
Returns the port passed to the c'tor as a suffix to the hostname,
if that existed, otherwise as passed directly to the c'tor.
*/
int getPort() const;
//! Get hostname
/*!
Returns the hostname passed to the c'tor sans any port suffix.
*/
CString getHostname() const;
//@}
private:
void checkPort();
private:
CArchNetAddress m_address;
CString m_hostname;
int m_port;
};
#endif

View File

@@ -0,0 +1,362 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2004 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* 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 "CSocketMultiplexer.h"
#include "ISocketMultiplexerJob.h"
#include "CCondVar.h"
#include "CLock.h"
#include "CMutex.h"
#include "CThread.h"
#include "CLog.h"
#include "TMethodJob.h"
#include "CArch.h"
#include "XArch.h"
#include "stdvector.h"
//
// CSocketMultiplexer
//
CSocketMultiplexer* CSocketMultiplexer::s_instance = NULL;
CSocketMultiplexer::CSocketMultiplexer() :
m_mutex(new CMutex),
m_thread(NULL),
m_update(false),
m_jobsReady(new CCondVar<bool>(m_mutex, false)),
m_jobListLock(new CCondVar<bool>(m_mutex, false)),
m_jobListLockLocked(new CCondVar<bool>(m_mutex, false)),
m_jobListLocker(NULL),
m_jobListLockLocker(NULL)
{
assert(s_instance == NULL);
// this pointer just has to be unique and not NULL. it will
// never be dereferenced. it's used to identify cursor nodes
// in the jobs list.
m_cursorMark = reinterpret_cast<ISocketMultiplexerJob*>(this);
// start thread
m_thread = new CThread(new TMethodJob<CSocketMultiplexer>(
this, &CSocketMultiplexer::serviceThread));
s_instance = this;
}
CSocketMultiplexer::~CSocketMultiplexer()
{
m_thread->cancel();
m_thread->unblockPollSocket();
m_thread->wait();
delete m_thread;
delete m_jobsReady;
delete m_jobListLock;
delete m_jobListLockLocked;
delete m_jobListLocker;
delete m_jobListLockLocker;
delete m_mutex;
// clean up jobs
for (CSocketJobMap::iterator i = m_socketJobMap.begin();
i != m_socketJobMap.end(); ++i) {
delete *(i->second);
}
s_instance = NULL;
}
CSocketMultiplexer*
CSocketMultiplexer::getInstance()
{
return s_instance;
}
void
CSocketMultiplexer::addSocket(ISocket* socket, ISocketMultiplexerJob* job)
{
assert(socket != NULL);
assert(job != NULL);
// prevent other threads from locking the job list
lockJobListLock();
// break thread out of poll
m_thread->unblockPollSocket();
// lock the job list
lockJobList();
// insert/replace job
CSocketJobMap::iterator i = m_socketJobMap.find(socket);
if (i == m_socketJobMap.end()) {
// we *must* put the job at the end so the order of jobs in
// the list continue to match the order of jobs in pfds in
// serviceThread().
CJobCursor j = m_socketJobs.insert(m_socketJobs.end(), job);
m_update = true;
m_socketJobMap.insert(std::make_pair(socket, j));
}
else {
CJobCursor j = i->second;
if (*j != job) {
delete *j;
*j = job;
}
m_update = true;
}
// unlock the job list
unlockJobList();
}
void
CSocketMultiplexer::removeSocket(ISocket* socket)
{
assert(socket != NULL);
// prevent other threads from locking the job list
lockJobListLock();
// break thread out of poll
m_thread->unblockPollSocket();
// lock the job list
lockJobList();
// remove job. rather than removing it from the map we put NULL
// in the list instead so the order of jobs in the list continues
// to match the order of jobs in pfds in serviceThread().
CSocketJobMap::iterator i = m_socketJobMap.find(socket);
if (i != m_socketJobMap.end()) {
if (*(i->second) != NULL) {
delete *(i->second);
*(i->second) = NULL;
m_update = true;
}
}
// unlock the job list
unlockJobList();
}
void
CSocketMultiplexer::serviceThread(void*)
{
std::vector<IArchNetwork::CPollEntry> pfds;
IArchNetwork::CPollEntry pfd;
// service the connections
for (;;) {
CThread::testCancel();
// wait until there are jobs to handle
{
CLock lock(m_mutex);
while (!(bool)*m_jobsReady) {
m_jobsReady->wait();
}
}
// lock the job list
lockJobListLock();
lockJobList();
// collect poll entries
if (m_update) {
m_update = false;
pfds.clear();
pfds.reserve(m_socketJobMap.size());
CJobCursor cursor = newCursor();
CJobCursor jobCursor = nextCursor(cursor);
while (jobCursor != m_socketJobs.end()) {
ISocketMultiplexerJob* job = *jobCursor;
if (job != NULL) {
pfd.m_socket = job->getSocket();
pfd.m_events = 0;
if (job->isReadable()) {
pfd.m_events |= IArchNetwork::kPOLLIN;
}
if (job->isWritable()) {
pfd.m_events |= IArchNetwork::kPOLLOUT;
}
pfds.push_back(pfd);
}
jobCursor = nextCursor(cursor);
}
deleteCursor(cursor);
}
int status;
try {
// check for status
if (!pfds.empty()) {
status = ARCH->pollSocket(&pfds[0], (int)pfds.size(), -1);
}
else {
status = 0;
}
}
catch (XArchNetwork& e) {
LOG((CLOG_WARN "error in socket multiplexer: %s", e.what().c_str()));
status = 0;
}
if (status != 0) {
// iterate over socket jobs, invoking each and saving the
// new job.
UInt32 i = 0;
CJobCursor cursor = newCursor();
CJobCursor jobCursor = nextCursor(cursor);
while (i < pfds.size() && jobCursor != m_socketJobs.end()) {
if (*jobCursor != NULL) {
// get poll state
unsigned short revents = pfds[i].m_revents;
bool read = ((revents & IArchNetwork::kPOLLIN) != 0);
bool write = ((revents & IArchNetwork::kPOLLOUT) != 0);
bool error = ((revents & (IArchNetwork::kPOLLERR |
IArchNetwork::kPOLLNVAL)) != 0);
// run job
ISocketMultiplexerJob* job = *jobCursor;
ISocketMultiplexerJob* newJob = job->run(read, write, error);
// save job, if different
if (newJob != job) {
CLock lock(m_mutex);
delete job;
*jobCursor = newJob;
m_update = true;
}
++i;
}
// next job
jobCursor = nextCursor(cursor);
}
deleteCursor(cursor);
}
// delete any removed socket jobs
for (CSocketJobMap::iterator i = m_socketJobMap.begin();
i != m_socketJobMap.end();) {
if (*(i->second) == NULL) {
m_socketJobMap.erase(i++);
m_update = true;
}
else {
++i;
}
}
// unlock the job list
unlockJobList();
}
}
CSocketMultiplexer::CJobCursor
CSocketMultiplexer::newCursor()
{
CLock lock(m_mutex);
return m_socketJobs.insert(m_socketJobs.begin(), m_cursorMark);
}
CSocketMultiplexer::CJobCursor
CSocketMultiplexer::nextCursor(CJobCursor cursor)
{
CLock lock(m_mutex);
CJobCursor j = m_socketJobs.end();
CJobCursor i = cursor;
while (++i != m_socketJobs.end()) {
if (*i != m_cursorMark) {
// found a real job (as opposed to a cursor)
j = i;
// move our cursor just past the job
m_socketJobs.splice(++i, m_socketJobs, cursor);
break;
}
}
return j;
}
void
CSocketMultiplexer::deleteCursor(CJobCursor cursor)
{
CLock lock(m_mutex);
m_socketJobs.erase(cursor);
}
void
CSocketMultiplexer::lockJobListLock()
{
CLock lock(m_mutex);
// wait for the lock on the lock
while (*m_jobListLockLocked) {
m_jobListLockLocked->wait();
}
// take ownership of the lock on the lock
*m_jobListLockLocked = true;
m_jobListLockLocker = new CThread(CThread::getCurrentThread());
}
void
CSocketMultiplexer::lockJobList()
{
CLock lock(m_mutex);
// make sure we're the one that called lockJobListLock()
assert(*m_jobListLockLocker == CThread::getCurrentThread());
// wait for the job list lock
while (*m_jobListLock) {
m_jobListLock->wait();
}
// take ownership of the lock
*m_jobListLock = true;
m_jobListLocker = m_jobListLockLocker;
m_jobListLockLocker = NULL;
// release the lock on the lock
*m_jobListLockLocked = false;
m_jobListLockLocked->broadcast();
}
void
CSocketMultiplexer::unlockJobList()
{
CLock lock(m_mutex);
// make sure we're the one that called lockJobList()
assert(*m_jobListLocker == CThread::getCurrentThread());
// release the lock
delete m_jobListLocker;
m_jobListLocker = NULL;
*m_jobListLock = false;
m_jobListLock->signal();
// set new jobs ready state
bool isReady = !m_socketJobMap.empty();
if (*m_jobsReady != isReady) {
*m_jobsReady = isReady;
m_jobsReady->signal();
}
}

View File

@@ -0,0 +1,114 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2004 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CSOCKETMULTIPLEXER_H
#define CSOCKETMULTIPLEXER_H
#include "IArchNetwork.h"
#include "stdlist.h"
#include "stdmap.h"
template <class T>
class CCondVar;
class CMutex;
class CThread;
class ISocket;
class ISocketMultiplexerJob;
//! Socket multiplexer
/*!
A socket multiplexer services multiple sockets simultaneously.
*/
class CSocketMultiplexer {
public:
CSocketMultiplexer();
~CSocketMultiplexer();
//! @name manipulators
//@{
void addSocket(ISocket*, ISocketMultiplexerJob*);
void removeSocket(ISocket*);
//@}
//! @name accessors
//@{
// maybe belongs on ISocketMultiplexer
static CSocketMultiplexer*
getInstance();
//@}
private:
// list of jobs. we use a list so we can safely iterate over it
// while other threads modify it.
typedef std::list<ISocketMultiplexerJob*> CSocketJobs;
typedef CSocketJobs::iterator CJobCursor;
typedef std::map<ISocket*, CJobCursor> CSocketJobMap;
// service sockets. the service thread will only access m_sockets
// and m_update while m_pollable and m_polling are true. all other
// threads must only modify these when m_pollable and m_polling are
// false. only the service thread sets m_polling.
void serviceThread(void*);
// create, iterate, and destroy a cursor. a cursor is used to
// safely iterate through the job list while other threads modify
// the list. it works by inserting a dummy item in the list and
// moving that item through the list. the dummy item will never
// be removed by other edits so an iterator pointing at the item
// remains valid until we remove the dummy item in deleteCursor().
// nextCursor() finds the next non-dummy item, moves our dummy
// item just past it, and returns an iterator for the non-dummy
// item. all cursor calls lock the mutex for their duration.
CJobCursor newCursor();
CJobCursor nextCursor(CJobCursor);
void deleteCursor(CJobCursor);
// lock out locking the job list. this blocks if another thread
// has already locked out locking. once it returns, only the
// calling thread will be able to lock the job list after any
// current lock is released.
void lockJobListLock();
// lock the job list. this blocks if the job list is already
// locked. the calling thread must have called requestJobLock.
void lockJobList();
// unlock the job list and the lock out on locking.
void unlockJobList();
private:
CMutex* m_mutex;
CThread* m_thread;
bool m_update;
CCondVar<bool>* m_jobsReady;
CCondVar<bool>* m_jobListLock;
CCondVar<bool>* m_jobListLockLocked;
CThread* m_jobListLocker;
CThread* m_jobListLockLocker;
CSocketJobs m_socketJobs;
CSocketJobMap m_socketJobMap;
ISocketMultiplexerJob* m_cursorMark;
static CSocketMultiplexer* s_instance;
};
#endif

View File

@@ -0,0 +1,146 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* 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 "CTCPListenSocket.h"
#include "CNetworkAddress.h"
#include "CSocketMultiplexer.h"
#include "CTCPSocket.h"
#include "TSocketMultiplexerMethodJob.h"
#include "XSocket.h"
#include "XIO.h"
#include "CLock.h"
#include "CMutex.h"
#include "IEventQueue.h"
#include "CArch.h"
#include "XArch.h"
//
// CTCPListenSocket
//
CTCPListenSocket::CTCPListenSocket()
{
m_mutex = new CMutex;
try {
m_socket = ARCH->newSocket(IArchNetwork::kINET, IArchNetwork::kSTREAM);
}
catch (XArchNetwork& e) {
throw XSocketCreate(e.what());
}
}
CTCPListenSocket::~CTCPListenSocket()
{
try {
if (m_socket != NULL) {
CSocketMultiplexer::getInstance()->removeSocket(this);
ARCH->closeSocket(m_socket);
}
}
catch (...) {
// ignore
}
delete m_mutex;
}
void
CTCPListenSocket::bind(const CNetworkAddress& addr)
{
try {
CLock lock(m_mutex);
ARCH->setReuseAddrOnSocket(m_socket, true);
ARCH->bindSocket(m_socket, addr.getAddress());
ARCH->listenOnSocket(m_socket);
CSocketMultiplexer::getInstance()->addSocket(this,
new TSocketMultiplexerMethodJob<CTCPListenSocket>(
this, &CTCPListenSocket::serviceListening,
m_socket, true, false));
}
catch (XArchNetworkAddressInUse& e) {
throw XSocketAddressInUse(e.what());
}
catch (XArchNetwork& e) {
throw XSocketBind(e.what());
}
}
void
CTCPListenSocket::close()
{
CLock lock(m_mutex);
if (m_socket == NULL) {
throw XIOClosed();
}
try {
CSocketMultiplexer::getInstance()->removeSocket(this);
ARCH->closeSocket(m_socket);
m_socket = NULL;
}
catch (XArchNetwork& e) {
throw XSocketIOClose(e.what());
}
}
void*
CTCPListenSocket::getEventTarget() const
{
return const_cast<void*>(reinterpret_cast<const void*>(this));
}
IDataSocket*
CTCPListenSocket::accept()
{
IDataSocket* socket = NULL;
try {
socket = new CTCPSocket(ARCH->acceptSocket(m_socket, NULL));
if (socket != NULL) {
CSocketMultiplexer::getInstance()->addSocket(this,
new TSocketMultiplexerMethodJob<CTCPListenSocket>(
this, &CTCPListenSocket::serviceListening,
m_socket, true, false));
}
return socket;
}
catch (XArchNetwork&) {
if (socket != NULL) {
delete socket;
}
return NULL;
}
catch (std::exception &ex) {
if (socket != NULL) {
delete socket;
}
throw ex;
}
}
ISocketMultiplexerJob*
CTCPListenSocket::serviceListening(ISocketMultiplexerJob* job,
bool read, bool, bool error)
{
if (error) {
close();
return NULL;
}
if (read) {
EVENTQUEUE->addEvent(CEvent(getConnectingEvent(), this, NULL));
// stop polling on this socket until the client accepts
return NULL;
}
return job;
}

View File

@@ -0,0 +1,54 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CTCPLISTENSOCKET_H
#define CTCPLISTENSOCKET_H
#include "IListenSocket.h"
#include "IArchNetwork.h"
class CMutex;
class ISocketMultiplexerJob;
//! TCP listen socket
/*!
A listen socket using TCP.
*/
class CTCPListenSocket : public IListenSocket {
public:
CTCPListenSocket();
~CTCPListenSocket();
// ISocket overrides
virtual void bind(const CNetworkAddress&);
virtual void close();
virtual void* getEventTarget() const;
// IListenSocket overrides
virtual IDataSocket* accept();
private:
ISocketMultiplexerJob*
serviceListening(ISocketMultiplexerJob*,
bool, bool, bool);
private:
CArchSocket m_socket;
CMutex* m_mutex;
};
#endif

545
src/lib/net/CTCPSocket.cpp Normal file
View File

@@ -0,0 +1,545 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* 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 "CTCPSocket.h"
#include "CNetworkAddress.h"
#include "CSocketMultiplexer.h"
#include "TSocketMultiplexerMethodJob.h"
#include "XSocket.h"
#include "CLock.h"
#include "CLog.h"
#include "IEventQueue.h"
#include "IEventJob.h"
#include "CArch.h"
#include "XArch.h"
#include <cstring>
#include <cstdlib>
#include <memory>
//
// CTCPSocket
//
CTCPSocket::CTCPSocket() :
m_mutex(),
m_flushed(&m_mutex, true)
{
try {
m_socket = ARCH->newSocket(IArchNetwork::kINET, IArchNetwork::kSTREAM);
}
catch (XArchNetwork& e) {
throw XSocketCreate(e.what());
}
init();
}
CTCPSocket::CTCPSocket(CArchSocket socket) :
m_mutex(),
m_socket(socket),
m_flushed(&m_mutex, true)
{
assert(m_socket != NULL);
// socket starts in connected state
init();
onConnected();
setJob(newJob());
}
CTCPSocket::~CTCPSocket()
{
try {
close();
}
catch (...) {
// ignore
}
}
void
CTCPSocket::bind(const CNetworkAddress& addr)
{
try {
ARCH->bindSocket(m_socket, addr.getAddress());
}
catch (XArchNetworkAddressInUse& e) {
throw XSocketAddressInUse(e.what());
}
catch (XArchNetwork& e) {
throw XSocketBind(e.what());
}
}
void
CTCPSocket::close()
{
// remove ourself from the multiplexer
setJob(NULL);
CLock lock(&m_mutex);
// clear buffers and enter disconnected state
if (m_connected) {
sendEvent(getDisconnectedEvent());
}
onDisconnected();
// close the socket
if (m_socket != NULL) {
CArchSocket socket = m_socket;
m_socket = NULL;
try {
ARCH->closeSocket(socket);
}
catch (XArchNetwork& e) {
// ignore, there's not much we can do
LOG((CLOG_WARN "error closing socket: %s", e.what().c_str()));
}
}
}
void*
CTCPSocket::getEventTarget() const
{
return const_cast<void*>(reinterpret_cast<const void*>(this));
}
UInt32
CTCPSocket::read(void* buffer, UInt32 n)
{
// copy data directly from our input buffer
CLock lock(&m_mutex);
UInt32 size = m_inputBuffer.getSize();
if (n > size) {
n = size;
}
if (buffer != NULL && n != 0) {
memcpy(buffer, m_inputBuffer.peek(n), n);
}
m_inputBuffer.pop(n);
// if no more data and we cannot read or write then send disconnected
if (n > 0 && m_inputBuffer.getSize() == 0 && !m_readable && !m_writable) {
sendEvent(getDisconnectedEvent());
m_connected = false;
}
return n;
}
void
CTCPSocket::write(const void* buffer, UInt32 n)
{
bool wasEmpty;
{
CLock lock(&m_mutex);
// must not have shutdown output
if (!m_writable) {
sendEvent(getOutputErrorEvent());
return;
}
// ignore empty writes
if (n == 0) {
return;
}
// copy data to the output buffer
wasEmpty = (m_outputBuffer.getSize() == 0);
m_outputBuffer.write(buffer, n);
// there's data to write
m_flushed = false;
}
// make sure we're waiting to write
if (wasEmpty) {
setJob(newJob());
}
}
void
CTCPSocket::flush()
{
CLock lock(&m_mutex);
while (m_flushed == false) {
m_flushed.wait();
}
}
void
CTCPSocket::shutdownInput()
{
bool useNewJob = false;
{
CLock lock(&m_mutex);
// shutdown socket for reading
try {
ARCH->closeSocketForRead(m_socket);
}
catch (XArchNetwork&) {
// ignore
}
// shutdown buffer for reading
if (m_readable) {
sendEvent(getInputShutdownEvent());
onInputShutdown();
useNewJob = true;
}
}
if (useNewJob) {
setJob(newJob());
}
}
void
CTCPSocket::shutdownOutput()
{
bool useNewJob = false;
{
CLock lock(&m_mutex);
// shutdown socket for writing
try {
ARCH->closeSocketForWrite(m_socket);
}
catch (XArchNetwork&) {
// ignore
}
// shutdown buffer for writing
if (m_writable) {
sendEvent(getOutputShutdownEvent());
onOutputShutdown();
useNewJob = true;
}
}
if (useNewJob) {
setJob(newJob());
}
}
bool
CTCPSocket::isReady() const
{
CLock lock(&m_mutex);
return (m_inputBuffer.getSize() > 0);
}
UInt32
CTCPSocket::getSize() const
{
CLock lock(&m_mutex);
return m_inputBuffer.getSize();
}
void
CTCPSocket::connect(const CNetworkAddress& addr)
{
{
CLock lock(&m_mutex);
// fail on attempts to reconnect
if (m_socket == NULL || m_connected) {
sendConnectionFailedEvent("busy");
return;
}
try {
if (ARCH->connectSocket(m_socket, addr.getAddress())) {
sendEvent(getConnectedEvent());
onConnected();
}
else {
// connection is in progress
m_writable = true;
}
}
catch (XArchNetwork& e) {
throw XSocketConnect(e.what());
}
}
setJob(newJob());
}
void
CTCPSocket::init()
{
// default state
m_connected = false;
m_readable = false;
m_writable = false;
try {
// turn off Nagle algorithm. we send lots of very short messages
// that should be sent without (much) delay. for example, the
// mouse motion messages are much less useful if they're delayed.
ARCH->setNoDelayOnSocket(m_socket, true);
}
catch (XArchNetwork& e) {
try {
ARCH->closeSocket(m_socket);
m_socket = NULL;
}
catch (XArchNetwork&) {
// ignore
}
throw XSocketCreate(e.what());
}
}
void
CTCPSocket::setJob(ISocketMultiplexerJob* job)
{
// multiplexer will delete the old job
if (job == NULL) {
CSocketMultiplexer::getInstance()->removeSocket(this);
}
else {
CSocketMultiplexer::getInstance()->addSocket(this, job);
}
}
ISocketMultiplexerJob*
CTCPSocket::newJob()
{
// note -- must have m_mutex locked on entry
if (m_socket == NULL) {
return NULL;
}
else if (!m_connected) {
assert(!m_readable);
if (!(m_readable || m_writable)) {
return NULL;
}
return new TSocketMultiplexerMethodJob<CTCPSocket>(
this, &CTCPSocket::serviceConnecting,
m_socket, m_readable, m_writable);
}
else {
if (!(m_readable || (m_writable && (m_outputBuffer.getSize() > 0)))) {
return NULL;
}
return new TSocketMultiplexerMethodJob<CTCPSocket>(
this, &CTCPSocket::serviceConnected,
m_socket, m_readable,
m_writable && (m_outputBuffer.getSize() > 0));
}
}
void
CTCPSocket::sendConnectionFailedEvent(const char* msg)
{
CConnectionFailedInfo* info = new CConnectionFailedInfo(msg);
EVENTQUEUE->addEvent(CEvent(getConnectionFailedEvent(),
getEventTarget(), info, CEvent::kDontFreeData));
}
void
CTCPSocket::sendEvent(CEvent::Type type)
{
EVENTQUEUE->addEvent(CEvent(type, getEventTarget(), NULL));
}
void
CTCPSocket::onConnected()
{
m_connected = true;
m_readable = true;
m_writable = true;
}
void
CTCPSocket::onInputShutdown()
{
m_inputBuffer.pop(m_inputBuffer.getSize());
m_readable = false;
}
void
CTCPSocket::onOutputShutdown()
{
m_outputBuffer.pop(m_outputBuffer.getSize());
m_writable = false;
// we're now flushed
m_flushed = true;
m_flushed.broadcast();
}
void
CTCPSocket::onDisconnected()
{
// disconnected
onInputShutdown();
onOutputShutdown();
m_connected = false;
}
ISocketMultiplexerJob*
CTCPSocket::serviceConnecting(ISocketMultiplexerJob* job,
bool, bool write, bool error)
{
CLock lock(&m_mutex);
// should only check for errors if error is true but checking a new
// socket (and a socket that's connecting should be new) for errors
// should be safe and Mac OS X appears to have a bug where a
// non-blocking stream socket that fails to connect immediately is
// reported by select as being writable (i.e. connected) even when
// the connection has failed. this is easily demonstrated on OS X
// 10.3.4 by starting a synergy client and telling to connect to
// another system that's not running a synergy server. it will
// claim to have connected then quickly disconnect (i guess because
// read returns 0 bytes). unfortunately, synergy attempts to
// reconnect immediately, the process repeats and we end up
// spinning the CPU. luckily, OS X does set SO_ERROR on the
// socket correctly when the connection has failed so checking for
// errors works. (curiously, sometimes OS X doesn't report
// connection refused. when that happens it at least doesn't
// report the socket as being writable so synergy is able to time
// out the attempt.)
if (error || true) {
try {
// connection may have failed or succeeded
ARCH->throwErrorOnSocket(m_socket);
}
catch (XArchNetwork& e) {
sendConnectionFailedEvent(e.what().c_str());
onDisconnected();
return newJob();
}
}
if (write) {
sendEvent(getConnectedEvent());
onConnected();
return newJob();
}
return job;
}
ISocketMultiplexerJob*
CTCPSocket::serviceConnected(ISocketMultiplexerJob* job,
bool read, bool write, bool error)
{
CLock lock(&m_mutex);
if (error) {
sendEvent(getDisconnectedEvent());
onDisconnected();
return newJob();
}
bool needNewJob = false;
if (write) {
try {
// write data
UInt32 n = m_outputBuffer.getSize();
const void* buffer = m_outputBuffer.peek(n);
n = (UInt32)ARCH->writeSocket(m_socket, buffer, n);
// discard written data
if (n > 0) {
m_outputBuffer.pop(n);
if (m_outputBuffer.getSize() == 0) {
sendEvent(getOutputFlushedEvent());
m_flushed = true;
m_flushed.broadcast();
needNewJob = true;
}
}
}
catch (XArchNetworkShutdown&) {
// remote read end of stream hungup. our output side
// has therefore shutdown.
onOutputShutdown();
sendEvent(getOutputShutdownEvent());
if (!m_readable && m_inputBuffer.getSize() == 0) {
sendEvent(getDisconnectedEvent());
m_connected = false;
}
needNewJob = true;
}
catch (XArchNetworkDisconnected&) {
// stream hungup
onDisconnected();
sendEvent(getDisconnectedEvent());
needNewJob = true;
}
catch (XArchNetwork& e) {
// other write error
LOG((CLOG_WARN "error writing socket: %s", e.what().c_str()));
onDisconnected();
sendEvent(getOutputErrorEvent());
sendEvent(getDisconnectedEvent());
needNewJob = true;
}
}
if (read && m_readable) {
try {
UInt8 buffer[4096];
size_t n = ARCH->readSocket(m_socket, buffer, sizeof(buffer));
if (n > 0) {
bool wasEmpty = (m_inputBuffer.getSize() == 0);
// slurp up as much as possible
do {
m_inputBuffer.write(buffer, (UInt32)n);
n = ARCH->readSocket(m_socket, buffer, sizeof(buffer));
} while (n > 0);
// send input ready if input buffer was empty
if (wasEmpty) {
sendEvent(getInputReadyEvent());
}
}
else {
// remote write end of stream hungup. our input side
// has therefore shutdown but don't flush our buffer
// since there's still data to be read.
sendEvent(getInputShutdownEvent());
if (!m_writable && m_inputBuffer.getSize() == 0) {
sendEvent(getDisconnectedEvent());
m_connected = false;
}
m_readable = false;
needNewJob = true;
}
}
catch (XArchNetworkDisconnected&) {
// stream hungup
sendEvent(getDisconnectedEvent());
onDisconnected();
needNewJob = true;
}
catch (XArchNetwork& e) {
// ignore other read error
LOG((CLOG_WARN "error reading socket: %s", e.what().c_str()));
}
}
return needNewJob ? newJob() : job;
}

89
src/lib/net/CTCPSocket.h Normal file
View File

@@ -0,0 +1,89 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CTCPSOCKET_H
#define CTCPSOCKET_H
#include "IDataSocket.h"
#include "CStreamBuffer.h"
#include "CCondVar.h"
#include "CMutex.h"
#include "IArchNetwork.h"
class CMutex;
class CThread;
class ISocketMultiplexerJob;
//! TCP data socket
/*!
A data socket using TCP.
*/
class CTCPSocket : public IDataSocket {
public:
CTCPSocket();
CTCPSocket(CArchSocket);
~CTCPSocket();
// ISocket overrides
virtual void bind(const CNetworkAddress&);
virtual void close();
virtual void* getEventTarget() const;
// IStream overrides
virtual UInt32 read(void* buffer, UInt32 n);
virtual void write(const void* buffer, UInt32 n);
virtual void flush();
virtual void shutdownInput();
virtual void shutdownOutput();
virtual bool isReady() const;
virtual UInt32 getSize() const;
// IDataSocket overrides
virtual void connect(const CNetworkAddress&);
private:
void init();
void setJob(ISocketMultiplexerJob*);
ISocketMultiplexerJob* newJob();
void sendConnectionFailedEvent(const char*);
void sendEvent(CEvent::Type);
void onConnected();
void onInputShutdown();
void onOutputShutdown();
void onDisconnected();
ISocketMultiplexerJob*
serviceConnecting(ISocketMultiplexerJob*,
bool, bool, bool);
ISocketMultiplexerJob*
serviceConnected(ISocketMultiplexerJob*,
bool, bool, bool);
private:
CMutex m_mutex;
CArchSocket m_socket;
CStreamBuffer m_inputBuffer;
CStreamBuffer m_outputBuffer;
CCondVar<bool> m_flushed;
bool m_connected;
bool m_readable;
bool m_writable;
};
#endif

View File

@@ -0,0 +1,46 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* 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 "CTCPSocketFactory.h"
#include "CTCPSocket.h"
#include "CTCPListenSocket.h"
//
// CTCPSocketFactory
//
CTCPSocketFactory::CTCPSocketFactory()
{
// do nothing
}
CTCPSocketFactory::~CTCPSocketFactory()
{
// do nothing
}
IDataSocket*
CTCPSocketFactory::create() const
{
return new CTCPSocket;
}
IListenSocket*
CTCPSocketFactory::createListen() const
{
return new CTCPListenSocket;
}

View File

@@ -0,0 +1,34 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CTCPSOCKETFACTORY_H
#define CTCPSOCKETFACTORY_H
#include "ISocketFactory.h"
//! Socket factory for TCP sockets
class CTCPSocketFactory : public ISocketFactory {
public:
CTCPSocketFactory();
virtual ~CTCPSocketFactory();
// ISocketFactory overrides
virtual IDataSocket* create() const;
virtual IListenSocket* createListen() const;
};
#endif

View File

@@ -0,0 +1,55 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* 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 "IDataSocket.h"
#include "CEventQueue.h"
//
// IDataSocket
//
CEvent::Type IDataSocket::s_connectedEvent = CEvent::kUnknown;
CEvent::Type IDataSocket::s_failedEvent = CEvent::kUnknown;
CEvent::Type
IDataSocket::getConnectedEvent()
{
return EVENTQUEUE->registerTypeOnce(s_connectedEvent,
"IDataSocket::connected");
}
CEvent::Type
IDataSocket::getConnectionFailedEvent()
{
return EVENTQUEUE->registerTypeOnce(s_failedEvent,
"IDataSocket::failed");
}
void
IDataSocket::close()
{
// this is here to work around a VC++6 bug. see the header file.
assert(0 && "bad call");
}
void*
IDataSocket::getEventTarget() const
{
// this is here to work around a VC++6 bug. see the header file.
assert(0 && "bad call");
return NULL;
}

94
src/lib/net/IDataSocket.h Normal file
View File

@@ -0,0 +1,94 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2004 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef IDATASOCKET_H
#define IDATASOCKET_H
#include "ISocket.h"
#include "IStream.h"
#include "CString.h"
//! Data stream socket interface
/*!
This interface defines the methods common to all network sockets that
represent a full-duplex data stream.
*/
class IDataSocket : public ISocket, public IStream {
public:
class CConnectionFailedInfo {
public:
CConnectionFailedInfo(const char* what) : m_what(what) { }
CString m_what;
};
//! @name manipulators
//@{
//! Connect socket
/*!
Attempt to connect to a remote endpoint. This returns immediately
and sends a connected event when successful or a connection failed
event when it fails. The stream acts as if shutdown for input and
output until the stream connects.
*/
virtual void connect(const CNetworkAddress&) = 0;
//@}
//! @name accessors
//@{
//! Get connected event type
/*!
Returns the socket connected event type. A socket sends this
event when a remote connection has been established.
*/
static CEvent::Type getConnectedEvent();
//! Get connection failed event type
/*!
Returns the socket connection failed event type. A socket sends
this event when an attempt to connect to a remote port has failed.
The data is a pointer to a CConnectionFailedInfo.
*/
static CEvent::Type getConnectionFailedEvent();
//@}
// ISocket overrides
// close() and getEventTarget() aren't pure to work around a bug
// in VC++6. it claims the methods are unused locals and warns
// that it's removing them. it's presumably tickled by inheriting
// methods with identical signatures from both superclasses.
virtual void bind(const CNetworkAddress&) = 0;
virtual void close();
virtual void* getEventTarget() const;
// IStream overrides
virtual UInt32 read(void* buffer, UInt32 n) = 0;
virtual void write(const void* buffer, UInt32 n) = 0;
virtual void flush() = 0;
virtual void shutdownInput() = 0;
virtual void shutdownOutput() = 0;
virtual bool isReady() const = 0;
virtual UInt32 getSize() const = 0;
private:
static CEvent::Type s_connectedEvent;
static CEvent::Type s_failedEvent;
};
#endif

View File

@@ -0,0 +1,32 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* 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 "IListenSocket.h"
#include "CEventQueue.h"
//
// IListenSocket
//
CEvent::Type IListenSocket::s_connectingEvent = CEvent::kUnknown;
CEvent::Type
IListenSocket::getConnectingEvent()
{
return EVENTQUEUE->registerTypeOnce(s_connectingEvent,
"IListenSocket::connecting");
}

View File

@@ -0,0 +1,65 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ILISTENSOCKET_H
#define ILISTENSOCKET_H
#include "ISocket.h"
class IDataSocket;
//! Listen socket interface
/*!
This interface defines the methods common to all network sockets that
listen for incoming connections.
*/
class IListenSocket : public ISocket {
public:
//! @name manipulators
//@{
//! Accept connection
/*!
Accept a connection, returning a socket representing the full-duplex
data stream. Returns NULL if no socket is waiting to be accepted.
This is only valid after a call to \c bind().
*/
virtual IDataSocket* accept() = 0;
//@}
//! @name accessors
//@{
//! Get connecting event type
/*!
Returns the socket connecting event type. A socket sends this
event when a remote connection is waiting to be accepted.
*/
static CEvent::Type getConnectingEvent();
//@}
// ISocket overrides
virtual void bind(const CNetworkAddress&) = 0;
virtual void close() = 0;
virtual void* getEventTarget() const = 0;
private:
static CEvent::Type s_connectingEvent;
};
#endif

32
src/lib/net/ISocket.cpp Normal file
View File

@@ -0,0 +1,32 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* 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 "ISocket.h"
#include "CEventQueue.h"
//
// ISocket
//
CEvent::Type ISocket::s_disconnectedEvent = CEvent::kUnknown;
CEvent::Type
ISocket::getDisconnectedEvent()
{
return EVENTQUEUE->registerTypeOnce(s_disconnectedEvent,
"ISocket::disconnected");
}

72
src/lib/net/ISocket.h Normal file
View File

@@ -0,0 +1,72 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ISOCKET_H
#define ISOCKET_H
#include "IInterface.h"
#include "CEvent.h"
class CNetworkAddress;
//! Generic socket interface
/*!
This interface defines the methods common to all network sockets.
Generated events use \c this as the target.
*/
class ISocket : public IInterface {
public:
//! @name manipulators
//@{
//! Bind socket to address
/*!
Binds the socket to a particular address.
*/
virtual void bind(const CNetworkAddress&) = 0;
//! Close socket
/*!
Closes the socket. This should flush the output stream.
*/
virtual void close() = 0;
//@}
//! @name accessors
//@{
//! Get event target
/*!
Returns the event target for events generated by this socket.
*/
virtual void* getEventTarget() const = 0;
//! Get disconnected event type
/*!
Returns the socket disconnected event type. A socket sends this
event when the remote side of the socket has disconnected or
shutdown both input and output.
*/
static CEvent::Type getDisconnectedEvent();
//@}
private:
static CEvent::Type s_disconnectedEvent;
};
#endif

View File

@@ -0,0 +1,45 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ISOCKETFACTORY_H
#define ISOCKETFACTORY_H
#include "IInterface.h"
class IDataSocket;
class IListenSocket;
//! Socket factory
/*!
This interface defines the methods common to all factories used to
create sockets.
*/
class ISocketFactory : public IInterface {
public:
//! @name accessors
//@{
//! Create data socket
virtual IDataSocket* create() const = 0;
//! Create listen socket
virtual IListenSocket* createListen() const = 0;
//@}
};
#endif

View File

@@ -0,0 +1,78 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2004 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ISOCKETMULTIPLEXERJOB_H
#define ISOCKETMULTIPLEXERJOB_H
#include "IArchNetwork.h"
#include "IInterface.h"
//! Socket multiplexer job
/*!
A socket multiplexer job handles events on a socket.
*/
class ISocketMultiplexerJob : public IInterface {
public:
//! @name manipulators
//@{
//! Handle socket event
/*!
Called by a socket multiplexer when the socket becomes readable,
writable, or has an error. It should return itself if the same
job can continue to service events, a new job if the socket must
be serviced differently, or NULL if the socket should no longer
be serviced. The socket is readable if \p readable is true,
writable if \p writable is true, and in error if \p error is
true.
This call must not attempt to directly change the job for this
socket by calling \c addSocket() or \c removeSocket() on the
multiplexer. It must instead return the new job. It can,
however, add or remove jobs for other sockets.
*/
virtual ISocketMultiplexerJob*
run(bool readable, bool writable, bool error) = 0;
//@}
//! @name accessors
//@{
//! Get the socket
/*!
Return the socket to multiplex
*/
virtual CArchSocket getSocket() const = 0;
//! Check for interest in readability
/*!
Return true if the job is interested in being run if the socket
becomes readable.
*/
virtual bool isReadable() const = 0;
//! Check for interest in writability
/*!
Return true if the job is interested in being run if the socket
becomes writable.
*/
virtual bool isWritable() const = 0;
//@}
};
#endif

View File

@@ -0,0 +1,111 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2004 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TSOCKERMULTIPLEXERMETHODJOB_H
#define TSOCKERMULTIPLEXERMETHODJOB_H
#include "ISocketMultiplexerJob.h"
#include "CArch.h"
//! Use a method as a socket multiplexer job
/*!
A socket multiplexer job class that invokes a member function.
*/
template <class T>
class TSocketMultiplexerMethodJob : public ISocketMultiplexerJob {
public:
typedef ISocketMultiplexerJob*
(T::*Method)(ISocketMultiplexerJob*, bool, bool, bool);
//! run() invokes \c object->method(arg)
TSocketMultiplexerMethodJob(T* object, Method method,
CArchSocket socket, bool readable, bool writeable);
virtual ~TSocketMultiplexerMethodJob();
// IJob overrides
virtual ISocketMultiplexerJob*
run(bool readable, bool writable, bool error);
virtual CArchSocket getSocket() const;
virtual bool isReadable() const;
virtual bool isWritable() const;
private:
T* m_object;
Method m_method;
CArchSocket m_socket;
bool m_readable;
bool m_writable;
void* m_arg;
};
template <class T>
inline
TSocketMultiplexerMethodJob<T>::TSocketMultiplexerMethodJob(T* object,
Method method, CArchSocket socket,
bool readable, bool writable) :
m_object(object),
m_method(method),
m_socket(ARCH->copySocket(socket)),
m_readable(readable),
m_writable(writable)
{
// do nothing
}
template <class T>
inline
TSocketMultiplexerMethodJob<T>::~TSocketMultiplexerMethodJob()
{
ARCH->closeSocket(m_socket);
}
template <class T>
inline
ISocketMultiplexerJob*
TSocketMultiplexerMethodJob<T>::run(bool read, bool write, bool error)
{
if (m_object != NULL) {
return (m_object->*m_method)(this, read, write, error);
}
return NULL;
}
template <class T>
inline
CArchSocket
TSocketMultiplexerMethodJob<T>::getSocket() const
{
return m_socket;
}
template <class T>
inline
bool
TSocketMultiplexerMethodJob<T>::isReadable() const
{
return m_readable;
}
template <class T>
inline
bool
TSocketMultiplexerMethodJob<T>::isWritable() const
{
return m_writable;
}
#endif

116
src/lib/net/XSocket.cpp Normal file
View File

@@ -0,0 +1,116 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* 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 "XSocket.h"
#include "CStringUtil.h"
//
// XSocketAddress
//
XSocketAddress::XSocketAddress(EError error,
const CString& hostname, int port) throw() :
m_error(error),
m_hostname(hostname),
m_port(port)
{
// do nothing
}
XSocketAddress::EError
XSocketAddress::getError() const throw()
{
return m_error;
}
CString
XSocketAddress::getHostname() const throw()
{
return m_hostname;
}
int
XSocketAddress::getPort() const throw()
{
return m_port;
}
CString
XSocketAddress::getWhat() const throw()
{
static const char* s_errorID[] = {
"XSocketAddressUnknown",
"XSocketAddressNotFound",
"XSocketAddressNoAddress",
"XSocketAddressUnsupported",
"XSocketAddressBadPort"
};
static const char* s_errorMsg[] = {
"unknown error for: %{1}:%{2}",
"address not found for: %{1}",
"no address for: %{1}",
"unsupported address for: %{1}",
"invalid port" // m_port may not be set to the bad port
};
return format(s_errorID[m_error], s_errorMsg[m_error],
m_hostname.c_str(),
CStringUtil::print("%d", m_port).c_str());
}
//
// XSocketIOClose
//
CString
XSocketIOClose::getWhat() const throw()
{
return format("XSocketIOClose", "close: %{1}", what());
}
//
// XSocketBind
//
CString
XSocketBind::getWhat() const throw()
{
return format("XSocketBind", "cannot bind address: %{1}", what());
}
//
// XSocketConnect
//
CString
XSocketConnect::getWhat() const throw()
{
return format("XSocketConnect", "cannot connect socket: %{1}", what());
}
//
// XSocketCreate
//
CString
XSocketCreate::getWhat() const throw()
{
return format("XSocketCreate", "cannot create socket: %{1}", what());
}

99
src/lib/net/XSocket.h Normal file
View File

@@ -0,0 +1,99 @@
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2002 Chris Schoeneman, Nick Bolton, Sorin Sbarnea
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef XSOCKET_H
#define XSOCKET_H
#include "XIO.h"
#include "XBase.h"
#include "CString.h"
#include "BasicTypes.h"
//! Generic socket exception
XBASE_SUBCLASS(XSocket, XBase);
//! Socket bad address exception
/*!
Thrown when attempting to create an invalid network address.
*/
class XSocketAddress : public XSocket {
public:
//! Failure codes
enum EError {
kUnknown, //!< Unknown error
kNotFound, //!< The hostname is unknown
kNoAddress, //!< The hostname is valid but has no IP address
kUnsupported, //!< The hostname is valid but has no supported address
kBadPort //!< The port is invalid
};
XSocketAddress(EError, const CString& hostname, int port) throw();
//! @name accessors
//@{
//! Get the error code
EError getError() const throw();
//! Get the hostname
CString getHostname() const throw();
//! Get the port
int getPort() const throw();
//@}
protected:
// XBase overrides
virtual CString getWhat() const throw();
private:
EError m_error;
CString m_hostname;
int m_port;
};
//! I/O closing exception
/*!
Thrown if a stream cannot be closed.
*/
XBASE_SUBCLASS_FORMAT(XSocketIOClose, XIOClose);
//! Socket cannot bind address exception
/*!
Thrown when a socket cannot be bound to an address.
*/
XBASE_SUBCLASS_FORMAT(XSocketBind, XSocket);
//! Socket address in use exception
/*!
Thrown when a socket cannot be bound to an address because the address
is already in use.
*/
XBASE_SUBCLASS(XSocketAddressInUse, XSocketBind);
//! Cannot connect socket exception
/*!
Thrown when a socket cannot connect to a remote endpoint.
*/
XBASE_SUBCLASS_FORMAT(XSocketConnect, XSocket);
//! Cannot create socket exception
/*!
Thrown when a socket cannot be created (by the operating system).
*/
XBASE_SUBCLASS_FORMAT(XSocketCreate, XSocket);
#endif