diff --git a/common/network/Socket.cxx b/common/network/Socket.cxx index 8bb9676371..879a63d0f7 100644 --- a/common/network/Socket.cxx +++ b/common/network/Socket.cxx @@ -39,6 +39,8 @@ #include #include +#include + #include using namespace network; @@ -53,7 +55,7 @@ void network::initSockets() { WSADATA initResult; if (WSAStartup(requiredVersion, &initResult) != 0) - throw rdr::SocketException("unable to initialise Winsock2", errorNumber); + throw rdr::socket_error("unable to initialise Winsock2", errorNumber); #else signal(SIGPIPE, SIG_IGN); #endif @@ -161,7 +163,7 @@ Socket* SocketListener::accept() { // Accept an incoming connection if ((new_sock = ::accept(fd, nullptr, nullptr)) < 0) - throw rdr::SocketException("unable to accept new connection", errorNumber); + throw rdr::socket_error("unable to accept new connection", errorNumber); // Create the socket object & check connection is allowed Socket* s = createSocket(new_sock); @@ -179,7 +181,7 @@ void SocketListener::listen(int sock) if (::listen(sock, 5) < 0) { int e = errorNumber; closesocket(sock); - throw rdr::SocketException("unable to set socket to listening mode", e); + throw rdr::socket_error("unable to set socket to listening mode", e); } fd = sock; diff --git a/common/network/TcpSocket.cxx b/common/network/TcpSocket.cxx index 3f2f0f1fdc..bf603755b2 100644 --- a/common/network/TcpSocket.cxx +++ b/common/network/TcpSocket.cxx @@ -38,7 +38,10 @@ #include #include +#include + #include + #include #include #include @@ -82,15 +85,15 @@ int network::findFreeTcpPort (void) addr.sin_addr.s_addr = INADDR_ANY; if ((sock = socket (AF_INET, SOCK_STREAM, 0)) < 0) - throw SocketException ("unable to create socket", errorNumber); + throw socket_error("unable to create socket", errorNumber); addr.sin_port = 0; if (bind (sock, (struct sockaddr *)&addr, sizeof (addr)) < 0) - throw SocketException ("unable to find free port", errorNumber); + throw socket_error("unable to find free port", errorNumber); socklen_t n = sizeof(addr); if (getsockname (sock, (struct sockaddr *)&addr, &n) < 0) - throw SocketException ("unable to get port number", errorNumber); + throw socket_error("unable to get port number", errorNumber); closesocket (sock); return ntohs(addr.sin_port); @@ -134,7 +137,7 @@ TcpSocket::TcpSocket(const char *host, int port) hints.ai_next = nullptr; if ((result = getaddrinfo(host, nullptr, &hints, &ai)) != 0) { - throw GAIException("unable to resolve host by name", result); + throw getaddrinfo_error("unable to resolve host by name", result); } sock = -1; @@ -175,7 +178,7 @@ TcpSocket::TcpSocket(const char *host, int port) if (sock == -1) { err = errorNumber; freeaddrinfo(ai); - throw SocketException("unable to create socket", err); + throw socket_error("unable to create socket", err); } /* Attempt to connect to the remote host */ @@ -200,9 +203,9 @@ TcpSocket::TcpSocket(const char *host, int port) if (sock == -1) { if (err == 0) - throw Exception("No useful address for host"); + throw std::runtime_error("No useful address for host"); else - throw SocketException("unable to connect to socket", err); + throw socket_error("unable to connect to socket", err); } // Take proper ownership of the socket @@ -299,7 +302,7 @@ TcpListener::TcpListener(const struct sockaddr *listenaddr, int sock; if ((sock = socket (listenaddr->sa_family, SOCK_STREAM, 0)) < 0) - throw SocketException("unable to create listening socket", errorNumber); + throw socket_error("unable to create listening socket", errorNumber); memcpy (&sa, listenaddr, listenaddrlen); #ifdef IPV6_V6ONLY @@ -307,7 +310,7 @@ TcpListener::TcpListener(const struct sockaddr *listenaddr, if (setsockopt (sock, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&one, sizeof(one))) { int e = errorNumber; closesocket(sock); - throw SocketException("unable to set IPV6_V6ONLY", e); + throw socket_error("unable to set IPV6_V6ONLY", e); } } #endif /* defined(IPV6_V6ONLY) */ @@ -325,14 +328,14 @@ TcpListener::TcpListener(const struct sockaddr *listenaddr, (char *)&one, sizeof(one)) < 0) { int e = errorNumber; closesocket(sock); - throw SocketException("unable to create listening socket", e); + throw socket_error("unable to create listening socket", e); } #endif if (bind(sock, &sa.u.sa, listenaddrlen) == -1) { int e = errorNumber; closesocket(sock); - throw SocketException("failed to bind socket", e); + throw socket_error("failed to bind socket", e); } listen(sock); @@ -443,7 +446,7 @@ void network::createTcpListeners(std::list *listeners, snprintf (service, sizeof (service) - 1, "%d", port); service[sizeof (service) - 1] = '\0'; if ((result = getaddrinfo(addr, service, &hints, &ai)) != 0) - throw GAIException("unable to resolve listening address", result); + throw getaddrinfo_error("unable to resolve listening address", result); try { createTcpListeners(listeners, ai); @@ -482,7 +485,7 @@ void network::createTcpListeners(std::list *listeners, try { new_listeners.push_back(new TcpListener(current->ai_addr, current->ai_addrlen)); - } catch (SocketException& e) { + } catch (socket_error& e) { // Ignore this if it is due to lack of address family support on // the interface or on the system if (e.err != EADDRNOTAVAIL && e.err != EAFNOSUPPORT) { @@ -607,7 +610,7 @@ TcpFilter::Pattern TcpFilter::parsePattern(const char* p) { parts = rfb::split(&p[1], '/'); if (parts.size() > 2) - throw Exception("invalid filter specified"); + throw std::invalid_argument("invalid filter specified"); if (parts[0].empty()) { // Match any address @@ -630,7 +633,7 @@ TcpFilter::Pattern TcpFilter::parsePattern(const char* p) { } if ((result = getaddrinfo (parts[0].c_str(), nullptr, &hints, &ai)) != 0) { - throw GAIException("unable to resolve host by name", result); + throw getaddrinfo_error("unable to resolve host by name", result); } memcpy (&pattern.address.u.sa, ai->ai_addr, ai->ai_addrlen); @@ -641,8 +644,8 @@ TcpFilter::Pattern TcpFilter::parsePattern(const char* p) { if (parts.size() > 1) { if (family == AF_INET && (parts[1].find('.') != std::string::npos)) { - throw Exception("mask no longer supported for filter, " - "use prefix instead"); + throw std::invalid_argument("mask no longer supported for " + "filter, use prefix instead"); } pattern.prefixlen = (unsigned int) atoi(parts[1].c_str()); @@ -655,7 +658,7 @@ TcpFilter::Pattern TcpFilter::parsePattern(const char* p) { pattern.prefixlen = 128; break; default: - throw Exception("unknown address family"); + throw std::runtime_error("unknown address family"); } } } @@ -663,8 +666,9 @@ TcpFilter::Pattern TcpFilter::parsePattern(const char* p) { family = pattern.address.u.sa.sa_family; if (pattern.prefixlen > (family == AF_INET ? 32: 128)) - throw Exception("invalid prefix length for filter address: %u", - pattern.prefixlen); + throw std::invalid_argument(rfb::format("invalid prefix length for " + "filter address: %u", + pattern.prefixlen)); // Compute mask from address and prefix length memset (&pattern.mask, 0, sizeof (pattern.mask)); diff --git a/common/network/UnixSocket.cxx b/common/network/UnixSocket.cxx index 3a422b6c21..c8517300cb 100644 --- a/common/network/UnixSocket.cxx +++ b/common/network/UnixSocket.cxx @@ -29,7 +29,10 @@ #include #include +#include + #include + #include using namespace network; @@ -50,12 +53,12 @@ UnixSocket::UnixSocket(const char *path) socklen_t salen; if (strlen(path) >= sizeof(addr.sun_path)) - throw SocketException("socket path is too long", ENAMETOOLONG); + throw socket_error("socket path is too long", ENAMETOOLONG); // - Create a socket sock = socket(AF_UNIX, SOCK_STREAM, 0); if (sock == -1) - throw SocketException("unable to create socket", errno); + throw socket_error("unable to create socket", errno); // - Attempt to connect memset(&addr, 0, sizeof(addr)); @@ -69,7 +72,7 @@ UnixSocket::UnixSocket(const char *path) } if (result == -1) - throw SocketException("unable to connect to socket", err); + throw socket_error("unable to connect to socket", err); setFd(sock); } @@ -116,11 +119,11 @@ UnixListener::UnixListener(const char *path, int mode) int err, result; if (strlen(path) >= sizeof(addr.sun_path)) - throw SocketException("socket path is too long", ENAMETOOLONG); + throw socket_error("socket path is too long", ENAMETOOLONG); // - Create a socket if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) - throw SocketException("unable to create listening socket", errno); + throw socket_error("unable to create listening socket", errno); // - Delete existing socket (ignore result) unlink(path); @@ -135,14 +138,14 @@ UnixListener::UnixListener(const char *path, int mode) umask(saved_umask); if (result < 0) { close(fd); - throw SocketException("unable to bind listening socket", err); + throw socket_error("unable to bind listening socket", err); } // - Set socket mode if (chmod(path, mode) < 0) { err = errno; close(fd); - throw SocketException("unable to set socket mode", err); + throw socket_error("unable to set socket mode", err); } listen(fd); diff --git a/common/os/Mutex.cxx b/common/os/Mutex.cxx index b82de4152e..1889e66b43 100644 --- a/common/os/Mutex.cxx +++ b/common/os/Mutex.cxx @@ -43,7 +43,7 @@ Mutex::Mutex() systemMutex = new pthread_mutex_t; ret = pthread_mutex_init((pthread_mutex_t*)systemMutex, nullptr); if (ret != 0) - throw rdr::PosixException("Failed to create mutex", ret); + throw rdr::posix_error("Failed to create mutex", ret); #endif } @@ -67,7 +67,7 @@ void Mutex::lock() ret = pthread_mutex_lock((pthread_mutex_t*)systemMutex); if (ret != 0) - throw rdr::PosixException("Failed to lock mutex", ret); + throw rdr::posix_error("Failed to lock mutex", ret); #endif } @@ -80,7 +80,7 @@ void Mutex::unlock() ret = pthread_mutex_unlock((pthread_mutex_t*)systemMutex); if (ret != 0) - throw rdr::PosixException("Failed to unlock mutex", ret); + throw rdr::posix_error("Failed to unlock mutex", ret); #endif } @@ -97,7 +97,7 @@ Condition::Condition(Mutex* mutex_) systemCondition = new pthread_cond_t; ret = pthread_cond_init((pthread_cond_t*)systemCondition, nullptr); if (ret != 0) - throw rdr::PosixException("Failed to create condition variable", ret); + throw rdr::posix_error("Failed to create condition variable", ret); #endif } @@ -120,14 +120,14 @@ void Condition::wait() (CRITICAL_SECTION*)mutex->systemMutex, INFINITE); if (!ret) - throw rdr::Win32Exception("Failed to wait on condition variable", GetLastError()); + throw rdr::win32_error("Failed to wait on condition variable", GetLastError()); #else int ret; ret = pthread_cond_wait((pthread_cond_t*)systemCondition, (pthread_mutex_t*)mutex->systemMutex); if (ret != 0) - throw rdr::PosixException("Failed to wait on condition variable", ret); + throw rdr::posix_error("Failed to wait on condition variable", ret); #endif } @@ -140,7 +140,7 @@ void Condition::signal() ret = pthread_cond_signal((pthread_cond_t*)systemCondition); if (ret != 0) - throw rdr::PosixException("Failed to signal condition variable", ret); + throw rdr::posix_error("Failed to signal condition variable", ret); #endif } @@ -153,6 +153,6 @@ void Condition::broadcast() ret = pthread_cond_broadcast((pthread_cond_t*)systemCondition); if (ret != 0) - throw rdr::PosixException("Failed to broadcast condition variable", ret); + throw rdr::posix_error("Failed to broadcast condition variable", ret); #endif } diff --git a/common/os/Thread.cxx b/common/os/Thread.cxx index e99be63e24..6dca75a1d1 100644 --- a/common/os/Thread.cxx +++ b/common/os/Thread.cxx @@ -66,7 +66,7 @@ void Thread::start() #ifdef WIN32 *(HANDLE*)threadId = CreateThread(nullptr, 0, startRoutine, this, 0, nullptr); if (*(HANDLE*)threadId == nullptr) - throw rdr::Win32Exception("Failed to create thread", GetLastError()); + throw rdr::win32_error("Failed to create thread", GetLastError()); #else int ret; sigset_t all, old; @@ -76,14 +76,14 @@ void Thread::start() sigfillset(&all); ret = pthread_sigmask(SIG_SETMASK, &all, &old); if (ret != 0) - throw rdr::PosixException("Failed to mask signals", ret); + throw rdr::posix_error("Failed to mask signals", ret); ret = pthread_create((pthread_t*)threadId, nullptr, startRoutine, this); pthread_sigmask(SIG_SETMASK, &old, nullptr); if (ret != 0) - throw rdr::PosixException("Failed to create thread", ret); + throw rdr::posix_error("Failed to create thread", ret); #endif running = true; @@ -99,13 +99,13 @@ void Thread::wait() ret = WaitForSingleObject(*(HANDLE*)threadId, INFINITE); if (ret != WAIT_OBJECT_0) - throw rdr::Win32Exception("Failed to join thread", GetLastError()); + throw rdr::win32_error("Failed to join thread", GetLastError()); #else int ret; ret = pthread_join(*(pthread_t*)threadId, nullptr); if (ret != 0) - throw rdr::PosixException("Failed to join thread", ret); + throw rdr::posix_error("Failed to join thread", ret); #endif } diff --git a/common/os/winerrno.h b/common/os/winerrno.h index 052d4de2b4..a81fdc944b 100644 --- a/common/os/winerrno.h +++ b/common/os/winerrno.h @@ -5,6 +5,8 @@ cat /usr/i686-pc-mingw32/sys-root/mingw/include/winerror.h \ | egrep -v 'EINTR|EBADF|EACCES|EFAULT|EINVAL|EMFILE|_QOS|PROVIDER|PROCTABLE' */ +#include + #undef EWOULDBLOCK #define EWOULDBLOCK WSAEWOULDBLOCK #undef EINPROGRESS diff --git a/common/rdr/AESInStream.cxx b/common/rdr/AESInStream.cxx index d6d944a330..3a56ef7381 100644 --- a/common/rdr/AESInStream.cxx +++ b/common/rdr/AESInStream.cxx @@ -21,8 +21,8 @@ #endif #include + #include -#include #ifdef HAVE_NETTLE using namespace rdr; @@ -68,7 +68,7 @@ bool AESInStream::fillBuffer() EAX_DIGEST(&eaxCtx256, aes256_encrypt, 16, macComputed); } if (memcmp(mac, macComputed, 16) != 0) - throw Exception("AESInStream: failed to authenticate message"); + throw std::runtime_error("AESInStream: failed to authenticate message"); in->setptr(2 + length + 16); end += length; diff --git a/common/rdr/BufferedInStream.cxx b/common/rdr/BufferedInStream.cxx index 3c04bafc34..bf94a9507a 100644 --- a/common/rdr/BufferedInStream.cxx +++ b/common/rdr/BufferedInStream.cxx @@ -24,7 +24,8 @@ #include #include -#include + +#include using namespace rdr; @@ -63,9 +64,12 @@ void BufferedInStream::ensureSpace(size_t needed) uint8_t* newBuffer; if (needed > MAX_BUF_SIZE) - throw Exception("BufferedInStream overrun: requested size of " - "%lu bytes exceeds maximum of %lu bytes", - (long unsigned)needed, (long unsigned)MAX_BUF_SIZE); + throw std::out_of_range(rfb::format("BufferedInStream overrun: " + "requested size of %lu bytes " + "exceeds maximum of %lu " + "bytes", + (long unsigned)needed, + (long unsigned)MAX_BUF_SIZE)); newSize = DEFAULT_BUF_SIZE; while (newSize < needed) diff --git a/common/rdr/BufferedOutStream.cxx b/common/rdr/BufferedOutStream.cxx index 0d6a1eb6b0..efb71dd7d9 100644 --- a/common/rdr/BufferedOutStream.cxx +++ b/common/rdr/BufferedOutStream.cxx @@ -23,8 +23,8 @@ #endif #include -#include +#include using namespace rdr; @@ -138,10 +138,11 @@ void BufferedOutStream::overrun(size_t needed) // We'll need to allocate more buffer space... if (totalNeeded > MAX_BUF_SIZE) - throw Exception("BufferedOutStream overrun: requested size of " - "%lu bytes exceeds maximum of %lu bytes", - (long unsigned)totalNeeded, - (long unsigned)MAX_BUF_SIZE); + throw std::out_of_range(rfb::format("BufferedOutStream overrun: " + "requested size of %lu bytes " + "exceeds maximum of %lu bytes", + (long unsigned)totalNeeded, + (long unsigned)MAX_BUF_SIZE)); newSize = DEFAULT_BUF_SIZE; while (newSize < totalNeeded) diff --git a/common/rdr/Exception.cxx b/common/rdr/Exception.cxx index 6a03fa540a..694ee35989 100644 --- a/common/rdr/Exception.cxx +++ b/common/rdr/Exception.cxx @@ -1,6 +1,7 @@ /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. * Copyright (C) 2004 Red Hat Inc. * Copyright (C) 2010 TigerVNC Team + * Copyright 2014-2024 Pierre Ossman for Cendio AB * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -27,6 +28,8 @@ #include #include +#include + #ifdef _WIN32 #include #include @@ -37,77 +40,94 @@ #include -#ifdef HAVE_GNUTLS -#include -#endif - using namespace rdr; -Exception::Exception(const char *format, ...) { - va_list ap; - va_start(ap, format); - (void) vsnprintf(str_, len, format, ap); - va_end(ap); +getaddrinfo_error::getaddrinfo_error(const char* s, int err_) + : std::runtime_error(rfb::format("%s: %s (%d)", s, + strerror(err_).c_str(), err_)), + err(err_) +{ +} + +getaddrinfo_error::getaddrinfo_error(const std::string& s, int err_) + : std::runtime_error(rfb::format("%s: %s (%d)", s.c_str(), + strerror(err_).c_str(), err_)), + err(err_) +{ } -GAIException::GAIException(const char* s, int err_) - : Exception("%s", s), err(err_) +std::string getaddrinfo_error::strerror(int err_) const { - strncat(str_, ": ", len-1-strlen(str_)); #ifdef _WIN32 - wchar_t *currStr = new wchar_t[len-strlen(str_)]; - wcsncpy(currStr, gai_strerrorW(err), len-1-strlen(str_)); - WideCharToMultiByte(CP_UTF8, 0, currStr, -1, str_+strlen(str_), - len-1-strlen(str_), nullptr, nullptr); - delete [] currStr; + char str[256]; + + WideCharToMultiByte(CP_UTF8, 0, gai_strerrorW(err_), -1, str, + sizeof(str), nullptr, nullptr); + + return str; #else - strncat(str_, gai_strerror(err), len-1-strlen(str_)); -#endif - strncat(str_, " (", len-1-strlen(str_)); - char buf[20]; -#ifdef WIN32 - if (err < 0) - sprintf(buf, "%x", err); - else + return gai_strerror(err_); #endif - sprintf(buf,"%d",err); - strncat(str_, buf, len-1-strlen(str_)); - strncat(str_, ")", len-1-strlen(str_)); } -PosixException::PosixException(const char* s, int err_) - : Exception("%s", s), err(err_) +posix_error::posix_error(const char* what_arg, int err_) + : std::runtime_error(rfb::format("%s: %s (%d)", what_arg, + strerror(err_).c_str(), err_)), + err(err_) +{ +} + +posix_error::posix_error(const std::string& what_arg, int err_) + : std::runtime_error(rfb::format("%s: %s (%d)", what_arg.c_str(), + strerror(err_).c_str(), err_)), + err(err_) { - strncat(str_, ": ", len-1-strlen(str_)); - strncat(str_, strerror(err), len-1-strlen(str_)); - strncat(str_, " (", len-1-strlen(str_)); - char buf[20]; - sprintf(buf,"%d",err); - strncat(str_, buf, len-1-strlen(str_)); - strncat(str_, ")", len-1-strlen(str_)); +} + +std::string posix_error::strerror(int err_) const +{ +#ifdef _WIN32 + char str[256]; + + WideCharToMultiByte(CP_UTF8, 0, _wcserror(err_), -1, str, + sizeof(str), nullptr, nullptr); + + return str; +#else + return ::strerror(err_); +#endif } #ifdef WIN32 -Win32Exception::Win32Exception(const char* s, unsigned err_) - : Exception("%s", s), err(err_) +win32_error::win32_error(const char* what_arg, unsigned err_) + : std::runtime_error(rfb::format("%s: %s (%d)", what_arg, + strerror(err_).c_str(), err_)), + err(err_) { - strncat(str_, ": ", len-1-strlen(str_)); - wchar_t *currStr = new wchar_t[len-strlen(str_)]; +} + +win32_error::win32_error(const std::string& what_arg, unsigned err_) + : std::runtime_error(rfb::format("%s: %s (%d)", what_arg.c_str(), + strerror(err_).c_str(), err_)), + err(err_) +{ +} + +std::string win32_error::strerror(unsigned err_) const +{ + wchar_t wstr[256]; + char str[256]; + FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, err, 0, currStr, len-1-strlen(str_), nullptr); - WideCharToMultiByte(CP_UTF8, 0, currStr, -1, str_+strlen(str_), - len-1-strlen(str_), nullptr, nullptr); - delete [] currStr; - - int l = strlen(str_); - if ((l >= 2) && (str_[l-2] == '\r') && (str_[l-1] == '\n')) - str_[l-2] = 0; - - strncat(str_, " (", len-1-strlen(str_)); - char buf[20]; - sprintf(buf,"%d",err); - strncat(str_, buf, len-1-strlen(str_)); - strncat(str_, ")", len-1-strlen(str_)); + nullptr, err_, 0, wstr, sizeof(wstr), nullptr); + WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, + sizeof(str), nullptr, nullptr); + + int l = strlen(str); + if ((l >= 2) && (str[l-2] == '\r') && (str[l-1] == '\n')) + str[l-2] = 0; + + return str; } #endif diff --git a/common/rdr/Exception.h b/common/rdr/Exception.h index c59f7e5500..f3f878cbb8 100644 --- a/common/rdr/Exception.h +++ b/common/rdr/Exception.h @@ -1,6 +1,7 @@ /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. * Copyright (C) 2004 Red Hat Inc. * Copyright (C) 2010 TigerVNC Team + * Copyright 2015-2024 Pierre Ossman for Cendio AB * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -21,46 +22,57 @@ #ifndef __RDR_EXCEPTION_H__ #define __RDR_EXCEPTION_H__ -namespace rdr { +#include +#include - struct Exception { - enum { len = 256 }; - char str_[len]; - Exception(const char *format=nullptr, ...) - __attribute__((__format__ (__printf__, 2, 3))); - virtual ~Exception() {} - virtual const char* str() const { return str_; } - }; +namespace rdr { - struct PosixException : public Exception { + class posix_error : public std::runtime_error { + public: int err; - PosixException(const char* s, int err_); + posix_error(const char* what_arg, int err_); + posix_error(const std::string& what_arg, int err_); + private: + std::string strerror(int err_) const; }; #ifdef WIN32 - struct Win32Exception : public Exception { + class win32_error : public std::runtime_error { + public: unsigned err; - Win32Exception(const char* s, unsigned err_); + win32_error(const char* what_arg, unsigned err_); + win32_error(const std::string& what_arg, unsigned err_); + private: + std::string strerror(unsigned err_) const; }; #endif #ifdef WIN32 - struct SocketException : public Win32Exception { - SocketException(const char* text, unsigned err_) : Win32Exception(text, err_) {} + class socket_error : public win32_error { + public: + socket_error(const char* what_arg, unsigned err_) : win32_error(what_arg, err_) {} + socket_error(const std::string& what_arg, unsigned err_) : win32_error(what_arg, err_) {} }; #else - struct SocketException : public PosixException { - SocketException(const char* text, int err_) : PosixException(text, err_) {} + class socket_error : public posix_error { + public: + socket_error(const char* what_arg, unsigned err_) : posix_error(what_arg, err_) {} + socket_error(const std::string& what_arg, unsigned err_) : posix_error(what_arg, err_) {} }; #endif - struct GAIException : public Exception { + class getaddrinfo_error : public std::runtime_error { + public: int err; - GAIException(const char* s, int err_); + getaddrinfo_error(const char* s, int err_); + getaddrinfo_error(const std::string& s, int err_); + private: + std::string strerror(int err_) const; }; - struct EndOfStream : public Exception { - EndOfStream() : Exception("End of stream") {} + class end_of_stream : public std::runtime_error { + public: + end_of_stream() : std::runtime_error("End of stream") {} }; } diff --git a/common/rdr/FdInStream.cxx b/common/rdr/FdInStream.cxx index bddee482f7..23ea2f8cc8 100644 --- a/common/rdr/FdInStream.cxx +++ b/common/rdr/FdInStream.cxx @@ -92,7 +92,7 @@ size_t FdInStream::readFd(uint8_t* buf, size_t len) } while (n < 0 && errorNumber == EINTR); if (n < 0) - throw SocketException("select", errorNumber); + throw socket_error("select", errorNumber); if (n == 0) return 0; @@ -102,9 +102,9 @@ size_t FdInStream::readFd(uint8_t* buf, size_t len) } while (n < 0 && errorNumber == EINTR); if (n < 0) - throw SocketException("read", errorNumber); + throw socket_error("read", errorNumber); if (n == 0) - throw EndOfStream(); + throw end_of_stream(); return n; } diff --git a/common/rdr/FdOutStream.cxx b/common/rdr/FdOutStream.cxx index 1b6049caeb..6db8c0bb22 100644 --- a/common/rdr/FdOutStream.cxx +++ b/common/rdr/FdOutStream.cxx @@ -117,7 +117,7 @@ size_t FdOutStream::writeFd(const uint8_t* data, size_t length) } while (n < 0 && errorNumber == EINTR); if (n < 0) - throw SocketException("select", errorNumber); + throw socket_error("select", errorNumber); if (n == 0) return 0; @@ -134,7 +134,7 @@ size_t FdOutStream::writeFd(const uint8_t* data, size_t length) } while (n < 0 && (errorNumber == EINTR)); if (n < 0) - throw SocketException("write", errorNumber); + throw socket_error("write", errorNumber); gettimeofday(&lastWrite, nullptr); diff --git a/common/rdr/FileInStream.cxx b/common/rdr/FileInStream.cxx index db646a7e4b..df09ea768c 100644 --- a/common/rdr/FileInStream.cxx +++ b/common/rdr/FileInStream.cxx @@ -33,7 +33,7 @@ FileInStream::FileInStream(const char *fileName) { file = fopen(fileName, "rb"); if (!file) - throw PosixException("fopen", errno); + throw posix_error("fopen", errno); } FileInStream::~FileInStream(void) { @@ -48,9 +48,9 @@ bool FileInStream::fillBuffer() size_t n = fread((uint8_t*)end, 1, availSpace(), file); if (n == 0) { if (ferror(file)) - throw PosixException("fread", errno); + throw posix_error("fread", errno); if (feof(file)) - throw EndOfStream(); + throw end_of_stream(); return false; } end += n; diff --git a/common/rdr/HexInStream.cxx b/common/rdr/HexInStream.cxx index 11f98498ee..69c3e26084 100644 --- a/common/rdr/HexInStream.cxx +++ b/common/rdr/HexInStream.cxx @@ -23,7 +23,6 @@ #include #include -#include #include using namespace rdr; @@ -46,7 +45,7 @@ bool HexInStream::fillBuffer() { uint8_t* optr = (uint8_t*) end; for (size_t i=0; i #include // for memcpy -#include +#include // Check that callers are using InStream properly, // useful when writing new protocol handling @@ -101,21 +101,21 @@ namespace rdr { inline void setRestorePoint() { #ifdef RFB_INSTREAM_CHECK if (restorePoint != nullptr) - throw Exception("Nested use of input stream restore point"); + throw std::logic_error("Nested use of input stream restore point"); #endif restorePoint = ptr; } inline void clearRestorePoint() { #ifdef RFB_INSTREAM_CHECK if (restorePoint == nullptr) - throw Exception("Incorrect clearing of input stream restore point"); + throw std::logic_error("Incorrect clearing of input stream restore point"); #endif restorePoint = nullptr; } inline void gotoRestorePoint() { #ifdef RFB_INSTREAM_CHECK if (restorePoint == nullptr) - throw Exception("Incorrect activation of input stream restore point"); + throw std::logic_error("Incorrect activation of input stream restore point"); #endif ptr = restorePoint; clearRestorePoint(); @@ -176,7 +176,7 @@ namespace rdr { inline const uint8_t* getptr(size_t length) { check(length); return ptr; } inline void setptr(size_t length) { if (length > avail()) - throw Exception("Input stream overflow"); + throw std::out_of_range("Input stream overflow"); skip(length); } private: @@ -189,11 +189,11 @@ namespace rdr { inline void check(size_t bytes) { #ifdef RFB_INSTREAM_CHECK if (bytes > checkedBytes) - throw Exception("Input stream used without underrun check"); + throw std::logic_error("Input stream used without underrun check"); checkedBytes -= bytes; #endif if (bytes > (size_t)(end - ptr)) - throw Exception("InStream buffer underrun"); + throw std::out_of_range("InStream buffer underrun"); } // overrun() is implemented by a derived class to cope with buffer overrun. diff --git a/common/rdr/MemInStream.h b/common/rdr/MemInStream.h index e10273b165..78ee2dee4d 100644 --- a/common/rdr/MemInStream.h +++ b/common/rdr/MemInStream.h @@ -59,7 +59,7 @@ namespace rdr { private: - bool overrun(size_t /*needed*/) override { throw EndOfStream(); } + bool overrun(size_t /*needed*/) override { throw end_of_stream(); } const uint8_t* start; bool deleteWhenDone; }; diff --git a/common/rdr/MemOutStream.h b/common/rdr/MemOutStream.h index 9bf2b810fc..bf05d92cb8 100644 --- a/common/rdr/MemOutStream.h +++ b/common/rdr/MemOutStream.h @@ -23,7 +23,6 @@ #ifndef __RDR_MEMOUTSTREAM_H__ #define __RDR_MEMOUTSTREAM_H__ -#include #include namespace rdr { @@ -61,7 +60,7 @@ namespace rdr { len = (end - start) * 2; if (len < (size_t)(end - start)) - throw Exception("Overflow in MemOutStream::overrun()"); + throw std::out_of_range("Overflow in MemOutStream::overrun()"); uint8_t* newStart = new uint8_t[len]; memcpy(newStart, start, ptr - start); diff --git a/common/rdr/OutStream.h b/common/rdr/OutStream.h index 2921b23265..b78ec4b069 100644 --- a/common/rdr/OutStream.h +++ b/common/rdr/OutStream.h @@ -27,7 +27,8 @@ #include #include // for memcpy -#include +#include + #include namespace rdr { @@ -129,7 +130,7 @@ namespace rdr { inline uint8_t* getptr(size_t length) { check(length); return ptr; } inline void setptr(size_t length) { if (length > avail()) - throw Exception("Output stream overflow"); + throw std::out_of_range("Output stream overflow"); ptr += length; } private: diff --git a/common/rdr/RandomStream.cxx b/common/rdr/RandomStream.cxx index 449a84c0ae..485259cf14 100644 --- a/common/rdr/RandomStream.cxx +++ b/common/rdr/RandomStream.cxx @@ -89,7 +89,7 @@ bool RandomStream::fillBuffer() { #ifdef RFB_HAVE_WINCRYPT if (provider) { if (!CryptGenRandom(provider, availSpace(), (uint8_t*)end)) - throw rdr::Win32Exception("unable to CryptGenRandom", GetLastError()); + throw rdr::win32_error("unable to CryptGenRandom", GetLastError()); end += availSpace(); } else { #else @@ -97,8 +97,8 @@ bool RandomStream::fillBuffer() { if (fp) { size_t n = fread((uint8_t*)end, 1, availSpace(), fp); if (n <= 0) - throw rdr::PosixException("reading /dev/urandom or /dev/random failed", - errno); + throw rdr::posix_error("reading /dev/urandom or /dev/random " + "failed", errno); end += n; } else { #else diff --git a/common/rdr/TLSException.cxx b/common/rdr/TLSException.cxx index 0f75a4dacc..ccff6090ca 100644 --- a/common/rdr/TLSException.cxx +++ b/common/rdr/TLSException.cxx @@ -24,6 +24,8 @@ #include +#include + #include #include #ifdef HAVE_GNUTLS @@ -33,8 +35,10 @@ using namespace rdr; #ifdef HAVE_GNUTLS -TLSException::TLSException(const char* s, int err_) - : Exception("%s: %s (%d)", s, gnutls_strerror(err_), err_), err(err_) +tls_error::tls_error(const char* s, int err_) + : std::runtime_error(rfb::format("%s: %s (%d)", s, + gnutls_strerror(err_), err_)), + err(err_) { } #endif /* HAVE_GNUTLS */ diff --git a/common/rdr/TLSException.h b/common/rdr/TLSException.h index b519bfef69..cfa73f697f 100644 --- a/common/rdr/TLSException.h +++ b/common/rdr/TLSException.h @@ -25,9 +25,10 @@ namespace rdr { - struct TLSException : public Exception { + class tls_error : public std::runtime_error { + public: int err; - TLSException(const char* s, int err_); + tls_error(const char* s, int err_); }; } diff --git a/common/rdr/TLSInStream.cxx b/common/rdr/TLSInStream.cxx index f8f4fcf98a..7c867e88c2 100644 --- a/common/rdr/TLSInStream.cxx +++ b/common/rdr/TLSInStream.cxx @@ -54,17 +54,17 @@ ssize_t TLSInStream::pull(gnutls_transport_ptr_t str, void* data, size_t size) size = in->avail(); in->readBytes((uint8_t*)data, size); - } catch (EndOfStream&) { + } catch (end_of_stream&) { return 0; - } catch (SocketException& e) { - vlog.error("Failure reading TLS data: %s", e.str()); + } catch (socket_error& e) { + vlog.error("Failure reading TLS data: %s", e.what()); gnutls_transport_set_errno(self->session, e.err); - self->saved_exception = new SocketException(e); + self->saved_exception = new socket_error(e); return -1; - } catch (Exception& e) { - vlog.error("Failure reading TLS data: %s", e.str()); + } catch (std::exception& e) { + vlog.error("Failure reading TLS data: %s", e.what()); gnutls_transport_set_errno(self->session, EINVAL); - self->saved_exception = new Exception(e); + self->saved_exception = new std::exception(e); return -1; } @@ -121,10 +121,10 @@ size_t TLSInStream::readTLS(uint8_t* buf, size_t len) throw *saved_exception; if (n < 0) - throw TLSException("readTLS", n); + throw tls_error("readTLS", n); if (n == 0) - throw EndOfStream(); + throw end_of_stream(); return n; } diff --git a/common/rdr/TLSInStream.h b/common/rdr/TLSInStream.h index ca69dddea0..2269b09d4f 100644 --- a/common/rdr/TLSInStream.h +++ b/common/rdr/TLSInStream.h @@ -41,7 +41,7 @@ namespace rdr { InStream* in; bool streamEmpty; - Exception* saved_exception; + std::exception* saved_exception; }; }; diff --git a/common/rdr/TLSOutStream.cxx b/common/rdr/TLSOutStream.cxx index ccb229e16d..1e555fc15f 100644 --- a/common/rdr/TLSOutStream.cxx +++ b/common/rdr/TLSOutStream.cxx @@ -46,15 +46,15 @@ ssize_t TLSOutStream::push(gnutls_transport_ptr_t str, const void* data, try { out->writeBytes((const uint8_t*)data, size); out->flush(); - } catch (SocketException& e) { - vlog.error("Failure sending TLS data: %s", e.str()); + } catch (socket_error& e) { + vlog.error("Failure sending TLS data: %s", e.what()); gnutls_transport_set_errno(self->session, e.err); - self->saved_exception = new SocketException(e); + self->saved_exception = new socket_error(e); return -1; - } catch (Exception& e) { - vlog.error("Failure sending TLS data: %s", e.str()); + } catch (std::exception& e) { + vlog.error("Failure sending TLS data: %s", e.what()); gnutls_transport_set_errno(self->session, EINVAL); - self->saved_exception = new Exception(e); + self->saved_exception = new std::exception(e); return -1; } @@ -118,7 +118,7 @@ size_t TLSOutStream::writeTLS(const uint8_t* data, size_t length) throw *saved_exception; if (n < 0) - throw TLSException("writeTLS", n); + throw tls_error("writeTLS", n); return n; } diff --git a/common/rdr/TLSOutStream.h b/common/rdr/TLSOutStream.h index 3571423821..659f16f07a 100644 --- a/common/rdr/TLSOutStream.h +++ b/common/rdr/TLSOutStream.h @@ -42,7 +42,7 @@ namespace rdr { gnutls_session_t session; OutStream* out; - Exception* saved_exception; + std::exception* saved_exception; }; }; diff --git a/common/rdr/ZlibInStream.cxx b/common/rdr/ZlibInStream.cxx index a90d50f754..c9f8aecaa3 100644 --- a/common/rdr/ZlibInStream.cxx +++ b/common/rdr/ZlibInStream.cxx @@ -23,7 +23,6 @@ #include #include -#include #include using namespace rdr; @@ -50,7 +49,7 @@ void ZlibInStream::flushUnderlying() { while (bytesIn > 0) { if (!hasData(1)) - throw Exception("ZlibInStream: failed to flush remaining stream data"); + throw std::runtime_error("ZlibInStream: failed to flush remaining stream data"); skip(avail()); } @@ -76,7 +75,7 @@ void ZlibInStream::init() if (inflateInit(zs) != Z_OK) { delete zs; zs = nullptr; - throw Exception("ZlibInStream: inflateInit failed"); + throw std::runtime_error("ZlibInStream: inflateInit failed"); } } @@ -92,7 +91,7 @@ void ZlibInStream::deinit() bool ZlibInStream::fillBuffer() { if (!underlying) - throw Exception("ZlibInStream overrun: no underlying stream"); + throw std::runtime_error("ZlibInStream overrun: no underlying stream"); zs->next_out = (uint8_t*)end; zs->avail_out = availSpace(); @@ -107,7 +106,7 @@ bool ZlibInStream::fillBuffer() int rc = inflate(zs, Z_SYNC_FLUSH); if (rc < 0) { - throw Exception("ZlibInStream: inflate failed"); + throw std::runtime_error("ZlibInStream: inflate failed"); } bytesIn -= length - zs->avail_in; diff --git a/common/rdr/ZlibOutStream.cxx b/common/rdr/ZlibOutStream.cxx index 0b167711ea..13788f8db2 100644 --- a/common/rdr/ZlibOutStream.cxx +++ b/common/rdr/ZlibOutStream.cxx @@ -24,7 +24,6 @@ #include #include -#include #include #include @@ -46,7 +45,7 @@ ZlibOutStream::ZlibOutStream(OutStream* os, int compressLevel) zs->avail_in = 0; if (deflateInit(zs, compressLevel) != Z_OK) { delete zs; - throw Exception("ZlibOutStream: deflateInit failed"); + throw std::runtime_error("ZlibOutStream: deflateInit failed"); } } @@ -54,7 +53,7 @@ ZlibOutStream::~ZlibOutStream() { try { flush(); - } catch (Exception&) { + } catch (std::exception&) { } deflateEnd(zs); delete zs; @@ -113,7 +112,7 @@ void ZlibOutStream::deflate(int flush) int rc; if (!underlying) - throw Exception("ZlibOutStream: underlying OutStream has not been set"); + throw std::runtime_error("ZlibOutStream: underlying OutStream has not been set"); if ((flush == Z_NO_FLUSH) && (zs->avail_in == 0)) return; @@ -134,7 +133,7 @@ void ZlibOutStream::deflate(int flush) if ((rc == Z_BUF_ERROR) && (flush != Z_NO_FLUSH)) break; - throw Exception("ZlibOutStream: deflate failed"); + throw std::runtime_error("ZlibOutStream: deflate failed"); } #ifdef ZLIBOUT_DEBUG @@ -168,7 +167,7 @@ void ZlibOutStream::checkCompressionLevel() // explicit flush we did above. It should be safe to ignore though // as the first flush should have left things in a stable state... if (rc != Z_BUF_ERROR) - throw Exception("ZlibOutStream: deflateParams failed"); + throw std::runtime_error("ZlibOutStream: deflateParams failed"); } compressionLevel = newLevel; diff --git a/common/rfb/CConnection.cxx b/common/rfb/CConnection.cxx index b4017dba8e..a4d6d17354 100644 --- a/common/rfb/CConnection.cxx +++ b/common/rfb/CConnection.cxx @@ -147,11 +147,11 @@ bool CConnection::processMsg() case RFBSTATE_INITIALISATION: return processInitMsg(); break; case RFBSTATE_NORMAL: return reader_->readMsg(); break; case RFBSTATE_CLOSING: - throw Exception("CConnection::processMsg: called while closing"); + throw std::logic_error("CConnection::processMsg: called while closing"); case RFBSTATE_UNINITIALISED: - throw Exception("CConnection::processMsg: not initialised yet?"); + throw std::logic_error("CConnection::processMsg: not initialised yet?"); default: - throw Exception("CConnection::processMsg: invalid state"); + throw std::logic_error("CConnection::processMsg: invalid state"); } } @@ -172,7 +172,7 @@ bool CConnection::processVersionMsg() if (sscanf(verStr, "RFB %03d.%03d\n", &majorVersion, &minorVersion) != 2) { state_ = RFBSTATE_INVALID; - throw Exception("reading version failed: not an RFB server?"); + throw protocol_error("reading version failed: not an RFB server?"); } server.setVersion(majorVersion, minorVersion); @@ -185,8 +185,10 @@ bool CConnection::processVersionMsg() vlog.error("Server gave unsupported RFB protocol version %d.%d", server.majorVersion, server.minorVersion); state_ = RFBSTATE_INVALID; - throw Exception("Server gave unsupported RFB protocol version %d.%d", - server.majorVersion, server.minorVersion); + throw protocol_error(format("Server gave unsupported RFB protocol " + "version %d.%d", + server.majorVersion, + server.minorVersion)); } else if (server.beforeVersion(3,7)) { server.setVersion(3,3); } else if (server.afterVersion(3,8)) { @@ -233,7 +235,7 @@ bool CConnection::processSecurityTypesMsg() secType = secTypeInvalid; } else { vlog.error("Unknown 3.3 security type %d", secType); - throw Exception("Unknown 3.3 security type"); + throw protocol_error("Unknown 3.3 security type"); } } else { @@ -283,7 +285,7 @@ bool CConnection::processSecurityTypesMsg() if (secType == secTypeInvalid) { state_ = RFBSTATE_INVALID; vlog.error("No matching security types"); - throw Exception("No matching security types"); + throw protocol_error("No matching security types"); } state_ = RFBSTATE_SECURITY; @@ -327,12 +329,12 @@ bool CConnection::processSecurityResultMsg() vlog.debug("auth failed - too many tries"); break; default: - throw Exception("Unknown security result from server"); + throw protocol_error("Unknown security result from server"); } if (server.beforeVersion(3,8)) { state_ = RFBSTATE_INVALID; - throw AuthFailureException("Authentication failed"); + throw auth_error("Authentication failed"); } state_ = RFBSTATE_SECURITY_REASON; @@ -358,7 +360,7 @@ bool CConnection::processSecurityReasonMsg() reason[len] = '\0'; state_ = RFBSTATE_INVALID; - throw AuthFailureException(reason.data()); + throw auth_error(reason.data()); } bool CConnection::processInitMsg() @@ -387,8 +389,8 @@ void CConnection::close() */ try { decoder.flush(); - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); } setFramebuffer(nullptr); diff --git a/common/rfb/CConnection.h b/common/rfb/CConnection.h index 3f277d7163..9101bf2672 100644 --- a/common/rfb/CConnection.h +++ b/common/rfb/CConnection.h @@ -273,7 +273,7 @@ namespace rfb { bool processSecurityResultMsg(); bool processSecurityReasonMsg(); bool processInitMsg(); - void throwAuthFailureException(); + void throwAuthError(); void securityCompleted(); void requestNewUpdate(); diff --git a/common/rfb/CMsgReader.cxx b/common/rfb/CMsgReader.cxx index 8bcdbfd04e..3025959f03 100644 --- a/common/rfb/CMsgReader.cxx +++ b/common/rfb/CMsgReader.cxx @@ -119,7 +119,7 @@ bool CMsgReader::readMsg() ret = readEndOfContinuousUpdates(); break; default: - throw Exception("Unknown message type %d", currentMsgType); + throw protocol_error(format("Unknown message type %d", currentMsgType)); } if (ret) @@ -301,7 +301,7 @@ bool CMsgReader::readExtendedClipboard(int32_t len) return false; if (len < 4) - throw Exception("Invalid extended clipboard message"); + throw protocol_error("Invalid extended clipboard message"); if (len > maxCutText) { vlog.error("Extended clipboard message too long (%d bytes) - ignoring", len); is->skip(len); @@ -323,7 +323,7 @@ bool CMsgReader::readExtendedClipboard(int32_t len) } if (len < (int32_t)(4 + 4*num)) - throw Exception("Invalid extended clipboard message"); + throw protocol_error("Invalid extended clipboard message"); num = 0; for (i = 0;i < 16;i++) { @@ -348,7 +348,7 @@ bool CMsgReader::readExtendedClipboard(int32_t len) continue; if (!zis.hasData(4)) - throw Exception("Extended clipboard decode error"); + throw protocol_error("Extended clipboard decode error"); lengths[num] = zis.readU32(); @@ -361,7 +361,7 @@ bool CMsgReader::readExtendedClipboard(int32_t len) size_t chunk; if (!zis.hasData(1)) - throw Exception("Extended clipboard decode error"); + throw protocol_error("Extended clipboard decode error"); chunk = zis.avail(); if (chunk > lengths[num]) @@ -377,7 +377,7 @@ bool CMsgReader::readExtendedClipboard(int32_t len) } if (!zis.hasData(lengths[num])) - throw Exception("Extended clipboard decode error"); + throw protocol_error("Extended clipboard decode error"); buffers[num] = new uint8_t[lengths[num]]; zis.readBytes(buffers[num], lengths[num]); @@ -407,7 +407,7 @@ bool CMsgReader::readExtendedClipboard(int32_t len) handler->handleClipboardNotify(flags); break; default: - throw Exception("Invalid extended clipboard action"); + throw protocol_error("Invalid extended clipboard action"); } } @@ -473,7 +473,7 @@ bool CMsgReader::readRect(const Rect& r, int encoding) vlog.error("Rect too big: %dx%d at %d,%d exceeds %dx%d", r.width(), r.height(), r.tl.x, r.tl.y, handler->server.width(), handler->server.height()); - throw Exception("Rect too big"); + throw protocol_error("Rect too big"); } if (r.is_empty()) @@ -485,7 +485,7 @@ bool CMsgReader::readRect(const Rect& r, int encoding) bool CMsgReader::readSetXCursor(int width, int height, const Point& hotspot) { if (width > maxCursorSize || height > maxCursorSize) - throw Exception("Too big cursor"); + throw protocol_error("Too big cursor"); std::vector rgba(width*height*4); @@ -549,7 +549,7 @@ bool CMsgReader::readSetXCursor(int width, int height, const Point& hotspot) bool CMsgReader::readSetCursor(int width, int height, const Point& hotspot) { if (width > maxCursorSize || height > maxCursorSize) - throw Exception("Too big cursor"); + throw protocol_error("Too big cursor"); int data_len = width * height * (handler->server.pf().bpp/8); int mask_len = ((width+7)/8) * height; @@ -595,7 +595,7 @@ bool CMsgReader::readSetCursor(int width, int height, const Point& hotspot) bool CMsgReader::readSetCursorWithAlpha(int width, int height, const Point& hotspot) { if (width > maxCursorSize || height > maxCursorSize) - throw Exception("Too big cursor"); + throw protocol_error("Too big cursor"); const PixelFormat rgbaPF(32, 32, false, true, 255, 255, 255, 16, 8, 0); ManagedPixelBuffer pb(rgbaPF, width, height); @@ -656,7 +656,7 @@ bool CMsgReader::readSetCursorWithAlpha(int width, int height, const Point& hots bool CMsgReader::readSetVMwareCursor(int width, int height, const Point& hotspot) { if (width > maxCursorSize || height > maxCursorSize) - throw Exception("Too big cursor"); + throw protocol_error("Too big cursor"); uint8_t type; @@ -750,7 +750,7 @@ bool CMsgReader::readSetVMwareCursor(int width, int height, const Point& hotspot handler->setCursor(width, height, hotspot, data.data()); } else { - throw Exception("Unknown cursor type"); + throw protocol_error("Unknown cursor type"); } return true; diff --git a/common/rfb/CMsgWriter.cxx b/common/rfb/CMsgWriter.cxx index 1bd8040f7a..1c801412ce 100644 --- a/common/rfb/CMsgWriter.cxx +++ b/common/rfb/CMsgWriter.cxx @@ -31,7 +31,6 @@ #include #include #include -#include #include #include #include @@ -77,7 +76,7 @@ void CMsgWriter::writeSetDesktopSize(int width, int height, const ScreenSet& layout) { if (!server->supportsSetDesktopSize) - throw Exception("Server does not support SetDesktopSize"); + throw std::logic_error("Server does not support SetDesktopSize"); startMsg(msgTypeSetDesktopSize); os->pad(1); @@ -116,7 +115,7 @@ void CMsgWriter::writeEnableContinuousUpdates(bool enable, int x, int y, int w, int h) { if (!server->supportsContinuousUpdates) - throw Exception("Server does not support continuous updates"); + throw std::logic_error("Server does not support continuous updates"); startMsg(msgTypeEnableContinuousUpdates); @@ -133,11 +132,11 @@ void CMsgWriter::writeEnableContinuousUpdates(bool enable, void CMsgWriter::writeFence(uint32_t flags, unsigned len, const uint8_t data[]) { if (!server->supportsFence) - throw Exception("Server does not support fences"); + throw std::logic_error("Server does not support fences"); if (len > 64) - throw Exception("Too large fence payload"); + throw std::out_of_range("Too large fence payload"); if ((flags & ~fenceFlagsSupported) != 0) - throw Exception("Unknown fence flags"); + throw std::invalid_argument("Unknown fence flags"); startMsg(msgTypeClientFence); os->pad(3); @@ -192,7 +191,7 @@ void CMsgWriter::writePointerEvent(const Point& pos, uint8_t buttonMask) void CMsgWriter::writeClientCutText(const char* str) { if (strchr(str, '\r') != nullptr) - throw Exception("Invalid carriage return in clipboard data"); + throw std::invalid_argument("Invalid carriage return in clipboard data"); std::string latin1(utf8ToLatin1(str)); @@ -209,7 +208,7 @@ void CMsgWriter::writeClipboardCaps(uint32_t caps, size_t i, count; if (!(server->clipboardFlags() & clipboardCaps)) - throw Exception("Server does not support clipboard \"caps\" action"); + throw std::logic_error("Server does not support clipboard \"caps\" action"); count = 0; for (i = 0;i < 16;i++) { @@ -235,7 +234,7 @@ void CMsgWriter::writeClipboardCaps(uint32_t caps, void CMsgWriter::writeClipboardRequest(uint32_t flags) { if (!(server->clipboardFlags() & clipboardRequest)) - throw Exception("Server does not support clipboard \"request\" action"); + throw std::logic_error("Server does not support clipboard \"request\" action"); startMsg(msgTypeClientCutText); os->pad(3); @@ -247,7 +246,7 @@ void CMsgWriter::writeClipboardRequest(uint32_t flags) void CMsgWriter::writeClipboardPeek(uint32_t flags) { if (!(server->clipboardFlags() & clipboardPeek)) - throw Exception("Server does not support clipboard \"peek\" action"); + throw std::logic_error("Server does not support clipboard \"peek\" action"); startMsg(msgTypeClientCutText); os->pad(3); @@ -259,7 +258,7 @@ void CMsgWriter::writeClipboardPeek(uint32_t flags) void CMsgWriter::writeClipboardNotify(uint32_t flags) { if (!(server->clipboardFlags() & clipboardNotify)) - throw Exception("Server does not support clipboard \"notify\" action"); + throw std::logic_error("Server does not support clipboard \"notify\" action"); startMsg(msgTypeClientCutText); os->pad(3); @@ -278,7 +277,7 @@ void CMsgWriter::writeClipboardProvide(uint32_t flags, int i, count; if (!(server->clipboardFlags() & clipboardProvide)) - throw Exception("Server does not support clipboard \"provide\" action"); + throw std::logic_error("Server does not support clipboard \"provide\" action"); zos.setUnderlying(&mos); diff --git a/common/rfb/CSecurityDH.cxx b/common/rfb/CSecurityDH.cxx index 6eafbd9ca5..d8308cbf8a 100644 --- a/common/rfb/CSecurityDH.cxx +++ b/common/rfb/CSecurityDH.cxx @@ -86,9 +86,9 @@ bool CSecurityDH::readKey() uint16_t gen = is->readU16(); keyLength = is->readU16(); if (keyLength < MinKeyLength) - throw Exception("DH key is too short"); + throw protocol_error("DH key is too short"); if (keyLength > MaxKeyLength) - throw Exception("DH key is too long"); + throw protocol_error("DH key is too long"); if (!is->hasDataOrRestore(keyLength * 2)) return false; is->clearRestorePoint(); @@ -112,7 +112,7 @@ void CSecurityDH::writeCredentials() std::vector bBytes(keyLength); if (!rs.hasData(keyLength)) - throw Exception("failed to generate DH private key"); + throw std::runtime_error("failed to generate DH private key"); rs.readBytes(bBytes.data(), bBytes.size()); nettle_mpz_set_str_256_u(b, bBytes.size(), bBytes.data()); mpz_powm(k, A, b, p); @@ -132,13 +132,13 @@ void CSecurityDH::writeCredentials() uint8_t buf[128]; if (!rs.hasData(128)) - throw Exception("failed to generate random padding"); + throw std::runtime_error("failed to generate random padding"); rs.readBytes(buf, 128); if (username.size() >= 64) - throw Exception("username is too long"); + throw std::out_of_range("username is too long"); memcpy(buf, username.c_str(), username.size() + 1); if (password.size() >= 64) - throw Exception("password is too long"); + throw std::out_of_range("password is too long"); memcpy(buf + 64, password.c_str(), password.size() + 1); aes128_encrypt(&aesCtx, 128, buf, buf); diff --git a/common/rfb/CSecurityMSLogonII.cxx b/common/rfb/CSecurityMSLogonII.cxx index f8ff36c155..85736b44f0 100644 --- a/common/rfb/CSecurityMSLogonII.cxx +++ b/common/rfb/CSecurityMSLogonII.cxx @@ -39,7 +39,6 @@ #include #include #include -#include #include using namespace rfb; @@ -101,7 +100,7 @@ void CSecurityMSLogonII::writeCredentials() std::vector bBytes(8); if (!rs.hasData(8)) - throw Exception("failed to generate DH private key"); + throw std::runtime_error("failed to generate DH private key"); rs.readBytes(bBytes.data(), bBytes.size()); nettle_mpz_set_str_256_u(b, bBytes.size(), bBytes.data()); mpz_powm(k, A, b, p); @@ -123,14 +122,14 @@ void CSecurityMSLogonII::writeCredentials() } if (!rs.hasData(256 + 64)) - throw Exception("failed to generate random padding"); + throw std::runtime_error("failed to generate random padding"); rs.readBytes(user, 256); rs.readBytes(pass, 64); if (username.size() >= 256) - throw Exception("username is too long"); + throw std::out_of_range("username is too long"); memcpy(user, username.c_str(), username.size() + 1); if (password.size() >= 64) - throw Exception("password is too long"); + throw std::out_of_range("password is too long"); memcpy(pass, password.c_str(), password.size() + 1); // DES-CBC with the original key as IV, and the reversed one as the DES key diff --git a/common/rfb/CSecurityRSAAES.cxx b/common/rfb/CSecurityRSAAES.cxx index 4baeb235c2..96fd20cd6a 100644 --- a/common/rfb/CSecurityRSAAES.cxx +++ b/common/rfb/CSecurityRSAAES.cxx @@ -134,7 +134,7 @@ static void random_func(void* ctx, size_t length, uint8_t* dst) { rdr::RandomStream* rs = (rdr::RandomStream*)ctx; if (!rs->hasData(length)) - throw Exception("failed to generate random"); + throw std::runtime_error("failed to generate random"); rs->readBytes(dst, length); } @@ -155,7 +155,7 @@ void CSecurityRSAAES::writePublicKey() if (!rsa_generate_keypair(&clientPublicKey, &clientKey, &rs, random_func, nullptr, nullptr, clientKeyLength, 0)) - throw Exception("failed to generate key"); + throw std::runtime_error("failed to generate key"); clientKeyN = new uint8_t[rsaKeySize]; clientKeyE = new uint8_t[rsaKeySize]; nettle_mpz_get_str_256(rsaKeySize, clientKeyN, clientPublicKey.n); @@ -174,9 +174,9 @@ bool CSecurityRSAAES::readPublicKey() is->setRestorePoint(); serverKeyLength = is->readU32(); if (serverKeyLength < MinKeyLength) - throw Exception("server key is too short"); + throw protocol_error("server key is too short"); if (serverKeyLength > MaxKeyLength) - throw Exception("server key is too long"); + throw protocol_error("server key is too long"); size_t size = (serverKeyLength + 7) / 8; if (!is->hasDataOrRestore(size * 2)) return false; @@ -189,7 +189,7 @@ bool CSecurityRSAAES::readPublicKey() nettle_mpz_set_str_256_u(serverKey.n, size, serverKeyN); nettle_mpz_set_str_256_u(serverKey.e, size, serverKeyE); if (!rsa_public_key_prepare(&serverKey)) - throw Exception("server key is invalid"); + throw protocol_error("server key is invalid"); return true; } @@ -215,14 +215,14 @@ void CSecurityRSAAES::verifyServer() "Please verify that the information is correct and press \"Yes\". " "Otherwise press \"No\"", f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7]); if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, title, text.c_str())) - throw AuthCancelledException(); + throw auth_cancelled(); } void CSecurityRSAAES::writeRandom() { rdr::OutStream* os = cc->getOutStream(); if (!rs.hasData(keySize / 8)) - throw Exception("failed to generate random"); + throw std::runtime_error("failed to generate random"); rs.readBytes(clientRandom, keySize / 8); mpz_t x; mpz_init(x); @@ -236,7 +236,7 @@ void CSecurityRSAAES::writeRandom() } if (!res) { mpz_clear(x); - throw Exception("failed to encrypt random"); + throw std::runtime_error("failed to encrypt random"); } uint8_t* buffer = new uint8_t[serverKey.size]; nettle_mpz_get_str_256(serverKey.size, buffer, x); @@ -255,7 +255,7 @@ bool CSecurityRSAAES::readRandom() is->setRestorePoint(); size_t size = is->readU16(); if (size != clientKey.size) - throw Exception("client key length doesn't match"); + throw protocol_error("client key length doesn't match"); if (!is->hasDataOrRestore(size)) return false; is->clearRestorePoint(); @@ -268,7 +268,7 @@ bool CSecurityRSAAES::readRandom() if (!rsa_decrypt(&clientKey, &randomSize, serverRandom, x) || randomSize != (size_t)keySize / 8) { mpz_clear(x); - throw Exception("failed to decrypt server random"); + throw protocol_error("failed to decrypt server random"); } mpz_clear(x); return true; @@ -397,7 +397,7 @@ bool CSecurityRSAAES::readHash() sha256_digest(&ctx, hashSize, realHash); } if (memcmp(hash, realHash, hashSize) != 0) - throw Exception("hash doesn't match"); + throw protocol_error("hash doesn't match"); return true; } @@ -427,7 +427,7 @@ bool CSecurityRSAAES::readSubtype() return false; subtype = rais->readU8(); if (subtype != secTypeRA2UserPass && subtype != secTypeRA2Pass) - throw Exception("unknown RSA-AES subtype"); + throw protocol_error("unknown RSA-AES subtype"); return true; } @@ -443,7 +443,7 @@ void CSecurityRSAAES::writeCredentials() if (subtype == secTypeRA2UserPass) { if (username.size() > 255) - throw Exception("username is too long"); + throw std::out_of_range("username is too long"); raos->writeU8(username.size()); raos->writeBytes((const uint8_t*)username.data(), username.size()); } else { @@ -451,7 +451,7 @@ void CSecurityRSAAES::writeCredentials() } if (password.size() > 255) - throw Exception("password is too long"); + throw std::out_of_range("password is too long"); raos->writeU8(password.size()); raos->writeBytes((const uint8_t*)password.data(), password.size()); raos->flush(); diff --git a/common/rfb/CSecurityTLS.cxx b/common/rfb/CSecurityTLS.cxx index 6eeb6a84d3..3761ca30bf 100644 --- a/common/rfb/CSecurityTLS.cxx +++ b/common/rfb/CSecurityTLS.cxx @@ -80,7 +80,7 @@ CSecurityTLS::CSecurityTLS(CConnection* cc_, bool _anon) { int err = gnutls_global_init(); if (err != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_global_init()", err); + throw rdr::tls_error("gnutls_global_init()", err); } void CSecurityTLS::shutdown() @@ -146,15 +146,15 @@ bool CSecurityTLS::processMsg() return false; if (is->readU8() == 0) - throw Exception("Server failed to initialize TLS session"); + throw protocol_error("Server failed to initialize TLS session"); ret = gnutls_init(&session, GNUTLS_CLIENT); if (ret != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_init()", ret); + throw rdr::tls_error("gnutls_init()", ret); ret = gnutls_set_default_priority(session); if (ret != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_set_default_priority()", ret); + throw rdr::tls_error("gnutls_set_default_priority()", ret); setParam(); @@ -177,7 +177,7 @@ bool CSecurityTLS::processMsg() vlog.error("TLS Handshake failed: %s\n", gnutls_strerror (err)); shutdown(); - throw rdr::TLSException("TLS Handshake failed", err); + throw rdr::tls_error("TLS Handshake failed", err); } vlog.debug("TLS handshake completed with %s", @@ -201,10 +201,8 @@ void CSecurityTLS::setParam() char *prio; const char *err; - prio = (char*)malloc(strlen(Security::GnuTLSPriority) + - strlen(kx_anon_priority) + 1); - if (prio == nullptr) - throw Exception("Not enough memory for GnuTLS priority string"); + prio = new char[strlen(Security::GnuTLSPriority) + + strlen(kx_anon_priority) + 1]; strcpy(prio, Security::GnuTLSPriority); if (anon) @@ -212,12 +210,12 @@ void CSecurityTLS::setParam() ret = gnutls_priority_set_direct(session, prio, &err); - free(prio); + delete [] prio; if (ret != GNUTLS_E_SUCCESS) { if (ret == GNUTLS_E_INVALID_REQUEST) vlog.error("GnuTLS priority syntax error at: %s", err); - throw rdr::TLSException("gnutls_set_priority_direct()", ret); + throw rdr::tls_error("gnutls_set_priority_direct()", ret); } } else if (anon) { const char *err; @@ -229,7 +227,7 @@ void CSecurityTLS::setParam() if (ret != GNUTLS_E_SUCCESS) { if (ret == GNUTLS_E_INVALID_REQUEST) vlog.error("GnuTLS priority syntax error at: %s", err); - throw rdr::TLSException("gnutls_set_default_priority_append()", ret); + throw rdr::tls_error("gnutls_set_default_priority_append()", ret); } #else // We don't know what the system default priority is, so we guess @@ -237,22 +235,20 @@ void CSecurityTLS::setParam() static const char gnutls_default_priority[] = "NORMAL"; char *prio; - prio = (char*)malloc(strlen(gnutls_default_priority) + - strlen(kx_anon_priority) + 1); - if (prio == nullptr) - throw Exception("Not enough memory for GnuTLS priority string"); + prio = new char[malloc(strlen(gnutls_default_priority) + + strlen(kx_anon_priority) + 1]; strcpy(prio, gnutls_default_priority); strcat(prio, kx_anon_priority); ret = gnutls_priority_set_direct(session, prio, &err); - free(prio); + delete [] prio; if (ret != GNUTLS_E_SUCCESS) { if (ret == GNUTLS_E_INVALID_REQUEST) vlog.error("GnuTLS priority syntax error at: %s", err); - throw rdr::TLSException("gnutls_set_priority_direct()", ret); + throw rdr::tls_error("gnutls_set_priority_direct()", ret); } #endif } @@ -260,17 +256,17 @@ void CSecurityTLS::setParam() if (anon) { ret = gnutls_anon_allocate_client_credentials(&anon_cred); if (ret != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_anon_allocate_client_credentials()", ret); + throw rdr::tls_error("gnutls_anon_allocate_client_credentials()", ret); ret = gnutls_credentials_set(session, GNUTLS_CRD_ANON, anon_cred); if (ret != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_credentials_set()", ret); + throw rdr::tls_error("gnutls_credentials_set()", ret); vlog.debug("Anonymous session has been set"); } else { ret = gnutls_certificate_allocate_credentials(&cert_cred); if (ret != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_certificate_allocate_credentials()", ret); + throw rdr::tls_error("gnutls_certificate_allocate_credentials()", ret); if (gnutls_certificate_set_x509_system_trust(cert_cred) < 1) vlog.error("Could not load system certificate trust store"); @@ -283,7 +279,7 @@ void CSecurityTLS::setParam() ret = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, cert_cred); if (ret != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_credentials_set()", ret); + throw rdr::tls_error("gnutls_credentials_set()", ret); if (gnutls_server_name_set(session, GNUTLS_NAME_DNS, client->getServerName(), @@ -316,12 +312,12 @@ void CSecurityTLS::checkSession() return; if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509) - throw Exception("unsupported certificate type"); + throw protocol_error("unsupported certificate type"); err = gnutls_certificate_verify_peers2(session, &status); if (err != 0) { vlog.error("server certificate verification failed: %s", gnutls_strerror(err)); - throw rdr::TLSException("server certificate verification()", err); + throw rdr::tls_error("server certificate verification()", err); } if (status != 0) { @@ -338,13 +334,14 @@ void CSecurityTLS::checkSession() &status_str, 0); if (err != GNUTLS_E_SUCCESS) - throw rdr::TLSException("Failed to get certificate error description", err); + throw rdr::tls_error("Failed to get certificate error description", err); error = (const char*)status_str.data; gnutls_free(status_str.data); - throw Exception("Invalid server certificate: %s", error.c_str()); + throw protocol_error(format("Invalid server certificate: %s", + error.c_str())); } err = gnutls_certificate_verification_status_print(status, @@ -352,7 +349,7 @@ void CSecurityTLS::checkSession() &status_str, 0); if (err != GNUTLS_E_SUCCESS) - throw rdr::TLSException("Failed to get certificate error description", err); + throw rdr::tls_error("Failed to get certificate error description", err); vlog.info("Server certificate errors: %s", status_str.data); @@ -363,7 +360,7 @@ void CSecurityTLS::checkSession() cert_list = gnutls_certificate_get_peers(session, &cert_list_size); if (!cert_list_size) - throw Exception("empty certificate chain"); + throw protocol_error("empty certificate chain"); /* Process only server's certificate, not issuer's certificate */ gnutls_x509_crt_t crt; @@ -371,7 +368,7 @@ void CSecurityTLS::checkSession() err = gnutls_x509_crt_import(crt, &cert_list[0], GNUTLS_X509_FMT_DER); if (err != GNUTLS_E_SUCCESS) - throw rdr::TLSException("Failed to decode server certificate", err); + throw rdr::tls_error("Failed to decode server certificate", err); if (gnutls_x509_crt_check_hostname(crt, client->getServerName()) == 0) { vlog.info("Server certificate doesn't match given server name"); @@ -390,8 +387,8 @@ void CSecurityTLS::checkSession() hostsDir = os::getvncstatedir(); if (hostsDir == nullptr) { - throw Exception("Could not obtain VNC state directory path for " - "known hosts storage"); + throw std::runtime_error("Could not obtain VNC state directory " + "path for known hosts storage"); } std::string dbPath; @@ -410,12 +407,12 @@ void CSecurityTLS::checkSession() if ((known != GNUTLS_E_NO_CERTIFICATE_FOUND) && (known != GNUTLS_E_CERTIFICATE_KEY_MISMATCH)) { - throw rdr::TLSException("Could not load known hosts database", known); + throw rdr::tls_error("Could not load known hosts database", known); } err = gnutls_x509_crt_print(crt, GNUTLS_CRT_PRINT_ONELINE, &info); if (err != GNUTLS_E_SUCCESS) - throw rdr::TLSException("Could not find certificate to display", err); + throw rdr::tls_error("Could not find certificate to display", err); len = strlen((char*)info.data); for (size_t i = 0; i < len - 1; i++) { @@ -447,7 +444,7 @@ void CSecurityTLS::checkSession() if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Unknown certificate issuer", text.c_str())) - throw AuthCancelledException(); + throw auth_cancelled(); status &= ~(GNUTLS_CERT_INVALID | GNUTLS_CERT_SIGNER_NOT_FOUND | @@ -467,7 +464,7 @@ void CSecurityTLS::checkSession() if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Certificate is not yet valid", text.c_str())) - throw AuthCancelledException(); + throw auth_cancelled(); status &= ~GNUTLS_CERT_NOT_ACTIVATED; } @@ -486,7 +483,7 @@ void CSecurityTLS::checkSession() if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Expired certificate", text.c_str())) - throw AuthCancelledException(); + throw auth_cancelled(); status &= ~GNUTLS_CERT_EXPIRED; } @@ -505,14 +502,14 @@ void CSecurityTLS::checkSession() if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Insecure certificate algorithm", text.c_str())) - throw AuthCancelledException(); + throw auth_cancelled(); status &= ~GNUTLS_CERT_INSECURE_ALGORITHM; } if (status != 0) { vlog.error("Unhandled certificate problems: 0x%x", status); - throw Exception("Unhandled certificate problems"); + throw std::logic_error("Unhandled certificate problems"); } if (!hostname_match) { @@ -530,7 +527,7 @@ void CSecurityTLS::checkSession() if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Certificate hostname mismatch", text.c_str())) - throw AuthCancelledException(); + throw auth_cancelled(); } } else if (known == GNUTLS_E_CERTIFICATE_KEY_MISMATCH) { std::string text; @@ -556,7 +553,7 @@ void CSecurityTLS::checkSession() if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Unexpected server certificate", text.c_str())) - throw AuthCancelledException(); + throw auth_cancelled(); status &= ~(GNUTLS_CERT_INVALID | GNUTLS_CERT_SIGNER_NOT_FOUND | @@ -579,7 +576,7 @@ void CSecurityTLS::checkSession() if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Unexpected server certificate", text.c_str())) - throw AuthCancelledException(); + throw auth_cancelled(); status &= ~GNUTLS_CERT_NOT_ACTIVATED; } @@ -600,7 +597,7 @@ void CSecurityTLS::checkSession() if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Unexpected server certificate", text.c_str())) - throw AuthCancelledException(); + throw auth_cancelled(); status &= ~GNUTLS_CERT_EXPIRED; } @@ -621,14 +618,14 @@ void CSecurityTLS::checkSession() if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Unexpected server certificate", text.c_str())) - throw AuthCancelledException(); + throw auth_cancelled(); status &= ~GNUTLS_CERT_INSECURE_ALGORITHM; } if (status != 0) { vlog.error("Unhandled certificate problems: 0x%x", status); - throw Exception("Unhandled certificate problems"); + throw std::logic_error("Unhandled certificate problems"); } if (!hostname_match) { @@ -648,7 +645,7 @@ void CSecurityTLS::checkSession() if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Unexpected server certificate", text.c_str())) - throw AuthCancelledException(); + throw auth_cancelled(); } } diff --git a/common/rfb/CSecurityVeNCrypt.cxx b/common/rfb/CSecurityVeNCrypt.cxx index 3ebb38552c..1b6ecf2205 100644 --- a/common/rfb/CSecurityVeNCrypt.cxx +++ b/common/rfb/CSecurityVeNCrypt.cxx @@ -105,7 +105,7 @@ bool CSecurityVeNCrypt::processMsg() os->writeU8(0); os->writeU8(0); os->flush(); - throw Exception("The server reported an unsupported VeNCrypt version"); + throw protocol_error("The server reported an unsupported VeNCrypt version"); } haveSentVersion = true; @@ -117,8 +117,8 @@ bool CSecurityVeNCrypt::processMsg() return false; if (is->readU8()) - throw Exception("The server reported it could not support the " - "VeNCrypt version"); + throw protocol_error("The server reported it could not " + "support the VeNCrypt version"); haveAgreedVersion = true; } @@ -131,7 +131,7 @@ bool CSecurityVeNCrypt::processMsg() nAvailableTypes = is->readU8(); if (!nAvailableTypes) - throw Exception("The server reported no VeNCrypt sub-types"); + throw protocol_error("The server reported no VeNCrypt sub-types"); availableTypes = new uint32_t[nAvailableTypes]; haveNumberOfTypes = true; @@ -172,7 +172,7 @@ bool CSecurityVeNCrypt::processMsg() /* Set up the stack according to the chosen type: */ if (chosenType == secTypeInvalid || chosenType == secTypeVeNCrypt) - throw Exception("No valid VeNCrypt sub-type"); + throw protocol_error("No valid VeNCrypt sub-type"); vlog.info("Choosing security type %s (%d)", secTypeName(chosenType), chosenType); @@ -191,7 +191,7 @@ bool CSecurityVeNCrypt::processMsg() * happen, since if the server supports 0 sub-types, it doesn't support * this security type */ - throw Exception("The server reported 0 VeNCrypt sub-types"); + throw protocol_error("The server reported 0 VeNCrypt sub-types"); } return csecurity->processMsg(); diff --git a/common/rfb/ClientParams.cxx b/common/rfb/ClientParams.cxx index bc20c3d726..495b4bd127 100644 --- a/common/rfb/ClientParams.cxx +++ b/common/rfb/ClientParams.cxx @@ -22,11 +22,13 @@ #include #endif -#include +#include + #include #include #include #include +#include using namespace rfb; @@ -62,7 +64,7 @@ void ClientParams::setDimensions(int width, int height) void ClientParams::setDimensions(int width, int height, const ScreenSet& layout) { if (!layout.validate(width, height)) - throw Exception("Attempted to configure an invalid screen layout"); + throw std::invalid_argument("Attempted to configure an invalid screen layout"); width_ = width; height_ = height; @@ -74,7 +76,7 @@ void ClientParams::setPF(const PixelFormat& pf) pf_ = pf; if (pf.bpp != 8 && pf.bpp != 16 && pf.bpp != 32) - throw Exception("setPF: not 8, 16 or 32 bpp?"); + throw std::invalid_argument("setPF: not 8, 16 or 32 bpp?"); } void ClientParams::setName(const char* name) @@ -160,7 +162,7 @@ uint32_t ClientParams::clipboardSize(unsigned int format) const return clipSizes[i]; } - throw Exception("Invalid clipboard format 0x%x", format); + throw std::invalid_argument(rfb::format("Invalid clipboard format 0x%x", format)); } void ClientParams::setClipboardCaps(uint32_t flags, const uint32_t* lengths) diff --git a/common/rfb/Configuration.cxx b/common/rfb/Configuration.cxx index f58a9c2f9d..8f7cb6a769 100644 --- a/common/rfb/Configuration.cxx +++ b/common/rfb/Configuration.cxx @@ -30,12 +30,13 @@ #include #include +#include + #include #include #include #include -#include #define LOCK_CONFIG os::AutoMutex a(mutex) @@ -376,7 +377,7 @@ StringParameter::StringParameter(const char* name_, const char* desc_, { if (!v) { vlog.error("Default value for %s not allowed",name_); - throw rfb::Exception("Default value not allowed"); + throw std::invalid_argument("Default value not allowed"); } } @@ -387,7 +388,7 @@ bool StringParameter::setParam(const char* v) { LOCK_CONFIG; if (immutable) return true; if (!v) - throw rfb::Exception("setParam() not allowed"); + throw std::invalid_argument("setParam() not allowed"); vlog.debug("set %s(String) to %s", getName(), v); value = v; return true; diff --git a/common/rfb/Cursor.cxx b/common/rfb/Cursor.cxx index fa596bc5b6..9484414415 100644 --- a/common/rfb/Cursor.cxx +++ b/common/rfb/Cursor.cxx @@ -24,9 +24,10 @@ #include #include +#include + #include #include -#include using namespace rfb; @@ -260,7 +261,7 @@ const uint8_t* RenderedCursor::getBuffer(const Rect& _r, int* stride) const r = _r.translate(offset.negate()); if (!r.enclosed_by(buffer.getRect())) - throw Exception("RenderedCursor: Invalid area requested"); + throw std::out_of_range("RenderedCursor: Invalid area requested"); return buffer.getBuffer(r, stride); } diff --git a/common/rfb/DecodeManager.cxx b/common/rfb/DecodeManager.cxx index ef41588611..09118f36e6 100644 --- a/common/rfb/DecodeManager.cxx +++ b/common/rfb/DecodeManager.cxx @@ -114,14 +114,14 @@ bool DecodeManager::decodeRect(const Rect& r, int encoding, if (!Decoder::supported(encoding)) { vlog.error("Unknown encoding %d", encoding); - throw rdr::Exception("Unknown encoding"); + throw protocol_error("Unknown encoding"); } if (!decoders[encoding]) { decoders[encoding] = Decoder::createDecoder(encoding); if (!decoders[encoding]) { vlog.error("Unknown encoding %d", encoding); - throw rdr::Exception("Unknown encoding"); + throw protocol_error("Unknown encoding"); } } @@ -148,8 +148,8 @@ bool DecodeManager::decodeRect(const Rect& r, int encoding, try { if (!decoder->readRect(r, conn->getInStream(), conn->server, bufferStream)) return false; - } catch (rdr::Exception& e) { - throw Exception("Error reading rect: %s", e.str()); + } catch (std::exception& e) { + throw std::runtime_error(format("Error reading rect: %s", e.what())); } stats[encoding].rects++; @@ -243,14 +243,14 @@ void DecodeManager::logStats() iecPrefix(bytes, "B").c_str(), ratio); } -void DecodeManager::setThreadException(const rdr::Exception& e) +void DecodeManager::setThreadException(const std::exception& e) { os::AutoMutex a(queueMutex); if (threadException != nullptr) return; - threadException = new rdr::Exception("Exception on worker thread: %s", e.str()); + threadException = new std::runtime_error(format("Exception on worker thread: %s", e.what())); } void DecodeManager::throwThreadException() @@ -260,7 +260,7 @@ void DecodeManager::throwThreadException() if (threadException == nullptr) return; - rdr::Exception e(*threadException); + std::exception e(*threadException); delete threadException; threadException = nullptr; @@ -318,7 +318,7 @@ void DecodeManager::DecodeThread::worker() entry->decoder->decodeRect(entry->rect, entry->bufferStream->data(), entry->bufferStream->length(), *entry->server, entry->pb); - } catch (rdr::Exception& e) { + } catch (std::exception& e) { manager->setThreadException(e); } catch(...) { assert(false); diff --git a/common/rfb/DecodeManager.h b/common/rfb/DecodeManager.h index 5435bfc179..b11b704492 100644 --- a/common/rfb/DecodeManager.h +++ b/common/rfb/DecodeManager.h @@ -32,7 +32,6 @@ namespace os { } namespace rdr { - struct Exception; class MemOutStream; } @@ -55,7 +54,7 @@ namespace rfb { private: void logStats(); - void setThreadException(const rdr::Exception& e); + void setThreadException(const std::exception& e); void throwThreadException(); private: @@ -108,7 +107,7 @@ namespace rfb { }; std::list threads; - rdr::Exception *threadException; + std::exception *threadException; }; } diff --git a/common/rfb/EncodeManager.cxx b/common/rfb/EncodeManager.cxx index 5c1429d2af..4526c0b3e0 100644 --- a/common/rfb/EncodeManager.cxx +++ b/common/rfb/EncodeManager.cxx @@ -32,7 +32,6 @@ #include #include #include -#include #include #include @@ -1055,7 +1054,7 @@ void EncodeManager::OffsetPixelBuffer::update(const PixelFormat& pf, uint8_t* EncodeManager::OffsetPixelBuffer::getBufferRW(const Rect& /*r*/, int* /*stride*/) { - throw rfb::Exception("Invalid write attempt to OffsetPixelBuffer"); + throw std::logic_error("Invalid write attempt to OffsetPixelBuffer"); } template diff --git a/common/rfb/Exception.h b/common/rfb/Exception.h index 773c65fae9..0e74209ca4 100644 --- a/common/rfb/Exception.h +++ b/common/rfb/Exception.h @@ -1,4 +1,5 @@ /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. + * Copyright 2014-2024 Pierre Ossman for Cendio AB * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,17 +19,25 @@ #ifndef __RFB_EXCEPTION_H__ #define __RFB_EXCEPTION_H__ -#include +#include namespace rfb { - typedef rdr::Exception Exception; - struct AuthFailureException : public Exception { - AuthFailureException(const char* reason) - : Exception("%s", reason) {} + class protocol_error : public std::runtime_error { + public: + protocol_error(const char* what_arg) : std::runtime_error(what_arg) {} + protocol_error(const std::string& what_arg) : std::runtime_error(what_arg) {} }; - struct AuthCancelledException : public rfb::Exception { - AuthCancelledException() - : Exception("Authentication cancelled") {} + + class auth_error : public std::runtime_error { + public: + auth_error(const char* reason) : std::runtime_error(reason) {} + auth_error(std::string& reason) : std::runtime_error(reason) {} + }; + + class auth_cancelled : public std::runtime_error { + public: + auth_cancelled() + : std::runtime_error("Authentication cancelled") {} }; } #endif diff --git a/common/rfb/H264Decoder.cxx b/common/rfb/H264Decoder.cxx index 3178a17bea..89850ba470 100644 --- a/common/rfb/H264Decoder.cxx +++ b/common/rfb/H264Decoder.cxx @@ -30,7 +30,6 @@ #include #include #include -#include #include #include @@ -128,12 +127,12 @@ void H264Decoder::decodeRect(const Rect& r, const uint8_t* buffer, } ctx = H264DecoderContext::createContext(r); if (!ctx) - throw Exception("H264Decoder: Context not be created"); + throw std::runtime_error("H264Decoder: Context not be created"); contexts.push_back(ctx); } if (!ctx->isReady()) - throw Exception("H264Decoder: Context is not ready"); + throw std::runtime_error("H264Decoder: Context is not ready"); if (reset & resetContext) ctx->reset(); diff --git a/common/rfb/H264DecoderContext.cxx b/common/rfb/H264DecoderContext.cxx index 87ac0d8535..b2054554e7 100644 --- a/common/rfb/H264DecoderContext.cxx +++ b/common/rfb/H264DecoderContext.cxx @@ -22,8 +22,9 @@ #include #endif +#include + #include -#include #include #include @@ -45,7 +46,7 @@ H264DecoderContext *H264DecoderContext::createContext(const Rect &r) H264DecoderContext *ret = new H264DecoderContextType(r); if (!ret->initCodec()) { - throw Exception("H264DecoderContext: Unable to create context"); + throw std::runtime_error("H264DecoderContext: Unable to create context"); } return ret; diff --git a/common/rfb/H264LibavDecoderContext.cxx b/common/rfb/H264LibavDecoderContext.cxx index fa2f367b3f..2d8d03e7d6 100644 --- a/common/rfb/H264LibavDecoderContext.cxx +++ b/common/rfb/H264LibavDecoderContext.cxx @@ -33,7 +33,6 @@ extern "C" { #define FFMPEG_INIT_PACKET_DEPRECATED #endif -#include #include #include #include @@ -118,7 +117,7 @@ uint8_t* H264LibavDecoderContext::makeH264WorkBuffer(const uint8_t* buffer, uint { h264WorkBuffer = (uint8_t*)realloc(h264WorkBuffer, reserve_len); if (h264WorkBuffer == nullptr) { - throw Exception("H264LibavDecoderContext: Unable to allocate memory"); + throw std::bad_alloc(); } h264WorkBufferLength = reserve_len; } diff --git a/common/rfb/HextileDecoder.cxx b/common/rfb/HextileDecoder.cxx index dc9b9be72f..35ec79285f 100644 --- a/common/rfb/HextileDecoder.cxx +++ b/common/rfb/HextileDecoder.cxx @@ -189,7 +189,7 @@ void HextileDecoder::hextileDecode(const Rect& r, rdr::InStream* is, int w = ((wh >> 4) & 15) + 1; int h = (wh & 15) + 1; if (x + w > 16 || y + h > 16) { - throw rfb::Exception("HEXTILE_DECODE: Hextile out of bounds"); + throw protocol_error("HEXTILE_DECODE: Hextile out of bounds"); } ptr = buf + y * t.width() + x; int rowAdd = t.width() - w; diff --git a/common/rfb/Hostname.h b/common/rfb/Hostname.h index f6a11a6053..de4a330e65 100644 --- a/common/rfb/Hostname.h +++ b/common/rfb/Hostname.h @@ -23,7 +23,9 @@ #include #include #include -#include + +#include + #include namespace rfb { @@ -47,7 +49,7 @@ namespace rfb { const char* portStart; if (hi == nullptr) - throw rdr::Exception("NULL host specified"); + throw std::invalid_argument("NULL host specified"); // Trim leading whitespace while(isspace(*hi)) @@ -60,7 +62,7 @@ namespace rfb { hostStart = &hi[1]; hostEnd = strchr(hostStart, ']'); if (hostEnd == nullptr) - throw rdr::Exception("unmatched [ in host"); + throw std::invalid_argument("unmatched [ in host"); portStart = hostEnd + 1; if (isAllSpace(portStart)) @@ -99,14 +101,14 @@ namespace rfb { char* end; if (portStart[0] != ':') - throw rdr::Exception("invalid port specified"); + throw std::invalid_argument("invalid port specified"); if (portStart[1] != ':') *port = strtol(portStart + 1, &end, 10); else *port = strtol(portStart + 2, &end, 10); if (*end != '\0' && ! isAllSpace(end)) - throw rdr::Exception("invalid port specified"); + throw std::invalid_argument("invalid port specified"); if ((portStart[1] != ':') && (*port < 100)) *port += basePort; diff --git a/common/rfb/JpegCompressor.cxx b/common/rfb/JpegCompressor.cxx index 42d5c475bf..67a86cd932 100644 --- a/common/rfb/JpegCompressor.cxx +++ b/common/rfb/JpegCompressor.cxx @@ -22,8 +22,9 @@ #include #endif +#include + #include -#include #include #include #include @@ -127,7 +128,7 @@ JpegCompressor::JpegCompressor(int bufferLen) : MemOutStream(bufferLen) if(setjmp(err->jmpBuffer)) { // this will execute if libjpeg has an error - throw rdr::Exception("%s", err->lastError); + throw std::runtime_error(err->lastError); } jpeg_create_compress(cinfo); @@ -171,7 +172,7 @@ void JpegCompressor::compress(const uint8_t *buf, volatile int stride, jpeg_abort_compress(cinfo); if (srcBufIsTemp && srcBuf) delete[] srcBuf; if (rowPointer) delete[] rowPointer; - throw rdr::Exception("%s", err->lastError); + throw std::runtime_error(err->lastError); } cinfo->image_width = w; @@ -256,5 +257,5 @@ void JpegCompressor::compress(const uint8_t *buf, volatile int stride, void JpegCompressor::writeBytes(const uint8_t* /*data*/, int /*length*/) { - throw rdr::Exception("writeBytes() is not valid with a JpegCompressor instance. Use compress() instead."); + throw std::logic_error("writeBytes() is not valid with a JpegCompressor instance. Use compress() instead."); } diff --git a/common/rfb/JpegDecompressor.cxx b/common/rfb/JpegDecompressor.cxx index 92ef014faf..10c9e49cd6 100644 --- a/common/rfb/JpegDecompressor.cxx +++ b/common/rfb/JpegDecompressor.cxx @@ -24,7 +24,7 @@ #endif #include -#include +#include #include #include @@ -120,7 +120,7 @@ JpegDecompressor::JpegDecompressor(void) if(setjmp(err->jmpBuffer)) { // this will execute if libjpeg has an error - throw rdr::Exception("%s", err->lastError); + throw std::runtime_error(err->lastError); } jpeg_create_decompress(dinfo); @@ -168,7 +168,7 @@ void JpegDecompressor::decompress(const uint8_t *jpegBuf, jpeg_abort_decompress(dinfo); if (dstBufIsTemp && dstBuf) delete[] dstBuf; if (rowPointer) delete[] rowPointer; - throw rdr::Exception("%s", err->lastError); + throw std::runtime_error(err->lastError); } src->pub.next_input_byte = jpegBuf; @@ -217,7 +217,7 @@ void JpegDecompressor::decompress(const uint8_t *jpegBuf, jpeg_abort_decompress(dinfo); if (dstBufIsTemp && dstBuf) delete[] dstBuf; if (rowPointer) delete[] rowPointer; - throw rdr::Exception("Tight Decoding: Wrong JPEG data received.\n"); + throw protocol_error("Tight Decoding: Wrong JPEG data received.\n"); } while (dinfo->output_scanline < dinfo->output_height) { diff --git a/common/rfb/PixelBuffer.cxx b/common/rfb/PixelBuffer.cxx index 0a287544bc..5590c21407 100644 --- a/common/rfb/PixelBuffer.cxx +++ b/common/rfb/PixelBuffer.cxx @@ -28,9 +28,11 @@ #include -#include +#include + #include #include +#include using namespace rfb; @@ -70,9 +72,10 @@ PixelBuffer::getImage(void* imageBuf, const Rect& r, int outStride) const const uint8_t* end; if (!r.enclosed_by(getRect())) - throw rfb::Exception("Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", - r.width(), r.height(), - r.tl.x, r.tl.y, width(), height()); + throw std::out_of_range(rfb::format("Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", + r.width(), r.height(), + r.tl.x, r.tl.y, + width(), height())); data = getBuffer(r, &inStride); @@ -106,9 +109,10 @@ void PixelBuffer::getImage(const PixelFormat& pf, void* imageBuf, } if (!r.enclosed_by(getRect())) - throw rfb::Exception("Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", - r.width(), r.height(), - r.tl.x, r.tl.y, width(), height()); + throw std::out_of_range(rfb::format("Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", + r.width(), r.height(), + r.tl.x, r.tl.y, + width(), height())); if (stride == 0) stride = r.width(); @@ -122,9 +126,9 @@ void PixelBuffer::getImage(const PixelFormat& pf, void* imageBuf, void PixelBuffer::setSize(int width, int height) { if ((width < 0) || (width > maxPixelBufferWidth)) - throw rfb::Exception("Invalid PixelBuffer width of %d pixels requested", width); + throw std::out_of_range(rfb::format("Invalid PixelBuffer width of %d pixels requested", width)); if ((height < 0) || (height > maxPixelBufferHeight)) - throw rfb::Exception("Invalid PixelBuffer height of %d pixels requested", height); + throw std::out_of_range(rfb::format("Invalid PixelBuffer height of %d pixels requested", height)); width_ = width; height_ = height; @@ -153,8 +157,10 @@ void ModifiablePixelBuffer::fillRect(const Rect& r, const void* pix) int w, h, b; if (!r.enclosed_by(getRect())) - throw rfb::Exception("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", - r.width(), r.height(), r.tl.x, r.tl.y, width(), height()); + throw std::out_of_range(rfb::format("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", + r.width(), r.height(), + r.tl.x, r.tl.y, + width(), height())); w = r.width(); h = r.height(); @@ -203,9 +209,10 @@ void ModifiablePixelBuffer::imageRect(const Rect& r, uint8_t* end; if (!r.enclosed_by(getRect())) - throw rfb::Exception("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", - r.width(), r.height(), - r.tl.x, r.tl.y, width(), height()); + throw std::out_of_range(rfb::format("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", + r.width(), r.height(), + r.tl.x, r.tl.y, + width(), height())); bytesPerPixel = getPF().bpp/8; @@ -242,15 +249,17 @@ void ModifiablePixelBuffer::copyRect(const Rect &rect, drect = rect; if (!drect.enclosed_by(getRect())) - throw rfb::Exception("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", - drect.width(), drect.height(), - drect.tl.x, drect.tl.y, width(), height()); + throw std::out_of_range(rfb::format("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", + drect.width(), drect.height(), + drect.tl.x, drect.tl.y, + width(), height())); srect = drect.translate(move_by_delta.negate()); if (!srect.enclosed_by(getRect())) - throw rfb::Exception("Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", - srect.width(), srect.height(), - srect.tl.x, srect.tl.y, width(), height()); + throw std::out_of_range(rfb::format("Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", + srect.width(), srect.height(), + srect.tl.x, srect.tl.y, + width(), height())); bytesPerPixel = format.bpp/8; @@ -303,9 +312,10 @@ void ModifiablePixelBuffer::imageRect(const PixelFormat& pf, const Rect &dest, int dstStride; if (!dest.enclosed_by(getRect())) - throw rfb::Exception("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", - dest.width(), dest.height(), - dest.tl.x, dest.tl.y, width(), height()); + throw std::out_of_range(rfb::format("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", + dest.width(), dest.height(), + dest.tl.x, dest.tl.y, + width(), height())); if (stride == 0) stride = dest.width(); @@ -332,9 +342,10 @@ FullFramePixelBuffer::~FullFramePixelBuffer() {} uint8_t* FullFramePixelBuffer::getBufferRW(const Rect& r, int* stride_) { if (!r.enclosed_by(getRect())) - throw rfb::Exception("Pixel buffer request %dx%d at %d,%d exceeds framebuffer %dx%d", - r.width(), r.height(), - r.tl.x, r.tl.y, width(), height()); + throw std::out_of_range(rfb::format("Pixel buffer request %dx%d at %d,%d exceeds framebuffer %dx%d", + r.width(), r.height(), + r.tl.x, r.tl.y, + width(), height())); *stride_ = stride; return &data[(r.tl.x + (r.tl.y * stride)) * (format.bpp/8)]; @@ -347,9 +358,10 @@ void FullFramePixelBuffer::commitBufferRW(const Rect& /*r*/) const uint8_t* FullFramePixelBuffer::getBuffer(const Rect& r, int* stride_) const { if (!r.enclosed_by(getRect())) - throw rfb::Exception("Pixel buffer request %dx%d at %d,%d exceeds framebuffer %dx%d", - r.width(), r.height(), - r.tl.x, r.tl.y, width(), height()); + throw std::out_of_range(rfb::format("Pixel buffer request %dx%d at %d,%d exceeds framebuffer %dx%d", + r.width(), r.height(), + r.tl.x, r.tl.y, + width(), height())); *stride_ = stride; return &data[(r.tl.x + (r.tl.y * stride)) * (format.bpp/8)]; @@ -359,13 +371,13 @@ void FullFramePixelBuffer::setBuffer(int width, int height, uint8_t* data_, int stride_) { if ((width < 0) || (width > maxPixelBufferWidth)) - throw rfb::Exception("Invalid PixelBuffer width of %d pixels requested", width); + throw std::out_of_range(rfb::format("Invalid PixelBuffer width of %d pixels requested", width)); if ((height < 0) || (height > maxPixelBufferHeight)) - throw rfb::Exception("Invalid PixelBuffer height of %d pixels requested", height); + throw std::out_of_range(rfb::format("Invalid PixelBuffer height of %d pixels requested", height)); if ((stride_ < 0) || (stride_ > maxPixelBufferStride) || (stride_ < width)) - throw rfb::Exception("Invalid PixelBuffer stride of %d pixels requested", stride_); + throw std::invalid_argument(rfb::format("Invalid PixelBuffer stride of %d pixels requested", stride_)); if ((width != 0) && (height != 0) && (data_ == nullptr)) - throw rfb::Exception("PixelBuffer requested without a valid memory area"); + throw std::logic_error(rfb::format("PixelBuffer requested without a valid memory area")); ModifiablePixelBuffer::setSize(width, height); stride = stride_; @@ -375,7 +387,7 @@ void FullFramePixelBuffer::setBuffer(int width, int height, void FullFramePixelBuffer::setSize(int /*w*/, int /*h*/) { // setBuffer() should be used - throw rfb::Exception("Invalid call to FullFramePixelBuffer::setSize()"); + throw std::logic_error("Invalid call to FullFramePixelBuffer::setSize()"); } // -=- Managed pixel buffer class diff --git a/common/rfb/PixelFormat.cxx b/common/rfb/PixelFormat.cxx index b90fc206c1..e312b3c91c 100644 --- a/common/rfb/PixelFormat.cxx +++ b/common/rfb/PixelFormat.cxx @@ -86,7 +86,7 @@ PixelFormat::PixelFormat(int b, int d, bool e, bool t, redShift(rs), greenShift(gs), blueShift(bs) { if (!isSane()) - throw Exception("invalid pixel format"); + throw std::invalid_argument("invalid pixel format"); updateState(); } @@ -180,7 +180,7 @@ void PixelFormat::read(rdr::InStream* is) } if (!isSane()) - throw Exception("invalid pixel format"); + throw protocol_error("invalid pixel format"); updateState(); } diff --git a/common/rfb/RREDecoder.cxx b/common/rfb/RREDecoder.cxx index 41bf501a24..53ddc2da49 100644 --- a/common/rfb/RREDecoder.cxx +++ b/common/rfb/RREDecoder.cxx @@ -107,7 +107,7 @@ void RREDecoder::rreDecode(const Rect& r, rdr::InStream* is, int h = is->readU16(); if (((x+w) > r.width()) || ((y+h) > r.height())) - throw Exception ("RRE decode error"); + throw protocol_error("RRE decode error"); pb->fillRect(pf, Rect(r.tl.x+x, r.tl.y+y, r.tl.x+x+w, r.tl.y+y+h), &pix); } diff --git a/common/rfb/SConnection.cxx b/common/rfb/SConnection.cxx index 905f88a43a..0cde5bc69a 100644 --- a/common/rfb/SConnection.cxx +++ b/common/rfb/SConnection.cxx @@ -95,14 +95,14 @@ bool SConnection::processMsg() case RFBSTATE_INITIALISATION: return processInitMsg(); break; case RFBSTATE_NORMAL: return reader_->readMsg(); break; case RFBSTATE_QUERYING: - throw Exception("SConnection::processMsg: bogus data from client while " - "querying"); + throw std::logic_error("SConnection::processMsg: bogus data from " + "client while querying"); case RFBSTATE_CLOSING: - throw Exception("SConnection::processMsg: called while closing"); + throw std::logic_error("SConnection::processMsg: called while closing"); case RFBSTATE_UNINITIALISED: - throw Exception("SConnection::processMsg: not initialised yet?"); + throw std::logic_error("SConnection::processMsg: not initialised yet?"); default: - throw Exception("SConnection::processMsg: invalid state"); + throw std::logic_error("SConnection::processMsg: invalid state"); } } @@ -123,7 +123,7 @@ bool SConnection::processVersionMsg() if (sscanf(verStr, "RFB %03d.%03d\n", &majorVersion, &minorVersion) != 2) { state_ = RFBSTATE_INVALID; - throw Exception("reading version failed: not an RFB client?"); + throw protocol_error("reading version failed: not an RFB client?"); } client.setVersion(majorVersion, minorVersion); @@ -133,9 +133,10 @@ bool SConnection::processVersionMsg() if (client.majorVersion != 3) { // unknown protocol version - failConnection("Client needs protocol version %d.%d, server has %d.%d", - client.majorVersion, client.minorVersion, - defaultMajorVersion, defaultMinorVersion); + failConnection(format("Client needs protocol version %d.%d, " + "server has %d.%d", + client.majorVersion, client.minorVersion, + defaultMajorVersion, defaultMinorVersion)); } if (client.minorVersion != 3 && client.minorVersion != 7 && client.minorVersion != 8) { @@ -165,8 +166,9 @@ bool SConnection::processVersionMsg() if (*i == secTypeNone || *i == secTypeVncAuth) break; } if (i == secTypes.end()) { - failConnection("No supported security type for %d.%d client", - client.majorVersion, client.minorVersion); + failConnection(format("No supported security type for " + "%d.%d client", + client.majorVersion, client.minorVersion)); } os->writeU32(*i); @@ -213,7 +215,7 @@ void SConnection::processSecurityType(int secType) secTypes = security.GetEnabledSecTypes(); if (std::find(secTypes.begin(), secTypes.end(), secType) == secTypes.end()) - throw Exception("Requested security type not available"); + throw protocol_error("Requested security type not available"); vlog.info("Client requests security type %s(%d)", secTypeName(secType),secType); @@ -221,8 +223,8 @@ void SConnection::processSecurityType(int secType) try { state_ = RFBSTATE_SECURITY; ssecurity = security.GetSSecurity(this, secType); - } catch (rdr::Exception& e) { - failConnection("%s", e.str()); + } catch (std::exception& e) { + failConnection(e.what()); } } @@ -232,12 +234,12 @@ bool SConnection::processSecurityMsg() try { if (!ssecurity->processMsg()) return false; - } catch (AuthFailureException& e) { - vlog.error("AuthFailureException: %s", e.str()); + } catch (auth_error& e) { + vlog.error("Authentication error: %s", e.what()); state_ = RFBSTATE_SECURITY_FAILURE; // Introduce a slight delay of the authentication failure response // to make it difficult to brute force a password - authFailureMsg = e.str(); + authFailureMsg = e.what(); authFailureTimer.start(100); return true; } @@ -291,41 +293,39 @@ void SConnection::handleAuthFailureTimeout(Timer* /*t*/) authFailureMsg.size()); } os->flush(); - } catch (rdr::Exception& e) { - close(e.str()); + } catch (std::exception& e) { + close(e.what()); return; } close(authFailureMsg.c_str()); } -void SConnection::failConnection(const char* format, ...) +void SConnection::failConnection(const char* message) { - va_list ap; - char str[256]; - - va_start(ap, format); - (void) vsnprintf(str, sizeof(str), format, ap); - va_end(ap); - - vlog.info("Connection failed: %s", str); + vlog.info("Connection failed: %s", message); if (state_ == RFBSTATE_PROTOCOL_VERSION) { if (client.majorVersion == 3 && client.minorVersion == 3) { os->writeU32(0); - os->writeU32(strlen(str)); - os->writeBytes((const uint8_t*)str, strlen(str)); + os->writeU32(strlen(message)); + os->writeBytes((const uint8_t*)message, strlen(message)); os->flush(); } else { os->writeU8(0); - os->writeU32(strlen(str)); - os->writeBytes((const uint8_t*)str, strlen(str)); + os->writeU32(strlen(message)); + os->writeBytes((const uint8_t*)message, strlen(message)); os->flush(); } } state_ = RFBSTATE_INVALID; - throw Exception("%s", str); + throw protocol_error(message); +} + +void SConnection::failConnection(const std::string& message) +{ + failConnection(message.c_str()); } void SConnection::setAccessRights(AccessRights ar) @@ -336,7 +336,7 @@ void SConnection::setAccessRights(AccessRights ar) bool SConnection::accessCheck(AccessRights ar) const { if (state_ < RFBSTATE_QUERYING) - throw Exception("SConnection::accessCheck: invalid state"); + throw std::logic_error("SConnection::accessCheck: invalid state"); return (accessRights & ar) == ar; } @@ -449,7 +449,7 @@ void SConnection::queryConnection(const char* /*userName*/) void SConnection::approveConnection(bool accept, const char* reason) { if (state_ != RFBSTATE_QUERYING) - throw Exception("SConnection::approveConnection: invalid state"); + throw std::logic_error("SConnection::approveConnection: invalid state"); if (!client.beforeVersion(3,8) || ssecurity->getType() != secTypeNone) { if (accept) { @@ -474,9 +474,9 @@ void SConnection::approveConnection(bool accept, const char* reason) } else { state_ = RFBSTATE_INVALID; if (reason) - throw AuthFailureException(reason); + throw auth_error(reason); else - throw AuthFailureException("Connection rejected"); + throw auth_error("Connection rejected"); } } diff --git a/common/rfb/SConnection.h b/common/rfb/SConnection.h index 0a11f67b6c..ccffa74fc1 100644 --- a/common/rfb/SConnection.h +++ b/common/rfb/SConnection.h @@ -68,12 +68,13 @@ namespace rfb { // data is available. bool processMsg(); - // approveConnection() is called to either accept or reject the connection. - // If accept is false, the reason string gives the reason for the - // rejection. It can either be called directly from queryConnection() or - // later, after queryConnection() has returned. It can only be called when - // in state RFBSTATE_QUERYING. On rejection, an AuthFailureException is - // thrown, so this must be handled appropriately by the caller. + // approveConnection() is called to either accept or reject the + // connection. If accept is false, the reason string gives the + // reason for the rejection. It can either be called directly from + // queryConnection() or later, after queryConnection() has returned. + // It can only be called when in state RFBSTATE_QUERYING. On + // rejection, an auth_error is thrown, so this must be handled + // appropriately by the caller. void approveConnection(bool accept, const char* reason=nullptr); @@ -219,8 +220,8 @@ namespace rfb { // failConnection() prints a message to the log, sends a connection // failed message to the client (if possible) and throws an // Exception. - void failConnection(const char* format, ...) - __attribute__((__format__ (__printf__, 2, 3))); + void failConnection(const char* message); + void failConnection(const std::string& message); void setState(stateEnum s) { state_ = s; } diff --git a/common/rfb/SMsgReader.cxx b/common/rfb/SMsgReader.cxx index 9ddea53df6..fcc0a63c81 100644 --- a/common/rfb/SMsgReader.cxx +++ b/common/rfb/SMsgReader.cxx @@ -107,7 +107,7 @@ bool SMsgReader::readMsg() break; default: vlog.error("unknown message type %d", currentMsgType); - throw Exception("unknown message type"); + throw protocol_error("unknown message type"); } if (ret) @@ -334,7 +334,7 @@ bool SMsgReader::readExtendedClipboard(int32_t len) return false; if (len < 4) - throw Exception("Invalid extended clipboard message"); + throw protocol_error("Invalid extended clipboard message"); if (len > maxCutText) { vlog.error("Extended clipboard message too long (%d bytes) - ignoring", len); is->skip(len); @@ -356,7 +356,7 @@ bool SMsgReader::readExtendedClipboard(int32_t len) } if (len < (int32_t)(4 + 4*num)) - throw Exception("Invalid extended clipboard message"); + throw protocol_error("Invalid extended clipboard message"); num = 0; for (i = 0;i < 16;i++) { @@ -381,7 +381,7 @@ bool SMsgReader::readExtendedClipboard(int32_t len) continue; if (!zis.hasData(4)) - throw Exception("Extended clipboard decode error"); + throw protocol_error("Extended clipboard decode error"); lengths[num] = zis.readU32(); @@ -394,7 +394,7 @@ bool SMsgReader::readExtendedClipboard(int32_t len) size_t chunk; if (!zis.hasData(1)) - throw Exception("Extended clipboard decode error"); + throw protocol_error("Extended clipboard decode error"); chunk = zis.avail(); if (chunk > lengths[num]) @@ -410,7 +410,7 @@ bool SMsgReader::readExtendedClipboard(int32_t len) } if (!zis.hasData(lengths[num])) - throw Exception("Extended clipboard decode error"); + throw protocol_error("Extended clipboard decode error"); buffers[num] = new uint8_t[lengths[num]]; zis.readBytes(buffers[num], lengths[num]); @@ -440,7 +440,7 @@ bool SMsgReader::readExtendedClipboard(int32_t len) handler->handleClipboardNotify(flags); break; default: - throw Exception("Invalid extended clipboard action"); + throw protocol_error("Invalid extended clipboard action"); } } @@ -464,7 +464,7 @@ bool SMsgReader::readQEMUMessage() ret = readQEMUKeyEvent(); break; default: - throw Exception("unknown QEMU submessage type %d", subType); + throw protocol_error(format("unknown QEMU submessage type %d", subType)); } if (!ret) { diff --git a/common/rfb/SMsgWriter.cxx b/common/rfb/SMsgWriter.cxx index 0c03b51dc1..f525d25a24 100644 --- a/common/rfb/SMsgWriter.cxx +++ b/common/rfb/SMsgWriter.cxx @@ -31,7 +31,6 @@ #include #include #include -#include #include #include #include @@ -94,7 +93,7 @@ void SMsgWriter::writeBell() void SMsgWriter::writeServerCutText(const char* str) { if (strchr(str, '\r') != nullptr) - throw Exception("Invalid carriage return in clipboard data"); + throw std::invalid_argument("Invalid carriage return in clipboard data"); std::string latin1(utf8ToLatin1(str)); @@ -111,7 +110,7 @@ void SMsgWriter::writeClipboardCaps(uint32_t caps, size_t i, count; if (!client->supportsEncoding(pseudoEncodingExtendedClipboard)) - throw Exception("Client does not support extended clipboard"); + throw std::logic_error("Client does not support extended clipboard"); count = 0; for (i = 0;i < 16;i++) { @@ -137,9 +136,9 @@ void SMsgWriter::writeClipboardCaps(uint32_t caps, void SMsgWriter::writeClipboardRequest(uint32_t flags) { if (!client->supportsEncoding(pseudoEncodingExtendedClipboard)) - throw Exception("Client does not support extended clipboard"); + throw std::logic_error("Client does not support extended clipboard"); if (!(client->clipboardFlags() & clipboardRequest)) - throw Exception("Client does not support clipboard \"request\" action"); + throw std::logic_error("Client does not support clipboard \"request\" action"); startMsg(msgTypeServerCutText); os->pad(3); @@ -151,9 +150,9 @@ void SMsgWriter::writeClipboardRequest(uint32_t flags) void SMsgWriter::writeClipboardPeek(uint32_t flags) { if (!client->supportsEncoding(pseudoEncodingExtendedClipboard)) - throw Exception("Client does not support extended clipboard"); + throw std::logic_error("Client does not support extended clipboard"); if (!(client->clipboardFlags() & clipboardPeek)) - throw Exception("Client does not support clipboard \"peek\" action"); + throw std::logic_error("Client does not support clipboard \"peek\" action"); startMsg(msgTypeServerCutText); os->pad(3); @@ -165,9 +164,9 @@ void SMsgWriter::writeClipboardPeek(uint32_t flags) void SMsgWriter::writeClipboardNotify(uint32_t flags) { if (!client->supportsEncoding(pseudoEncodingExtendedClipboard)) - throw Exception("Client does not support extended clipboard"); + throw std::logic_error("Client does not support extended clipboard"); if (!(client->clipboardFlags() & clipboardNotify)) - throw Exception("Client does not support clipboard \"notify\" action"); + throw std::logic_error("Client does not support clipboard \"notify\" action"); startMsg(msgTypeServerCutText); os->pad(3); @@ -186,9 +185,9 @@ void SMsgWriter::writeClipboardProvide(uint32_t flags, int i, count; if (!client->supportsEncoding(pseudoEncodingExtendedClipboard)) - throw Exception("Client does not support extended clipboard"); + throw std::logic_error("Client does not support extended clipboard"); if (!(client->clipboardFlags() & clipboardProvide)) - throw Exception("Client does not support clipboard \"provide\" action"); + throw std::logic_error("Client does not support clipboard \"provide\" action"); zos.setUnderlying(&mos); @@ -215,11 +214,11 @@ void SMsgWriter::writeFence(uint32_t flags, unsigned len, const uint8_t data[]) { if (!client->supportsEncoding(pseudoEncodingFence)) - throw Exception("Client does not support fences"); + throw std::logic_error("Client does not support fences"); if (len > 64) - throw Exception("Too large fence payload"); + throw std::out_of_range("Too large fence payload"); if ((flags & ~fenceFlagsSupported) != 0) - throw Exception("Unknown fence flags"); + throw std::invalid_argument("Unknown fence flags"); startMsg(msgTypeServerFence); os->pad(3); @@ -237,7 +236,7 @@ void SMsgWriter::writeFence(uint32_t flags, unsigned len, void SMsgWriter::writeEndOfContinuousUpdates() { if (!client->supportsEncoding(pseudoEncodingContinuousUpdates)) - throw Exception("Client does not support continuous updates"); + throw std::logic_error("Client does not support continuous updates"); startMsg(msgTypeEndOfContinuousUpdates); endMsg(); @@ -249,7 +248,7 @@ void SMsgWriter::writeDesktopSize(uint16_t reason, uint16_t result) if (!client->supportsEncoding(pseudoEncodingDesktopSize) && !client->supportsEncoding(pseudoEncodingExtendedDesktopSize)) - throw Exception("Client does not support desktop size changes"); + throw std::logic_error("Client does not support desktop size changes"); msg.reason = reason; msg.result = result; @@ -260,7 +259,7 @@ void SMsgWriter::writeDesktopSize(uint16_t reason, uint16_t result) void SMsgWriter::writeSetDesktopName() { if (!client->supportsEncoding(pseudoEncodingDesktopName)) - throw Exception("Client does not support desktop name changes"); + throw std::logic_error("Client does not support desktop name changes"); needSetDesktopName = true; } @@ -271,7 +270,7 @@ void SMsgWriter::writeCursor() !client->supportsEncoding(pseudoEncodingXCursor) && !client->supportsEncoding(pseudoEncodingCursorWithAlpha) && !client->supportsEncoding(pseudoEncodingVMwareCursor)) - throw Exception("Client does not support local cursor"); + throw std::logic_error("Client does not support local cursor"); needCursor = true; } @@ -279,7 +278,7 @@ void SMsgWriter::writeCursor() void SMsgWriter::writeCursorPos() { if (!client->supportsEncoding(pseudoEncodingVMwareCursorPosition)) - throw Exception("Client does not support cursor position"); + throw std::logic_error("Client does not support cursor position"); needCursorPos = true; } @@ -288,9 +287,9 @@ void SMsgWriter::writeLEDState() { if (!client->supportsEncoding(pseudoEncodingLEDState) && !client->supportsEncoding(pseudoEncodingVMwareLEDState)) - throw Exception("Client does not support LED state"); + throw std::logic_error("Client does not support LED state"); if (client->ledState() == ledUnknown) - throw Exception("Server has not specified LED state"); + throw std::logic_error("Server has not specified LED state"); needLEDState = true; } @@ -298,7 +297,7 @@ void SMsgWriter::writeLEDState() void SMsgWriter::writeQEMUKeyEvent() { if (!client->supportsEncoding(pseudoEncodingQEMUKeyEvent)) - throw Exception("Client does not support QEMU key events"); + throw std::logic_error("Client does not support QEMU key events"); needQEMUKeyEvent = true; } @@ -379,8 +378,8 @@ void SMsgWriter::writeFramebufferUpdateStart(int nRects) void SMsgWriter::writeFramebufferUpdateEnd() { if (nRectsInUpdate != nRectsInHeader && nRectsInHeader) - throw Exception("SMsgWriter::writeFramebufferUpdateEnd: " - "nRects out of sync"); + throw std::logic_error("SMsgWriter::writeFramebufferUpdateEnd: " + "nRects out of sync"); if (nRectsInHeader == 0) { // Send last rect. marker @@ -405,7 +404,7 @@ void SMsgWriter::writeCopyRect(const Rect& r, int srcX, int srcY) void SMsgWriter::startRect(const Rect& r, int encoding) { if (++nRectsInUpdate > nRectsInHeader && nRectsInHeader) - throw Exception("SMsgWriter::startRect: nRects out of sync"); + throw std::logic_error("SMsgWriter::startRect: nRects out of sync"); os->writeS16(r.tl.x); os->writeS16(r.tl.y); @@ -470,7 +469,7 @@ void SMsgWriter::writePseudoRects() cursor.hotspot().x, cursor.hotspot().y, bitmap.data(), mask.data()); } else { - throw Exception("Client does not support local cursor"); + throw std::logic_error("Client does not support local cursor"); } needCursor = false; @@ -482,7 +481,7 @@ void SMsgWriter::writePseudoRects() if (client->supportsEncoding(pseudoEncodingVMwareCursorPosition)) { writeSetVMwareCursorPositionRect(cursorPos.x, cursorPos.y); } else { - throw Exception("Client does not support cursor position"); + throw std::logic_error("Client does not support cursor position"); } needCursorPos = false; @@ -519,7 +518,7 @@ void SMsgWriter::writeNoDataRects() // more after this writeSetDesktopSizeRect(client->width(), client->height()); } else { - throw Exception("Client does not support desktop size changes"); + throw std::logic_error("Client does not support desktop size changes"); } extendedDesktopSizeMsgs.clear(); @@ -529,9 +528,9 @@ void SMsgWriter::writeNoDataRects() void SMsgWriter::writeSetDesktopSizeRect(int width, int height) { if (!client->supportsEncoding(pseudoEncodingDesktopSize)) - throw Exception("Client does not support desktop resize"); + throw std::logic_error("Client does not support desktop resize"); if (++nRectsInUpdate > nRectsInHeader && nRectsInHeader) - throw Exception("SMsgWriter::writeSetDesktopSizeRect: nRects out of sync"); + throw std::logic_error("SMsgWriter::writeSetDesktopSizeRect: nRects out of sync"); os->writeS16(0); os->writeS16(0); @@ -549,9 +548,9 @@ void SMsgWriter::writeExtendedDesktopSizeRect(uint16_t reason, ScreenSet::const_iterator si; if (!client->supportsEncoding(pseudoEncodingExtendedDesktopSize)) - throw Exception("Client does not support extended desktop resize"); + throw std::logic_error("Client does not support extended desktop resize"); if (++nRectsInUpdate > nRectsInHeader && nRectsInHeader) - throw Exception("SMsgWriter::writeExtendedDesktopSizeRect: nRects out of sync"); + throw std::logic_error("SMsgWriter::writeExtendedDesktopSizeRect: nRects out of sync"); os->writeU16(reason); os->writeU16(result); @@ -575,9 +574,9 @@ void SMsgWriter::writeExtendedDesktopSizeRect(uint16_t reason, void SMsgWriter::writeSetDesktopNameRect(const char *name) { if (!client->supportsEncoding(pseudoEncodingDesktopName)) - throw Exception("Client does not support desktop rename"); + throw std::logic_error("Client does not support desktop rename"); if (++nRectsInUpdate > nRectsInHeader && nRectsInHeader) - throw Exception("SMsgWriter::writeSetDesktopNameRect: nRects out of sync"); + throw std::logic_error("SMsgWriter::writeSetDesktopNameRect: nRects out of sync"); os->writeS16(0); os->writeS16(0); @@ -594,9 +593,9 @@ void SMsgWriter::writeSetCursorRect(int width, int height, const uint8_t* mask) { if (!client->supportsEncoding(pseudoEncodingCursor)) - throw Exception("Client does not support local cursors"); + throw std::logic_error("Client does not support local cursors"); if (++nRectsInUpdate > nRectsInHeader && nRectsInHeader) - throw Exception("SMsgWriter::writeSetCursorRect: nRects out of sync"); + throw std::logic_error("SMsgWriter::writeSetCursorRect: nRects out of sync"); os->writeS16(hotspotX); os->writeS16(hotspotY); @@ -613,9 +612,9 @@ void SMsgWriter::writeSetXCursorRect(int width, int height, const uint8_t* mask) { if (!client->supportsEncoding(pseudoEncodingXCursor)) - throw Exception("Client does not support local cursors"); + throw std::logic_error("Client does not support local cursors"); if (++nRectsInUpdate > nRectsInHeader && nRectsInHeader) - throw Exception("SMsgWriter::writeSetXCursorRect: nRects out of sync"); + throw std::logic_error("SMsgWriter::writeSetXCursorRect: nRects out of sync"); os->writeS16(hotspotX); os->writeS16(hotspotY); @@ -639,9 +638,9 @@ void SMsgWriter::writeSetCursorWithAlphaRect(int width, int height, const uint8_t* data) { if (!client->supportsEncoding(pseudoEncodingCursorWithAlpha)) - throw Exception("Client does not support local cursors"); + throw std::logic_error("Client does not support local cursors"); if (++nRectsInUpdate > nRectsInHeader && nRectsInHeader) - throw Exception("SMsgWriter::writeSetCursorWithAlphaRect: nRects out of sync"); + throw std::logic_error("SMsgWriter::writeSetCursorWithAlphaRect: nRects out of sync"); os->writeS16(hotspotX); os->writeS16(hotspotY); @@ -667,9 +666,9 @@ void SMsgWriter::writeSetVMwareCursorRect(int width, int height, const uint8_t* data) { if (!client->supportsEncoding(pseudoEncodingVMwareCursor)) - throw Exception("Client does not support local cursors"); + throw std::logic_error("Client does not support local cursors"); if (++nRectsInUpdate > nRectsInHeader && nRectsInHeader) - throw Exception("SMsgWriter::writeSetVMwareCursorRect: nRects out of sync"); + throw std::logic_error("SMsgWriter::writeSetVMwareCursorRect: nRects out of sync"); os->writeS16(hotspotX); os->writeS16(hotspotY); @@ -687,9 +686,9 @@ void SMsgWriter::writeSetVMwareCursorRect(int width, int height, void SMsgWriter::writeSetVMwareCursorPositionRect(int hotspotX, int hotspotY) { if (!client->supportsEncoding(pseudoEncodingVMwareCursorPosition)) - throw Exception("Client does not support cursor position"); + throw std::logic_error("Client does not support cursor position"); if (++nRectsInUpdate > nRectsInHeader && nRectsInHeader) - throw Exception("SMsgWriter::writeSetVMwareCursorRect: nRects out of sync"); + throw std::logic_error("SMsgWriter::writeSetVMwareCursorRect: nRects out of sync"); os->writeS16(hotspotX); os->writeS16(hotspotY); @@ -702,11 +701,11 @@ void SMsgWriter::writeLEDStateRect(uint8_t state) { if (!client->supportsEncoding(pseudoEncodingLEDState) && !client->supportsEncoding(pseudoEncodingVMwareLEDState)) - throw Exception("Client does not support LED state updates"); + throw std::logic_error("Client does not support LED state updates"); if (client->ledState() == ledUnknown) - throw Exception("Server does not support LED state updates"); + throw std::logic_error("Server does not support LED state updates"); if (++nRectsInUpdate > nRectsInHeader && nRectsInHeader) - throw Exception("SMsgWriter::writeLEDStateRect: nRects out of sync"); + throw std::logic_error("SMsgWriter::writeLEDStateRect: nRects out of sync"); os->writeS16(0); os->writeS16(0); @@ -724,9 +723,9 @@ void SMsgWriter::writeLEDStateRect(uint8_t state) void SMsgWriter::writeQEMUKeyEventRect() { if (!client->supportsEncoding(pseudoEncodingQEMUKeyEvent)) - throw Exception("Client does not support QEMU extended key events"); + throw std::logic_error("Client does not support QEMU extended key events"); if (++nRectsInUpdate > nRectsInHeader && nRectsInHeader) - throw Exception("SMsgWriter::writeQEMUKeyEventRect: nRects out of sync"); + throw std::logic_error("SMsgWriter::writeQEMUKeyEventRect: nRects out of sync"); os->writeS16(0); os->writeS16(0); diff --git a/common/rfb/SSecurity.h b/common/rfb/SSecurity.h index 8e296c5ac9..0911ecd83b 100644 --- a/common/rfb/SSecurity.h +++ b/common/rfb/SSecurity.h @@ -20,14 +20,15 @@ // derived class for a particular security type overrides the processMsg() // method. -// processMsg() is called first when the security type has been decided on, and -// will keep being called whenever there is data to read from the client. It -// should return false when it needs more data, or true when the connection has -// been successfully authenticated. In the event of authentication failure an -// AuthFailureException should be thrown - this will result in a "failed" -// security result being sent to the client with the str() from the exception -// being sent as the reason. Any other type of failure should be indicated by -// some other kind of exception which will cause the connection to be aborted. +// processMsg() is called first when the security type has been decided +// on, and will keep being called whenever there is data to read from +// the client. It should return false when it needs more data, or true +// when the connection has been successfully authenticated. In the +// event of authentication failure an auth_error should be thrown - this +// will result in a "failed" security result being sent to the client +// with the str() from the exception being sent as the reason. Any +// other type of failure should be indicated by some other kind of +// exception which will cause the connection to be aborted. // // processMsg() must never block (or at least must never block until the client // has been authenticated) - this is to prevent denial of service attacks. diff --git a/common/rfb/SSecurityPlain.cxx b/common/rfb/SSecurityPlain.cxx index e009de39e1..e62e6d6086 100644 --- a/common/rfb/SSecurityPlain.cxx +++ b/common/rfb/SSecurityPlain.cxx @@ -87,7 +87,7 @@ bool SSecurityPlain::processMsg() char password[1024]; if (!valid) - throw Exception("No password validator configured"); + throw std::logic_error("No password validator configured"); if (state == 0) { if (!is->hasData(8)) @@ -95,11 +95,11 @@ bool SSecurityPlain::processMsg() ulen = is->readU32(); if (ulen >= sizeof(username)) - throw AuthFailureException("Too long username"); + throw auth_error("Too long username"); plen = is->readU32(); if (plen >= sizeof(password)) - throw AuthFailureException("Too long password"); + throw auth_error("Too long password"); state = 1; } @@ -114,7 +114,7 @@ bool SSecurityPlain::processMsg() username[ulen] = 0; plen = 0; if (!valid->validate(sc, username, password)) - throw AuthFailureException("Authentication failed"); + throw auth_error("Authentication failed"); } return true; diff --git a/common/rfb/SSecurityRSAAES.cxx b/common/rfb/SSecurityRSAAES.cxx index 6dd700cef4..2f26de2680 100644 --- a/common/rfb/SSecurityRSAAES.cxx +++ b/common/rfb/SSecurityRSAAES.cxx @@ -36,12 +36,15 @@ #include #include #include + +#include +#include +#include + #include #include #include #include -#include -#include #if !defined(WIN32) && !defined(__APPLE__) #include #endif @@ -156,18 +159,18 @@ void SSecurityRSAAES::loadPrivateKey() { FILE* file = fopen(keyFile, "rb"); if (!file) - throw rdr::PosixException("failed to open key file", errno); + throw rdr::posix_error("failed to open key file", errno); fseek(file, 0, SEEK_END); size_t size = ftell(file); if (size == 0 || size > MaxKeyFileSize) { fclose(file); - throw Exception("size of key file is zero or too big"); + throw std::runtime_error("size of key file is zero or too big"); } fseek(file, 0, SEEK_SET); std::vector data(size); if (fread(data.data(), 1, data.size(), file) != size) { fclose(file); - throw rdr::PosixException("failed to read key", errno); + throw rdr::posix_error("failed to read key", errno); } fclose(file); @@ -184,7 +187,7 @@ void SSecurityRSAAES::loadPrivateKey() loadPKCS8Key(der.data(), der.size()); return; } - throw Exception("failed to import key"); + throw std::runtime_error("failed to import key"); } void SSecurityRSAAES::loadPKCS1Key(const uint8_t* data, size_t size) @@ -195,7 +198,7 @@ void SSecurityRSAAES::loadPKCS1Key(const uint8_t* data, size_t size) if (!rsa_keypair_from_der(&pub, &serverKey, 0, size, data)) { rsa_private_key_clear(&serverKey); rsa_public_key_clear(&pub); - throw Exception("failed to import key"); + throw std::runtime_error("failed to import key"); } serverKeyLength = serverKey.size * 8; serverKeyN = new uint8_t[serverKey.size]; @@ -235,7 +238,7 @@ void SSecurityRSAAES::loadPKCS8Key(const uint8_t* data, size_t size) loadPKCS1Key(i.data, i.length); return; failed: - throw Exception("failed to import key"); + throw std::runtime_error("failed to import key"); } bool SSecurityRSAAES::processMsg() @@ -296,9 +299,9 @@ bool SSecurityRSAAES::readPublicKey() is->setRestorePoint(); clientKeyLength = is->readU32(); if (clientKeyLength < MinKeyLength) - throw Exception("client key is too short"); + throw protocol_error("client key is too short"); if (clientKeyLength > MaxKeyLength) - throw Exception("client key is too long"); + throw protocol_error("client key is too long"); size_t size = (clientKeyLength + 7) / 8; if (!is->hasDataOrRestore(size * 2)) return false; @@ -311,7 +314,7 @@ bool SSecurityRSAAES::readPublicKey() nettle_mpz_set_str_256_u(clientKey.n, size, clientKeyN); nettle_mpz_set_str_256_u(clientKey.e, size, clientKeyE); if (!rsa_public_key_prepare(&clientKey)) - throw Exception("client key is invalid"); + throw protocol_error("client key is invalid"); return true; } @@ -319,7 +322,7 @@ static void random_func(void* ctx, size_t length, uint8_t* dst) { rdr::RandomStream* rs = (rdr::RandomStream*)ctx; if (!rs->hasData(length)) - throw Exception("failed to encrypt random"); + throw std::runtime_error("failed to encrypt random"); rs->readBytes(dst, length); } @@ -327,7 +330,7 @@ void SSecurityRSAAES::writeRandom() { rdr::OutStream* os = sc->getOutStream(); if (!rs.hasData(keySize / 8)) - throw Exception("failed to generate random"); + throw std::runtime_error("failed to generate random"); rs.readBytes(serverRandom, keySize / 8); mpz_t x; mpz_init(x); @@ -341,7 +344,7 @@ void SSecurityRSAAES::writeRandom() } if (!res) { mpz_clear(x); - throw Exception("failed to encrypt random"); + throw std::runtime_error("failed to encrypt random"); } uint8_t* buffer = new uint8_t[clientKey.size]; nettle_mpz_get_str_256(clientKey.size, buffer, x); @@ -360,7 +363,7 @@ bool SSecurityRSAAES::readRandom() is->setRestorePoint(); size_t size = is->readU16(); if (size != serverKey.size) - throw Exception("server key length doesn't match"); + throw protocol_error("server key length doesn't match"); if (!is->hasDataOrRestore(size)) return false; is->clearRestorePoint(); @@ -373,7 +376,7 @@ bool SSecurityRSAAES::readRandom() if (!rsa_decrypt(&serverKey, &randomSize, clientRandom, x) || randomSize != (size_t)keySize / 8) { mpz_clear(x); - throw Exception("failed to decrypt client random"); + throw protocol_error("failed to decrypt client random"); } mpz_clear(x); return true; @@ -502,7 +505,7 @@ bool SSecurityRSAAES::readHash() sha256_digest(&ctx, hashSize, realHash); } if (memcmp(hash, realHash, hashSize) != 0) - throw Exception("hash doesn't match"); + throw protocol_error("hash doesn't match"); return true; } @@ -562,11 +565,11 @@ void SSecurityRSAAES::verifyUserPass() #endif if (!valid->validate(sc, username, password)) { delete valid; - throw AuthFailureException("Authentication failed"); + throw auth_error("Authentication failed"); } delete valid; #else - throw Exception("No password validator configured"); + throw std::logic_error("No password validator configured"); #endif } @@ -577,7 +580,7 @@ void SSecurityRSAAES::verifyPass() pg->getVncAuthPasswd(&passwd, &passwdReadOnly); if (passwd.empty()) - throw Exception("No password configured"); + throw std::runtime_error("No password configured"); if (password == passwd) { accessRights = AccessDefault; @@ -589,7 +592,7 @@ void SSecurityRSAAES::verifyPass() return; } - throw AuthFailureException("Authentication failed"); + throw auth_error("Authentication failed"); } const char* SSecurityRSAAES::getUserName() const diff --git a/common/rfb/SSecurityTLS.cxx b/common/rfb/SSecurityTLS.cxx index 465126eb7e..4b036e273f 100644 --- a/common/rfb/SSecurityTLS.cxx +++ b/common/rfb/SSecurityTLS.cxx @@ -80,7 +80,7 @@ SSecurityTLS::SSecurityTLS(SConnection* sc_, bool _anon) ret = gnutls_global_init(); if (ret != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_global_init()", ret); + throw rdr::tls_error("gnutls_global_init()", ret); } void SSecurityTLS::shutdown() @@ -152,11 +152,11 @@ bool SSecurityTLS::processMsg() err = gnutls_init(&session, GNUTLS_SERVER); if (err != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_init()", err); + throw rdr::tls_error("gnutls_init()", err); err = gnutls_set_default_priority(session); if (err != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_set_default_priority()", err); + throw rdr::tls_error("gnutls_set_default_priority()", err); try { setParams(); @@ -186,7 +186,7 @@ bool SSecurityTLS::processMsg() } vlog.error("TLS Handshake failed: %s", gnutls_strerror (err)); shutdown(); - throw rdr::TLSException("TLS Handshake failed", err); + throw rdr::tls_error("TLS Handshake failed", err); } vlog.debug("TLS handshake completed with %s", @@ -208,10 +208,8 @@ void SSecurityTLS::setParams() char *prio; const char *err; - prio = (char*)malloc(strlen(Security::GnuTLSPriority) + - strlen(kx_anon_priority) + 1); - if (prio == nullptr) - throw Exception("Not enough memory for GnuTLS priority string"); + prio = new char[strlen(Security::GnuTLSPriority) + + strlen(kx_anon_priority) + 1]; strcpy(prio, Security::GnuTLSPriority); if (anon) @@ -219,12 +217,12 @@ void SSecurityTLS::setParams() ret = gnutls_priority_set_direct(session, prio, &err); - free(prio); + delete [] prio; if (ret != GNUTLS_E_SUCCESS) { if (ret == GNUTLS_E_INVALID_REQUEST) vlog.error("GnuTLS priority syntax error at: %s", err); - throw rdr::TLSException("gnutls_set_priority_direct()", ret); + throw rdr::tls_error("gnutls_set_priority_direct()", ret); } } else if (anon) { const char *err; @@ -236,7 +234,7 @@ void SSecurityTLS::setParams() if (ret != GNUTLS_E_SUCCESS) { if (ret == GNUTLS_E_INVALID_REQUEST) vlog.error("GnuTLS priority syntax error at: %s", err); - throw rdr::TLSException("gnutls_set_default_priority_append()", ret); + throw rdr::tls_error("gnutls_set_default_priority_append()", ret); } #else // We don't know what the system default priority is, so we guess @@ -244,22 +242,20 @@ void SSecurityTLS::setParams() static const char gnutls_default_priority[] = "NORMAL"; char *prio; - prio = (char*)malloc(strlen(gnutls_default_priority) + - strlen(kx_anon_priority) + 1); - if (prio == nullptr) - throw Exception("Not enough memory for GnuTLS priority string"); + prio = new char[strlen(gnutls_default_priority) + + strlen(kx_anon_priority) + 1]; strcpy(prio, gnutls_default_priority); strcat(prio, kx_anon_priority); ret = gnutls_priority_set_direct(session, prio, &err); - free(prio); + delete [] prio; if (ret != GNUTLS_E_SUCCESS) { if (ret == GNUTLS_E_INVALID_REQUEST) vlog.error("GnuTLS priority syntax error at: %s", err); - throw rdr::TLSException("gnutls_set_priority_direct()", ret); + throw rdr::tls_error("gnutls_set_priority_direct()", ret); } #endif } @@ -267,18 +263,18 @@ void SSecurityTLS::setParams() #if defined (SSECURITYTLS__USE_DEPRECATED_DH) ret = gnutls_dh_params_init(&dh_params); if (ret != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_dh_params_init()", ret); + throw rdr::tls_error("gnutls_dh_params_init()", ret); ret = gnutls_dh_params_import_pkcs3(dh_params, &ffdhe_pkcs3_param, GNUTLS_X509_FMT_PEM); if (ret != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_dh_params_import_pkcs3()", ret); + throw rdr::tls_error("gnutls_dh_params_import_pkcs3()", ret); #endif if (anon) { ret = gnutls_anon_allocate_server_credentials(&anon_cred); if (ret != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_anon_allocate_server_credentials()", ret); + throw rdr::tls_error("gnutls_anon_allocate_server_credentials()", ret); #if defined (SSECURITYTLS__USE_DEPRECATED_DH) gnutls_anon_set_server_dh_params(anon_cred, dh_params); @@ -286,14 +282,14 @@ void SSecurityTLS::setParams() ret = gnutls_credentials_set(session, GNUTLS_CRD_ANON, anon_cred); if (ret != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_credentials_set()", ret); + throw rdr::tls_error("gnutls_credentials_set()", ret); vlog.debug("Anonymous session has been set"); } else { ret = gnutls_certificate_allocate_credentials(&cert_cred); if (ret != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_certificate_allocate_credentials()", ret); + throw rdr::tls_error("gnutls_certificate_allocate_credentials()", ret); #if defined (SSECURITYTLS__USE_DEPRECATED_DH) gnutls_certificate_set_dh_params(cert_cred, dh_params); @@ -303,11 +299,11 @@ void SSecurityTLS::setParams() X509_KeyFile, GNUTLS_X509_FMT_PEM); if (ret != GNUTLS_E_SUCCESS) - throw rdr::TLSException("Failed to load certificate and key", ret); + throw rdr::tls_error("Failed to load certificate and key", ret); ret = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, cert_cred); if (ret != GNUTLS_E_SUCCESS) - throw rdr::TLSException("gnutls_credentials_set()", ret); + throw rdr::tls_error("gnutls_credentials_set()", ret); vlog.debug("X509 session has been set"); diff --git a/common/rfb/SSecurityVeNCrypt.cxx b/common/rfb/SSecurityVeNCrypt.cxx index 164ea927b9..4617fddba9 100644 --- a/common/rfb/SSecurityVeNCrypt.cxx +++ b/common/rfb/SSecurityVeNCrypt.cxx @@ -99,8 +99,8 @@ bool SSecurityVeNCrypt::processMsg() case 0x0001: /* 0.1 Legacy VeNCrypt, not supported */ os->writeU8(0xFF); /* This is not OK */ os->flush(); - throw Exception("The client cannot support the server's " - "VeNCrypt version"); + throw protocol_error("The client cannot support the server's " + "VeNCrypt version"); case 0x0002: /* 0.2 */ os->writeU8(0); /* OK */ @@ -109,7 +109,7 @@ bool SSecurityVeNCrypt::processMsg() default: os->writeU8(0xFF); /* Not OK */ os->flush(); - throw Exception("The client returned an unsupported VeNCrypt version"); + throw protocol_error("The client returned an unsupported VeNCrypt version"); } } @@ -138,7 +138,7 @@ bool SSecurityVeNCrypt::processMsg() os->flush(); haveSentTypes = true; } else - throw Exception("There are no VeNCrypt sub-types to send to the client"); + throw protocol_error("There are no VeNCrypt sub-types to send to the client"); } /* get type back from client (must be one of the ones we sent) */ @@ -163,7 +163,7 @@ bool SSecurityVeNCrypt::processMsg() /* Set up the stack according to the chosen type */ if (chosenType == secTypeInvalid || chosenType == secTypeVeNCrypt) - throw Exception("No valid VeNCrypt sub-type"); + throw protocol_error("No valid VeNCrypt sub-type"); ssecurity = security->GetSSecurity(sc, chosenType); } diff --git a/common/rfb/SSecurityVncAuth.cxx b/common/rfb/SSecurityVncAuth.cxx index 272c7ca1ec..c4899aa907 100644 --- a/common/rfb/SSecurityVncAuth.cxx +++ b/common/rfb/SSecurityVncAuth.cxx @@ -83,7 +83,7 @@ bool SSecurityVncAuth::processMsg() if (!sentChallenge) { rdr::RandomStream rs; if (!rs.hasData(vncAuthChallengeSize)) - throw Exception("Could not generate random data for VNC auth challenge"); + throw std::runtime_error("Could not generate random data for VNC auth challenge"); rs.readBytes(challenge, vncAuthChallengeSize); os->writeBytes(challenge, vncAuthChallengeSize); os->flush(); @@ -100,7 +100,7 @@ bool SSecurityVncAuth::processMsg() pg->getVncAuthPasswd(&passwd, &passwdReadOnly); if (passwd.empty()) - throw Exception("No password configured"); + throw std::runtime_error("No password configured"); if (verifyResponse(passwd.c_str())) { accessRights = AccessDefault; @@ -113,7 +113,7 @@ bool SSecurityVncAuth::processMsg() return true; } - throw AuthFailureException("Authentication failed"); + throw auth_error("Authentication failed"); } VncAuthPasswdParameter::VncAuthPasswdParameter(const char* name_, diff --git a/common/rfb/SecurityClient.cxx b/common/rfb/SecurityClient.cxx index 9cd3b90475..878edde940 100644 --- a/common/rfb/SecurityClient.cxx +++ b/common/rfb/SecurityClient.cxx @@ -27,7 +27,6 @@ #include #include #include -#include #include #ifdef HAVE_GNUTLS #include @@ -110,5 +109,5 @@ CSecurity* SecurityClient::GetCSecurity(CConnection* cc, uint32_t secType) } bail: - throw Exception("Security type not supported"); + throw std::invalid_argument("Security type not supported"); } diff --git a/common/rfb/SecurityServer.cxx b/common/rfb/SecurityServer.cxx index b52977366e..d692f4fc93 100644 --- a/common/rfb/SecurityServer.cxx +++ b/common/rfb/SecurityServer.cxx @@ -21,7 +21,6 @@ #include #endif -#include #include #include #include @@ -90,6 +89,6 @@ SSecurity* SecurityServer::GetSSecurity(SConnection* sc, uint32_t secType) } bail: - throw Exception("Security type not supported"); + throw std::invalid_argument("Security type not supported"); } diff --git a/common/rfb/ServerParams.cxx b/common/rfb/ServerParams.cxx index 9f6f530764..df8ad40d3a 100644 --- a/common/rfb/ServerParams.cxx +++ b/common/rfb/ServerParams.cxx @@ -22,9 +22,11 @@ #include #endif -#include +#include + #include #include +#include using namespace rfb; @@ -59,7 +61,7 @@ void ServerParams::setDimensions(int width, int height) void ServerParams::setDimensions(int width, int height, const ScreenSet& layout) { if (!layout.validate(width, height)) - throw Exception("Attempted to configure an invalid screen layout"); + throw std::invalid_argument("Attempted to configure an invalid screen layout"); width_ = width; height_ = height; @@ -71,7 +73,7 @@ void ServerParams::setPF(const PixelFormat& pf) pf_ = pf; if (pf.bpp != 8 && pf.bpp != 16 && pf.bpp != 32) - throw Exception("setPF: not 8, 16 or 32 bpp?"); + throw std::invalid_argument("setPF: not 8, 16 or 32 bpp?"); } void ServerParams::setName(const char* name) @@ -99,7 +101,7 @@ uint32_t ServerParams::clipboardSize(unsigned int format) const return clipSizes[i]; } - throw Exception("Invalid clipboard format 0x%x", format); + throw std::invalid_argument(rfb::format("Invalid clipboard format 0x%x", format)); } void ServerParams::setClipboardCaps(uint32_t flags, const uint32_t* lengths) diff --git a/common/rfb/TightDecoder.cxx b/common/rfb/TightDecoder.cxx index 807f71a5d8..ccf45a9df6 100644 --- a/common/rfb/TightDecoder.cxx +++ b/common/rfb/TightDecoder.cxx @@ -36,6 +36,7 @@ #include #include #include +#include using namespace rfb; @@ -103,14 +104,14 @@ bool TightDecoder::readRect(const Rect& r, rdr::InStream* is, // Quit on unsupported compression type. if (comp_ctl > tightMaxSubencoding) - throw Exception("TightDecoder: bad subencoding value received"); + throw protocol_error("TightDecoder: bad subencoding value received"); // "Basic" compression type. int palSize = 0; if (r.width() > TIGHT_MAX_WIDTH) - throw Exception("TightDecoder: too large rectangle (%d pixels)", r.width()); + throw protocol_error(format("TightDecoder: too large rectangle (%d pixels)", r.width())); // Possible palette if ((comp_ctl & tightExplicitFilter) != 0) { @@ -142,12 +143,12 @@ bool TightDecoder::readRect(const Rect& r, rdr::InStream* is, break; case tightFilterGradient: if (server.pf().bpp == 8) - throw Exception("TightDecoder: invalid BPP for gradient filter"); + throw protocol_error("TightDecoder: invalid BPP for gradient filter"); break; case tightFilterCopy: break; default: - throw Exception("TightDecoder: unknown filter code received"); + throw protocol_error("TightDecoder: unknown filter code received"); } } @@ -383,7 +384,7 @@ void TightDecoder::decodeRect(const Rect& r, const uint8_t* buffer, netbuf = new uint8_t[dataSize]; if (!zis[streamId].hasData(dataSize)) - throw Exception("Tight decode error"); + throw protocol_error("Tight decode error"); zis[streamId].readBytes(netbuf, dataSize); zis[streamId].flushUnderlying(); diff --git a/common/rfb/VNCSConnectionST.cxx b/common/rfb/VNCSConnectionST.cxx index 7dc2a0b8c2..c1cb96f2df 100644 --- a/common/rfb/VNCSConnectionST.cxx +++ b/common/rfb/VNCSConnectionST.cxx @@ -22,6 +22,8 @@ #include #endif +#include + #include #include @@ -129,8 +131,8 @@ void VNCSConnectionST::close(const char* reason) if (sock->outStream().hasBufferedData()) vlog.error("Failed to flush remaining socket data on close"); } - } catch (rdr::Exception& e) { - vlog.error("Failed to flush remaining socket data on close: %s", e.str()); + } catch (std::exception& e) { + vlog.error("Failed to flush remaining socket data on close: %s", e.what()); } // Just shutdown the socket and mark our state as closing. Eventually the @@ -146,8 +148,8 @@ bool VNCSConnectionST::init() { try { initialiseProtocol(); - } catch (rdr::Exception& e) { - close(e.str()); + } catch (std::exception& e) { + close(e.what()); return false; } return true; @@ -187,10 +189,10 @@ void VNCSConnectionST::processMessages() // We wait until now with this to aggregate responses and to give // higher priority to user actions such as keyboard and pointer events. writeFramebufferUpdate(); - } catch (rdr::EndOfStream&) { + } catch (rdr::end_of_stream&) { close("Clean disconnection"); - } catch (rdr::Exception &e) { - close(e.str()); + } catch (std::exception& e) { + close(e.what()); } } @@ -203,8 +205,8 @@ void VNCSConnectionST::flushSocket() // delayed because of congestion. if (!sock->outStream().hasBufferedData()) writeFramebufferUpdate(); - } catch (rdr::Exception &e) { - close(e.str()); + } catch (std::exception& e) { + close(e.what()); } } @@ -252,8 +254,8 @@ void VNCSConnectionST::pixelBufferChange() updates.clear(); updates.add_changed(server->getPixelBuffer()->getRect()); writeFramebufferUpdate(); - } catch(rdr::Exception &e) { - close(e.str()); + } catch(std::exception& e) { + close(e.what()); } } @@ -261,8 +263,8 @@ void VNCSConnectionST::writeFramebufferUpdateOrClose() { try { writeFramebufferUpdate(); - } catch(rdr::Exception &e) { - close(e.str()); + } catch(std::exception& e) { + close(e.what()); } } @@ -271,8 +273,8 @@ void VNCSConnectionST::screenLayoutChangeOrClose(uint16_t reason) try { screenLayoutChange(reason); writeFramebufferUpdate(); - } catch(rdr::Exception &e) { - close(e.str()); + } catch(std::exception& e) { + close(e.what()); } } @@ -280,8 +282,8 @@ void VNCSConnectionST::bellOrClose() { try { if (state() == RFBSTATE_NORMAL) writer()->writeBell(); - } catch(rdr::Exception& e) { - close(e.str()); + } catch(std::exception& e) { + close(e.what()); } } @@ -290,8 +292,8 @@ void VNCSConnectionST::setDesktopNameOrClose(const char *name) try { setDesktopName(name); writeFramebufferUpdate(); - } catch(rdr::Exception& e) { - close(e.str()); + } catch(std::exception& e) { + close(e.what()); } } @@ -300,8 +302,8 @@ void VNCSConnectionST::setCursorOrClose() try { setCursor(); writeFramebufferUpdate(); - } catch(rdr::Exception& e) { - close(e.str()); + } catch(std::exception& e) { + close(e.what()); } } @@ -310,8 +312,8 @@ void VNCSConnectionST::setLEDStateOrClose(unsigned int state) try { setLEDState(state); writeFramebufferUpdate(); - } catch(rdr::Exception& e) { - close(e.str()); + } catch(std::exception& e) { + close(e.what()); } } @@ -322,8 +324,8 @@ void VNCSConnectionST::requestClipboardOrClose() if (!accessCheck(AccessCutText)) return; if (!rfb::Server::acceptCutText) return; requestClipboard(); - } catch(rdr::Exception& e) { - close(e.str()); + } catch(std::exception& e) { + close(e.what()); } } @@ -334,8 +336,8 @@ void VNCSConnectionST::announceClipboardOrClose(bool available) if (!accessCheck(AccessCutText)) return; if (!rfb::Server::sendCutText) return; announceClipboard(available); - } catch(rdr::Exception& e) { - close(e.str()); + } catch(std::exception& e) { + close(e.what()); } } @@ -346,8 +348,8 @@ void VNCSConnectionST::sendClipboardDataOrClose(const char* data) if (!accessCheck(AccessCutText)) return; if (!rfb::Server::sendCutText) return; sendClipboardData(data); - } catch(rdr::Exception& e) { - close(e.str()); + } catch(std::exception& e) { + close(e.what()); } } @@ -418,8 +420,8 @@ void VNCSConnectionST::approveConnectionOrClose(bool accept, { try { approveConnection(accept, reason); - } catch (rdr::Exception& e) { - close(e.str()); + } catch (std::exception& e) { + close(e.what()); } } @@ -728,7 +730,7 @@ void VNCSConnectionST::enableContinuousUpdates(bool enable, Rect rect; if (!client.supportsFence() || !client.supportsContinuousUpdates()) - throw Exception("Client tried to enable continuous updates when not allowed"); + throw protocol_error("Client tried to enable continuous updates when not allowed"); continuousUpdates = enable; @@ -805,8 +807,8 @@ void VNCSConnectionST::handleTimeout(Timer* t) if ((t == &congestionTimer) || (t == &losslessTimer)) writeFramebufferUpdate(); - } catch (rdr::Exception& e) { - close(e.str()); + } catch (std::exception& e) { + close(e.what()); } if (t == &idleTimer) diff --git a/common/rfb/VNCServerST.cxx b/common/rfb/VNCServerST.cxx index 66b05fae5b..c2f47476db 100644 --- a/common/rfb/VNCServerST.cxx +++ b/common/rfb/VNCServerST.cxx @@ -58,7 +58,6 @@ #include #include -#include #include #include #include @@ -151,7 +150,7 @@ void VNCServerST::addSocket(network::Socket* sock, bool outgoing, AccessRights a os.writeU32(strlen(reason)); os.writeBytes((const uint8_t*)reason, strlen(reason)); os.flush(); - } catch (rdr::Exception&) { + } catch (std::exception&) { } sock->shutdown(); closingSockets.push_back(sock); @@ -224,7 +223,7 @@ void VNCServerST::processSocketReadEvent(network::Socket* sock) return; } } - throw rdr::Exception("invalid Socket in VNCServerST"); + throw std::invalid_argument("invalid Socket in VNCServerST"); } void VNCServerST::processSocketWriteEvent(network::Socket* sock) @@ -237,7 +236,7 @@ void VNCServerST::processSocketWriteEvent(network::Socket* sock) return; } } - throw rdr::Exception("invalid Socket in VNCServerST"); + throw std::invalid_argument("invalid Socket in VNCServerST"); } void VNCServerST::blockUpdates() @@ -284,13 +283,13 @@ void VNCServerST::setPixelBuffer(PixelBuffer* pb_, const ScreenSet& layout) screenLayout = ScreenSet(); if (desktopStarted) - throw Exception("setPixelBuffer: null PixelBuffer when desktopStarted?"); + throw std::logic_error("setPixelBuffer: null PixelBuffer when desktopStarted?"); return; } if (!layout.validate(pb->width(), pb->height())) - throw Exception("setPixelBuffer: invalid screen layout"); + throw std::invalid_argument("setPixelBuffer: invalid screen layout"); screenLayout = layout; @@ -342,9 +341,9 @@ void VNCServerST::setPixelBuffer(PixelBuffer* pb_) void VNCServerST::setScreenLayout(const ScreenSet& layout) { if (!pb) - throw Exception("setScreenLayout: new screen layout without a PixelBuffer"); + throw std::logic_error("setScreenLayout: new screen layout without a PixelBuffer"); if (!layout.validate(pb->width(), pb->height())) - throw Exception("setScreenLayout: invalid screen layout"); + throw std::invalid_argument("setScreenLayout: invalid screen layout"); screenLayout = layout; @@ -378,7 +377,7 @@ void VNCServerST::sendClipboardData(const char* data) std::list::iterator ci; if (strchr(data, '\r') != nullptr) - throw Exception("Invalid carriage return in clipboard data"); + throw std::invalid_argument("Invalid carriage return in clipboard data"); for (ci = clipboardRequestors.begin(); ci != clipboardRequestors.end(); ++ci) @@ -566,7 +565,7 @@ unsigned int VNCServerST::setDesktopSize(VNCSConnectionST* requester, // Sanity check if (screenLayout != layout) - throw Exception("Desktop configured a different screen layout than requested"); + throw std::runtime_error("Desktop configured a different screen layout than requested"); // Notify other clients for (ci = clients.begin(); ci != clients.end(); ++ci) { @@ -727,7 +726,7 @@ void VNCServerST::startDesktop() slog.debug("starting desktop"); desktop->start(); if (!pb) - throw Exception("SDesktop::start() did not set a valid PixelBuffer"); + throw std::logic_error("SDesktop::start() did not set a valid PixelBuffer"); desktopStarted = true; // The tracker might have accumulated changes whilst we were // stopped, so flush those out diff --git a/common/rfb/ZRLEDecoder.cxx b/common/rfb/ZRLEDecoder.cxx index e274a697ac..633d1c36eb 100644 --- a/common/rfb/ZRLEDecoder.cxx +++ b/common/rfb/ZRLEDecoder.cxx @@ -64,7 +64,7 @@ static inline T readPixel(rdr::ZlibInStream* zis) static inline void zlibHasData(rdr::ZlibInStream* zis, size_t length) { if (!zis->hasData(length)) - throw Exception("ZRLE decode error"); + throw protocol_error("ZRLE decode error"); } ZRLEDecoder::ZRLEDecoder() : Decoder(DecoderOrdered) @@ -242,7 +242,7 @@ void ZRLEDecoder::zrleDecode(const Rect& r, rdr::InStream* is, } while (b == 255); if (end - ptr < len) { - throw Exception ("ZRLE decode error"); + throw protocol_error("ZRLE decode error"); } while (len-- > 0) *ptr++ = pix; @@ -267,7 +267,7 @@ void ZRLEDecoder::zrleDecode(const Rect& r, rdr::InStream* is, } while (b == 255); if (end - ptr < len) { - throw Exception ("ZRLE decode error"); + throw protocol_error("ZRLE decode error"); } } diff --git a/common/rfb/obfuscate.cxx b/common/rfb/obfuscate.cxx index 2afc151233..a88d282297 100644 --- a/common/rfb/obfuscate.cxx +++ b/common/rfb/obfuscate.cxx @@ -28,11 +28,12 @@ #include #include +#include + extern "C" { #include } -#include #include static unsigned char d3desObfuscationKey[] = {23,82,107,6,35,78,88,7}; @@ -57,7 +58,7 @@ std::string rfb::deobfuscate(const uint8_t *data, size_t len) char buf[9]; if (len != 8) - throw rdr::Exception("bad obfuscated password length"); + throw std::invalid_argument("bad obfuscated password length"); assert(data != nullptr); diff --git a/tests/perf/decperf.cxx b/tests/perf/decperf.cxx index fb2390be2c..46f42fa2ef 100644 --- a/tests/perf/decperf.cxx +++ b/tests/perf/decperf.cxx @@ -110,7 +110,7 @@ void DummyOutStream::overrun(size_t needed) { flush(); if (avail() < needed) - throw rdr::Exception("Insufficient dummy output buffer"); + throw std::out_of_range("Insufficient dummy output buffer"); } CConn::CConn(const char *filename) @@ -202,17 +202,17 @@ static struct stats runTest(const char *fn) try { cc = new CConn(fn); - } catch (rdr::Exception& e) { - fprintf(stderr, "Failed to open rfb file: %s\n", e.str()); + } catch (std::exception& e) { + fprintf(stderr, "Failed to open rfb file: %s\n", e.what()); exit(1); } try { while (true) cc->processMsg(); - } catch (rdr::EndOfStream& e) { - } catch (rdr::Exception& e) { - fprintf(stderr, "Failed to run rfb file: %s\n", e.str()); + } catch (rdr::end_of_stream& e) { + } catch (std::exception& e) { + fprintf(stderr, "Failed to run rfb file: %s\n", e.what()); exit(1); } diff --git a/tests/perf/encperf.cxx b/tests/perf/encperf.cxx index c6e2d3b7a1..d761bbed0c 100644 --- a/tests/perf/encperf.cxx +++ b/tests/perf/encperf.cxx @@ -171,7 +171,7 @@ void DummyOutStream::overrun(size_t needed) { flush(); if (avail() < needed) - throw rdr::Exception("Insufficient dummy output buffer"); + throw std::out_of_range("Insufficient dummy output buffer"); } CConn::CConn(const char *filename) @@ -372,17 +372,17 @@ static struct stats runTest(const char *fn) try { cc = new CConn(fn); - } catch (rdr::Exception& e) { - fprintf(stderr, "Failed to open rfb file: %s\n", e.str()); + } catch (std::exception& e) { + fprintf(stderr, "Failed to open rfb file: %s\n", e.what()); exit(1); } try { while (true) cc->processMsg(); - } catch (rdr::EndOfStream& e) { - } catch (rdr::Exception& e) { - fprintf(stderr, "Failed to run rfb file: %s\n", e.str()); + } catch (rdr::end_of_stream& e) { + } catch (std::exception& e) { + fprintf(stderr, "Failed to run rfb file: %s\n", e.what()); exit(1); } diff --git a/tests/unit/pixelformat.cxx b/tests/unit/pixelformat.cxx index 614d12554a..54e68ccf0d 100644 --- a/tests/unit/pixelformat.cxx +++ b/tests/unit/pixelformat.cxx @@ -22,8 +22,9 @@ #include +#include + #include -#include static void doTest(bool should_fail, int b, int d, bool e, bool t, int rm, int gm, int bm, int rs, int gs, int bs) @@ -36,7 +37,7 @@ static void doTest(bool should_fail, int b, int d, bool e, bool t, try { pf = new rfb::PixelFormat(b, d, e, t, rm, gm, bm, rs, gs, bs); - } catch(rfb::Exception&) { + } catch(std::exception&) { if (should_fail) printf("OK"); else diff --git a/unix/tx/TXDialog.h b/unix/tx/TXDialog.h index 3a22fd07db..6533377f6b 100644 --- a/unix/tx/TXDialog.h +++ b/unix/tx/TXDialog.h @@ -28,6 +28,8 @@ #ifndef __TXDIALOG_H__ #define __TXDIALOG_H__ +#include + #include "TXWindow.h" #include @@ -63,7 +65,7 @@ class TXDialog : public TXWindow, public TXDeleteWindowCallback { FD_ZERO(&rfds); FD_SET(ConnectionNumber(dpy), &rfds); int n = select(FD_SETSIZE, &rfds, nullptr, nullptr, nullptr); - if (n < 0) throw rdr::SocketException("select", errno); + if (n < 0) throw rdr::socket_error("select", errno); } } return true; diff --git a/unix/vncconfig/vncconfig.cxx b/unix/vncconfig/vncconfig.cxx index 1498bbdb58..ecc6eddc28 100644 --- a/unix/vncconfig/vncconfig.cxx +++ b/unix/vncconfig/vncconfig.cxx @@ -330,13 +330,13 @@ int main(int argc, char** argv) FD_ZERO(&rfds); FD_SET(ConnectionNumber(dpy), &rfds); int n = select(FD_SETSIZE, &rfds, nullptr, nullptr, tvp); - if (n < 0) throw rdr::SocketException("select", errno); + if (n < 0) throw rdr::socket_error("select", errno); } XCloseDisplay(dpy); - } catch (rdr::Exception &e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); } return 0; diff --git a/unix/x0vncserver/XDesktop.cxx b/unix/x0vncserver/XDesktop.cxx index fd19dd710f..b4e795efcd 100644 --- a/unix/x0vncserver/XDesktop.cxx +++ b/unix/x0vncserver/XDesktop.cxx @@ -31,7 +31,6 @@ #include #include -#include #include @@ -98,7 +97,7 @@ XDesktop::XDesktop(Display* dpy_, Geometry *geometry_) if (!XkbQueryExtension(dpy, &xkbOpcode, &xkbEventBase, &xkbErrorBase, &major, &minor)) { vlog.error("XKEYBOARD extension not present"); - throw Exception(); + throw std::runtime_error("XKEYBOARD extension not present"); } XkbSelectEvents(dpy, XkbUseCoreKbd, XkbIndicatorStateNotifyMask, @@ -1049,8 +1048,8 @@ bool XDesktop::setCursor() try { server->setCursor(cim->width, cim->height, Point(cim->xhot, cim->yhot), cursorData); - } catch (rdr::Exception& e) { - vlog.error("XserverDesktop::setCursor: %s",e.str()); + } catch (std::exception& e) { + vlog.error("XserverDesktop::setCursor: %s",e.what()); } delete [] cursorData; diff --git a/unix/x0vncserver/x0vncserver.cxx b/unix/x0vncserver/x0vncserver.cxx index fce32c7447..03f31576d9 100644 --- a/unix/x0vncserver/x0vncserver.cxx +++ b/unix/x0vncserver/x0vncserver.cxx @@ -436,7 +436,7 @@ int main(int argc, char** argv) vlog.debug("Interrupted select() system call"); continue; } else { - throw rdr::SocketException("select", errno); + throw rdr::socket_error("select", errno); } } @@ -475,8 +475,8 @@ int main(int argc, char** argv) } } - } catch (rdr::Exception &e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); return 1; } diff --git a/unix/xserver/hw/vnc/RFBGlue.cc b/unix/xserver/hw/vnc/RFBGlue.cc index 2cbee35c51..2295bee85d 100644 --- a/unix/xserver/hw/vnc/RFBGlue.cc +++ b/unix/xserver/hw/vnc/RFBGlue.cc @@ -216,7 +216,7 @@ int vncIsTCPPortUsed(int port) delete dummy.back(); dummy.pop_back(); } - } catch (rdr::Exception& e) { + } catch (std::exception& e) { return 1; } return 0; diff --git a/unix/xserver/hw/vnc/XserverDesktop.cc b/unix/xserver/hw/vnc/XserverDesktop.cc index e3bc57d870..9c4486c850 100644 --- a/unix/xserver/hw/vnc/XserverDesktop.cc +++ b/unix/xserver/hw/vnc/XserverDesktop.cc @@ -38,7 +38,6 @@ #include #include -#include #include #include #include @@ -195,8 +194,8 @@ void XserverDesktop::requestClipboard() { try { server->requestClipboard(); - } catch (rdr::Exception& e) { - vlog.error("XserverDesktop::requestClipboard: %s",e.str()); + } catch (std::exception& e) { + vlog.error("XserverDesktop::requestClipboard: %s",e.what()); } } @@ -204,8 +203,8 @@ void XserverDesktop::announceClipboard(bool available) { try { server->announceClipboard(available); - } catch (rdr::Exception& e) { - vlog.error("XserverDesktop::announceClipboard: %s",e.str()); + } catch (std::exception& e) { + vlog.error("XserverDesktop::announceClipboard: %s",e.what()); } } @@ -213,8 +212,8 @@ void XserverDesktop::sendClipboardData(const char* data_) { try { server->sendClipboardData(data_); - } catch (rdr::Exception& e) { - vlog.error("XserverDesktop::sendClipboardData: %s",e.str()); + } catch (std::exception& e) { + vlog.error("XserverDesktop::sendClipboardData: %s",e.what()); } } @@ -232,8 +231,8 @@ void XserverDesktop::setDesktopName(const char* name) { try { server->setName(name); - } catch (rdr::Exception& e) { - vlog.error("XserverDesktop::setDesktopName: %s",e.str()); + } catch (std::exception& e) { + vlog.error("XserverDesktop::setDesktopName: %s",e.what()); } } @@ -267,8 +266,8 @@ void XserverDesktop::setCursor(int width, int height, int hotX, int hotY, try { server->setCursor(width, height, Point(hotX, hotY), cursorData); - } catch (rdr::Exception& e) { - vlog.error("XserverDesktop::setCursor: %s",e.str()); + } catch (std::exception& e) { + vlog.error("XserverDesktop::setCursor: %s",e.what()); } delete [] cursorData; @@ -278,8 +277,8 @@ void XserverDesktop::setCursorPos(int x, int y, bool warped) { try { server->setCursorPos(Point(x, y), warped); - } catch (rdr::Exception& e) { - vlog.error("XserverDesktop::setCursorPos: %s",e.str()); + } catch (std::exception& e) { + vlog.error("XserverDesktop::setCursorPos: %s",e.what()); } } @@ -287,8 +286,8 @@ void XserverDesktop::add_changed(const rfb::Region ®ion) { try { server->add_changed(region); - } catch (rdr::Exception& e) { - vlog.error("XserverDesktop::add_changed: %s",e.str()); + } catch (std::exception& e) { + vlog.error("XserverDesktop::add_changed: %s",e.what()); } } @@ -296,8 +295,8 @@ void XserverDesktop::add_copied(const rfb::Region &dest, const rfb::Point &delta { try { server->add_copied(dest, delta); - } catch (rdr::Exception& e) { - vlog.error("XserverDesktop::add_copied: %s",e.str()); + } catch (std::exception& e) { + vlog.error("XserverDesktop::add_copied: %s",e.what()); } } @@ -313,8 +312,8 @@ void XserverDesktop::handleSocketEvent(int fd, bool read, bool write) return; vlog.error("Cannot find file descriptor for socket event"); - } catch (rdr::Exception& e) { - vlog.error("XserverDesktop::handleSocketEvent: %s",e.str()); + } catch (std::exception& e) { + vlog.error("XserverDesktop::handleSocketEvent: %s",e.what()); } } @@ -406,8 +405,8 @@ void XserverDesktop::blockHandler(int* timeout) int nextTimeout = Timer::checkTimeouts(); if (nextTimeout >= 0 && (*timeout == -1 || nextTimeout < *timeout)) *timeout = nextTimeout; - } catch (rdr::Exception& e) { - vlog.error("XserverDesktop::blockHandler: %s",e.str()); + } catch (std::exception& e) { + vlog.error("XserverDesktop::blockHandler: %s", e.what()); } } diff --git a/unix/xserver/hw/vnc/vncExtInit.cc b/unix/xserver/hw/vnc/vncExtInit.cc index 073b07e296..e56e0db017 100644 --- a/unix/xserver/hw/vnc/vncExtInit.cc +++ b/unix/xserver/hw/vnc/vncExtInit.cc @@ -250,7 +250,7 @@ void vncExtensionInit(void) } if (!inetd && listeners.empty()) - throw rdr::Exception("No path or port configured for incoming connections"); + throw std::runtime_error("No path or port configured for incoming connections"); PixelFormat pf = vncGetPixelFormat(scr); @@ -274,8 +274,8 @@ void vncExtensionInit(void) vncHooksInit(scr); } - } catch (rdr::Exception& e) { - vncFatalError("vncExtInit: %s\n",e.str()); + } catch (std::exception& e) { + vncFatalError("vncExtInit: %s\n",e.what()); } vncRegisterBlockHandlers(); @@ -288,8 +288,8 @@ void vncExtensionClose(void) delete desktop[scr]; desktop[scr] = nullptr; } - } catch (rdr::Exception& e) { - vncFatalError("vncExtInit: %s\n",e.str()); + } catch (std::exception& e) { + vncFatalError("vncExtInit: %s\n",e.what()); } } @@ -348,8 +348,8 @@ int vncConnectClient(const char *addr, int viewOnly) if (strlen(addr) == 0) { try { desktop[0]->disconnectClients(); - } catch (rdr::Exception& e) { - vlog.error("Disconnecting all clients: %s",e.str()); + } catch (std::exception& e) { + vlog.error("Disconnecting all clients: %s", e.what()); return -1; } return 0; @@ -365,8 +365,8 @@ int vncConnectClient(const char *addr, int viewOnly) vlog.info("Reverse connection: %s:%d%s", host.c_str(), port, viewOnly ? " (view only)" : ""); desktop[0]->addClient(sock, true, (bool)viewOnly); - } catch (rdr::Exception& e) { - vlog.error("Reverse connection: %s",e.str()); + } catch (std::exception& e) { + vlog.error("Reverse connection: %s", e.what()); return -1; } @@ -462,8 +462,8 @@ void vncPostScreenResize(int scrIdx, int success, int width, int height) desktop[scrIdx]->setFramebuffer(width, height, vncFbptr[scrIdx], vncFbstride[scrIdx]); - } catch (rdr::Exception& e) { - vncFatalError("vncPostScreenResize: %s\n", e.str()); + } catch (std::exception& e) { + vncFatalError("vncPostScreenResize: %s\n", e.what()); } } @@ -479,8 +479,8 @@ void vncRefreshScreenLayout(int scrIdx) { try { desktop[scrIdx]->refreshScreenLayout(); - } catch (rdr::Exception& e) { - vncFatalError("vncRefreshScreenLayout: %s\n", e.str()); + } catch (std::exception& e) { + vncFatalError("vncRefreshScreenLayout: %s\n", e.what()); } } @@ -488,8 +488,8 @@ uint64_t vncGetMsc(int scrIdx) { try { return desktop[scrIdx]->getMsc(); - } catch (rdr::Exception& e) { - vncFatalError("vncGetMsc: %s\n", e.str()); + } catch (std::exception& e) { + vncFatalError("vncGetMsc: %s\n", e.what()); } } @@ -497,8 +497,8 @@ void vncQueueMsc(int scrIdx, uint64_t id, uint64_t msc) { try { desktop[scrIdx]->queueMsc(id, msc); - } catch (rdr::Exception& e) { - vncFatalError("vncQueueMsc: %s\n", e.str()); + } catch (std::exception& e) { + vncFatalError("vncQueueMsc: %s\n", e.what()); } } @@ -506,8 +506,8 @@ void vncAbortMsc(int scrIdx, uint64_t id) { try { desktop[scrIdx]->abortMsc(id); - } catch (rdr::Exception& e) { - vncFatalError("vncAbortMsc: %s\n", e.str()); + } catch (std::exception& e) { + vncFatalError("vncAbortMsc: %s\n", e.what()); } } diff --git a/vncviewer/CConn.cxx b/vncviewer/CConn.cxx index 81bea534c1..31f5321d44 100644 --- a/vncviewer/CConn.cxx +++ b/vncviewer/CConn.cxx @@ -27,6 +27,8 @@ #include #endif +#include + #include #include #include @@ -107,10 +109,10 @@ CConn::CConn(const char* vncServerName, network::Socket* socket=nullptr) vlog.info(_("Connected to host %s port %d"), serverHost.c_str(), serverPort); } - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); abort_connection(_("Failed to connect to \"%s\":\n\n%s"), - vncServerName, e.str()); + vncServerName, e.what()); return; } } @@ -261,8 +263,8 @@ void CConn::socketEvent(FL_SOCKET fd, void *data) } cc->getOutStream()->cork(false); - } catch (rdr::EndOfStream& e) { - vlog.info("%s", e.str()); + } catch (rdr::end_of_stream& e) { + vlog.info("%s", e.what()); if (!cc->desktop) { vlog.error(_("The connection was dropped by the server before " "the session could be established.")); @@ -271,16 +273,16 @@ void CConn::socketEvent(FL_SOCKET fd, void *data) } else { disconnect(); } - } catch (rfb::AuthCancelledException& e) { - vlog.info("%s", e.str()); + } catch (rfb::auth_cancelled& e) { + vlog.info("%s", e.what()); disconnect(); - } catch (rfb::AuthFailureException& e) { + } catch (rfb::auth_error& e) { cc->resetPassword(); - vlog.error(_("Authentication failed: %s"), e.str()); + vlog.error(_("Authentication failed: %s"), e.what()); abort_connection(_("Failed to authenticate with the server. Reason " - "given by the server:\n\n%s"), e.str()); - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + "given by the server:\n\n%s"), e.what()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); abort_connection_with_unexpected_error(e); } diff --git a/vncviewer/EmulateMB.cxx b/vncviewer/EmulateMB.cxx index fef8b3d90e..8eeed56810 100644 --- a/vncviewer/EmulateMB.cxx +++ b/vncviewer/EmulateMB.cxx @@ -54,7 +54,7 @@ #include -#include +#include #include "parameters.h" #include "i18n.h" @@ -223,7 +223,7 @@ void EmulateMB::filterPointerEvent(const rfb::Point& pos, uint8_t buttonMask) btstate |= 0x2; if ((state > 10) || (state < 0)) - throw rfb::Exception(_("Invalid state for 3 button emulation")); + throw std::runtime_error(_("Invalid state for 3 button emulation")); action1 = stateTab[state][btstate][0]; @@ -286,7 +286,7 @@ void EmulateMB::handleTimeout(rfb::Timer *t) return; if ((state > 10) || (state < 0)) - throw rfb::Exception(_("Invalid state for 3 button emulation")); + throw std::runtime_error(_("Invalid state for 3 button emulation")); // Timeout shouldn't trigger when there's no timeout action assert(stateTab[state][4][2] >= 0); diff --git a/vncviewer/PlatformPixelBuffer.cxx b/vncviewer/PlatformPixelBuffer.cxx index bcb4cb231e..0f152e114c 100644 --- a/vncviewer/PlatformPixelBuffer.cxx +++ b/vncviewer/PlatformPixelBuffer.cxx @@ -28,11 +28,12 @@ #include #endif +#include + #include #include #include -#include #include "PlatformPixelBuffer.h" @@ -52,11 +53,11 @@ PlatformPixelBuffer::PlatformPixelBuffer(int width, int height) : xim = XCreateImage(fl_display, (Visual*)CopyFromParent, 32, ZPixmap, 0, nullptr, width, height, 32, 0); if (!xim) - throw rdr::Exception("XCreateImage"); + throw std::runtime_error("XCreateImage"); xim->data = (char*)malloc(xim->bytes_per_line * xim->height); if (!xim->data) - throw rdr::Exception("malloc"); + throw std::bad_alloc(); vlog.debug("Using standard XImage"); } diff --git a/vncviewer/ServerDialog.cxx b/vncviewer/ServerDialog.cxx index 8622fff186..e24438d6b6 100644 --- a/vncviewer/ServerDialog.cxx +++ b/vncviewer/ServerDialog.cxx @@ -36,7 +36,9 @@ #include #include -#include + +#include + #include #include #include @@ -140,10 +142,10 @@ void ServerDialog::run(const char* servername, char *newservername) for (const string& entry : dialog.serverHistory) fltk_menu_add(dialog.serverName->menubutton(), entry.c_str(), 0, nullptr); - } catch (Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); fl_alert(_("Unable to load the server history:\n\n%s"), - e.str()); + e.what()); } while (dialog.shown()) Fl::wait(); @@ -192,10 +194,10 @@ void ServerDialog::handleLoad(Fl_Widget* /*widget*/, void* data) try { dialog->serverName->value(loadViewerParameters(filename)); - } catch (Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); fl_alert(_("Unable to load the specified configuration file:\n\n%s"), - e.str()); + e.what()); } delete(file_chooser); @@ -253,10 +255,10 @@ void ServerDialog::handleSaveAs(Fl_Widget* /*widget*/, void* data) try { saveViewerParameters(filename, servername); - } catch (Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); fl_alert(_("Unable to save the specified configuration " - "file:\n\n%s"), e.str()); + "file:\n\n%s"), e.what()); } delete(file_chooser); @@ -287,10 +289,10 @@ void ServerDialog::handleConnect(Fl_Widget* /*widget*/, void *data) try { saveViewerParameters(nullptr, servername); - } catch (Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); fl_alert(_("Unable to save the default configuration:\n\n%s"), - e.str()); + e.what()); } // avoid duplicates in the history @@ -299,10 +301,10 @@ void ServerDialog::handleConnect(Fl_Widget* /*widget*/, void *data) try { dialog->saveServerHistory(); - } catch (Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); fl_alert(_("Unable to save the server history:\n\n%s"), - e.str()); + e.what()); } } @@ -320,7 +322,7 @@ static bool same_server(const string& a, const string& b) try { getHostAndPort(a.c_str(), &hostA, &portA); getHostAndPort(b.c_str(), &hostB, &portB); - } catch (Exception& e) { + } catch (std::exception& e) { return false; } @@ -346,7 +348,7 @@ void ServerDialog::loadServerHistory() const char* stateDir = os::getvncstatedir(); if (stateDir == nullptr) - throw Exception(_("Could not determine VNC state directory path")); + throw std::runtime_error(_("Could not determine VNC state directory path")); char filepath[PATH_MAX]; snprintf(filepath, sizeof(filepath), "%s/%s", stateDir, SERVER_HISTORY); @@ -359,7 +361,7 @@ void ServerDialog::loadServerHistory() return; } std::string msg = format(_("Could not open \"%s\""), filepath); - throw rdr::PosixException(msg.c_str(), errno); + throw rdr::posix_error(msg.c_str(), errno); } int lineNr = 0; @@ -375,15 +377,18 @@ void ServerDialog::loadServerHistory() fclose(f); std::string msg = format(_("Failed to read line %d in " "file \"%s\""), lineNr, filepath); - throw rdr::PosixException(msg.c_str(), errno); + throw rdr::posix_error(msg.c_str(), errno); } int len = strlen(line); if (len == (sizeof(line) - 1)) { fclose(f); - throw Exception(_("Failed to read line %d in file %s: %s"), - lineNr, filepath, _("Line too long")); + throw std::runtime_error(format("%s: %s", + format(_("Failed to read line %d " + "in file %s"), + lineNr, filepath).c_str(), + _("Line too long"))); } if ((len > 0) && (line[len-1] == '\n')) { @@ -422,7 +427,7 @@ void ServerDialog::saveServerHistory() const char* stateDir = os::getvncstatedir(); if (stateDir == nullptr) - throw Exception(_("Could not determine VNC state directory path")); + throw std::runtime_error(_("Could not determine VNC state directory path")); char filepath[PATH_MAX]; snprintf(filepath, sizeof(filepath), "%s/%s", stateDir, SERVER_HISTORY); @@ -431,7 +436,7 @@ void ServerDialog::saveServerHistory() FILE* f = fopen(filepath, "w+"); if (!f) { std::string msg = format(_("Could not open \"%s\""), filepath); - throw rdr::PosixException(msg.c_str(), errno); + throw rdr::posix_error(msg.c_str(), errno); } // Save the last X elements to the config file. diff --git a/vncviewer/Surface_OSX.cxx b/vncviewer/Surface_OSX.cxx index 673f37e995..dcc3d85727 100644 --- a/vncviewer/Surface_OSX.cxx +++ b/vncviewer/Surface_OSX.cxx @@ -22,14 +22,14 @@ #include +#include + #include #include #include #include -#include - #include "cocoa.h" #include "Surface.h" @@ -47,7 +47,7 @@ static CGImageRef create_image(CGColorSpaceRef lut, provider = CGDataProviderCreateWithData(nullptr, data, w * h * 4, nullptr); if (!provider) - throw rdr::Exception("CGDataProviderCreateWithData"); + throw std::runtime_error("CGDataProviderCreateWithData"); // FIXME: This causes a performance hit, but is necessary to avoid // artifacts in the edges of the window @@ -62,7 +62,7 @@ static CGImageRef create_image(CGColorSpaceRef lut, kCGRenderingIntentDefault); CGDataProviderRelease(provider); if (!image) - throw rdr::Exception("CGImageCreate"); + throw std::runtime_error("CGImageCreate"); return image; } @@ -85,7 +85,7 @@ static void render(CGContextRef gc, CGColorSpaceRef lut, subimage = CGImageCreateWithImageInRect(image, rect); if (!subimage) - throw rdr::Exception("CGImageCreateImageWithImageInRect"); + throw std::runtime_error("CGImageCreateImageWithImageInRect"); CGContextSaveGState(gc); @@ -112,7 +112,7 @@ static CGContextRef make_bitmap(int width, int height, unsigned char* data) bitmap = CGBitmapContextCreate(data, width, height, 8, width*4, srgb, kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little); if (!bitmap) - throw rdr::Exception("CGBitmapContextCreate"); + throw std::runtime_error("CGBitmapContextCreate"); return bitmap; } diff --git a/vncviewer/Surface_Win32.cxx b/vncviewer/Surface_Win32.cxx index 67ba15c5ce..c992dbea40 100644 --- a/vncviewer/Surface_Win32.cxx +++ b/vncviewer/Surface_Win32.cxx @@ -57,10 +57,10 @@ void Surface::draw(int src_x, int src_y, int dst_x, int dst_y, dc = CreateCompatibleDC(fl_gc); if (!dc) - throw rdr::Win32Exception("CreateCompatibleDC", GetLastError()); + throw rdr::win32_error("CreateCompatibleDC", GetLastError()); if (!SelectObject(dc, bitmap)) - throw rdr::Win32Exception("SelectObject", GetLastError()); + throw rdr::win32_error("SelectObject", GetLastError()); if (!BitBlt(fl_gc, dst_x, dst_y, dst_w, dst_h, dc, src_x, src_y, SRCCOPY)) { @@ -70,7 +70,7 @@ void Surface::draw(int src_x, int src_y, int dst_x, int dst_y, // with it. For now, we've only seen this error and for this function // so only ignore this combination. if (GetLastError() != ERROR_INVALID_HANDLE) - throw rdr::Win32Exception("BitBlt", GetLastError()); + throw rdr::win32_error("BitBlt", GetLastError()); } DeleteDC(dc); @@ -83,10 +83,10 @@ void Surface::draw(Surface* dst, int src_x, int src_y, dstdc = CreateCompatibleDC(nullptr); if (!dstdc) - throw rdr::Win32Exception("CreateCompatibleDC", GetLastError()); + throw rdr::win32_error("CreateCompatibleDC", GetLastError()); if (!SelectObject(dstdc, dst->bitmap)) - throw rdr::Win32Exception("SelectObject", GetLastError()); + throw rdr::win32_error("SelectObject", GetLastError()); origdc = fl_gc; fl_gc = dstdc; @@ -113,15 +113,15 @@ void Surface::blend(Surface* dst, int src_x, int src_y, dstdc = CreateCompatibleDC(nullptr); if (!dstdc) - throw rdr::Win32Exception("CreateCompatibleDC", GetLastError()); + throw rdr::win32_error("CreateCompatibleDC", GetLastError()); srcdc = CreateCompatibleDC(nullptr); if (!srcdc) - throw rdr::Win32Exception("CreateCompatibleDC", GetLastError()); + throw rdr::win32_error("CreateCompatibleDC", GetLastError()); if (!SelectObject(dstdc, dst->bitmap)) - throw rdr::Win32Exception("SelectObject", GetLastError()); + throw rdr::win32_error("SelectObject", GetLastError()); if (!SelectObject(srcdc, bitmap)) - throw rdr::Win32Exception("SelectObject", GetLastError()); + throw rdr::win32_error("SelectObject", GetLastError()); blend.BlendOp = AC_SRC_OVER; blend.BlendFlags = 0; @@ -136,7 +136,7 @@ void Surface::blend(Surface* dst, int src_x, int src_y, // with it. For now, we've only seen this error and for this function // so only ignore this combination. if (GetLastError() != ERROR_INVALID_HANDLE) - throw rdr::Win32Exception("BitBlt", GetLastError()); + throw rdr::win32_error("BitBlt", GetLastError()); } DeleteDC(srcdc); @@ -161,7 +161,7 @@ void Surface::alloc() bitmap = CreateDIBSection(nullptr, (BITMAPINFO*)&bih, DIB_RGB_COLORS, (void**)&data, nullptr, 0); if (!bitmap) - throw rdr::Win32Exception("CreateDIBSection", GetLastError()); + throw rdr::win32_error("CreateDIBSection", GetLastError()); } void Surface::dealloc() diff --git a/vncviewer/Surface_X11.cxx b/vncviewer/Surface_X11.cxx index d27fcd262e..e73985f054 100644 --- a/vncviewer/Surface_X11.cxx +++ b/vncviewer/Surface_X11.cxx @@ -23,11 +23,11 @@ #include #include +#include + #include #include -#include - #include "Surface.h" void Surface::clear(unsigned char r, unsigned char g, unsigned char b, unsigned char a) @@ -156,7 +156,7 @@ void Surface::alloc() &templ, 0); if (!format) - throw rdr::Exception("XRenderFindFormat"); + throw std::runtime_error("XRenderFindFormat"); picture = XRenderCreatePicture(fl_display, pixmap, format, 0, nullptr); @@ -185,11 +185,11 @@ void Surface::update(const Fl_RGB_Image* image) ZPixmap, 0, nullptr, width(), height(), 32, 0); if (!img) - throw rdr::Exception("XCreateImage"); + throw std::runtime_error("XCreateImage"); img->data = (char*)malloc(img->bytes_per_line * img->height); if (!img->data) - throw rdr::Exception("malloc"); + throw std::bad_alloc(); // Convert data and pre-multiply alpha in = (const unsigned char*)image->data()[0]; diff --git a/vncviewer/UserDialog.cxx b/vncviewer/UserDialog.cxx index ed75a53c46..c6cc02f78d 100644 --- a/vncviewer/UserDialog.cxx +++ b/vncviewer/UserDialog.cxx @@ -36,6 +36,8 @@ #include #include +#include + #include #include @@ -118,7 +120,7 @@ void UserDialog::getUserPasswd(bool secure_, std::string* user, fp = fopen(passwordFileName, "rb"); if (!fp) - throw rdr::PosixException(_("Opening password file failed"), errno); + throw rdr::posix_error(_("Opening password file failed"), errno); obfPwd.resize(fread(obfPwd.data(), 1, obfPwd.size(), fp)); fclose(fp); @@ -249,7 +251,7 @@ void UserDialog::getUserPasswd(bool secure_, std::string* user, delete win; if (ret_val != 0) - throw rfb::AuthCancelledException(); + throw rfb::auth_cancelled(); } bool UserDialog::showMsgBox(MsgBoxFlags flags, const char* title, const char* text) diff --git a/vncviewer/Viewport.cxx b/vncviewer/Viewport.cxx index e29c877cf5..52fde49c7c 100644 --- a/vncviewer/Viewport.cxx +++ b/vncviewer/Viewport.cxx @@ -27,7 +27,6 @@ #include #include -#include #include #include #include @@ -130,11 +129,11 @@ Viewport::Viewport(int w, int h, const rfb::PixelFormat& /*serverPF*/, CConn* cc xkb = XkbGetMap(fl_display, 0, XkbUseCoreKbd); if (!xkb) - throw rfb::Exception("XkbGetMap"); + throw std::runtime_error("XkbGetMap"); status = XkbGetNames(fl_display, XkbKeyNamesMask, xkb); if (status != Success) - throw rfb::Exception("XkbGetNames"); + throw std::runtime_error("XkbGetNames"); memset(code_map_keycode_to_qnum, 0, sizeof(code_map_keycode_to_qnum)); for (KeyCode keycode = xkb->min_key_code; @@ -575,8 +574,8 @@ int Viewport::handle(int event) try { cc->sendClipboardData(filtered.c_str()); - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); abort_connection_with_unexpected_error(e); } @@ -668,8 +667,8 @@ void Viewport::sendPointerEvent(const rfb::Point& pos, uint8_t buttonMask) if ((pointerEventInterval == 0) || (buttonMask != lastButtonMask)) { try { cc->writer()->writePointerEvent(pos, buttonMask); - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); abort_connection_with_unexpected_error(e); } } else { @@ -775,8 +774,8 @@ void Viewport::handleClipboardChange(int source, void *data) vlog.debug("Local clipboard changed, notifying server"); try { self->cc->announceClipboard(true); - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); abort_connection_with_unexpected_error(e); } } @@ -788,8 +787,8 @@ void Viewport::flushPendingClipboard() vlog.debug("Focus regained after local clipboard change, notifying server"); try { cc->announceClipboard(true); - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); abort_connection_with_unexpected_error(e); } } @@ -813,8 +812,8 @@ void Viewport::handlePointerTimeout(void *data) try { self->cc->writer()->writePointerEvent(self->lastPointerPos, self->lastButtonMask); - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); abort_connection_with_unexpected_error(e); } } @@ -885,8 +884,8 @@ void Viewport::handleKeyPress(int keyCode, uint32_t keySym) cc->writer()->writeKeyEvent(keySym, 0, true); else cc->writer()->writeKeyEvent(keySym, keyCode, true); - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); abort_connection_with_unexpected_error(e); } } @@ -915,8 +914,8 @@ void Viewport::handleKeyRelease(int keyCode) cc->writer()->writeKeyEvent(iter->second, 0, false); else cc->writer()->writeKeyEvent(iter->second, keyCode, false); - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); abort_connection_with_unexpected_error(e); } diff --git a/vncviewer/Win32TouchHandler.cxx b/vncviewer/Win32TouchHandler.cxx index e21768f926..2be27ede9a 100644 --- a/vncviewer/Win32TouchHandler.cxx +++ b/vncviewer/Win32TouchHandler.cxx @@ -22,9 +22,10 @@ #include +#include + #define XK_MISCELLANY #include -#include #include #include "i18n.h" @@ -44,7 +45,7 @@ Win32TouchHandler::Win32TouchHandler(HWND hWnd_) : // If window is registered as touch we can not receive gestures, // this should not happen if (IsTouchWindow(hWnd, nullptr)) - throw rfb::Exception(_("Window is registered for touch instead of gestures")); + throw std::runtime_error(_("Window is registered for touch instead of gestures")); // We will not receive any touch/gesture events if this service // isn't running - Logging is enough diff --git a/vncviewer/parameters.cxx b/vncviewer/parameters.cxx index c75cad8bd3..a6229a349c 100644 --- a/vncviewer/parameters.cxx +++ b/vncviewer/parameters.cxx @@ -33,7 +33,9 @@ #include "parameters.h" #include -#include + +#include + #include #include #include @@ -305,20 +307,20 @@ static void setKeyString(const char *_name, const char *_value, HKEY* hKey) { wchar_t name[buffersize]; unsigned size = fl_utf8towc(_name, strlen(_name)+1, name, buffersize); if (size >= buffersize) - throw Exception(_("The name of the parameter is too large")); + throw std::invalid_argument(_("The name of the parameter is too large")); char encodingBuffer[buffersize]; if (!encodeValue(_value, encodingBuffer, buffersize)) - throw Exception(_("The parameter is too large")); + throw std::invalid_argument(_("The parameter is too large")); wchar_t value[buffersize]; size = fl_utf8towc(encodingBuffer, strlen(encodingBuffer)+1, value, buffersize); if (size >= buffersize) - throw Exception(_("The parameter is too large")); + throw std::invalid_argument(_("The parameter is too large")); LONG res = RegSetValueExW(*hKey, name, 0, REG_SZ, (BYTE*)&value, (wcslen(value)+1)*2); if (res != ERROR_SUCCESS) - throw rdr::Win32Exception("RegSetValueExW", res); + throw rdr::win32_error("RegSetValueExW", res); } @@ -330,11 +332,11 @@ static void setKeyInt(const char *_name, const int _value, HKEY* hKey) { unsigned size = fl_utf8towc(_name, strlen(_name)+1, name, buffersize); if (size >= buffersize) - throw Exception(_("The name of the parameter is too large")); + throw std::out_of_range(_("The name of the parameter is too large")); LONG res = RegSetValueExW(*hKey, name, 0, REG_DWORD, (BYTE*)&value, sizeof(DWORD)); if (res != ERROR_SUCCESS) - throw rdr::Win32Exception("RegSetValueExW", res); + throw rdr::win32_error("RegSetValueExW", res); } @@ -347,7 +349,7 @@ static bool getKeyString(const char* _name, char* dest, size_t destSize, HKEY* h unsigned size = fl_utf8towc(_name, strlen(_name)+1, name, buffersize); if (size >= buffersize) - throw Exception(_("The name of the parameter is too large")); + throw std::out_of_range(_("The name of the parameter is too large")); value = new WCHAR[destSize]; valuesize = destSize; @@ -355,7 +357,7 @@ static bool getKeyString(const char* _name, char* dest, size_t destSize, HKEY* h if (res != ERROR_SUCCESS){ delete [] value; if (res != ERROR_FILE_NOT_FOUND) - throw rdr::Win32Exception("RegQueryValueExW", res); + throw rdr::win32_error("RegQueryValueExW", res); // The value does not exist, defaults will be used. return false; } @@ -365,14 +367,14 @@ static bool getKeyString(const char* _name, char* dest, size_t destSize, HKEY* h delete [] value; if (size >= destSize) { delete [] utf8val; - throw Exception(_("The parameter is too large")); + throw std::out_of_range(_("The parameter is too large")); } bool ret = decodeValue(utf8val, dest, destSize); delete [] utf8val; if (!ret) - throw Exception(_("Invalid format or too large value")); + throw std::invalid_argument(_("Invalid format or too large value")); return true; } @@ -387,12 +389,12 @@ static bool getKeyInt(const char* _name, int* dest, HKEY* hKey) { unsigned size = fl_utf8towc(_name, strlen(_name)+1, name, buffersize); if (size >= buffersize) - throw Exception(_("The name of the parameter is too large")); + throw std::out_of_range(_("The name of the parameter is too large")); LONG res = RegQueryValueExW(*hKey, name, nullptr, nullptr, (LPBYTE)&value, &dwordsize); if (res != ERROR_SUCCESS){ if (res != ERROR_FILE_NOT_FOUND) - throw rdr::Win32Exception("RegQueryValueExW", res); + throw rdr::win32_error("RegQueryValueExW", res); // The value does not exist, defaults will be used. return false; } @@ -407,12 +409,12 @@ static void removeValue(const char* _name, HKEY* hKey) { unsigned size = fl_utf8towc(_name, strlen(_name)+1, name, buffersize); if (size >= buffersize) - throw Exception(_("The name of the parameter is too large")); + throw std::out_of_range(_("The name of the parameter is too large")); LONG res = RegDeleteValueW(*hKey, name); if (res != ERROR_SUCCESS) { if (res != ERROR_FILE_NOT_FOUND) - throw rdr::Win32Exception("RegDeleteValueW", res); + throw rdr::win32_error("RegDeleteValueW", res); // The value does not exist, no need to remove it. return; } @@ -426,7 +428,7 @@ void saveHistoryToRegKey(const list& serverHistory) { &hKey, nullptr); if (res != ERROR_SUCCESS) - throw rdr::Win32Exception(_("Failed to create registry key"), res); + throw rdr::win32_error(_("Failed to create registry key"), res); unsigned index = 0; assert(SERVER_HISTORY_SIZE < 100); @@ -440,14 +442,14 @@ void saveHistoryToRegKey(const list& serverHistory) { setKeyString(indexString, entry.c_str(), &hKey); index++; } - } catch (Exception& e) { + } catch (std::exception& e) { RegCloseKey(hKey); throw; } res = RegCloseKey(hKey); if (res != ERROR_SUCCESS) - throw rdr::Win32Exception(_("Failed to close registry key"), res); + throw rdr::win32_error(_("Failed to close registry key"), res); } static void saveToReg(const char* servername) { @@ -459,14 +461,14 @@ static void saveToReg(const char* servername) { REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, nullptr, &hKey, nullptr); if (res != ERROR_SUCCESS) - throw rdr::Win32Exception(_("Failed to create registry key"), res); + throw rdr::win32_error(_("Failed to create registry key"), res); try { setKeyString("ServerName", servername, &hKey); - } catch (Exception& e) { + } catch (std::exception& e) { RegCloseKey(hKey); - throw Exception(_("Failed to save \"%s\": %s"), - "ServerName", e.str()); + throw std::runtime_error(format(_("Failed to save \"%s\": %s"), + "ServerName", e.what())); } for (size_t i = 0; i < sizeof(parameterArray)/sizeof(VoidParameter*); i++) { @@ -478,12 +480,13 @@ static void saveToReg(const char* servername) { } else if (dynamic_cast(parameterArray[i]) != nullptr) { setKeyInt(parameterArray[i]->getName(), (int)*(BoolParameter*)parameterArray[i], &hKey); } else { - throw Exception(_("Unknown parameter type")); + throw std::logic_error(_("Unknown parameter type")); } - } catch (Exception& e) { + } catch (std::exception& e) { RegCloseKey(hKey); - throw Exception(_("Failed to save \"%s\": %s"), - parameterArray[i]->getName(), e.str()); + throw std::runtime_error(format(_("Failed to save \"%s\": %s"), + parameterArray[i]->getName(), + e.what())); } } @@ -493,16 +496,17 @@ static void saveToReg(const char* servername) { for (size_t i = 0; i < sizeof(readOnlyParameterArray)/sizeof(VoidParameter*); i++) { try { removeValue(readOnlyParameterArray[i]->getName(), &hKey); - } catch (Exception& e) { + } catch (std::exception& e) { RegCloseKey(hKey); - throw Exception(_("Failed to remove \"%s\": %s"), - readOnlyParameterArray[i]->getName(), e.str()); + throw std::runtime_error(format(_("Failed to remove \"%s\": %s"), + readOnlyParameterArray[i]->getName(), + e.what())); } } res = RegCloseKey(hKey); if (res != ERROR_SUCCESS) - throw rdr::Win32Exception(_("Failed to close registry key"), res); + throw rdr::win32_error(_("Failed to close registry key"), res); } list loadHistoryFromRegKey() { @@ -518,7 +522,7 @@ list loadHistoryFromRegKey() { return serverHistory; } - throw rdr::Win32Exception(_("Failed to open registry key"), res); + throw rdr::win32_error(_("Failed to open registry key"), res); } unsigned index; @@ -533,10 +537,10 @@ list loadHistoryFromRegKey() { if (!getKeyString(indexString, servernameBuffer, buffersize, &hKey)) break; - } catch (Exception& e) { + } catch (std::exception& e) { // Just ignore this entry and try the next one vlog.error(_("Failed to read server history entry %d: %s"), - (int)index, e.str()); + (int)index, e.what()); continue; } @@ -545,7 +549,7 @@ list loadHistoryFromRegKey() { res = RegCloseKey(hKey); if (res != ERROR_SUCCESS) - throw rdr::Win32Exception(_("Failed to close registry key"), res); + throw rdr::win32_error(_("Failed to close registry key"), res); return serverHistory; } @@ -569,12 +573,12 @@ static void getParametersFromReg(VoidParameter* parameters[], if (getKeyInt(parameters[i]->getName(), &intValue, hKey)) ((BoolParameter*)parameters[i])->setParam(intValue); } else { - throw Exception(_("Unknown parameter type")); + throw std::logic_error(_("Unknown parameter type")); } - } catch(Exception& e) { + } catch(std::exception& e) { // Just ignore this entry and continue with the rest vlog.error(_("Failed to read parameter \"%s\": %s"), - parameters[i]->getName(), e.str()); + parameters[i]->getName(), e.what()); } } } @@ -592,7 +596,7 @@ static char* loadFromReg() { return nullptr; } - throw rdr::Win32Exception(_("Failed to open registry key"), res); + throw rdr::win32_error(_("Failed to open registry key"), res); } const size_t buffersize = 256; @@ -602,9 +606,9 @@ static char* loadFromReg() { try { if (getKeyString("ServerName", servernameBuffer, buffersize, &hKey)) snprintf(servername, buffersize, "%s", servernameBuffer); - } catch(Exception& e) { + } catch(std::exception& e) { vlog.error(_("Failed to read parameter \"%s\": %s"), - "ServerName", e.str()); + "ServerName", e.what()); strcpy(servername, ""); } @@ -614,7 +618,7 @@ static char* loadFromReg() { res = RegCloseKey(hKey); if (res != ERROR_SUCCESS) - throw rdr::Win32Exception(_("Failed to close registry key"), res); + throw rdr::win32_error(_("Failed to close registry key"), res); return servername; } @@ -637,7 +641,7 @@ void saveViewerParameters(const char *filename, const char *servername) { const char* configDir = os::getvncconfigdir(); if (configDir == nullptr) - throw Exception(_("Could not determine VNC config directory path")); + throw std::runtime_error(_("Could not determine VNC config directory path")); snprintf(filepath, sizeof(filepath), "%s/default.tigervnc", configDir); } else { @@ -648,7 +652,7 @@ void saveViewerParameters(const char *filename, const char *servername) { FILE* f = fopen(filepath, "w+"); if (!f) { std::string msg = format(_("Could not open \"%s\""), filepath); - throw rdr::PosixException(msg.c_str(), errno); + throw rdr::posix_error(msg.c_str(), errno); } fprintf(f, "%s\n", IDENTIFIER_STRING); @@ -656,8 +660,9 @@ void saveViewerParameters(const char *filename, const char *servername) { if (!encodeValue(servername, encodingBuffer, buffersize)) { fclose(f); - throw Exception(_("Failed to save \"%s\": %s"), - "ServerName", _("Could not encode parameter")); + throw std::runtime_error(format(_("Failed to save \"%s\": %s"), + "ServerName", + _("Could not encode parameter"))); } fprintf(f, "ServerName=%s\n", encodingBuffer); @@ -666,9 +671,9 @@ void saveViewerParameters(const char *filename, const char *servername) { if (!encodeValue(*(StringParameter*)param, encodingBuffer, buffersize)) { fclose(f); - throw Exception(_("Failed to save \"%s\": %s"), - param->getName(), - _("Could not encode parameter")); + throw std::runtime_error(format(_("Failed to save \"%s\": %s"), + param->getName(), + _("Could not encode parameter"))); } fprintf(f, "%s=%s\n", ((StringParameter*)param)->getName(), encodingBuffer); } else if (dynamic_cast(param) != nullptr) { @@ -677,9 +682,9 @@ void saveViewerParameters(const char *filename, const char *servername) { fprintf(f, "%s=%d\n", ((BoolParameter*)param)->getName(), (int)*(BoolParameter*)param); } else { fclose(f); - throw Exception(_("Failed to save \"%s\": %s"), - param->getName(), - _("Unknown parameter type")); + throw std::logic_error(format(_("Failed to save \"%s\": %s"), + param->getName(), + _("Unknown parameter type"))); } } fclose(f); @@ -698,7 +703,7 @@ static bool findAndSetViewerParameterFromValue( if (dynamic_cast(parameters[i]) != nullptr) { if (strcasecmp(line, ((StringParameter*)parameters[i])->getName()) == 0) { if(!decodeValue(value, decodingBuffer, sizeof(decodingBuffer))) - throw Exception(_("Invalid format or too large value")); + throw std::runtime_error(_("Invalid format or too large value")); ((StringParameter*)parameters[i])->setParam(decodingBuffer); return false; } @@ -716,7 +721,7 @@ static bool findAndSetViewerParameterFromValue( } } else { - throw Exception(_("Unknown parameter type")); + throw std::logic_error(_("Unknown parameter type")); } } @@ -742,7 +747,7 @@ char* loadViewerParameters(const char *filename) { const char* configDir = os::getvncconfigdir(); if (configDir == nullptr) - throw Exception(_("Could not determine VNC config directory path")); + throw std::runtime_error(_("Could not determine VNC config directory path")); snprintf(filepath, sizeof(filepath), "%s/default.tigervnc", configDir); } else { @@ -755,7 +760,7 @@ char* loadViewerParameters(const char *filename) { if (!filename) return nullptr; // Use defaults. std::string msg = format(_("Could not open \"%s\""), filepath); - throw rdr::PosixException(msg.c_str(), errno); + throw rdr::posix_error(msg.c_str(), errno); } int lineNr = 0; @@ -770,13 +775,16 @@ char* loadViewerParameters(const char *filename) { fclose(f); std::string msg = format(_("Failed to read line %d in " "file \"%s\""), lineNr, filepath); - throw rdr::PosixException(msg.c_str(), errno); + throw rdr::posix_error(msg.c_str(), errno); } if (strlen(line) == (sizeof(line) - 1)) { fclose(f); - throw Exception(_("Failed to read line %d in file %s: %s"), - lineNr, filepath, _("Line too long")); + throw std::runtime_error(format("%s: %s", + format(_("Failed to read line %d " + "in file \"%s\""), + lineNr, filepath).c_str(), + _("Line too long"))); } // Make sure that the first line of the file has the file identifier string @@ -785,8 +793,9 @@ char* loadViewerParameters(const char *filename) { continue; fclose(f); - throw Exception(_("Configuration file %s is in an invalid format"), - filepath); + throw std::runtime_error(format(_("Configuration file %s is in " + "an invalid format"), + filepath)); } // Skip empty lines and comments @@ -820,7 +829,7 @@ char* loadViewerParameters(const char *filename) { if (strcasecmp(line, "ServerName") == 0) { if(!decodeValue(value, decodingBuffer, sizeof(decodingBuffer))) - throw Exception(_("Invalid format or too large value")); + throw std::runtime_error(_("Invalid format or too large value")); snprintf(servername, sizeof(decodingBuffer), "%s", decodingBuffer); invalidParameterName = false; @@ -833,10 +842,10 @@ char* loadViewerParameters(const char *filename) { value, line); } } - } catch(Exception& e) { + } catch(std::exception& e) { // Just ignore this entry and continue with the rest vlog.error(_("Failed to read line %d in file %s: %s"), - lineNr, filepath, e.str()); + lineNr, filepath, e.what()); continue; } diff --git a/vncviewer/touch.cxx b/vncviewer/touch.cxx index 1efd3e460d..572e726ef5 100644 --- a/vncviewer/touch.cxx +++ b/vncviewer/touch.cxx @@ -36,7 +36,6 @@ #include #include -#include #include #include "i18n.h" @@ -180,9 +179,9 @@ static int handleTouchEvent(void *event, void* /*data*/) if (msg->message == WM_PAINT && handlers.count(msg->hwnd) == 0) { try { handlers[msg->hwnd] = new Win32TouchHandler(msg->hwnd); - } catch (rfb::Exception& e) { - vlog.error(_("Failed to create touch handler: %s"), e.str()); - abort_vncviewer(_("Failed to create touch handler: %s"), e.str()); + } catch (std::exception& e) { + vlog.error(_("Failed to create touch handler: %s"), e.what()); + abort_vncviewer(_("Failed to create touch handler: %s"), e.what()); } // Add a special hook-in for handling events sent directly to WndProc if (!SetWindowSubclass(msg->hwnd, &win32WindowProc, 1, 0)) { diff --git a/vncviewer/vncviewer.cxx b/vncviewer/vncviewer.cxx index a1d9b39d62..5acab1a17c 100644 --- a/vncviewer/vncviewer.cxx +++ b/vncviewer/vncviewer.cxx @@ -55,7 +55,6 @@ #include #include #include -#include #include #include #include @@ -155,9 +154,9 @@ void abort_connection(const char *error, ...) exitMainloop = true; } -void abort_connection_with_unexpected_error(const rdr::Exception &e) { +void abort_connection_with_unexpected_error(const std::exception &e) { abort_connection(_("An unexpected error occurred when communicating " - "with the server:\n\n%s"), e.str()); + "with the server:\n\n%s"), e.what()); } void disconnect() @@ -513,10 +512,10 @@ potentiallyLoadConfigurationFile(const char *filename) // don't try to connect to the filename strncpy(vncServerName, newServerName, VNCSERVERNAMELEN-1); vncServerName[VNCSERVERNAMELEN-1] = '\0'; - } catch (rfb::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); abort_vncviewer(_("Unable to load the specified configuration " - "file:\n\n%s"), e.str()); + "file:\n\n%s"), e.what()); } } } @@ -671,8 +670,8 @@ int main(int argc, char** argv) strncpy(defaultServerName, configServerName, VNCSERVERNAMELEN-1); defaultServerName[VNCSERVERNAMELEN-1] = '\0'; } - } catch (rfb::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); } for (int i = 1; i < argc;) { @@ -757,7 +756,7 @@ int main(int argc, char** argv) createTcpListeners(&listeners, nullptr, port); if (listeners.empty()) - throw Exception(_("Unable to listen for incoming connections")); + throw std::runtime_error(_("Unable to listen for incoming connections")); vlog.info(_("Listening on port %d"), port); @@ -774,7 +773,7 @@ int main(int argc, char** argv) vlog.debug("Interrupted select() system call"); continue; } else { - throw rdr::SocketException("select", errno); + throw rdr::socket_error("select", errno); } } @@ -786,9 +785,9 @@ int main(int argc, char** argv) break; } } - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); - abort_vncviewer(_("Failure waiting for incoming VNC connection:\n\n%s"), e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); + abort_vncviewer(_("Failure waiting for incoming VNC connection:\n\n%s"), e.what()); return 1; /* Not reached */ } @@ -807,9 +806,9 @@ int main(int argc, char** argv) if (strlen(via) > 0) { try { mktunnel(); - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); - abort_vncviewer(_("Failure setting up encrypted tunnel:\n\n%s"), e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); + abort_vncviewer(_("Failure setting up encrypted tunnel:\n\n%s"), e.what()); } } #endif diff --git a/vncviewer/vncviewer.h b/vncviewer/vncviewer.h index f39a577618..57fd845dc5 100644 --- a/vncviewer/vncviewer.h +++ b/vncviewer/vncviewer.h @@ -21,15 +21,11 @@ #define VNCSERVERNAMELEN 256 -namespace rdr { - struct Exception; -}; - void abort_vncviewer(const char *error, ...) __attribute__((__format__ (__printf__, 1, 2))); void abort_connection(const char *error, ...) __attribute__((__format__ (__printf__, 1, 2))); -void abort_connection_with_unexpected_error(const rdr::Exception &); +void abort_connection_with_unexpected_error(const std::exception &); void disconnect(); bool should_disconnect(); diff --git a/win/rfb_win32/CleanDesktop.cxx b/win/rfb_win32/CleanDesktop.cxx index 6d933b2232..02fdd37476 100644 --- a/win/rfb_win32/CleanDesktop.cxx +++ b/win/rfb_win32/CleanDesktop.cxx @@ -45,7 +45,7 @@ struct ActiveDesktop { HRESULT result = CoCreateInstance(CLSID_ActiveDesktop, nullptr, CLSCTX_INPROC_SERVER, IID_IActiveDesktop, (PVOID*)&handle); if (result != S_OK) - throw rdr::Win32Exception("failed to contact Active Desktop", HRESULT_CODE(result)); + throw rdr::win32_error("failed to contact Active Desktop", HRESULT_CODE(result)); } ~ActiveDesktop() { if (handle) @@ -173,16 +173,16 @@ void CleanDesktop::disableWallpaper() { ActiveDesktop ad; if (ad.enable(false)) restoreActiveDesktop = true; - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); } // -=- Switch of normal wallpaper and notify apps SysParamsInfo(SPI_SETDESKWALLPAPER, 0, (PVOID) "", SPIF_SENDCHANGE); restoreWallpaper = true; - } catch (rdr::Exception& e) { - vlog.info("%s", e.str()); + } catch (std::exception& e) { + vlog.info("%s", e.what()); } } @@ -198,8 +198,8 @@ void CleanDesktop::enableWallpaper() { ActiveDesktop ad; ad.enable(true); restoreActiveDesktop = false; - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); } } @@ -211,8 +211,8 @@ void CleanDesktop::enableWallpaper() { restoreWallpaper = false; } - } catch (rdr::Exception& e) { - vlog.info("%s", e.str()); + } catch (std::exception& e) { + vlog.info("%s", e.what()); } } @@ -243,8 +243,8 @@ void CleanDesktop::disableEffects() { } restoreEffects = true; - } catch (rdr::Exception& e) { - vlog.info("%s", e.str()); + } catch (std::exception& e) { + vlog.info("%s", e.what()); } } @@ -268,7 +268,7 @@ void CleanDesktop::enableEffects() { restoreEffects = false; } - } catch (rdr::Exception& e) { - vlog.info("%s", e.str()); + } catch (std::exception& e) { + vlog.info("%s", e.what()); } } diff --git a/win/rfb_win32/Clipboard.cxx b/win/rfb_win32/Clipboard.cxx index 242ebf343f..8577df462e 100644 --- a/win/rfb_win32/Clipboard.cxx +++ b/win/rfb_win32/Clipboard.cxx @@ -23,6 +23,8 @@ #include #endif +#include + #include #include #include @@ -127,7 +129,7 @@ Clipboard::setClipText(const char* text) { // - Firstly, we must open the clipboard if (!OpenClipboard(getHandle())) - throw rdr::Win32Exception("unable to open Win32 clipboard", GetLastError()); + throw rdr::win32_error("unable to open Win32 clipboard", GetLastError()); // - Convert the supplied clipboard text into UTF-16 format with CRLF std::string filtered(convertCRLF(text)); @@ -142,16 +144,16 @@ Clipboard::setClipText(const char* text) { // - Next, we must clear out any existing data if (!EmptyClipboard()) - throw rdr::Win32Exception("unable to empty Win32 clipboard", GetLastError()); + throw rdr::win32_error("unable to empty Win32 clipboard", GetLastError()); // - Set the new clipboard data if (!SetClipboardData(CF_UNICODETEXT, clip_handle)) - throw rdr::Win32Exception("unable to set Win32 clipboard", GetLastError()); + throw rdr::win32_error("unable to set Win32 clipboard", GetLastError()); clip_handle = nullptr; vlog.debug("set clipboard"); - } catch (rdr::Exception& e) { - vlog.debug("%s", e.str()); + } catch (std::exception& e) { + vlog.debug("%s", e.what()); } // - Close the clipboard diff --git a/win/rfb_win32/CompatibleBitmap.h b/win/rfb_win32/CompatibleBitmap.h index 0ecc6a3ddb..c8fdf82913 100644 --- a/win/rfb_win32/CompatibleBitmap.h +++ b/win/rfb_win32/CompatibleBitmap.h @@ -30,7 +30,7 @@ namespace rfb { CompatibleBitmap(HDC hdc, int width, int height) { hbmp = CreateCompatibleBitmap(hdc, width, height); if (!hbmp) - throw rdr::Win32Exception("CreateCompatibleBitmap() failed", GetLastError()); + throw rdr::win32_error("CreateCompatibleBitmap() failed", GetLastError()); } virtual ~CompatibleBitmap() { if (hbmp) DeleteObject(hbmp); diff --git a/win/rfb_win32/CurrentUser.cxx b/win/rfb_win32/CurrentUser.cxx index fc0f689e62..be36368289 100644 --- a/win/rfb_win32/CurrentUser.cxx +++ b/win/rfb_win32/CurrentUser.cxx @@ -80,7 +80,7 @@ CurrentUserToken::CurrentUserToken() { if (!OpenProcessToken(GetCurrentProcess(), GENERIC_ALL, &h)) { DWORD err = GetLastError(); if (err != ERROR_CALL_NOT_IMPLEMENTED) - throw rdr::Win32Exception("OpenProcessToken failed", err); + throw rdr::win32_error("OpenProcessToken failed", err); h = INVALID_HANDLE_VALUE; } } @@ -92,11 +92,11 @@ ImpersonateCurrentUser::ImpersonateCurrentUser() { if (!isServiceProcess()) return; if (!token.canImpersonate()) - throw rdr::Exception("Cannot impersonate unsafe or null token"); + throw std::runtime_error("Cannot impersonate unsafe or null token"); if (!ImpersonateLoggedOnUser(token)) { DWORD err = GetLastError(); if (err != ERROR_CALL_NOT_IMPLEMENTED) - throw rdr::Win32Exception("Failed to impersonate user", GetLastError()); + throw rdr::win32_error("Failed to impersonate user", GetLastError()); } } @@ -114,7 +114,7 @@ UserName::UserName() { char buf[UNLEN+1]; DWORD len = UNLEN+1; if (!GetUserName(buf, &len)) - throw rdr::Win32Exception("GetUserName failed", GetLastError()); + throw rdr::win32_error("GetUserName failed", GetLastError()); assign(buf); } diff --git a/win/rfb_win32/DIBSectionBuffer.cxx b/win/rfb_win32/DIBSectionBuffer.cxx index ca6f3c9a41..440fe6b1b6 100644 --- a/win/rfb_win32/DIBSectionBuffer.cxx +++ b/win/rfb_win32/DIBSectionBuffer.cxx @@ -21,6 +21,8 @@ #include #endif +#include + #include #include #include @@ -56,7 +58,7 @@ void DIBSectionBuffer::initBuffer(const PixelFormat& pf, int w, int h) { uint8_t* new_data = nullptr; if (!pf.trueColour) - throw rfb::Exception("palette format not supported"); + throw std::invalid_argument("palette format not supported"); format = pf; @@ -85,7 +87,7 @@ void DIBSectionBuffer::initBuffer(const PixelFormat& pf, int w, int h) { if (!new_bitmap) { int err = GetLastError(); - throw rdr::Win32Exception("unable to create DIB section", err); + throw rdr::win32_error("unable to create DIB section", err); } vlog.debug("recreateBuffer()"); @@ -128,7 +130,7 @@ void DIBSectionBuffer::initBuffer(const PixelFormat& pf, int w, int h) { // Determine the *actual* DIBSection format DIBSECTION ds; if (!GetObject(bitmap, sizeof(ds), &ds)) - throw rdr::Win32Exception("GetObject", GetLastError()); + throw rdr::win32_error("GetObject", GetLastError()); // Correct the "stride" of the DIB // *** This code DWORD aligns each row - is that right??? @@ -158,7 +160,7 @@ void DIBSectionBuffer::initBuffer(const PixelFormat& pf, int w, int h) { bits = bits >> 1; } if (depth > bpp) - throw Exception("Bad DIBSection format (depth exceeds bpp)"); + throw std::runtime_error("Bad DIBSection format (depth exceeds bpp)"); format = PixelFormat(bpp, depth, false, true, redMax, greenMax, blueMax, diff --git a/win/rfb_win32/DeviceContext.cxx b/win/rfb_win32/DeviceContext.cxx index fa0beaf96c..1c64e1f519 100644 --- a/win/rfb_win32/DeviceContext.cxx +++ b/win/rfb_win32/DeviceContext.cxx @@ -51,10 +51,10 @@ PixelFormat DeviceContext::getPF(HDC dc) { bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bi.bmiHeader.biBitCount = 0; if (!::GetDIBits(dc, bitmap, 0, 1, nullptr, (BITMAPINFO*)&bi, DIB_RGB_COLORS)) { - throw rdr::Win32Exception("unable to determine device pixel format", GetLastError()); + throw rdr::win32_error("unable to determine device pixel format", GetLastError()); } if (!::GetDIBits(dc, bitmap, 0, 1, nullptr, (BITMAPINFO*)&bi, DIB_RGB_COLORS)) { - throw rdr::Win32Exception("unable to determine pixel shifts/palette", GetLastError()); + throw rdr::win32_error("unable to determine pixel shifts/palette", GetLastError()); } // Set the initial format information @@ -87,7 +87,7 @@ PixelFormat DeviceContext::getPF(HDC dc) { break; default: vlog.error("bits per pixel %u not supported", bi.bmiHeader.biBitCount); - throw rdr::Exception("unknown bits per pixel specified"); + throw std::invalid_argument("unknown bits per pixel specified"); }; break; case BI_BITFIELDS: @@ -151,7 +151,7 @@ Rect DeviceContext::getClipBox(HDC dc) { // Get the display dimensions RECT cr; if (!GetClipBox(dc, &cr)) - throw rdr::Win32Exception("GetClipBox", GetLastError()); + throw rdr::win32_error("GetClipBox", GetLastError()); return Rect(cr.left, cr.top, cr.right, cr.bottom); } @@ -159,7 +159,7 @@ Rect DeviceContext::getClipBox(HDC dc) { DeviceDC::DeviceDC(const char* deviceName) { dc = ::CreateDC("DISPLAY", deviceName, nullptr, nullptr); if (!dc) - throw rdr::Win32Exception("failed to create DeviceDC", GetLastError()); + throw rdr::win32_error("failed to create DeviceDC", GetLastError()); } DeviceDC::~DeviceDC() { @@ -171,7 +171,7 @@ DeviceDC::~DeviceDC() { WindowDC::WindowDC(HWND wnd) : hwnd(wnd) { dc = GetDC(wnd); if (!dc) - throw rdr::Win32Exception("GetDC failed", GetLastError()); + throw rdr::win32_error("GetDC failed", GetLastError()); } WindowDC::~WindowDC() { @@ -183,7 +183,7 @@ WindowDC::~WindowDC() { CompatibleDC::CompatibleDC(HDC existing) { dc = CreateCompatibleDC(existing); if (!dc) - throw rdr::Win32Exception("CreateCompatibleDC failed", GetLastError()); + throw rdr::win32_error("CreateCompatibleDC failed", GetLastError()); } CompatibleDC::~CompatibleDC() { @@ -195,7 +195,7 @@ CompatibleDC::~CompatibleDC() { BitmapDC::BitmapDC(HDC hdc, HBITMAP hbitmap) : CompatibleDC(hdc){ oldBitmap = (HBITMAP)SelectObject(dc, hbitmap); if (!oldBitmap) - throw rdr::Win32Exception("SelectObject to CompatibleDC failed", + throw rdr::win32_error("SelectObject to CompatibleDC failed", GetLastError()); } diff --git a/win/rfb_win32/DeviceFrameBuffer.cxx b/win/rfb_win32/DeviceFrameBuffer.cxx index ca2f57d494..1c3e9575a2 100644 --- a/win/rfb_win32/DeviceFrameBuffer.cxx +++ b/win/rfb_win32/DeviceFrameBuffer.cxx @@ -54,14 +54,14 @@ DeviceFrameBuffer::DeviceFrameBuffer(HDC deviceContext, const Rect& wRect) int capabilities = GetDeviceCaps(device, RASTERCAPS); if (!(capabilities & RC_BITBLT)) { - throw Exception("device does not support BitBlt"); + throw std::invalid_argument("device does not support BitBlt"); } if (!(capabilities & RC_DI_BITMAP)) { - throw Exception("device does not support GetDIBits"); + throw std::invalid_argument("device does not support GetDIBits"); } /* if (GetDeviceCaps(device, PLANES) != 1) { - throw Exception("device does not support planar displays"); + throw std::invalid_argument("device does not support planar displays"); } */ @@ -102,7 +102,7 @@ DeviceFrameBuffer::grabRect(const Rect &rect) { if (ignoreGrabErrors) vlog.error("BitBlt failed:%ld", GetLastError()); else - throw rdr::Win32Exception("BitBlt failed", GetLastError()); + throw rdr::win32_error("BitBlt failed", GetLastError()); } } @@ -138,11 +138,11 @@ void DeviceFrameBuffer::setCursor(HCURSOR hCursor, VNCServer* server) BITMAP maskInfo; if (!GetObject(iconInfo.hbmMask, sizeof(BITMAP), &maskInfo)) - throw rdr::Win32Exception("GetObject() failed", GetLastError()); + throw rdr::win32_error("GetObject() failed", GetLastError()); if (maskInfo.bmPlanes != 1) - throw rdr::Exception("unsupported multi-plane cursor"); + throw std::invalid_argument("unsupported multi-plane cursor"); if (maskInfo.bmBitsPixel != 1) - throw rdr::Exception("unsupported cursor mask format"); + throw std::invalid_argument("unsupported cursor mask format"); width = maskInfo.bmWidth; height = maskInfo.bmHeight; @@ -174,7 +174,7 @@ void DeviceFrameBuffer::setCursor(HCURSOR hCursor, VNCServer* server) if (!GetDIBits(dc, iconInfo.hbmColor, 0, height, buffer.data(), (LPBITMAPINFO)&bi, DIB_RGB_COLORS)) - throw rdr::Win32Exception("GetDIBits", GetLastError()); + throw rdr::win32_error("GetDIBits", GetLastError()); // We may not get the RGBA order we want, so shuffle things around int ridx, gidx, bidx, aidx; @@ -188,7 +188,7 @@ void DeviceFrameBuffer::setCursor(HCURSOR hCursor, VNCServer* server) if ((bi.bV5RedMask != ((unsigned)0xff << ridx*8)) || (bi.bV5GreenMask != ((unsigned)0xff << gidx*8)) || (bi.bV5BlueMask != ((unsigned)0xff << bidx*8))) - throw rdr::Exception("unsupported cursor colour format"); + throw std::invalid_argument("unsupported cursor colour format"); uint8_t* rwbuffer = buffer.data(); for (int y = 0; y < height; y++) { @@ -217,7 +217,7 @@ void DeviceFrameBuffer::setCursor(HCURSOR hCursor, VNCServer* server) if (!GetBitmapBits(iconInfo.hbmMask, maskInfo.bmWidthBytes * maskInfo.bmHeight, mask.data())) - throw rdr::Win32Exception("GetBitmapBits", GetLastError()); + throw rdr::win32_error("GetBitmapBits", GetLastError()); bool doOutline = false; uint8_t* rwbuffer = buffer.data(); @@ -308,7 +308,7 @@ void DeviceFrameBuffer::setCursor(HCURSOR hCursor, VNCServer* server) server->setCursor(width, height, hotspot, buffer.data()); - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); } } diff --git a/win/rfb_win32/Dialog.cxx b/win/rfb_win32/Dialog.cxx index 35ec065e99..e8af08465e 100644 --- a/win/rfb_win32/Dialog.cxx +++ b/win/rfb_win32/Dialog.cxx @@ -65,7 +65,7 @@ bool Dialog::showDialog(const char* resource, HWND owner) INT_PTR result = DialogBoxParam(inst, resource, owner, staticDialogProc, (LPARAM)this); if (result<0) - throw rdr::Win32Exception("DialogBoxParam failed", GetLastError()); + throw rdr::win32_error("DialogBoxParam failed", GetLastError()); alreadyShowing = false; return (result == 1); } @@ -78,7 +78,7 @@ int Dialog::getItemInt(int id) { BOOL trans; int result = GetDlgItemInt(handle, id, &trans, TRUE); if (!trans) - throw rdr::Exception("unable to read dialog Int"); + throw std::runtime_error("unable to read dialog Int"); return result; } const char* Dialog::getItemString(int id) { @@ -275,7 +275,7 @@ bool PropSheet::showPropSheet(HWND owner_, bool showApply, bool showCtxtHelp, bo handle = (HWND)PropertySheet(&header); if ((handle == nullptr) || (handle == (HWND)-1)) - throw rdr::Win32Exception("PropertySheet failed", GetLastError()); + throw rdr::win32_error("PropertySheet failed", GetLastError()); centerWindow(handle, owner_); plog.info("created %p", handle); @@ -347,7 +347,7 @@ bool PropSheet::showPropSheet(HWND owner_, bool showApply, bool showCtxtHelp, bo delete [] hpages; hpages = nullptr; return true; - } catch (rdr::Exception&) { + } catch (std::exception&) { alreadyShowing = false; std::list::iterator pspi; diff --git a/win/rfb_win32/EventManager.cxx b/win/rfb_win32/EventManager.cxx index f034d36d49..995c4fe209 100644 --- a/win/rfb_win32/EventManager.cxx +++ b/win/rfb_win32/EventManager.cxx @@ -22,8 +22,9 @@ #include +#include + #include -#include #include using namespace rfb; @@ -59,7 +60,7 @@ void EventManager::removeEvent(HANDLE event) { return; } } - throw rdr::Exception("Event not registered"); + throw std::runtime_error("Event not registered"); } diff --git a/win/rfb_win32/IconInfo.h b/win/rfb_win32/IconInfo.h index ca23451476..991a5a13ae 100644 --- a/win/rfb_win32/IconInfo.h +++ b/win/rfb_win32/IconInfo.h @@ -28,7 +28,7 @@ namespace rfb { struct IconInfo : public ICONINFO { IconInfo(HICON icon) { if (!GetIconInfo(icon, this)) - throw rdr::Win32Exception("GetIconInfo() failed", GetLastError()); + throw rdr::win32_error("GetIconInfo() failed", GetLastError()); } ~IconInfo() { if (hbmColor) diff --git a/win/rfb_win32/IntervalTimer.h b/win/rfb_win32/IntervalTimer.h index 5ced2c5eb5..b62040b35e 100644 --- a/win/rfb_win32/IntervalTimer.h +++ b/win/rfb_win32/IntervalTimer.h @@ -41,7 +41,7 @@ namespace rfb { if (!active || interval_ != interval) { interval = interval_; if (!SetTimer(hwnd, id, interval, nullptr)) - throw rdr::Win32Exception("SetTimer", GetLastError()); + throw rdr::win32_error("SetTimer", GetLastError()); active = true; } } diff --git a/win/rfb_win32/LaunchProcess.cxx b/win/rfb_win32/LaunchProcess.cxx index beb7e6b717..38aa720f2d 100644 --- a/win/rfb_win32/LaunchProcess.cxx +++ b/win/rfb_win32/LaunchProcess.cxx @@ -53,7 +53,7 @@ void LaunchProcess::start(HANDLE userToken, bool createConsole) { char buf[256]; HDESK desktop = GetThreadDesktop(GetCurrentThreadId()); if (!GetUserObjectInformation(desktop, UOI_NAME, buf, 256, &size)) - throw rdr::Win32Exception("unable to launch process", GetLastError()); + throw rdr::win32_error("unable to launch process", GetLastError()); snprintf(desktopName, 256, "WinSta0\\%s", buf); @@ -95,7 +95,7 @@ void LaunchProcess::start(HANDLE userToken, bool createConsole) { flags, nullptr, nullptr, &sinfo, &procInfo); if (!success) - throw rdr::Win32Exception("unable to launch process", GetLastError()); + throw rdr::win32_error("unable to launch process", GetLastError()); // Wait for it to finish initialising WaitForInputIdle(procInfo.hProcess, 15000); @@ -119,7 +119,7 @@ bool LaunchProcess::await(DWORD timeoutMs) { detach(); return true; } else if (result == WAIT_FAILED) { - throw rdr::Win32Exception("await() failed", GetLastError()); + throw rdr::win32_error("await() failed", GetLastError()); } return false; } diff --git a/win/rfb_win32/LocalMem.h b/win/rfb_win32/LocalMem.h index e2dc80bd8a..5280dea3ce 100644 --- a/win/rfb_win32/LocalMem.h +++ b/win/rfb_win32/LocalMem.h @@ -28,7 +28,7 @@ namespace rfb { // Allocate and/or manage LocalAlloc memory. struct LocalMem { LocalMem(int size) : ptr(LocalAlloc(LMEM_FIXED, size)) { - if (!ptr) throw rdr::Win32Exception("LocalAlloc", GetLastError()); + if (!ptr) throw rdr::win32_error("LocalAlloc", GetLastError()); } LocalMem(void* p) : ptr(p) {} ~LocalMem() {LocalFree(ptr);} diff --git a/win/rfb_win32/MonitorInfo.cxx b/win/rfb_win32/MonitorInfo.cxx index 854b467a6d..84a8d50147 100644 --- a/win/rfb_win32/MonitorInfo.cxx +++ b/win/rfb_win32/MonitorInfo.cxx @@ -44,7 +44,7 @@ static void fillMonitorInfo(HMONITOR monitor, MONITORINFOEXA* mi) { memset(mi, 0, sizeof(MONITORINFOEXA)); mi->cbSize = sizeof(MONITORINFOEXA); if (!GetMonitorInfo(monitor, mi)) - throw rdr::Win32Exception("failed to GetMonitorInfo", GetLastError()); + throw rdr::win32_error("failed to GetMonitorInfo", GetLastError()); vlog.debug("monitor is %ld,%ld-%ld,%ld", mi->rcMonitor.left, mi->rcMonitor.top, mi->rcMonitor.right, mi->rcMonitor.bottom); vlog.debug("work area is %ld,%ld-%ld,%ld", mi->rcWork.left, mi->rcWork.top, mi->rcWork.right, mi->rcWork.bottom); vlog.debug("device is \"%s\"", mi->szDevice); @@ -57,7 +57,7 @@ MonitorInfo::MonitorInfo(HWND window) { HMONITOR monitor = MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST); if (!monitor) - throw rdr::Win32Exception("failed to get monitor", GetLastError()); + throw rdr::win32_error("failed to get monitor", GetLastError()); fillMonitorInfo(monitor, this); } @@ -67,7 +67,7 @@ MonitorInfo::MonitorInfo(const RECT& r) { HMONITOR monitor = MonitorFromRect(&r, MONITOR_DEFAULTTONEAREST); if (!monitor) - throw rdr::Win32Exception("failed to get monitor", GetLastError()); + throw rdr::win32_error("failed to get monitor", GetLastError()); fillMonitorInfo(monitor, this); } diff --git a/win/rfb_win32/MsgWindow.cxx b/win/rfb_win32/MsgWindow.cxx index e94b60a872..4908126ec4 100644 --- a/win/rfb_win32/MsgWindow.cxx +++ b/win/rfb_win32/MsgWindow.cxx @@ -61,8 +61,8 @@ LRESULT CALLBACK MsgWindowProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) try { result = _this->processMessage(msg, wParam, lParam); - } catch (rdr::Exception& e) { - vlog.error("untrapped: %s", e.str()); + } catch (std::exception& e) { + vlog.error("untrapped: %s", e.what()); } return result; @@ -82,7 +82,7 @@ MsgWindowClass::MsgWindowClass() : classAtom(0) { wndClass.lpszClassName = "rfb::win32::MsgWindowClass"; classAtom = RegisterClass(&wndClass); if (!classAtom) { - throw rdr::Win32Exception("unable to register MsgWindow window class", GetLastError()); + throw rdr::win32_error("unable to register MsgWindow window class", GetLastError()); } } @@ -104,7 +104,7 @@ MsgWindow::MsgWindow(const char* name_) : name(name_), handle(nullptr) { name.c_str(), WS_OVERLAPPED, 0, 0, 10, 10, nullptr, nullptr, baseClass.instance, this); if (!handle) { - throw rdr::Win32Exception("unable to create WMNotifier window instance", GetLastError()); + throw rdr::win32_error("unable to create WMNotifier window instance", GetLastError()); } vlog.debug("created window \"%s\" (%p)", name.c_str(), handle); } diff --git a/win/rfb_win32/RegConfig.cxx b/win/rfb_win32/RegConfig.cxx index fc006b21f1..211570ca76 100644 --- a/win/rfb_win32/RegConfig.cxx +++ b/win/rfb_win32/RegConfig.cxx @@ -53,8 +53,8 @@ bool RegConfig::setKey(const HKEY rootkey, const char* keyname) { key.createKey(rootkey, keyname); processEvent(event); return true; - } catch (rdr::Exception& e) { - vlog.debug("%s", e.str()); + } catch (std::exception& e) { + vlog.debug("%s", e.what()); return false; } } @@ -69,9 +69,9 @@ void RegConfig::loadRegistryConfig(RegKey& key) { if (!Configuration::setParam(name, value.c_str())) vlog.info("unable to process %s", name); } - } catch (rdr::Win32Exception& e) { + } catch (rdr::win32_error& e) { if (e.err != ERROR_INVALID_HANDLE) - vlog.error("%s", e.str()); + vlog.error("%s", e.what()); } } @@ -115,5 +115,5 @@ void RegConfigThread::worker() { thread_id = GetCurrentThreadId(); while ((result = eventMgr.getMessage(&msg, nullptr, 0, 0)) > 0) {} if (result < 0) - throw rdr::Win32Exception("RegConfigThread failed", GetLastError()); + throw rdr::win32_error("RegConfigThread failed", GetLastError()); } diff --git a/win/rfb_win32/Registry.cxx b/win/rfb_win32/Registry.cxx index bbe15f4786..4775695075 100644 --- a/win/rfb_win32/Registry.cxx +++ b/win/rfb_win32/Registry.cxx @@ -54,7 +54,7 @@ RegKey::RegKey() : key(nullptr), freeKey(false), valueName(nullptr), valueNameBu RegKey::RegKey(const HKEY k) : key(nullptr), freeKey(false), valueName(nullptr), valueNameBufLen(0) { LONG result = RegOpenKeyEx(k, nullptr, 0, KEY_ALL_ACCESS, &key); if (result != ERROR_SUCCESS) - throw rdr::Win32Exception("RegOpenKeyEx(HKEY)", result); + throw rdr::win32_error("RegOpenKeyEx(HKEY)", result); vlog.debug("duplicated %p to %p", k, key); freeKey = true; } @@ -62,7 +62,7 @@ RegKey::RegKey(const HKEY k) : key(nullptr), freeKey(false), valueName(nullptr), RegKey::RegKey(const RegKey& k) : key(nullptr), freeKey(false), valueName(nullptr), valueNameBufLen(0) { LONG result = RegOpenKeyEx(k.key, nullptr, 0, KEY_ALL_ACCESS, &key); if (result != ERROR_SUCCESS) - throw rdr::Win32Exception("RegOpenKeyEx(RegKey&)", result); + throw rdr::win32_error("RegOpenKeyEx(RegKey&)", result); vlog.debug("duplicated %p to %p", k.key, key); freeKey = true; } @@ -86,7 +86,7 @@ bool RegKey::createKey(const RegKey& root, const char* name) { LONG result = RegCreateKey(root.key, name, &key); if (result != ERROR_SUCCESS) { vlog.error("RegCreateKey(%p, %s): %lx", root.key, name, result); - throw rdr::Win32Exception("RegCreateKeyEx", result); + throw rdr::win32_error("RegCreateKeyEx", result); } vlog.debug("createKey(%p,%s) = %p", root.key, name, key); freeKey = true; @@ -97,7 +97,7 @@ void RegKey::openKey(const RegKey& root, const char* name, bool readOnly) { close(); LONG result = RegOpenKeyEx(root.key, name, 0, readOnly ? KEY_READ : KEY_ALL_ACCESS, &key); if (result != ERROR_SUCCESS) - throw rdr::Win32Exception("RegOpenKeyEx (open)", result); + throw rdr::win32_error("RegOpenKeyEx (open)", result); vlog.debug("openKey(%p,%s,%s) = %p", root.key, name, readOnly ? "ro" : "rw", key); freeKey = true; @@ -109,7 +109,7 @@ void RegKey::setDACL(const PACL acl, bool inherit) { DACL_SECURITY_INFORMATION | (inherit ? UNPROTECTED_DACL_SECURITY_INFORMATION : PROTECTED_DACL_SECURITY_INFORMATION), nullptr, nullptr, acl, nullptr)) != ERROR_SUCCESS) - throw rdr::Win32Exception("RegKey::setDACL failed", result); + throw rdr::win32_error("RegKey::setDACL failed", result); } void RegKey::close() { @@ -123,19 +123,19 @@ void RegKey::close() { void RegKey::deleteKey(const char* name) const { LONG result = RegDeleteKey(key, name); if (result != ERROR_SUCCESS) - throw rdr::Win32Exception("RegDeleteKey", result); + throw rdr::win32_error("RegDeleteKey", result); } void RegKey::deleteValue(const char* name) const { LONG result = RegDeleteValue(key, name); if (result != ERROR_SUCCESS) - throw rdr::Win32Exception("RegDeleteValue", result); + throw rdr::win32_error("RegDeleteValue", result); } void RegKey::awaitChange(bool watchSubTree, DWORD filter, HANDLE event) const { LONG result = RegNotifyChangeKeyValue(key, watchSubTree, filter, event, event != nullptr); if (result != ERROR_SUCCESS) - throw rdr::Win32Exception("RegNotifyChangeKeyValue", result); + throw rdr::win32_error("RegNotifyChangeKeyValue", result); } @@ -144,22 +144,22 @@ RegKey::operator HKEY() const {return key;} void RegKey::setExpandString(const char* valname, const char* value) const { LONG result = RegSetValueEx(key, valname, 0, REG_EXPAND_SZ, (const BYTE*)value, (strlen(value)+1)*sizeof(char)); - if (result != ERROR_SUCCESS) throw rdr::Win32Exception("setExpandString", result); + if (result != ERROR_SUCCESS) throw rdr::win32_error("setExpandString", result); } void RegKey::setString(const char* valname, const char* value) const { LONG result = RegSetValueEx(key, valname, 0, REG_SZ, (const BYTE*)value, (strlen(value)+1)*sizeof(char)); - if (result != ERROR_SUCCESS) throw rdr::Win32Exception("setString", result); + if (result != ERROR_SUCCESS) throw rdr::win32_error("setString", result); } void RegKey::setBinary(const char* valname, const void* value, size_t length) const { LONG result = RegSetValueEx(key, valname, 0, REG_BINARY, (const BYTE*)value, length); - if (result != ERROR_SUCCESS) throw rdr::Win32Exception("setBinary", result); + if (result != ERROR_SUCCESS) throw rdr::win32_error("setBinary", result); } void RegKey::setInt(const char* valname, int value) const { LONG result = RegSetValueEx(key, valname, 0, REG_DWORD, (const BYTE*)&value, sizeof(value)); - if (result != ERROR_SUCCESS) throw rdr::Win32Exception("setInt", result); + if (result != ERROR_SUCCESS) throw rdr::win32_error("setInt", result); } void RegKey::setBool(const char* valname, bool value) const { @@ -173,7 +173,7 @@ std::string RegKey::getString(const char* valname) const { std::string RegKey::getString(const char* valname, const char* def) const { try { return getString(valname); - } catch(rdr::Exception&) { + } catch(std::exception&) { return def; } } @@ -185,7 +185,7 @@ std::vector RegKey::getBinary(const char* valname) const { std::vector RegKey::getBinary(const char* valname, const uint8_t* def, size_t deflen) const { try { return getBinary(valname); - } catch(rdr::Exception&) { + } catch(std::exception&) { std::vector out(deflen); memcpy(out.data(), def, deflen); return out; @@ -198,7 +198,7 @@ int RegKey::getInt(const char* valname) const { int RegKey::getInt(const char* valname, int def) const { try { return getInt(valname); - } catch(rdr::Exception&) { + } catch(std::exception&) { return def; } } @@ -214,11 +214,11 @@ std::string RegKey::getRepresentation(const char* valname) const { DWORD type, length; LONG result = RegQueryValueEx(key, valname, nullptr, &type, nullptr, &length); if (result != ERROR_SUCCESS) - throw rdr::Win32Exception("get registry value length", result); + throw rdr::win32_error("get registry value length", result); std::vector data(length); result = RegQueryValueEx(key, valname, nullptr, &type, (BYTE*)data.data(), &length); if (result != ERROR_SUCCESS) - throw rdr::Win32Exception("get registry value", result); + throw rdr::win32_error("get registry value", result); switch (type) { case REG_BINARY: @@ -243,18 +243,18 @@ std::string RegKey::getRepresentation(const char* valname) const { std::string str((char*)data.data(), length); DWORD required = ExpandEnvironmentStrings(str.c_str(), nullptr, 0); if (required==0) - throw rdr::Win32Exception("ExpandEnvironmentStrings", GetLastError()); + throw rdr::win32_error("ExpandEnvironmentStrings", GetLastError()); std::vector expanded(required); length = ExpandEnvironmentStrings(str.c_str(), expanded.data(), required); if (required #include #include -#include #include #include @@ -172,12 +171,12 @@ void SDisplay::startCore() { // Currently, we just check whether we're in the console session, and // fail if not if (!inConsoleSession()) - throw rdr::Exception("Console is not session zero - oreconnect to restore Console sessin"); + throw std::runtime_error("Console is not session zero - oreconnect to restore Console sessin"); // Switch to the current input desktop if (rfb::win32::desktopChangeRequired()) { if (!rfb::win32::changeDesktop()) - throw rdr::Exception("unable to switch into input desktop"); + throw std::runtime_error("unable to switch into input desktop"); } // Initialise the change tracker and clipper @@ -197,12 +196,12 @@ void SDisplay::startCore() { else core = new SDisplayCorePolling(this, &updates); core->setScreenRect(screenRect); - } catch (rdr::Exception& e) { + } catch (std::exception& e) { delete core; core = nullptr; if (tryMethod == 0) - throw rdr::Exception("unable to access desktop"); + throw std::runtime_error("unable to access desktop"); tryMethod--; - vlog.error("%s", e.str()); + vlog.error("%s", e.what()); } } vlog.info("Started %s", core->methodName()); @@ -287,12 +286,12 @@ void SDisplay::restartCore() { // Start a new Core if possible startCore(); vlog.info("restarted"); - } catch (rdr::Exception& e) { + } catch (std::exception& e) { // If startCore() fails then we MUST disconnect all clients, // to cause the server to stop() the desktop. // Otherwise, the SDesktop is in an inconsistent state // and the server will crash. - server->closeClients(e.str()); + server->closeClients(e.what()); } } @@ -400,8 +399,8 @@ SDisplay::processEvent(HANDLE event) { // - Flush any updates from the core try { core->flushUpdates(); - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); restartCore(); return; } @@ -435,7 +434,7 @@ SDisplay::processEvent(HANDLE event) { } return; } - throw rdr::Exception("No such event"); + throw std::runtime_error("No such event"); } diff --git a/win/rfb_win32/SDisplayCoreWMHooks.cxx b/win/rfb_win32/SDisplayCoreWMHooks.cxx index 8165be3d62..4c307600e5 100644 --- a/win/rfb_win32/SDisplayCoreWMHooks.cxx +++ b/win/rfb_win32/SDisplayCoreWMHooks.cxx @@ -40,7 +40,7 @@ SDisplayCoreWMHooks::SDisplayCoreWMHooks(SDisplay* d, UpdateTracker* ut) consolePollTimer(getHandle(), consolePollTimerId), pollConsoles(false) { if (!hooks.setEvent(display->getUpdateEvent())) - throw rdr::Exception("hook subsystem failed to initialise"); + throw std::runtime_error("hook subsystem failed to initialise"); poller.setUpdateTracker(updateTracker); cursorTimer.start(20); consolePollTimer.start(200); diff --git a/win/rfb_win32/SInput.cxx b/win/rfb_win32/SInput.cxx index 37144c29c6..f32ee1bd86 100644 --- a/win/rfb_win32/SInput.cxx +++ b/win/rfb_win32/SInput.cxx @@ -126,7 +126,7 @@ win32::SPointer::pointerEvent(const Point& pos, uint8_t buttonmask) evt.mi.mouseData = data; evt.mi.time = 0; if (SendInput(1, &evt, sizeof(evt)) != 1) - throw rdr::Win32Exception("SendInput", GetLastError()); + throw rdr::win32_error("SendInput", GetLastError()); } } diff --git a/win/rfb_win32/Security.cxx b/win/rfb_win32/Security.cxx index 04f9240213..9f970aeb43 100644 --- a/win/rfb_win32/Security.cxx +++ b/win/rfb_win32/Security.cxx @@ -96,19 +96,19 @@ void AccessEntries::addEntry(const PSID sid, PSID Sid::copySID(const PSID sid) { if (!IsValidSid(sid)) - throw rdr::Exception("invalid SID in copyPSID"); + throw std::invalid_argument("invalid SID in copyPSID"); PSID buf = (PSID)new uint8_t[GetLengthSid(sid)]; if (!CopySid(GetLengthSid(sid), buf, sid)) - throw rdr::Win32Exception("CopySid failed", GetLastError()); + throw rdr::win32_error("CopySid failed", GetLastError()); return buf; } void Sid::setSID(const PSID sid) { if (!IsValidSid(sid)) - throw rdr::Exception("invalid SID in copyPSID"); + throw std::invalid_argument("invalid SID in copyPSID"); resize(GetLengthSid(sid)); if (!CopySid(GetLengthSid(sid), data(), sid)) - throw rdr::Win32Exception("CopySid failed", GetLastError()); + throw rdr::win32_error("CopySid failed", GetLastError()); } void Sid::getUserNameAndDomain(char** name, char** domain) { @@ -117,12 +117,12 @@ void Sid::getUserNameAndDomain(char** name, char** domain) { SID_NAME_USE use; LookupAccountSid(nullptr, (PSID)*this, nullptr, &nameLen, nullptr, &domainLen, &use); if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) - throw rdr::Win32Exception("Unable to determine SID name lengths", GetLastError()); + throw rdr::win32_error("Unable to determine SID name lengths", GetLastError()); vlog.info("nameLen=%lu, domainLen=%lu, use=%d", nameLen, domainLen, use); *name = new char[nameLen]; *domain = new char[domainLen]; if (!LookupAccountSid(nullptr, (PSID)*this, *name, &nameLen, *domain, &domainLen, &use)) - throw rdr::Win32Exception("Unable to lookup account SID", GetLastError()); + throw rdr::win32_error("Unable to lookup account SID", GetLastError()); } @@ -133,7 +133,7 @@ Sid::Administrators::Administrators() { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid)) - throw rdr::Win32Exception("Sid::Administrators", GetLastError()); + throw rdr::win32_error("Sid::Administrators", GetLastError()); setSID(sid); FreeSid(sid); } @@ -144,7 +144,7 @@ Sid::SYSTEM::SYSTEM() { if (!AllocateAndInitializeSid(&ntAuth, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &sid)) - throw rdr::Win32Exception("Sid::SYSTEM", GetLastError()); + throw rdr::win32_error("Sid::SYSTEM", GetLastError()); setSID(sid); FreeSid(sid); } @@ -154,7 +154,7 @@ Sid::FromToken::FromToken(HANDLE h) { GetTokenInformation(h, TokenUser, nullptr, 0, &required); std::vector tmp(required); if (!GetTokenInformation(h, TokenUser, tmp.data(), tmp.size(), &required)) - throw rdr::Win32Exception("GetTokenInformation", GetLastError()); + throw rdr::win32_error("GetTokenInformation", GetLastError()); TOKEN_USER* tokenUser = (TOKEN_USER*)tmp.data(); setSID(tokenUser->User.Sid); } @@ -164,7 +164,7 @@ PACL rfb::win32::CreateACL(const AccessEntries& ae, PACL existing_acl) { PACL new_dacl; DWORD result; if ((result = SetEntriesInAcl(ae.entry_count, ae.entries, existing_acl, &new_dacl)) != ERROR_SUCCESS) - throw rdr::Win32Exception("SetEntriesInAcl", result); + throw rdr::win32_error("SetEntriesInAcl", result); return new_dacl; } @@ -172,18 +172,18 @@ PACL rfb::win32::CreateACL(const AccessEntries& ae, PACL existing_acl) { PSECURITY_DESCRIPTOR rfb::win32::CreateSdWithDacl(const PACL dacl) { SECURITY_DESCRIPTOR absSD; if (!InitializeSecurityDescriptor(&absSD, SECURITY_DESCRIPTOR_REVISION)) - throw rdr::Win32Exception("InitializeSecurityDescriptor", GetLastError()); + throw rdr::win32_error("InitializeSecurityDescriptor", GetLastError()); Sid::SYSTEM owner; if (!SetSecurityDescriptorOwner(&absSD, owner, FALSE)) - throw rdr::Win32Exception("SetSecurityDescriptorOwner", GetLastError()); + throw rdr::win32_error("SetSecurityDescriptorOwner", GetLastError()); Sid::Administrators group; if (!SetSecurityDescriptorGroup(&absSD, group, FALSE)) - throw rdr::Win32Exception("SetSecurityDescriptorGroupp", GetLastError()); + throw rdr::win32_error("SetSecurityDescriptorGroupp", GetLastError()); if (!SetSecurityDescriptorDacl(&absSD, TRUE, dacl, FALSE)) - throw rdr::Win32Exception("SetSecurityDescriptorDacl", GetLastError()); + throw rdr::win32_error("SetSecurityDescriptorDacl", GetLastError()); DWORD sdSize = GetSecurityDescriptorLength(&absSD); SecurityDescriptorPtr sd(sdSize); if (!MakeSelfRelativeSD(&absSD, (PSECURITY_DESCRIPTOR)sd.ptr, &sdSize)) - throw rdr::Win32Exception("MakeSelfRelativeSD", GetLastError()); + throw rdr::win32_error("MakeSelfRelativeSD", GetLastError()); return sd.takeSD(); } diff --git a/win/rfb_win32/Service.cxx b/win/rfb_win32/Service.cxx index be3381da07..907e321425 100644 --- a/win/rfb_win32/Service.cxx +++ b/win/rfb_win32/Service.cxx @@ -115,7 +115,7 @@ Service::start() { vlog.error("unable to set shutdown parameters: %lu", GetLastError()); service = this; if (!StartServiceCtrlDispatcher(entry)) - throw Win32Exception("unable to start service", GetLastError()); + throw win32_error("unable to start service", GetLastError()); } void @@ -335,7 +335,7 @@ bool rfb::win32::registerService(const char* name, // - Open the SCM ServiceHandle scm = OpenSCManager(nullptr, nullptr, SC_MANAGER_CREATE_SERVICE); if (!scm) - throw rdr::Win32Exception("unable to open Service Control Manager", GetLastError()); + throw rdr::win32_error("unable to open Service Control Manager", GetLastError()); // - Add the service ServiceHandle handle = CreateService(scm, @@ -344,7 +344,7 @@ bool rfb::win32::registerService(const char* name, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, cmdline.c_str(), nullptr, nullptr, nullptr, nullptr, nullptr); if (!handle) - throw rdr::Win32Exception("unable to create service", GetLastError()); + throw rdr::win32_error("unable to create service", GetLastError()); // - Set a description SERVICE_DESCRIPTION sdesc = {(LPTSTR)desc}; @@ -380,14 +380,14 @@ bool rfb::win32::unregisterService(const char* name) { // - Open the SCM ServiceHandle scm = OpenSCManager(nullptr, nullptr, SC_MANAGER_CREATE_SERVICE); if (!scm) - throw rdr::Win32Exception("unable to open Service Control Manager", GetLastError()); + throw rdr::win32_error("unable to open Service Control Manager", GetLastError()); // - Create the service ServiceHandle handle = OpenService(scm, name, SC_MANAGER_ALL_ACCESS); if (!handle) - throw rdr::Win32Exception("unable to locate the service", GetLastError()); + throw rdr::win32_error("unable to locate the service", GetLastError()); if (!DeleteService(handle)) - throw rdr::Win32Exception("unable to remove the service", GetLastError()); + throw rdr::win32_error("unable to remove the service", GetLastError()); // - Register the event log source RegKey hk; @@ -407,16 +407,16 @@ bool rfb::win32::startService(const char* name) { // - Open the SCM ServiceHandle scm = OpenSCManager(nullptr, nullptr, SC_MANAGER_CONNECT); if (!scm) - throw rdr::Win32Exception("unable to open Service Control Manager", GetLastError()); + throw rdr::win32_error("unable to open Service Control Manager", GetLastError()); // - Locate the service ServiceHandle handle = OpenService(scm, name, SERVICE_START); if (!handle) - throw rdr::Win32Exception("unable to open the service", GetLastError()); + throw rdr::win32_error("unable to open the service", GetLastError()); // - Start the service if (!StartService(handle, 0, nullptr)) - throw rdr::Win32Exception("unable to start the service", GetLastError()); + throw rdr::win32_error("unable to start the service", GetLastError()); Sleep(500); @@ -427,17 +427,17 @@ bool rfb::win32::stopService(const char* name) { // - Open the SCM ServiceHandle scm = OpenSCManager(nullptr, nullptr, SC_MANAGER_CONNECT); if (!scm) - throw rdr::Win32Exception("unable to open Service Control Manager", GetLastError()); + throw rdr::win32_error("unable to open Service Control Manager", GetLastError()); // - Locate the service ServiceHandle handle = OpenService(scm, name, SERVICE_STOP); if (!handle) - throw rdr::Win32Exception("unable to open the service", GetLastError()); + throw rdr::win32_error("unable to open the service", GetLastError()); // - Start the service SERVICE_STATUS status; if (!ControlService(handle, SERVICE_CONTROL_STOP, &status)) - throw rdr::Win32Exception("unable to stop the service", GetLastError()); + throw rdr::win32_error("unable to stop the service", GetLastError()); Sleep(500); @@ -448,17 +448,17 @@ DWORD rfb::win32::getServiceState(const char* name) { // - Open the SCM ServiceHandle scm = OpenSCManager(nullptr, nullptr, SC_MANAGER_CONNECT); if (!scm) - throw rdr::Win32Exception("unable to open Service Control Manager", GetLastError()); + throw rdr::win32_error("unable to open Service Control Manager", GetLastError()); // - Locate the service ServiceHandle handle = OpenService(scm, name, SERVICE_INTERROGATE); if (!handle) - throw rdr::Win32Exception("unable to open the service", GetLastError()); + throw rdr::win32_error("unable to open the service", GetLastError()); // - Get the service status SERVICE_STATUS status; if (!ControlService(handle, SERVICE_CONTROL_INTERROGATE, (SERVICE_STATUS*)&status)) - throw rdr::Win32Exception("unable to query the service", GetLastError()); + throw rdr::win32_error("unable to query the service", GetLastError()); return status.dwCurrentState; } diff --git a/win/rfb_win32/SocketManager.cxx b/win/rfb_win32/SocketManager.cxx index 2bc2f53e26..b42c66cb5a 100644 --- a/win/rfb_win32/SocketManager.cxx +++ b/win/rfb_win32/SocketManager.cxx @@ -25,6 +25,8 @@ #include #include +#include + #include #include @@ -67,7 +69,7 @@ void SocketManager::addListener(network::SocketListener* sock_, flags |= FD_ADDRESS_LIST_CHANGE; try { if (event && (WSAEventSelect(sock_->getFd(), event, flags) == SOCKET_ERROR)) - throw rdr::SocketException("Unable to select on listener", WSAGetLastError()); + throw rdr::socket_error("Unable to select on listener", WSAGetLastError()); // requestAddressChangeEvents MUST happen after WSAEventSelect, so that the socket is non-blocking if (acn) @@ -75,12 +77,12 @@ void SocketManager::addListener(network::SocketListener* sock_, // addEvent is the last thing we do, so that the event is NOT registered if previous steps fail if (!event || !addEvent(event, this)) - throw rdr::Exception("Unable to add listener"); - } catch (rdr::Exception& e) { + throw std::runtime_error("Unable to add listener"); + } catch (std::exception& e) { if (event) WSACloseEvent(event); delete sock_; - vlog.error("%s", e.str()); + vlog.error("%s", e.what()); throw; } @@ -103,7 +105,7 @@ void SocketManager::remListener(network::SocketListener* sock) { return; } } - throw rdr::Exception("Listener not registered"); + throw std::runtime_error("Listener not registered"); } @@ -136,7 +138,7 @@ void SocketManager::remSocket(network::Socket* sock_) { return; } } - throw rdr::Exception("Socket not registered"); + throw std::runtime_error("Socket not registered"); } bool SocketManager::getDisable(VNCServer* srvr) @@ -147,7 +149,7 @@ bool SocketManager::getDisable(VNCServer* srvr) return i->second.disable; } } - throw rdr::Exception("Listener not registered"); + throw std::runtime_error("Listener not registered"); } void SocketManager::setDisable(VNCServer* srvr, bool disable) @@ -163,7 +165,7 @@ void SocketManager::setDisable(VNCServer* srvr, bool disable) } } if (!found) - throw rdr::Exception("Listener not registered"); + throw std::runtime_error("Listener not registered"); } int SocketManager::checkTimeouts() { @@ -184,7 +186,7 @@ int SocketManager::checkTimeouts() { if (j->second.sock->outStream().hasBufferedData()) eventMask |= FD_WRITE; if (WSAEventSelect(j->second.sock->getFd(), j->first, eventMask) == SOCKET_ERROR) - throw rdr::SocketException("unable to adjust WSAEventSelect:%u", WSAGetLastError()); + throw rdr::socket_error("unable to adjust WSAEventSelect:%u", WSAGetLastError()); } } @@ -234,11 +236,11 @@ void SocketManager::processEvent(HANDLE event) { // Fetch why this event notification triggered if (WSAEnumNetworkEvents(ci.sock->getFd(), event, &network_events) == SOCKET_ERROR) - throw rdr::SocketException("unable to get WSAEnumNetworkEvents:%u", WSAGetLastError()); + throw rdr::socket_error("unable to get WSAEnumNetworkEvents:%u", WSAGetLastError()); // Cancel event notification for this socket if (WSAEventSelect(ci.sock->getFd(), event, 0) == SOCKET_ERROR) - throw rdr::SocketException("unable to disable WSAEventSelect:%u", WSAGetLastError()); + throw rdr::socket_error("unable to disable WSAEventSelect:%u", WSAGetLastError()); // Reset the event object WSAResetEvent(event); @@ -266,9 +268,9 @@ void SocketManager::processEvent(HANDLE event) { if (ci.sock->outStream().hasBufferedData()) eventMask |= FD_WRITE; if (WSAEventSelect(ci.sock->getFd(), event, eventMask) == SOCKET_ERROR) - throw rdr::SocketException("unable to re-enable WSAEventSelect:%u", WSAGetLastError()); - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + throw rdr::socket_error("unable to re-enable WSAEventSelect:%u", WSAGetLastError()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); remSocket(ci.sock); } } diff --git a/win/rfb_win32/TsSessions.cxx b/win/rfb_win32/TsSessions.cxx index a8602ad2b1..faf83e894c 100644 --- a/win/rfb_win32/TsSessions.cxx +++ b/win/rfb_win32/TsSessions.cxx @@ -35,7 +35,7 @@ namespace win32 { if (processId == (DWORD)-1) processId = GetCurrentProcessId(); if (!ProcessIdToSessionId(GetCurrentProcessId(), &id)) - throw rdr::Win32Exception("ProcessIdToSessionId", GetLastError()); + throw rdr::win32_error("ProcessIdToSessionId", GetLastError()); } ProcessSessionId mySessionId; @@ -57,7 +57,7 @@ namespace win32 { ConsoleSessionId console; vlog.info("Console session is %lu", console.id); if (!WTSConnectSession(sessionId, console.id, (PTSTR)"", 0)) - throw rdr::Win32Exception("Unable to connect session to Console", GetLastError()); + throw rdr::win32_error("Unable to connect session to Console", GetLastError()); // Lock the newly connected session, for security LockWorkStation(); diff --git a/win/rfb_win32/WMCursor.cxx b/win/rfb_win32/WMCursor.cxx index 603c7bc3e9..65d7a9d7bf 100644 --- a/win/rfb_win32/WMCursor.cxx +++ b/win/rfb_win32/WMCursor.cxx @@ -45,7 +45,7 @@ WMCursor::getCursorInfo() { CURSORINFO info; info.cbSize = sizeof(CURSORINFO); if (!GetCursorInfo(&info)) - throw rdr::Win32Exception("GetCursorInfo failed", GetLastError()); + throw rdr::win32_error("GetCursorInfo failed", GetLastError()); result.cursor = info.hCursor; result.position = Point(info.ptScreenPos.x, info.ptScreenPos.y); result.visible = info.flags & CURSOR_SHOWING; diff --git a/win/rfb_win32/WMPoller.cxx b/win/rfb_win32/WMPoller.cxx index 2c5917e96c..98e8dce340 100644 --- a/win/rfb_win32/WMPoller.cxx +++ b/win/rfb_win32/WMPoller.cxx @@ -22,8 +22,9 @@ #include #endif +#include + #include -#include #include #include @@ -57,7 +58,7 @@ bool rfb::win32::WMPoller::checkPollWindow(HWND w) { char buffer[128]; if (!GetClassName(w, buffer, 128)) - throw rdr::Win32Exception("unable to get window class:%u", GetLastError()); + throw rdr::win32_error("unable to get window class:%u", GetLastError()); if ((strcmp(buffer, "tty") != 0) && (strcmp(buffer, "ConsoleWindowClass") != 0)) { return false; diff --git a/win/rfb_win32/Win32Util.cxx b/win/rfb_win32/Win32Util.cxx index f7b5b6c731..b35bf6291f 100644 --- a/win/rfb_win32/Win32Util.cxx +++ b/win/rfb_win32/Win32Util.cxx @@ -46,19 +46,19 @@ FileVersionInfo::FileVersionInfo(const char* filename) { { Handle file(CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); if (file.h == INVALID_HANDLE_VALUE) - throw rdr::Win32Exception("Failed to open file", GetLastError()); + throw rdr::win32_error("Failed to open file", GetLastError()); } // Get version info size DWORD handle; int size = GetFileVersionInfoSize((char*)filename, &handle); if (!size) - throw rdr::Win32Exception("GetVersionInfoSize failed", GetLastError()); + throw rdr::win32_error("GetVersionInfoSize failed", GetLastError()); // Get version info buf = new char[size]; if (!GetFileVersionInfo((char*)filename, handle, size, buf)) - throw rdr::Win32Exception("GetVersionInfo failed", GetLastError()); + throw rdr::win32_error("GetVersionInfo failed", GetLastError()); } FileVersionInfo::~FileVersionInfo() { @@ -81,7 +81,7 @@ const char* FileVersionInfo::getVerString(const char* name, DWORD langId) { UINT length = 0; if (!VerQueryValue(buf, infoName.c_str(), (void**)&buffer, &length)) { printf("unable to find %s version string", infoName.c_str()); - throw rdr::Exception("VerQueryValue failed"); + throw std::runtime_error("VerQueryValue failed"); } return buffer; } diff --git a/win/vncconfig/Connections.h b/win/vncconfig/Connections.h index a540bd760b..dfa5c79f0a 100644 --- a/win/vncconfig/Connections.h +++ b/win/vncconfig/Connections.h @@ -73,8 +73,8 @@ namespace rfb { try { network::TcpFilter::Pattern pat(network::TcpFilter::parsePattern(newPat.c_str())); pattern = network::TcpFilter::patternToStr(pat); - } catch(rdr::Exception& e) { - MsgBox(nullptr, e.str(), MB_ICONEXCLAMATION | MB_OK); + } catch(std::exception& e) { + MsgBox(nullptr, e.what(), MB_ICONEXCLAMATION | MB_OK); return false; } return true; @@ -235,7 +235,7 @@ namespace rfb { (localHost != isItemChecked(IDC_LOCALHOST)) || (port_number != getItemInt(IDC_PORT)) || (rfb::Server::idleTimeout != getItemInt(IDC_IDLE_TIMEOUT)); - } catch (rdr::Exception&) { + } catch (std::exception&) { return false; } } diff --git a/win/vncconfig/Legacy.cxx b/win/vncconfig/Legacy.cxx index 9300bb051c..c6b245cc0b 100644 --- a/win/vncconfig/Legacy.cxx +++ b/win/vncconfig/Legacy.cxx @@ -42,7 +42,7 @@ void LegacyPage::LoadPrefs() std::string username; try { username = UserName(); - } catch (rdr::Win32Exception& e) { + } catch (rdr::win32_error& e) { if (e.err != ERROR_NOT_LOGGED_ON) throw; } @@ -85,7 +85,7 @@ void LegacyPage::LoadPrefs() if (bits) strcat(pattern, "."); if (parts[j].size() > 3) - throw rdr::Exception("Invalid IP address part"); + throw std::invalid_argument("Invalid IP address part"); if (!parts[j].empty()) { strcat(pattern, parts[j].c_str()); bits += 8; @@ -114,7 +114,7 @@ void LegacyPage::LoadPrefs() // Finally, save the Hosts value regKey.setString("Hosts", newHosts.c_str()); - } catch (rdr::Exception&) { + } catch (std::exception&) { MsgBox(nullptr, "Unable to convert AuthHosts setting to Hosts format.", MB_ICONWARNING | MB_OK); } @@ -135,7 +135,7 @@ void LegacyPage::LoadPrefs() regKey.setBool("AlwaysShared", connectPriority == 1); regKey.setBool("NeverShared", connectPriority == 2); - } catch(rdr::Exception&) { + } catch(std::exception&) { } // Open the local, default-user settings @@ -145,8 +145,8 @@ void LegacyPage::LoadPrefs() userKey.openKey(winvnc3, "Default"); vlog.info("loading Default prefs"); LoadUserPrefs(userKey); - } catch(rdr::Exception& e) { - vlog.error("error reading Default settings:%s", e.str()); + } catch(std::exception& e) { + vlog.error("error reading Default settings:%s", e.what()); } // Open the local, user-specific settings @@ -156,8 +156,8 @@ void LegacyPage::LoadPrefs() userKey.openKey(winvnc3, username.c_str()); vlog.info("loading local User prefs"); LoadUserPrefs(userKey); - } catch(rdr::Exception& e) { - vlog.error("error reading local User settings:%s", e.str()); + } catch(std::exception& e) { + vlog.error("error reading local User settings:%s", e.what()); } // Open the user's own settings @@ -167,8 +167,8 @@ void LegacyPage::LoadPrefs() userKey.openKey(HKEY_CURRENT_USER, "Software\\ORL\\WinVNC3"); vlog.info("loading global User prefs"); LoadUserPrefs(userKey); - } catch(rdr::Exception& e) { - vlog.error("error reading global User settings:%s", e.str()); + } catch(std::exception& e) { + vlog.error("error reading global User settings:%s", e.what()); } } } diff --git a/win/vncconfig/vncconfig.cxx b/win/vncconfig/vncconfig.cxx index 55f01d2e3f..7e692b9b76 100644 --- a/win/vncconfig/vncconfig.cxx +++ b/win/vncconfig/vncconfig.cxx @@ -125,7 +125,7 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE /*prev*/, char* /*cmdLine*/, int /* // Set the DACL, and don't allow the key to inherit its parent's DACL rootKey.setDACL(acl, false); - } catch (rdr::Win32Exception& e) { + } catch (rdr::win32_error& e) { // Something weird happens on NT 4.0 SP5 but I can't reproduce it on other // NT 4.0 service pack revisions. if (e.err == ERROR_INVALID_PARAMETER) { @@ -169,7 +169,7 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE /*prev*/, char* /*cmdLine*/, int /* #else sheet.showPropSheet(nullptr, true, false); #endif - } catch (rdr::Win32Exception& e) { + } catch (rdr::win32_error& e) { switch (e.err) { case ERROR_ACCESS_DENIED: MsgBox(nullptr, "You do not have sufficient access rights to run the VNC Configuration applet", @@ -179,8 +179,8 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE /*prev*/, char* /*cmdLine*/, int /* throw; } - } catch (rdr::Exception& e) { - MsgBox(nullptr, e.str(), MB_ICONEXCLAMATION | MB_OK); + } catch (std::exception& e) { + MsgBox(nullptr, e.what(), MB_ICONEXCLAMATION | MB_OK); return 1; } diff --git a/win/winvnc/ManagedListener.cxx b/win/winvnc/ManagedListener.cxx index adc074cf5f..78f383a608 100644 --- a/win/winvnc/ManagedListener.cxx +++ b/win/winvnc/ManagedListener.cxx @@ -100,8 +100,8 @@ void ManagedListener::refresh() { else network::createTcpListeners(&sockets, nullptr, port); } - } catch (rdr::Exception& e) { - vlog.error("%s", e.str()); + } catch (std::exception& e) { + vlog.error("%s", e.what()); } if (!sockets.empty()) { if (!localOnly) { diff --git a/win/winvnc/QueryConnectDialog.cxx b/win/winvnc/QueryConnectDialog.cxx index 24918b2a1c..1ef26e6380 100644 --- a/win/winvnc/QueryConnectDialog.cxx +++ b/win/winvnc/QueryConnectDialog.cxx @@ -60,7 +60,7 @@ void QueryConnectDialog::worker() { countdown = timeout; try { if (desktopChangeRequired() && !changeDesktop()) - throw rdr::Exception("changeDesktop failed"); + throw std::runtime_error("changeDesktop failed"); approve = Dialog::showDialog(MAKEINTRESOURCE(IDD_QUERY_CONNECT)); server->queryConnectionComplete(); } catch (...) { @@ -74,7 +74,7 @@ void QueryConnectDialog::worker() { void QueryConnectDialog::initDialog() { if (!SetTimer(handle, 1, 1000, nullptr)) - throw rdr::Win32Exception("SetTimer", GetLastError()); + throw rdr::win32_error("SetTimer", GetLastError()); setItemString(IDC_QUERY_HOST, peerIp.c_str()); if (userName.empty()) userName = "(anonymous)"; diff --git a/win/winvnc/STrayIcon.cxx b/win/winvnc/STrayIcon.cxx index d703f47a08..4420b57425 100644 --- a/win/winvnc/STrayIcon.cxx +++ b/win/winvnc/STrayIcon.cxx @@ -159,8 +159,8 @@ class STrayIcon : public TrayIcon { if (isServiceProcess()) { try { rfb::win32::stopService(VNCServerService::Name); - } catch (rdr::Exception& e) { - MsgBox(nullptr, e.str(), MB_ICONERROR | MB_OK); + } catch (std::exception& e) { + MsgBox(nullptr, e.what(), MB_ICONERROR | MB_OK); } } else { thread.server.stop(); diff --git a/win/winvnc/VNCServerWin32.cxx b/win/winvnc/VNCServerWin32.cxx index c1545ab6ee..cea0fe7837 100644 --- a/win/winvnc/VNCServerWin32.cxx +++ b/win/winvnc/VNCServerWin32.cxx @@ -188,7 +188,7 @@ int VNCServerWin32::run() { while (runServer) { result = sockMgr.getMessage(&msg, nullptr, 0, 0); if (result < 0) - throw rdr::Win32Exception("getMessage", GetLastError()); + throw rdr::win32_error("getMessage", GetLastError()); if (!isServiceProcess() && (result == 0)) break; TranslateMessage(&msg); @@ -196,11 +196,11 @@ int VNCServerWin32::run() { } vlog.debug("Server exited cleanly"); - } catch (rdr::Win32Exception &s) { - vlog.error("%s", s.str()); + } catch (rdr::win32_error &s) { + vlog.error("%s", s.what()); result = s.err; - } catch (rdr::Exception &e) { - vlog.error("%s", e.str()); + } catch (std::exception &e) { + vlog.error("%s", e.what()); } { diff --git a/win/winvnc/winvnc.cxx b/win/winvnc/winvnc.cxx index ceee0c6f2e..1a370522de 100644 --- a/win/winvnc/winvnc.cxx +++ b/win/winvnc/winvnc.cxx @@ -119,7 +119,7 @@ static void processParams(int argc, char** argv) { if (host != nullptr) { HWND hwnd = FindWindow(nullptr, "winvnc::IPC_Interface"); if (!hwnd) - throw rdr::Exception("Unable to locate existing VNC Server."); + throw std::runtime_error("Unable to locate existing VNC Server."); COPYDATASTRUCT copyData; copyData.dwData = 1; // *** AddNewClient copyData.cbData = strlen(host); @@ -132,7 +132,7 @@ static void processParams(int argc, char** argv) { runServer = false; HWND hwnd = FindWindow(nullptr, "winvnc::IPC_Interface"); if (!hwnd) - throw rdr::Exception("Unable to locate existing VNC Server."); + throw std::runtime_error("Unable to locate existing VNC Server."); COPYDATASTRUCT copyData; copyData.dwData = 2; // *** DisconnectClients copyData.lpData = nullptr; @@ -177,13 +177,13 @@ static void processParams(int argc, char** argv) { // Try to clean up earlier services we've had try { rfb::win32::unregisterService("WinVNC4"); - } catch (rdr::Win32Exception&) { + } catch (rdr::win32_error&) { // Do nothing as we might fail simply because there was no // service to remove } try { rfb::win32::unregisterService("TigerVNC Server"); - } catch (rdr::Win32Exception&) { + } catch (rdr::win32_error&) { } if (rfb::win32::registerService(VNCServerService::Name, @@ -228,8 +228,8 @@ static void processParams(int argc, char** argv) { break; } - } catch (rdr::Exception& e) { - MsgBoxOrLog(e.str(), true); + } catch (std::exception& e) { + MsgBoxOrLog(e.what(), true); } } } @@ -284,8 +284,8 @@ int WINAPI WinMain(HINSTANCE /*inst*/, HINSTANCE /*prevInst*/, char* /*cmdLine*/ } vlog.debug("WinVNC service destroyed"); - } catch (rdr::Exception& e) { - MsgBoxOrLog(e.str(), true); + } catch (std::exception& e) { + MsgBoxOrLog(e.what(), true); } vlog.debug("WinVNC process quitting");