#include <network/TcpSocket.h>
#include <rfb/LogWriter.h>
#include <rfb/Configuration.h>
+#include <rfb/util.h>
#ifdef WIN32
#include <os/winerrno.h>
supportsDesktopResize(false), supportsLEDState(false),
is(0), os(0), reader_(0), writer_(0),
shared(false),
- state_(RFBSTATE_UNINITIALISED), serverName(strDup("")),
+ state_(RFBSTATE_UNINITIALISED),
pendingPFChange(false), preferredEncoding(encodingTight),
compressLevel(2), qualityLevel(-1),
formatChange(false), encodingChange(false),
{
if (name_ == NULL)
name_ = "";
- serverName.replaceBuf(strDup(name_));
+ serverName = name_;
}
void CConnection::setStreams(rdr::InStream* is_, rdr::OutStream* os_)
#include <rfb/CMsgHandler.h>
#include <rfb/DecodeManager.h>
#include <rfb/SecurityClient.h>
-#include <rfb/util.h>
namespace rfb {
// Access method used by SSecurity implementations that can verify servers'
// Identities, to determine the unique(ish) name of the server.
- const char* getServerName() const { return serverName.buf; }
+ const char* getServerName() const { return serverName.c_str(); }
bool isSecure() const { return csecurity ? csecurity->isSecure() : false; }
bool shared;
stateEnum state_;
- CharArray serverName;
+ std::string serverName;
bool pendingPFChange;
rfb::PixelFormat pendingPF;
Logger.cxx
Logger_file.cxx
Logger_stdio.cxx
- Password.cxx
PixelBuffer.cxx
PixelFormat.cxx
RREEncoder.cxx
ZRLEEncoder.cxx
ZRLEDecoder.cxx
encodings.cxx
+ obfuscate.cxx
util.cxx)
target_link_libraries(rfb os rdr)
sha1_update(&ctx, serverKey.size, serverKeyE);
sha1_digest(&ctx, sizeof(f), f);
const char *title = "Server key fingerprint";
- CharArray text;
- text.format(
+ std::string text = strFormat(
"The server has provided the following identifying information:\n"
"Fingerprint: %02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x\n"
"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 (!msg->showMsgBox(UserMsgBox::M_YESNO, title, text.buf))
+ if (!msg->showMsgBox(UserMsgBox::M_YESNO, title, text.c_str()))
throw AuthFailureException("server key mismatch");
}
throw AuthFailureException("decoding of certificate failed");
if (gnutls_x509_crt_check_hostname(crt, client->getServerName()) == 0) {
- CharArray text;
+ std::string text;
vlog.debug("hostname mismatch");
- text.format("Hostname (%s) does not match the server certificate, "
- "do you want to continue?", client->getServerName());
+ text = strFormat("Hostname (%s) does not match the server "
+ "certificate, do you want to continue?",
+ client->getServerName());
if (!msg->showMsgBox(UserMsgBox::M_YESNO,
- "Certificate hostname mismatch", text.buf))
+ "Certificate hostname mismatch",
+ text.c_str()))
throw AuthFailureException("Certificate hostname mismatch");
}
"path for known hosts storage");
}
- CharArray dbPath(strlen(homeDir) + strlen("/x509_known_hosts") + 1);
- sprintf(dbPath.buf, "%s/x509_known_hosts", homeDir);
+ std::string dbPath;
+ dbPath = (std::string)homeDir + "/x509_known_hosts";
- err = gnutls_verify_stored_pubkey(dbPath.buf, NULL,
+ err = gnutls_verify_stored_pubkey(dbPath.c_str(), NULL,
client->getServerName(), NULL,
GNUTLS_CRT_X509, &cert_list[0], 0);
/* New host */
if (err == GNUTLS_E_NO_CERTIFICATE_FOUND) {
- CharArray text;
+ std::string text;
vlog.debug("Server host not previously known");
vlog.debug("%s", info.data);
if (status & (GNUTLS_CERT_SIGNER_NOT_FOUND |
GNUTLS_CERT_SIGNER_NOT_CA)) {
- text.format("This certificate has been signed by an unknown "
- "authority:\n\n%s\n\nSomeone could be trying to "
- "impersonate the site and you should not "
- "continue.\n\nDo you want to make an exception "
- "for this server?", info.data);
+ text = strFormat("This certificate has been signed by an "
+ "unknown authority:\n"
+ "\n"
+ "%s\n"
+ "\n"
+ "Someone could be trying to impersonate the "
+ "site and you should not continue.\n"
+ "\n"
+ "Do you want to make an exception for this "
+ "server?", info.data);
if (!msg->showMsgBox(UserMsgBox::M_YESNO,
"Unknown certificate issuer",
- text.buf))
+ text.c_str()))
throw AuthFailureException("Unknown certificate issuer");
}
if (status & GNUTLS_CERT_EXPIRED) {
- text.format("This certificate has expired:\n\n%s\n\nSomeone "
- "could be trying to impersonate the site and you "
- "should not continue.\n\nDo you want to make an "
- "exception for this server?", info.data);
+ text = strFormat("This certificate has expired:\n"
+ "\n"
+ "%s\n"
+ "\n"
+ "Someone could be trying to impersonate the "
+ "site and you should not continue.\n"
+ "\n"
+ "Do you want to make an exception for this "
+ "server?", info.data);
if (!msg->showMsgBox(UserMsgBox::M_YESNO,
"Expired certificate",
- text.buf))
+ text.c_str()))
throw AuthFailureException("Expired certificate");
}
} else if (err == GNUTLS_E_CERTIFICATE_KEY_MISMATCH) {
- CharArray text;
+ std::string text;
vlog.debug("Server host key mismatch");
vlog.debug("%s", info.data);
if (status & (GNUTLS_CERT_SIGNER_NOT_FOUND |
GNUTLS_CERT_SIGNER_NOT_CA)) {
- text.format("This host is previously known with a different "
- "certificate, and the new certificate has been "
- "signed by an unknown authority:\n\n%s\n\nSomeone "
- "could be trying to impersonate the site and you "
- "should not continue.\n\nDo you want to make an "
- "exception for this server?", info.data);
+ text = strFormat("This host is previously known with a "
+ "different certificate, and the new "
+ "certificate has been signed by an "
+ "unknown authority:\n"
+ "\n"
+ "%s\n"
+ "\n"
+ "Someone could be trying to impersonate the "
+ "site and you should not continue.\n"
+ "\n"
+ "Do you want to make an exception for this "
+ "server?", info.data);
if (!msg->showMsgBox(UserMsgBox::M_YESNO,
"Unexpected server certificate",
- text.buf))
+ text.c_str()))
throw AuthFailureException("Unexpected server certificate");
}
if (status & GNUTLS_CERT_EXPIRED) {
- text.format("This host is previously known with a different "
- "certificate, and the new certificate has expired:"
- "\n\n%s\n\nSomeone could be trying to impersonate "
- "the site and you should not continue.\n\nDo you "
- "want to make an exception for this server?",
- info.data);
+ text = strFormat("This host is previously known with a "
+ "different certificate, and the new "
+ "certificate has expired:\n"
+ "\n"
+ "%s\n"
+ "\n"
+ "Someone could be trying to impersonate the "
+ "site and you should not continue.\n"
+ "\n"
+ "Do you want to make an exception for this "
+ "server?", info.data);
if (!msg->showMsgBox(UserMsgBox::M_YESNO,
"Unexpected server certificate",
- text.buf))
+ text.c_str()))
throw AuthFailureException("Unexpected server certificate");
}
}
- if (gnutls_store_pubkey(dbPath.buf, NULL, client->getServerName(),
+ if (gnutls_store_pubkey(dbPath.c_str(), NULL, client->getServerName(),
NULL, GNUTLS_CRT_X509, &cert_list[0], 0, 0))
vlog.error("Failed to store server certificate to known hosts database");
void Configuration::list(int width, int nameWidth) {
VoidParameter* current = head;
- fprintf(stderr, "%s Parameters:\n", name.buf);
+ fprintf(stderr, "%s Parameters:\n", name.c_str());
while (current) {
std::string def_str = current->getDefaultStr();
const char* desc = current->getDescription();
#ifndef __RFB_CONFIGURATION_H__
#define __RFB_CONFIGURATION_H__
-#include <vector>
+#include <limits.h>
+#include <stdint.h>
-#include <rfb/util.h>
+#include <string>
+#include <vector>
namespace os { class Mutex; }
class Configuration {
public:
// - Create a new Configuration object
- Configuration(const char* name_) : name(strDup(name_)), head(0), _next(0) {}
+ Configuration(const char* name_) : name(name_), head(0), _next(0) {}
// - Return the buffer containing the Configuration's name
- const char* getName() const { return name.buf; }
+ const char* getName() const { return name.c_str(); }
// - Set named parameter to value
bool set(const char* param, const char* value, bool immutable=false);
friend struct ParameterIterator;
// Name for this Configuration
- CharArray name;
+ std::string name;
// - Pointer to first Parameter in this group
VoidParameter* head;
#endif
#include <assert.h>
+#include <string.h>
#include <sys/time.h>
#ifdef __linux__
#endif
#include <stdio.h>
+#include <string.h>
#include <os/Mutex.h>
+++ /dev/null
-/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
- *
- * This is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this software; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
- * USA.
- */
-
-//
-// XXX not thread-safe, because d3des isn't - do we need to worry about this?
-//
-
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
-#include <string.h>
-#include <stdint.h>
-extern "C" {
-#include <rfb/d3des.h>
-}
-
-#include <rdr/Exception.h>
-#include <rfb/Password.h>
-
-using namespace rfb;
-
-static unsigned char d3desObfuscationKey[] = {23,82,107,6,35,78,88,7};
-
-
-PlainPasswd::PlainPasswd() {}
-
-PlainPasswd::PlainPasswd(char* pwd) : CharArray(pwd) {
-}
-
-PlainPasswd::PlainPasswd(size_t len) : CharArray(len) {
-}
-
-PlainPasswd::PlainPasswd(const ObfuscatedPasswd& obfPwd) : CharArray(9) {
- if (obfPwd.length < 8)
- throw rdr::Exception("bad obfuscated password length");
- deskey(d3desObfuscationKey, DE1);
- des((uint8_t*)obfPwd.buf, (uint8_t*)buf);
- buf[8] = 0;
-}
-
-PlainPasswd::~PlainPasswd() {
- replaceBuf(0);
-}
-
-void PlainPasswd::replaceBuf(char* b) {
- if (buf)
- memset(buf, 0, strlen(buf));
- CharArray::replaceBuf(b);
-}
-
-
-ObfuscatedPasswd::ObfuscatedPasswd() : length(0) {
-}
-
-ObfuscatedPasswd::ObfuscatedPasswd(size_t len) : CharArray(len), length(len) {
-}
-
-ObfuscatedPasswd::ObfuscatedPasswd(const PlainPasswd& plainPwd) : CharArray(8), length(8) {
- size_t l = strlen(plainPwd.buf), i;
- for (i=0; i<8; i++)
- buf[i] = i<l ? plainPwd.buf[i] : 0;
- deskey(d3desObfuscationKey, EN0);
- des((uint8_t*)buf, (uint8_t*)buf);
-}
-
-ObfuscatedPasswd::~ObfuscatedPasswd() {
- if (buf)
- memset(buf, 0, length);
-}
+++ /dev/null
-/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
- *
- * This is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this software; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
- * USA.
- */
-#ifndef __RFB_PASSWORD_H__
-#define __RFB_PASSWORD_H__
-
-#include <rfb/util.h>
-
-namespace rfb {
-
- class ObfuscatedPasswd;
-
- class PlainPasswd : public CharArray {
- public:
- PlainPasswd();
- PlainPasswd(char* pwd);
- PlainPasswd(size_t len);
- PlainPasswd(const ObfuscatedPasswd& obfPwd);
- ~PlainPasswd();
- void replaceBuf(char* b);
- };
-
- class ObfuscatedPasswd : public CharArray {
- public:
- ObfuscatedPasswd();
- ObfuscatedPasswd(size_t l);
- ObfuscatedPasswd(const PlainPasswd& plainPwd);
- ~ObfuscatedPasswd();
- size_t length;
- };
-
-}
-#endif
state_ = RFBSTATE_SECURITY_FAILURE;
// Introduce a slight delay of the authentication failure response
// to make it difficult to brute force a password
- authFailureMsg.replaceBuf(strDup(e.str()));
+ authFailureMsg = e.str();
authFailureTimer.start(100);
return true;
}
try {
os->writeU32(secResultFailed);
if (!client.beforeVersion(3,8)) { // 3.8 onwards have failure message
- const char* reason = authFailureMsg.buf;
- os->writeU32(strlen(reason));
- os->writeBytes(reason, strlen(reason));
+ os->writeU32(authFailureMsg.size());
+ os->writeBytes(authFailureMsg.data(), authFailureMsg.size());
}
os->flush();
} catch (rdr::Exception& e) {
return false;
}
- close(authFailureMsg.buf);
+ close(authFailureMsg.c_str());
return false;
}
SSecurity* ssecurity;
MethodTimer<SConnection> authFailureTimer;
- CharArray authFailureMsg;
+ std::string authFailureMsg;
stateEnum state_;
int32_t preferredEncoding;
void SSecurityRSAAES::verifyPass()
{
VncAuthPasswdGetter* pg = &SSecurityVncAuth::vncAuthPasswd;
- PlainPasswd passwd, passwdReadOnly;
+ std::string passwd, passwdReadOnly;
pg->getVncAuthPasswd(&passwd, &passwdReadOnly);
- if (!passwd.buf)
+ if (passwd.empty())
throw AuthFailureException("No password configured for VNC Auth");
- if (strcmp(password, passwd.buf) == 0) {
+ if (password == passwd) {
accessRights = SConnection::AccessDefault;
return;
}
- if (passwdReadOnly.buf && strcmp(password, passwdReadOnly.buf) == 0) {
+ if (!passwdReadOnly.empty() && password == passwdReadOnly) {
accessRights = SConnection::AccessView;
return;
}
#include <rfb/SSecurityVncAuth.h>
#include <rdr/RandomStream.h>
#include <rfb/SConnection.h>
-#include <rfb/Password.h>
#include <rfb/Configuration.h>
#include <rfb/LogWriter.h>
#include <rfb/Exception.h>
+#include <rfb/obfuscate.h>
+#include <assert.h>
#include <string.h>
#include <stdio.h>
extern "C" {
{
}
-bool SSecurityVncAuth::verifyResponse(const PlainPasswd &password)
+bool SSecurityVncAuth::verifyResponse(const char* password)
{
uint8_t expectedResponse[vncAuthChallengeSize];
// Calculate the expected response
uint8_t key[8];
- int pwdLen = strlen(password.buf);
+ int pwdLen = strlen(password);
for (int i=0; i<8; i++)
- key[i] = i<pwdLen ? password.buf[i] : 0;
+ key[i] = i<pwdLen ? password[i] : 0;
deskey(key, EN0);
for (int j = 0; j < vncAuthChallengeSize; j += 8)
des(challenge+j, expectedResponse+j);
is->readBytes(response, vncAuthChallengeSize);
- PlainPasswd passwd, passwdReadOnly;
+ std::string passwd, passwdReadOnly;
pg->getVncAuthPasswd(&passwd, &passwdReadOnly);
- if (!passwd.buf)
+ if (passwd.empty())
throw AuthFailureException("No password configured for VNC Auth");
- if (verifyResponse(passwd)) {
+ if (verifyResponse(passwd.c_str())) {
accessRights = SConnection::AccessDefault;
return true;
}
- if (passwdReadOnly.buf && verifyResponse(passwdReadOnly)) {
+ if (!passwdReadOnly.empty() &&
+ verifyResponse(passwdReadOnly.c_str())) {
accessRights = SConnection::AccessView;
return true;
}
: BinaryParameter(name, desc, 0, 0, ConfServer), passwdFile(passwdFile_) {
}
-void VncAuthPasswdParameter::getVncAuthPasswd(PlainPasswd *password, PlainPasswd *readOnlyPassword) {
- ObfuscatedPasswd obfuscated, obfuscatedReadOnly;
- std::vector<uint8_t> data = getData();
- obfuscated.length = data.size();
- if (!data.empty()) {
- obfuscated.buf = new char[data.size()];
- memcpy(obfuscated.buf, data.data(), data.size());
- }
+void VncAuthPasswdParameter::getVncAuthPasswd(std::string *password, std::string *readOnlyPassword) {
+ std::vector<uint8_t> obfuscated, obfuscatedReadOnly;
+ obfuscated = getData();
- if (obfuscated.length == 0) {
+ if (obfuscated.size() == 0) {
if (passwdFile) {
const char *fname = *passwdFile;
if (!fname[0]) {
}
vlog.debug("reading password file");
- obfuscated.buf = new char[8];
- obfuscated.length = fread(obfuscated.buf, 1, 8, fp);
- obfuscatedReadOnly.buf = new char[8];
- obfuscatedReadOnly.length = fread(obfuscatedReadOnly.buf, 1, 8, fp);
+ obfuscated.resize(8);
+ obfuscated.resize(fread(obfuscated.data(), 1, 8, fp));
+ obfuscatedReadOnly.resize(8);
+ obfuscatedReadOnly.resize(fread(obfuscatedReadOnly.data(), 1, 8, fp));
fclose(fp);
} else {
vlog.info("%s parameter not set", getName());
}
}
+ assert(password != NULL);
+ assert(readOnlyPassword != NULL);
+
try {
- PlainPasswd plainPassword(obfuscated);
- password->replaceBuf(plainPassword.takeBuf());
- PlainPasswd plainPasswordReadOnly(obfuscatedReadOnly);
- readOnlyPassword->replaceBuf(plainPasswordReadOnly.takeBuf());
+ *password = deobfuscate(obfuscated.data(), obfuscated.size());
+ *readOnlyPassword = deobfuscate(obfuscatedReadOnly.data(), obfuscatedReadOnly.size());
} catch (...) {
}
}
#include <stdint.h>
#include <rfb/Configuration.h>
-#include <rfb/Password.h>
#include <rfb/SSecurity.h>
#include <rfb/Security.h>
public:
// getVncAuthPasswd() fills buffer of given password and readOnlyPassword.
// If there was no read only password in the file, readOnlyPassword buffer is null.
- virtual void getVncAuthPasswd(PlainPasswd *password, PlainPasswd *readOnlyPassword)=0;
+ virtual void getVncAuthPasswd(std::string *password, std::string *readOnlyPassword)=0;
virtual ~VncAuthPasswdGetter() { }
};
class VncAuthPasswdParameter : public VncAuthPasswdGetter, BinaryParameter {
public:
VncAuthPasswdParameter(const char* name, const char* desc, StringParameter* passwdFile_);
- virtual void getVncAuthPasswd(PlainPasswd *password, PlainPasswd *readOnlyPassword);
+ virtual void getVncAuthPasswd(std::string *password, std::string *readOnlyPassword);
protected:
StringParameter* passwdFile;
};
static StringParameter vncAuthPasswdFile;
static VncAuthPasswdParameter vncAuthPasswd;
private:
- bool verifyResponse(const PlainPasswd &password);
+ bool verifyResponse(const char* password);
enum {vncAuthChallengeSize = 16};
uint8_t challenge[vncAuthChallengeSize];
uint8_t response[vncAuthChallengeSize];
pointerEventTime(0), clientHasCursor(false)
{
setStreams(&sock->inStream(), &sock->outStream());
- peerEndpoint.buf = strDup(sock->getPeerEndpoint());
+ peerEndpoint = sock->getPeerEndpoint();
// Kick off the idle timer
if (rfb::Server::idleTimeout) {
VNCSConnectionST::~VNCSConnectionST()
{
// If we reach here then VNCServerST is deleting us!
- if (closeReason.buf)
- vlog.info("closing %s: %s", peerEndpoint.buf, closeReason.buf);
+ if (!closeReason.empty())
+ vlog.info("closing %s: %s", peerEndpoint.c_str(),
+ closeReason.c_str());
// Release any keys the client still had pressed
while (!pressedKeys.empty()) {
SConnection::close(reason);
// Log the reason for the close
- if (!closeReason.buf)
- closeReason.buf = strDup(reason);
+ if (closeReason.empty())
+ closeReason = reason;
else
- vlog.debug("second close: %s (%s)", peerEndpoint.buf, reason);
+ vlog.debug("second close: %s (%s)", peerEndpoint.c_str(), reason);
try {
if (sock->outStream().hasBufferedData()) {
updates.add_copied(dest, delta);
}
- const char* getPeerEndpoint() const {return peerEndpoint.buf;}
+ const char* getPeerEndpoint() const {return peerEndpoint.c_str();}
private:
// SConnection callbacks
private:
network::Socket* sock;
- CharArray peerEndpoint;
+ std::string peerEndpoint;
bool reverseConnection;
bool inProcessMessages;
Point pointerEventPos;
bool clientHasCursor;
- CharArray closeReason;
+ std::string closeReason;
};
}
#endif
VNCServerST::VNCServerST(const char* name_, SDesktop* desktop_)
: blHosts(&blacklist), desktop(desktop_), desktopStarted(false),
blockCounter(0), pb(0), ledState(ledUnknown),
- name(strDup(name_)), pointerClient(0), clipboardClient(0),
+ name(name_), pointerClient(0), clipboardClient(0),
comparer(0), cursor(new Cursor(0, 0, Point(), NULL)),
renderedCursorInvalid(false),
keyRemapper(&KeyRemapper::defInstance),
idleTimer(this), disconnectTimer(this), connectTimer(this),
frameTimer(this)
{
- slog.debug("creating single-threaded server %s", name.buf);
+ slog.debug("creating single-threaded server %s", name.c_str());
// FIXME: Do we really want to kick off these right away?
if (rfb::Server::maxIdleTime)
VNCServerST::~VNCServerST()
{
- slog.debug("shutting down server %s", name.buf);
+ slog.debug("shutting down server %s", name.c_str());
// Close any active clients, with appropriate logging & cleanup
closeClients("Server shutdown");
handleClipboardAnnounce(*ci, false);
clipboardRequestors.remove(*ci);
- CharArray name(strDup((*ci)->getPeerEndpoint()));
+ std::string name((*ci)->getPeerEndpoint());
// - Delete the per-Socket resources
delete *ci;
clients.remove(*ci);
- connectionsLog.status("closed: %s", name.buf);
+ connectionsLog.status("closed: %s", name.c_str());
// - Check that the desktop object is still required
if (authClientCount() == 0)
void VNCServerST::setName(const char* name_)
{
- name.replaceBuf(strDup(name_));
+ name = name_;
std::list<VNCSConnectionST*>::iterator ci, ci_next;
for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
ci_next = ci; ci_next++;
const ScreenSet& getScreenLayout() const { return screenLayout; }
const Cursor* getCursor() const { return cursor; }
const Point& getCursorPos() const { return cursorPos; }
- const char* getName() const { return name.buf; }
+ const char* getName() const { return name.c_str(); }
unsigned getLEDState() const { return ledState; }
// Event handlers
ScreenSet screenLayout;
unsigned int ledState;
- CharArray name;
+ std::string name;
std::list<VNCSConnectionST*> clients;
VNCSConnectionST* pointerClient;
--- /dev/null
+/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
+ * Copyright 2023 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
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this software; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+ * USA.
+ */
+
+//
+// XXX not thread-safe, because d3des isn't - do we need to worry about this?
+//
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <assert.h>
+#include <string.h>
+
+extern "C" {
+#include <rfb/d3des.h>
+}
+
+#include <rdr/Exception.h>
+#include <rfb/obfuscate.h>
+
+static unsigned char d3desObfuscationKey[] = {23,82,107,6,35,78,88,7};
+
+std::vector<uint8_t> rfb::obfuscate(const char *str)
+{
+ std::vector<uint8_t> buf(8);
+
+ assert(str != NULL);
+
+ size_t l = strlen(str), i;
+ for (i=0; i<8; i++)
+ buf[i] = i<l ? str[i] : 0;
+ deskey(d3desObfuscationKey, EN0);
+ des(buf.data(), buf.data());
+
+ return buf;
+}
+
+std::string rfb::deobfuscate(const uint8_t *data, size_t len)
+{
+ char buf[9];
+
+ assert(data != NULL);
+
+ if (len != 8)
+ throw rdr::Exception("bad obfuscated password length");
+
+ deskey(d3desObfuscationKey, DE1);
+ des((uint8_t*)data, (uint8_t*)buf);
+ buf[8] = 0;
+
+ return buf;
+}
--- /dev/null
+/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
+ * Copyright 2023 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
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this software; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+ * USA.
+ */
+
+#ifndef __RFB_OBFUSCATE_H__
+#define __RFB_OBFUSCATE_H__
+
+#include <stdint.h>
+
+#include <string>
+#include <vector>
+
+namespace rfb {
+
+ std::vector<uint8_t> obfuscate(const char *str);
+ std::string deobfuscate(const uint8_t *data, size_t len);
+
+}
+
+#endif
/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
- * Copyright 2011-2022 Pierre Ossman for Cendio AB
+ * Copyright 2011-2023 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
delete [] s;
}
+ std::string strFormat(const char *fmt, ...)
+ {
+ va_list ap;
+ int len;
+ char *buf;
+ std::string out;
+
+ va_start(ap, fmt);
+ len = vsnprintf(NULL, 0, fmt, ap);
+ va_end(ap);
+
+ if (len < 0)
+ return "";
+
+ buf = new char[len+1];
+
+ va_start(ap, fmt);
+ vsnprintf(buf, len+1, fmt, ap);
+ va_end(ap);
+
+ out = buf;
+
+ delete [] buf;
+
+ return out;
+ }
+
std::vector<std::string> strSplit(const char* src,
const char delimiter)
{
/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
- * Copyright 2011-2022 Pierre Ossman for Cendio AB
+ * Copyright 2011-2023 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
char* strDup(const char* s);
void strFree(char* s);
+ // Formats according to printf(), with a dynamic allocation
+ std::string strFormat(const char *fmt, ...)
+ __attribute__((__format__ (__printf__, 1, 2)));
+
// Splits a string with the specified delimiter
std::vector<std::string> strSplit(const char* src,
const char delimiter);
// setText() changes the text in the button.
void setText(const char* text_) {
- text.buf = rfb::strDup(text_);
- int textWidth = XTextWidth(defaultFS, text.buf, strlen(text.buf));
+ text = text_;
+ int textWidth = XTextWidth(defaultFS, text.data(), text.size());
int textHeight = (defaultFS->ascent + defaultFS->descent);
int newWidth = __rfbmax(width(), textWidth + xPad*2 + bevel*2);
int newHeight = __rfbmax(height(), textHeight + yPad*2 + bevel*2);
private:
void paint() {
- int tw = XTextWidth(defaultFS, text.buf, strlen(text.buf));
+ int tw = XTextWidth(defaultFS, text.data(), text.size());
int startx = (width() - tw) / 2;
int starty = (height() + defaultFS->ascent - defaultFS->descent) / 2;
if (down || disabled_) {
}
XSetForeground(dpy, gc, disabled_ ? disabledFg : defaultFg);
- XDrawString(dpy, win(), gc, startx, starty, text.buf, strlen(text.buf));
+ XDrawString(dpy, win(), gc, startx, starty, text.data(), text.size());
}
virtual void handleEvent(TXWindow* /*w*/, XEvent* ev) {
}
GC gc;
- rfb::CharArray text;
+ std::string text;
TXButtonCallback* cb;
bool down;
bool disabled_;
// setText() changes the text in the label.
void setText(const char* text_) {
- text.buf = rfb::strDup(text_);
+ text = text_;
lines = 0;
- int lineStart = 0;
+ size_t lineStart = 0;
int textWidth = 0;
- int i = -1;
+ size_t i = -1;
do {
i++;
- if (text.buf[i] == '\n' || text.buf[i] == 0) {
- int tw = XTextWidth(defaultFS, &text.buf[lineStart], i-lineStart);
+ if (i >= text.size() || text[i] == '\n') {
+ int tw = XTextWidth(defaultFS, &text[lineStart], i-lineStart);
if (tw > textWidth) textWidth = tw;
lineStart = i+1;
lines++;
}
- } while (text.buf[i] != 0);
+ } while (i < text.size());
int textHeight = ((defaultFS->ascent + defaultFS->descent + lineSpacing)
* lines);
int newWidth = __rfbmax(width(), textWidth + xPad*2);
}
void paint() {
- int lineNum = 0;
- int lineStart = 0;
- int i = -1;
+ size_t lineNum = 0;
+ size_t lineStart = 0;
+ size_t i = -1;
do {
i++;
- if (text.buf[i] == '\n' || text.buf[i] == 0) {
- int tw = XTextWidth(defaultFS, &text.buf[lineStart], i-lineStart);
+ if (i >= text.size() || text[i] == '\n') {
+ int tw = XTextWidth(defaultFS, &text[lineStart], i-lineStart);
XDrawString(dpy, win(), defaultGC, xOffset(tw), yOffset(lineNum),
- &text.buf[lineStart], i-lineStart);
+ &text[lineStart], i-lineStart);
lineStart = i+1;
lineNum++;
}
- } while (text.buf[i] != 0);
+ } while (i < text.size());
}
virtual void handleEvent(TXWindow* /*w*/, XEvent* ev) {
}
int lineSpacing;
- rfb::CharArray text;
+ std::string text;
int lines;
HAlign halign;
VAlign valign;
/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
* Copyright (C) 2010 Antoine Martin. All Rights Reserved.
* Copyright (C) 2010 D. R. Commander. All Rights Reserved.
+ * Copyright 2018-2023 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
#include <sys/stat.h>
#include <unistd.h>
#include <os/os.h>
-#include <rfb/Password.h>
+
+#include <rfb/obfuscate.h>
#include <termios.h>
tcsetattr(fileno(stdin), TCSAFLUSH, &attrs);
}
-static char* getpassword(const char* prompt) {
- PlainPasswd buf(256);
+static const char* getpassword(const char* prompt) {
+ static char buf[256];
if (prompt) fputs(prompt, stdout);
enableEcho(false);
- char* result = fgets(buf.buf, 256, stdin);
+ char* result = fgets(buf, 256, stdin);
enableEcho(true);
if (result) {
if (result[strlen(result)-1] == '\n')
result[strlen(result)-1] = 0;
- return buf.takeBuf();
+ return buf;
}
return 0;
}
// We support a maximum of two passwords right now
for (i = 0;i < 2;i++) {
- char *result = getpassword(NULL);
+ const char *result = getpassword(NULL);
if (!result)
break;
- ObfuscatedPasswd obfuscated(result);
- if (fwrite(obfuscated.buf, obfuscated.length, 1, stdout) != 1) {
+ std::vector<uint8_t> obfuscated = obfuscate(result);
+ if (fwrite(obfuscated.data(), obfuscated.size(), 1, stdout) != 1) {
fprintf(stderr,"Writing to stdout failed\n");
return 1;
}
return 0;
}
-static ObfuscatedPasswd* readpassword() {
+static std::vector<uint8_t> readpassword() {
while (true) {
- PlainPasswd passwd(getpassword("Password:"));
- if (!passwd.buf) {
+ const char *passwd = getpassword("Password:");
+ if (passwd == NULL) {
perror("getpassword error");
exit(1);
}
- if (strlen(passwd.buf) < 6) {
- if (strlen(passwd.buf) == 0) {
+ std::string first = passwd;
+ if (first.size() < 6) {
+ if (first.empty()) {
fprintf(stderr,"Password not changed\n");
exit(1);
}
continue;
}
- PlainPasswd passwd2(getpassword("Verify:"));
- if (!passwd2.buf) {
+ passwd = getpassword("Verify:");
+ if (passwd == NULL) {
perror("getpass error");
exit(1);
}
- if (strcmp(passwd.buf, passwd2.buf) != 0) {
+ std::string second = passwd;
+ if (first != second) {
fprintf(stderr,"Passwords don't match - try again\n");
continue;
}
- return new ObfuscatedPasswd(passwd);
+ return obfuscate(first.c_str());
}
}
}
while (true) {
- ObfuscatedPasswd* obfuscated = readpassword();
- ObfuscatedPasswd* obfuscatedReadOnly = 0;
+ std::vector<uint8_t> obfuscated = readpassword();
+ std::vector<uint8_t> obfuscatedReadOnly;
fprintf(stderr, "Would you like to enter a view-only password (y/n)? ");
char yesno[3];
FILE* fp = fopen(fname,"w");
if (!fp) {
fprintf(stderr,"Couldn't open %s for writing\n",fname);
- delete obfuscated;
- delete obfuscatedReadOnly;
exit(1);
}
chmod(fname, S_IRUSR|S_IWUSR);
- if (fwrite(obfuscated->buf, obfuscated->length, 1, fp) != 1) {
+ if (fwrite(obfuscated.data(), obfuscated.size(), 1, fp) != 1) {
fprintf(stderr,"Writing to %s failed\n",fname);
- delete obfuscated;
- delete obfuscatedReadOnly;
exit(1);
}
- delete obfuscated;
-
- if (obfuscatedReadOnly) {
- if (fwrite(obfuscatedReadOnly->buf, obfuscatedReadOnly->length, 1, fp) != 1) {
+ if (!obfuscatedReadOnly.empty()) {
+ if (fwrite(obfuscatedReadOnly.data(), obfuscatedReadOnly.size(), 1, fp) != 1) {
fprintf(stderr,"Writing to %s failed\n",fname);
- delete obfuscatedReadOnly;
exit(1);
}
}
fclose(fp);
- delete obfuscatedReadOnly;
-
return 0;
}
}
#include <config.h>
#endif
+#include <string.h>
+
#include <rfb/LogWriter.h>
#include <x0vncserver/Geometry.h>
#include <stdio.h>
#include <stdlib.h>
+#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <rfb/LogWriter.h>
#include <rfb/Logger_stdio.h>
#include <rfb/Logger_syslog.h>
+#include <rfb/util.h>
#include "RFBGlue.h"
return;
}
- queryConnectAddress.replaceBuf(strDup(sock->getPeerAddress()));
+ queryConnectAddress = sock->getPeerAddress();
if (!userName)
userName = "(anonymous)";
- queryConnectUsername.replaceBuf(strDup(userName));
+ queryConnectUsername = userName;
queryConnectId = (uint32_t)(intptr_t)sock;
queryConnectSocket = sock;
*username = "";
*timeout = 0;
} else {
- *address = queryConnectAddress.buf;
- *username = queryConnectUsername.buf;
+ *address = queryConnectAddress.c_str();
+ *username = queryConnectUsername.c_str();
*timeout = queryConnectTimeout;
}
}
uint32_t queryConnectId;
network::Socket* queryConnectSocket;
- rfb::CharArray queryConnectAddress;
- rfb::CharArray queryConnectUsername;
+ std::string queryConnectAddress;
+ std::string queryConnectUsername;
rfb::Timer queryConnectTimer;
OutputIdMap outputIdMap;
#include <os/os.h>
#include <rfb/Exception.h>
#include <rfb/LogWriter.h>
+#include <rfb/util.h>
#include "fltk/layout.h"
#include "ServerDialog.h"
#include <FL/Fl_Return_Button.H>
#include <FL/Fl_Pixmap.H>
-#include <rfb/Password.h>
#include <rfb/Exception.h>
+#include <rfb/obfuscate.h>
#include "fltk/layout.h"
#include "fltk/util.h"
}
if (!user && passwordFileName[0]) {
- ObfuscatedPasswd obfPwd(256);
+ std::vector<uint8_t> obfPwd(256);
FILE* fp;
fp = fopen(passwordFileName, "rb");
if (!fp)
throw rfb::Exception(_("Opening password file failed"));
- obfPwd.length = fread(obfPwd.buf, 1, obfPwd.length, fp);
+ obfPwd.resize(fread(obfPwd.data(), 1, obfPwd.size(), fp));
fclose(fp);
- PlainPasswd passwd(obfPwd);
- *password = passwd.buf;
+ *password = deobfuscate(obfPwd.data(), obfPwd.size());
return;
}
}
-UserName::UserName() : CharArray(UNLEN+1) {
+UserName::UserName() {
+ char buf[UNLEN+1];
DWORD len = UNLEN+1;
if (!GetUserName(buf, &len))
throw rdr::SystemException("GetUserName failed", GetLastError());
+ assign(buf);
}
#ifndef __RFB_WIN32_CURRENT_USER_H__
#define __RFB_WIN32_CURRENT_USER_H__
-#include <rfb/util.h>
+#include <string>
+
#include <rfb_win32/Handle.h>
#include <rfb_win32/Security.h>
// Returns the name of the user the thread is currently running as.
// Raises a SystemException in case of error.
- struct UserName : public CharArray {
+ struct UserName : public std::string {
UserName();
};
PropSheet::PropSheet(HINSTANCE inst_, const char* title_, std::list<PropSheetPage*> pages_, HICON icon_)
-: icon(icon_), pages(pages_), inst(inst_), title(strDup(title_)), handle(0), alreadyShowing(0) {
+: icon(icon_), pages(pages_), inst(inst_), title(title_), handle(0), alreadyShowing(0) {
}
PropSheet::~PropSheet() {
header.pfnCallback = removeCtxtHelp;
header.hwndParent = owner;
header.hInstance = inst;
- header.pszCaption = title.buf;
+ header.pszCaption = title.c_str();
header.nPages = count;
header.nStartPage = 0;
header.phpage = hpages;
(void)capture;
#ifdef _DIALOG_CAPTURE
if (capture) {
- plog.info("capturing \"%s\"", title.buf);
+ plog.info("capturing \"%s\"", title.c_str());
char* tmpdir = getenv("TEMP");
HDC dc = GetWindowDC(handle);
DeviceFrameBuffer fb(dc);
#ifndef __RFB_WIN32_DIALOG_H__
#define __RFB_WIN32_DIALOG_H__
+#include <string>
+
#include <windows.h>
#include <prsht.h>
#include <list>
-#include <rfb/util.h>
-
namespace rfb {
namespace win32 {
HICON icon;
std::list<PropSheetPage*> pages;
HINSTANCE inst;
- CharArray title;
+ std::string title;
HWND handle;
bool alreadyShowing;
};
LaunchProcess::LaunchProcess(const char* exeName_, const char* params_)
-: exeName(strDup(exeName_)), params(strDup(params_)) {
+: exeName(exeName_), params(params_) {
memset(&procInfo, 0, sizeof(procInfo));
}
sinfo.lpDesktop = desktopName;
// - Concoct a suitable command-line
- CharArray exePath;
- if (!strContains(exeName.buf, '\\')) {
+ std::string exePath;
+ if (exeName.find('\\') == std::string::npos) {
ModuleFileName filename;
- CharArray path(strDup(filename.buf));
- if (strContains(path.buf, '\\'))
- *strrchr(path.buf, '\\') = '\0';
- exePath.buf = new char[strlen(path.buf) + strlen(exeName.buf) + 2];
- sprintf(exePath.buf, "%s\\%s", path.buf, exeName.buf);
+ std::string path(filename.buf);
+ if (path.rfind('\\') != std::string::npos)
+ path.resize(path.rfind('\\'));
+ exePath = path + '\\' + exeName;
} else {
- exePath.buf = strDup(exeName.buf);
+ exePath = exeName;
}
// - Start the process
// Note: We specify the exe's precise path in the ApplicationName parameter,
// AND include the name as the first part of the CommandLine parameter,
// because CreateProcess doesn't make ApplicationName argv[0] in C programs.
- CharArray cmdLine(strlen(exeName.buf) + 3 + strlen(params.buf) + 1);
- sprintf(cmdLine.buf, "\"%s\" %s", exeName.buf, params.buf);
+ std::string cmdLine;
+ cmdLine = (std::string)"\"" + exeName + "\" " + params;
DWORD flags = createConsole ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW;
BOOL success;
if (userToken != INVALID_HANDLE_VALUE)
- success = CreateProcessAsUser(userToken, exePath.buf, cmdLine.buf, 0, 0, FALSE, flags, 0, 0, &sinfo, &procInfo);
+ success = CreateProcessAsUser(userToken, exePath.c_str(),
+ (char*)cmdLine.c_str(), 0, 0, FALSE,
+ flags, 0, 0, &sinfo, &procInfo);
else
- success = CreateProcess(exePath.buf, cmdLine.buf, 0, 0, FALSE, flags, 0, 0, &sinfo, &procInfo);
+ success = CreateProcess(exePath.c_str(), (char*)cmdLine.c_str(), 0,
+ 0, FALSE, flags, 0, 0, &sinfo, &procInfo);
if (!success)
throw rdr::SystemException("unable to launch process", GetLastError());
#ifndef __RFB_WIN32_LAUNCHPROCESS_H__
#define __RFB_WIN32_LAUNCHPROCESS_H__
-#include <windows.h>
+#include <string>
-#include <rfb/util.h>
+#include <windows.h>
namespace rfb {
PROCESS_INFORMATION procInfo;
DWORD returnCode;
protected:
- CharArray exeName;
- CharArray params;
+ std::string exeName;
+ std::string params;
};
#ifndef __RFB_WIN32_MSGBOX_H__
#define __RFB_WIN32_MSGBOX_H__
-#include <windows.h>
+#include <string>
-#include <rfb/util.h>
+#include <windows.h>
namespace rfb {
namespace win32 {
flags |= MB_TOPMOST | MB_SETFOREGROUND;
int len = strlen(AppName) + 1;
if (msgType) len += strlen(msgType) + 3;
- CharArray title(new char[len]);
- strcpy(title.buf, AppName);
+ std::string title = AppName;
if (msgType) {
- strcat(title.buf, " : ");
- strcat(title.buf, msgType);
+ title += " : ";
+ title += msgType;
}
- return MessageBox(parent, msg, title.buf, flags);
+ return MessageBox(parent, msg, title.c_str(), flags);
}
};
// -=- MsgWindow
//
-MsgWindow::MsgWindow(const char* name_) : name(strDup(name_)), handle(0) {
- vlog.debug("creating window \"%s\"", name.buf);
+MsgWindow::MsgWindow(const char* name_) : name(name_), handle(0) {
+ vlog.debug("creating window \"%s\"", name.c_str());
handle = CreateWindow((const char*)(intptr_t)baseClass.classAtom,
- name.buf, WS_OVERLAPPED, 0, 0, 10, 10, 0, 0,
+ name.c_str(), WS_OVERLAPPED, 0, 0, 10, 10, 0, 0,
baseClass.instance, this);
if (!handle) {
throw rdr::SystemException("unable to create WMNotifier window instance", GetLastError());
}
- vlog.debug("created window \"%s\" (%p)", name.buf, handle);
+ vlog.debug("created window \"%s\" (%p)", name.c_str(), handle);
}
MsgWindow::~MsgWindow() {
if (handle)
DestroyWindow(handle);
- vlog.debug("destroyed window \"%s\" (%p)", name.buf, handle);
+ vlog.debug("destroyed window \"%s\" (%p)", name.c_str(), handle);
}
LRESULT
#ifndef __RFB_WIN32_MSG_WINDOW_H__
#define __RFB_WIN32_MSG_WINDOW_H__
-#include <windows.h>
+#include <string>
-#include <rfb/util.h>
+#include <windows.h>
namespace rfb {
MsgWindow(const char* _name);
virtual ~MsgWindow();
- const char* getName() {return name.buf;}
+ const char* getName() {return name.c_str();}
HWND getHandle() const {return handle;}
virtual LRESULT processMessage(UINT msg, WPARAM wParam, LPARAM lParam);
protected:
- CharArray name;
+ std::string name;
HWND handle;
};
#include <rdr/HexInStream.h>
#include <stdlib.h>
#include <rfb/LogWriter.h>
+#include <rfb/util.h>
// These flags are required to control access control inheritance,
// but are not defined by VC6's headers. These definitions comes
#include <logmessages/messages.h>
#include <rdr/Exception.h>
#include <rfb/LogWriter.h>
+#include <rfb/util.h>
using namespace rdr;
}
// - Add the supplied extra parameters to the command line
- CharArray cmdline(cmdline_len+strlen(defaultcmdline));
- sprintf(cmdline.buf, "\"%s\" %s", buffer.buf, defaultcmdline);
+ std::string cmdline;
+ cmdline = strFormat("\"%s\" %s", buffer.buf, defaultcmdline);
for (i=0; i<argc; i++) {
- strcat(cmdline.buf, " \"");
- strcat(cmdline.buf, argv[i]);
- strcat(cmdline.buf, "\"");
+ cmdline += " \"";
+ cmdline += argv[i];
+ cmdline += "\"";
}
// - Register the service
name, display, SC_MANAGER_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS,
SERVICE_AUTO_START, SERVICE_ERROR_IGNORE,
- cmdline.buf, NULL, NULL, NULL, NULL, NULL);
+ cmdline.c_str(), NULL, NULL, NULL, NULL, NULL);
if (!service)
throw rdr::SystemException("unable to create service", GetLastError());
}
const char* dllFilename = "logmessages.dll";
- CharArray dllPath(strlen(buffer.buf) + strlen(dllFilename) + 1);
- strcpy(dllPath.buf, buffer.buf);
- strcat(dllPath.buf, dllFilename);
+ std::string dllPath;
+ dllPath = buffer.buf;
+ dllPath += dllFilename;
- hk.setExpandString("EventMessageFile", dllPath.buf);
+ hk.setExpandString("EventMessageFile", dllPath.c_str());
hk.setInt("TypesSupported", EVENTLOG_ERROR_TYPE | EVENTLOG_INFORMATION_TYPE);
Sleep(500);
#include <list>
#include <rfb/LogWriter.h>
#include <rfb/Timer.h>
+#include <rfb/util.h>
#include <rfb_win32/SocketManager.h>
using namespace rfb;
}
std::string langIdStr(binToHex(langIdBuf, sizeof(langId)));
- CharArray infoName(strlen("StringFileInfo") + 4 + strlen(name) + strlen(langIdStr.c_str()));
- sprintf(infoName.buf, "\\StringFileInfo\\%s\\%s", langIdStr.c_str(), name);
+ std::string infoName;
+ infoName = strFormat("\\StringFileInfo\\%s\\%s", langIdStr.c_str(), name);
// Locate the required version string within the version info
char* buffer = 0;
UINT length = 0;
- if (!VerQueryValue(buf, infoName.buf, (void**)&buffer, &length)) {
- printf("unable to find %s version string", infoName.buf);
+ if (!VerQueryValue(buf, infoName.c_str(), (void**)&buffer, &length)) {
+ printf("unable to find %s version string", infoName.c_str());
throw rdr::Exception("VerQueryValue failed");
}
return buffer;
#ifdef HAVE_GNUTLS
#include <rfb/SSecurityTLS.h>
#endif
-#include <rfb/Password.h>
static rfb::BoolParameter queryOnlyIfLoggedOn("QueryOnlyIfLoggedOn",
"Only prompt for a local user to accept incoming connections if there is a user logged on", false);
static bool haveVncPassword() {
- PlainPasswd password, passwordReadOnly;
+ std::string password, passwordReadOnly;
SSecurityVncAuth::vncAuthPasswd.getVncAuthPasswd(&password, &passwordReadOnly);
- return password.buf && strlen(password.buf) != 0;
+ return !password.empty();
}
static void verifyVncPassword(const RegKey& regKey) {
public:
ConnHostDialog() : Dialog(GetModuleHandle(0)) {}
bool showDialog(const char* pat) {
- pattern.replaceBuf(strDup(pat));
+ pattern = pat;
return Dialog::showDialog(MAKEINTRESOURCE(IDD_CONN_HOST));
}
void initDialog() {
- if (strlen(pattern.buf) == 0)
- pattern.replaceBuf(strDup("+"));
+ if (pattern.empty())
+ pattern = "+";
- if (pattern.buf[0] == '+')
+ if (pattern[0] == '+')
setItemChecked(IDC_ALLOW, true);
- else if (pattern.buf[0] == '?')
+ else if (pattern[0] == '?')
setItemChecked(IDC_QUERY, true);
else
setItemChecked(IDC_DENY, true);
- setItemString(IDC_HOST_PATTERN, &pattern.buf[1]);
- pattern.replaceBuf(0);
+ setItemString(IDC_HOST_PATTERN, &pattern.c_str()[1]);
+ pattern.clear();
}
bool onOk() {
- CharArray host(strDup(getItemString(IDC_HOST_PATTERN)));
- CharArray newPat(strlen(host.buf)+2);
+ std::string newPat;
if (isItemChecked(IDC_ALLOW))
- newPat.buf[0] = '+';
+ newPat = '+';
else if (isItemChecked(IDC_QUERY))
- newPat.buf[0] = '?';
+ newPat = '?';
else
- newPat.buf[0] = '-';
- newPat.buf[1] = 0;
- strcat(newPat.buf, host.buf);
+ newPat = '-';
+ newPat += getItemString(IDC_HOST_PATTERN);
try {
- network::TcpFilter::Pattern pat(network::TcpFilter::parsePattern(newPat.buf));
- pattern.replaceBuf(strDup(network::TcpFilter::patternToStr(pat).c_str()));
+ network::TcpFilter::Pattern pat(network::TcpFilter::parsePattern(newPat.c_str()));
+ pattern = network::TcpFilter::patternToStr(pat);
} catch(rdr::Exception& e) {
MsgBox(NULL, e.str(), MB_ICONEXCLAMATION | MB_OK);
return false;
}
return true;
}
- const char* getPattern() {return pattern.buf;}
+ const char* getPattern() {return pattern.c_str();}
protected:
- CharArray pattern;
+ std::string pattern;
};
class ConnectionsPage : public PropSheetPage {
// settings from HKCU/Software/ORL/WinVNC3.
// Get the name of the current user
- CharArray username;
+ std::string username;
try {
- UserName name;
- username.buf = name.takeBuf();
+ username = UserName();
} catch (rdr::SystemException& e) {
if (e.err != ERROR_NOT_LOGGED_ON)
throw;
std::string authHosts = winvnc3.getString("AuthHosts", "");
if (!authHosts.empty()) {
- CharArray newHosts;
- newHosts.buf = strDup("");
+ std::string newHosts;
// Reformat AuthHosts to Hosts. Wish I'd left the format the same. :( :( :(
try {
strcat(pattern, buf);
// Append this pattern to the Hosts value
- int length = strlen(newHosts.buf) + strlen(pattern) + 2;
- CharArray tmpHosts(length);
- strcpy(tmpHosts.buf, pattern);
- if (strlen(newHosts.buf)) {
- strcat(tmpHosts.buf, ",");
- strcat(tmpHosts.buf, newHosts.buf);
- }
- delete [] newHosts.buf;
- newHosts.buf = tmpHosts.takeBuf();
+ if (!newHosts.empty())
+ newHosts += ",";
+ newHosts += pattern;
}
}
// Finally, save the Hosts value
- regKey.setString("Hosts", newHosts.buf);
+ regKey.setString("Hosts", newHosts.c_str());
} catch (rdr::Exception&) {
MsgBox(0, "Unable to convert AuthHosts setting to Hosts format.",
MB_ICONWARNING | MB_OK);
}
// Open the local, user-specific settings
- if (userSettings && username.buf) {
+ if (userSettings && !username.empty()) {
try {
RegKey userKey;
- userKey.openKey(winvnc3, username.buf);
+ userKey.openKey(winvnc3, username.c_str());
vlog.info("loading local User prefs");
LoadUserPrefs(userKey);
} catch(rdr::Exception& e) {
#include <vncconfig/resource.h>
#include <vncconfig/PasswordDialog.h>
#include <rfb_win32/MsgBox.h>
-#include <rfb/Password.h>
+#include <rfb/obfuscate.h>
using namespace rfb;
using namespace win32;
}
bool PasswordDialog::onOk() {
- PlainPasswd password1(strDup(getItemString(IDC_PASSWORD1)));
- PlainPasswd password2(strDup(getItemString(IDC_PASSWORD2)));
- if (strcmp(password1.buf, password2.buf) != 0) {
+ std::string password1(getItemString(IDC_PASSWORD1));
+ std::string password2(getItemString(IDC_PASSWORD2));
+ if (password1 != password2) {
MsgBox(0, "The supplied passwords do not match",
MB_ICONEXCLAMATION | MB_OK);
return false;
"Are you sure you wish to continue?",
MB_YESNO | MB_ICONWARNING) == IDNO))
return false;
- PlainPasswd password(strDup(password1.buf));
- ObfuscatedPasswd obfPwd(password);
- regKey.setBinary("Password", obfPwd.buf, obfPwd.length);
+ std::vector<uint8_t> obfPwd = obfuscate(password1.c_str());
+ regKey.setBinary("Password", obfPwd.data(), obfPwd.size());
return true;
}
virtual bool showDialog() {
return Dialog::showDialog(MAKEINTRESOURCE(IDD_ADD_NEW_CLIENT));
}
- const char* getHostName() const {return hostName.buf;}
+ const char* getHostName() const {return hostName.c_str();}
protected:
// Dialog methods (protected)
virtual void initDialog() {
- if (hostName.buf)
- setItemString(IDC_HOST, hostName.buf);
+ if (!hostName.empty())
+ setItemString(IDC_HOST, hostName.c_str());
}
virtual bool onOk() {
- hostName.replaceBuf(rfb::strDup(getItemString(IDC_HOST)));
+ hostName = getItemString(IDC_HOST);
return true;
}
- rfb::CharArray hostName;
+ std::string hostName;
};
};
const char* userName_,
VNCServerWin32* s)
: Dialog(GetModuleHandle(0)),
- sock(sock_), approve(false), server(s) {
- peerIp.buf = strDup(sock->getPeerAddress());
- userName.buf = strDup(userName_);
+ sock(sock_), peerIp(sock->getPeerAddress()), userName(userName_),
+ approve(false), server(s) {
}
void QueryConnectDialog::startDialog() {
void QueryConnectDialog::initDialog() {
if (!SetTimer(handle, 1, 1000, 0))
throw rdr::SystemException("SetTimer", GetLastError());
- setItemString(IDC_QUERY_HOST, peerIp.buf);
- if (!userName.buf)
- userName.buf = strDup("(anonymous)");
- setItemString(IDC_QUERY_USER, userName.buf);
+ setItemString(IDC_QUERY_HOST, peerIp.c_str());
+ if (userName.empty())
+ userName = "(anonymous)";
+ setItemString(IDC_QUERY_USER, userName.c_str());
setCountdownLabel();
}
#define __WINVNC_QUERY_CONNECT_DIALOG_H__
#include <rfb_win32/Dialog.h>
-#include <rfb/util.h>
namespace os { class Thread; }
int countdown;
network::Socket* sock;
- rfb::CharArray peerIp;
- rfb::CharArray userName;
+ std::string peerIp;
+ std::string userName;
bool approve;
VNCServerWin32* server;
};
switch (command->dwData) {
case 1:
{
- CharArray viewer(command->cbData + 1);
- memcpy(viewer.buf, command->lpData, command->cbData);
- viewer.buf[command->cbData] = 0;
- return thread.server.addNewClient(viewer.buf) ? 1 : 0;
+ std::string viewer((char*)command->lpData, command->cbData);
+ return thread.server.addNewClient(viewer.c_str()) ? 1 : 0;
}
case 2:
return thread.server.disconnectClients("IPC disconnect") ? 1 : 0;
case WM_SET_TOOLTIP:
{
os::AutoMutex a(thread.lock);
- if (thread.toolTip.buf)
- setToolTip(thread.toolTip.buf);
+ if (!thread.toolTip.empty())
+ setToolTip(thread.toolTip.c_str());
}
return 0;
void STrayIconThread::setToolTip(const char* text) {
if (!windowHandle) return;
os::AutoMutex a(lock);
- delete [] toolTip.buf;
- toolTip.buf = strDup(text);
+ toolTip = text;
PostMessage(windowHandle, WM_SET_TOOLTIP, 0, 0);
}
os::Mutex* lock;
DWORD thread_id;
HWND windowHandle;
- rfb::CharArray toolTip;
+ std::string toolTip;
VNCServerWin32& server;
UINT inactiveIcon;
UINT activeIcon;
if (GetSessionUserTokenWin(&hToken))
{
ModuleFileName filename;
- CharArray cmdLine;
- cmdLine.format("\"%s\" -noconsole -service_run", filename.buf);
+ std::string cmdLine;
+ cmdLine = strFormat("\"%s\" -noconsole -service_run", filename.buf);
STARTUPINFO si;
ZeroMemory(&si, sizeof si);
si.cb = sizeof si;
si.dwFlags = STARTF_USESHOWWINDOW;
PROCESS_INFORMATION pi;
- if (CreateProcessAsUser(hToken, NULL, cmdLine.buf, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi))
+ if (CreateProcessAsUser(hToken, NULL, (char*)cmdLine.c_str(),
+ NULL, NULL, FALSE, DETACHED_PROCESS,
+ NULL, NULL, &si, &pi))
{
CloseHandle(pi.hThread);
hProcess = pi.hProcess;
length += i->size() + 1;
// Build the new tip
- CharArray toolTip(length);
- strcpy(toolTip.buf, prefix);
+ std::string toolTip(prefix);
for (i=addrs.begin(); i!= addrs.end(); i=next_i) {
next_i = i; next_i ++;
- strcat(toolTip.buf, i->c_str());
+ toolTip += *i;
if (next_i != addrs.end())
- strcat(toolTip.buf, ",");
+ toolTip += ",";
}
// Pass the new tip to the tray icon
vlog.info("Refreshing tray icon");
- trayIcon->setToolTip(toolTip.buf);
+ trayIcon->setToolTip(toolTip.c_str());
}
void VNCServerWin32::regConfigChanged() {
if (strcasecmp(argv[i], "-connect") == 0) {
runServer = false;
- CharArray host;
+ const char *host = NULL;
if (i+1 < argc) {
- host.buf = strDup(argv[i+1]);
+ host = argv[i+1];
i++;
} else {
AddNewClientDialog ancd;
if (ancd.showDialog())
- host.buf = strDup(ancd.getHostName());
+ host = ancd.getHostName();
}
- if (host.buf) {
+ if (host != NULL) {
HWND hwnd = FindWindow(0, "winvnc::IPC_Interface");
if (!hwnd)
throw rdr::Exception("Unable to locate existing VNC Server.");
COPYDATASTRUCT copyData;
copyData.dwData = 1; // *** AddNewClient
- copyData.cbData = strlen(host.buf);
- copyData.lpData = (void*)host.buf;
+ copyData.cbData = strlen(host);
+ copyData.lpData = (void*)host;
printf("Sending connect request to VNC Server...\n");
if (!SendMessage(hwnd, WM_COPYDATA, 0, (LPARAM)©Data))
MsgBoxOrLog("Connection failed.", true);
} else if (strcasecmp(argv[i], "-status") == 0) {
printf("Querying service status...\n");
runServer = false;
- CharArray result;
+ std::string result;
DWORD state = rfb::win32::getServiceState(VNCServerService::Name);
- result.format("The %s Service is in the %s state.",
- VNCServerService::Name,
- rfb::win32::serviceStateName(state));
- MsgBoxOrLog(result.buf);
+ result = strFormat("The %s Service is in the %s state.",
+ VNCServerService::Name,
+ rfb::win32::serviceStateName(state));
+ MsgBoxOrLog(result.c_str());
} else if (strcasecmp(argv[i], "-service") == 0) {
printf("Run in service mode\n");
runServer = false;